http://stackoverflow.com/a/49970253
answers question: http://stackoverflow.com/q/49970116
score: 0
has body: You are confusing the HTML/CSS/Javascript code that is running in your browser and the (PHP/Python) code that is running on the server. Even if in your case, they might be the same, it doesn't matter. The python script is not running in your browser and therefore cannot change the state of your html/css or even javascript. When you are executing your code with exec, the PHP server is running an external command and expecting a response to the immediate request. After that, it's over. I would recommend to ditch PHP and use a Python web application framework. Flask, Django or whatever else. This will allow you to interact directly with the python code. Your web browser could then request data to your server and know what is happening. Remember, the web is normally only from the browser to the server. Now, if you need real-time interactions, you should have a look at websockets. These will allow bidirectional communication between your browser and the running python app. There are a number of caveats with this technology but it might be better suited to your needs. Note that this will force you to write Javascript code in your browser to manage this communication but it shouldn't be too hard.
type: Answer
has comment: http://stackoverflow.com/comment/86956869

http://stackoverflow.com/comment/86952950
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49966065
has text: Enforce an ordering on stored ids in your association table for avoiding duplicates, and use a union of both possible ways to select as the secondary "table".

http://stackoverflow.com/a/50021136
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50020744
upvote count: 1
score: 1
has body: This reads a lot like someone coming from matlab to python. There are ways of pythonizing it. import numpy as np from scipy import sparse var1 = sparse.eye(9).tocsc() # we can make our truth matrix much faster bol = np.ones((3, 3), dtype='bool') bol[1, 1] = False In matlab to delete a row you set it to []. In python we can use numpy advanced indexing like so to only keep the rows we want (~ is the element wise not operator): # ~bol.flatten(): array([False, False, False, False, True, False, False, False, False]) var1 = var1[~bol.flatten()] var1 is now: repr: &lt;1x9 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 1 stored elements in Compressed Sparse Column format&gt; str: (0, 4) 1.0 Because we're in python each index is 1 less so this is the same as your matlab result.
type: Answer
answers question: http://stackoverflow.com/q/50020744
downvote count: 0

http://stackoverflow.com/q/50035978
score: 0
answer count: 3
tagged with: if-statement
tagged with: python
has answer: http://stackoverflow.com/a/65751306
tagged with: loops
has comment: http://stackoverflow.com/comment/87087987
type: Question
has title: Trying to translate Morse code into English
accepted answer: http://stackoverflow.com/a/50036655
has body: I am trying to translate Morse code into English with a dictionary I used. I am trying to have it where a user inputs a message and it will print his/her message into Morse code. I found it easy to translate into Morse code, however Morse code to English gives me some issues. First, if I type '.-' for 'A' I actually get 'E' instead as it's reading the first '.' key and translating it into 'E' instead of taking the whole string. This is what I have tried so far :) #If user types 'N' or 'n' it proceeds this loop if morse_message == 'N' or morse_message == 'n': #Loops looks to see if morse_message was 'N' or 'n' nomorse = input("Enter your Morse code here:") nomorse_list = (nomorse.join('') for letter in nomorse_list: not_morse = (morse_eng_dict[letter.upper()]) print(not_morse) And this is my dictionary I have morse_eng_dict = {".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z"} I would like to have Python take my Morse code and print the message back into English. Such as something like .. . .-.. .-.. --- (Which is HELLO) This is for a project, so I can't use any fancy modules or anything. Any ideas or input? Thank you!
has answer: http://stackoverflow.com/a/50036655
possible better answer: http://stackoverflow.com/a/50036156
has comment: http://stackoverflow.com/comment/87088234
tagged with: dictionary
has answer: http://stackoverflow.com/a/50036156
tagged with: morse-code
linked to: http://stackoverflow.com/q/32094525
type: AnsweredQuestion

scrapy
tags question: http://stackoverflow.com/q/49957978
tags question: http://stackoverflow.com/q/49973026
tags question: http://stackoverflow.com/q/49992726
tags question: http://stackoverflow.com/q/49964710
tags question: http://stackoverflow.com/q/50066034
tags question: http://stackoverflow.com/q/49989663
tags question: http://stackoverflow.com/q/49932855
tags question: http://stackoverflow.com/q/50051035
tags question: http://stackoverflow.com/q/49952417
tags question: http://stackoverflow.com/q/49969284
tags question: http://stackoverflow.com/q/49968758
tags question: http://stackoverflow.com/q/50048640
tags question: http://stackoverflow.com/q/49948470
tags question: http://stackoverflow.com/q/50029461
tags question: http://stackoverflow.com/q/49958388
tags question: http://stackoverflow.com/q/50062658
tags question: http://stackoverflow.com/q/50011155
tags question: http://stackoverflow.com/q/49946614
tag name: scrapy
tags question: http://stackoverflow.com/q/49970407
tags question: http://stackoverflow.com/q/50067938
tags question: http://stackoverflow.com/q/49968493
tags question: http://stackoverflow.com/q/49936127
tags question: http://stackoverflow.com/q/50037745
tags question: http://stackoverflow.com/q/50053373
tags question: http://stackoverflow.com/q/49946851
tags question: http://stackoverflow.com/q/49995641
tags question: http://stackoverflow.com/q/50028213
tags question: http://stackoverflow.com/q/49924876
tags question: http://stackoverflow.com/q/50002990
tags question: http://stackoverflow.com/q/49961214
tags question: http://stackoverflow.com/q/50046129
tags question: http://stackoverflow.com/q/49955430
tags question: http://stackoverflow.com/q/50049920
tags question: http://stackoverflow.com/q/50065422
tags question: http://stackoverflow.com/q/49971085
type: Tag
tags question: http://stackoverflow.com/q/49997331
tags question: http://stackoverflow.com/q/49961910
tags question: http://stackoverflow.com/q/49924050
tags question: http://stackoverflow.com/q/49971106
tags question: http://stackoverflow.com/q/49944582

http://stackoverflow.com/comment/87062432
has text: from this guide: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment
score: 0
comment on: http://stackoverflow.com/q/50022839
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50050757
tagged with: floating-point
has title: Why does Jupyter display of floating-point values differ from Python console?
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/87135508
has comment: http://stackoverflow.com/comment/87126803
has comment: http://stackoverflow.com/comment/87135403
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87135480
has comment: http://stackoverflow.com/comment/87135551
has comment: http://stackoverflow.com/comment/87117877
tagged with: python
has comment: http://stackoverflow.com/comment/87152921
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/87118005
has comment: http://stackoverflow.com/comment/87117858
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87118086
has body: When I run the following code in Jupyter 4.3.1 (Python 2.7.13) import numpy as np for i in np.arange(5, 6, 0.1): print(i) I got the following output 5.0 5.1 5.199999999999999 5.299999999999999 5.399999999999999 5.499999999999998 5.599999999999998 5.6999999999999975 5.799999999999997 5.899999999999997 However, when I run the code in the console, I got the following output 5.0 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 Why does the Jupyter output differ from the console output?
has comment: http://stackoverflow.com/comment/87135451

http://stackoverflow.com/a/50043355
type: Answer
answers question: http://stackoverflow.com/q/50042663
has comment: http://stackoverflow.com/comment/87107457
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87129132
has body: Check this: import pandas as pd df = pd.DataFrame({"Customer_PO_Number": ['nan','4500856427','4003363','nan','16 - 4989','nan','nan','WVE - 78686557032', 'nan','4501581113','D4 - SC - 0232737 - 1 / G1023716','nan','nan','4502549104', 'nan','nan','nan','IT008297','15\03662','8','299011667']}) df.replace('nan', 0, inplace=True) # for replacing nan to 0 df[df != 0] = 1 # for replacing others to 1 print(df) It will give you output like this: Customer_PO_Number 0 0 1 1 2 1 3 0 4 1 5 0 6 0 7 1 8 0 9 1 10 1 11 0 12 0 13 1 14 0 15 0 16 0 17 1 18 1 19 1 20 1 Hope it will help you! :)

http://stackoverflow.com/a/56436132
answers question: http://stackoverflow.com/q/49929617
has body: The method google.auth.default return a tuple (project_id, credentials) if that information is available on the environment. Also, the client object knows to which project it is linked from (either client.project or client.project_id, I'm not sure which one for the Monitoring API). If you set the service account manually with the GOOGLE_APPLICATION_CREDENTIALS env var, you can open the file and load its json. One of the parameters in a service account key file is the project id.
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/a/50010410
downvote count: 0
upvote count: 1
type: Answer
has body: This site may be the best scrapable listing of actors' ethnicities: import requests, re from bs4 import BeautifulSoup as soup import pandas as pd names = ['Chris Hemsworth', 'Paul Walker', 'Al Pacino'] final_results = {} for name in names: r = requests.get('http://ethnicelebs.com/{}'.format('-'.join(name.lower().split()))).text try: data = re.findall('(?&lt;=Ethnicity: )[a-zA-Z]+', soup(r, 'lxml').find('strong').text) final_results[name] = data[0] except: final_results[name] = 'Ethicity not found' table = pd.DataFrame([[a, b] for a, b in final_results.items()], columns = ['Name', 'Ethnicity']) Output: Name Ethnicity 0 Al Pacino Italian 1 Chris Hemsworth Dutch 2 Paul Walker English
answers question: http://stackoverflow.com/q/50010169
score: 1

node.js
tags question: http://stackoverflow.com/q/49947402
tags question: http://stackoverflow.com/q/50040481
tags question: http://stackoverflow.com/q/50032122
tags question: http://stackoverflow.com/q/50056169
type: Tag
tag name: node.js
tags question: http://stackoverflow.com/q/49966917
tags question: http://stackoverflow.com/q/49925322
tags question: http://stackoverflow.com/q/49953785
tags question: http://stackoverflow.com/q/50074188
tags question: http://stackoverflow.com/q/49992649

http://stackoverflow.com/q/49924470
favorite count: 0
has body: I am having trouble detecting contours in this image Class Diagram Image I want to detect all border contours in the diagram but so far my program is only detecting the image border as shown in this image Ignore the 0 in the center that is just to show that it is contour 0. I am not sure where the problem lies in my code as it can detect contours in images with a black background. filename = sys.argv[1] t = int(sys.argv[2]) img = cv2.imread(filename) resized = imutils.resize(img, width=300) ratio = img.shape[0] / float(resized.shape[0]) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5,5), 0) (t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY) _ ,cnts, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for (i,c) in enumerate(cnts): M = cv2.moments(c) if M["m00"] != 0: cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) else: cX, cY = 0, 0 (x,y,w,h) = cv2.boundingRect(c) area = cv2.contourArea(c) cv2.rectangle(img, (x, y), (x + w, y + h),(0, 255, 255), 2) print("Object %d has dimensions x=%d, y=%d, w=%d, h=%d area=%d" % (i,x,y,w,h,int(w*h))) cv2.putText(img, str(i), (cX, cY),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49924523
tagged with: image
has title: detecting contours in image with white background
tagged with: opencv
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49938217
possible better answer: http://stackoverflow.com/a/49938217
upvote count: 3
linked to: http://stackoverflow.com/q/19580102
has answer: http://stackoverflow.com/a/49924523
downvote count: 1

http://stackoverflow.com/q/49999408
has answer: http://stackoverflow.com/a/50002937
accepted answer: http://stackoverflow.com/a/50002937
has title: astropy FITS with multiple headers
favorite count: 0
type: AnsweredQuestion
has body: I'm trying to create a FITS file in Python but I appear to be having problems when compiling the headers and PrimaryHDU together. I've made a simple example which will give the error that I'm getting: import numpy as np from astropy.io import fits a = np.ones([5,5]) hdu = fits.PrimaryHDU(a) hdr = fits.Header() hdr['NPIX1'] = 60 hdr['NPIX2'] = 60 hdr['CRPIX1'] = 0 hdr['CRPIX2'] = 0 primary_hdu = fits.PrimaryHDU(header=hdr) hdul = fits.HDUList([primary_hdu, hdu]) hdul.writeto('table4.fits') When running this code, I get the following error: VerifyError: Verification reported errors: HDUList's element 1 is not an extension HDU. Note: astropy.io.fits uses zero-based indexing. I've seen some posts which claim this could be to do with the PrimaryHDU needing to be the first in the HDUList when exporting but looking at my code, I believe I'm doing that already. Any help would be greatly appreciated here, thanks.
tagged with: fits
type: Question
upvote count: 2
score: 2
answer count: 1
downvote count: 0
tagged with: python
tagged with: astropy

http://stackoverflow.com/q/49984012
tagged with: python
has comment: http://stackoverflow.com/comment/86985007
has comment: http://stackoverflow.com/comment/86984619
type: AnsweredQuestion
score: 0
answer count: 2
has title: How to make a groupby with sum and count?
has comment: http://stackoverflow.com/comment/86984948
accepted answer: http://stackoverflow.com/a/49984346
has comment: http://stackoverflow.com/comment/86984783
has answer: http://stackoverflow.com/a/49984346
has body: In Python3 and pandas I have this dataframe: import pandas as pd emendas_exec_geral = pd.read_csv("emendas_geral_autores.csv",sep=',',encoding = 'utf-8') emendas_exec_geral.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 43732 entries, 0 to 43731 Data columns (total 10 columns): Autor 43732 non-null object Emenda 43732 non-null object UO_Ajustada 43732 non-null object Funcional 43732 non-null object Acao_e_Subtitulo 43732 non-null object Valor_aprovado 43732 non-null float64 Empenhado 43732 non-null float64 Depesa_Executada 43732 non-null float64 Pago 43732 non-null float64 ano_execucao 43732 non-null int64 dtypes: float64(4), int64(1), object(5) memory usage: 3.3+ MB # I only select 2015 ano2015 = emendas_exec_geral[(emendas_exec_geral['ano_execucao'] == 2015)] # I make a groupby in "UO_Ajustada" and make a sum in column "Empenhado" ano2015.groupby("UO_Ajustada").Empenhado.sum().reset_index() UO_Ajustada Empenhado 0 COLÉGIO PEDRO II 899170.00 1 COMANDO DA AERONÁUTICA - ADMINISTRAÇÃO DIRETA 2342837.63 2 COMANDO DA MARINHA - ADMINISTRAÇÃO DIRETA 3429526.71 3 COMANDO DO EXÉRCITO - ADMINISTRAÇÃO DIRETA 6243558.10 4 COMPANHIA DE DESENVOLVIMENTO DOS VALES DO SÃO ... 70147265.05 5 COMPLEXO HOSPITALAR E DE SAÚDE DA UNIVERSIDADE... 190000.00 6 COMPLEXO HOSPITALAR E DE SAÚDE DA UNIVERSIDADE... 1297216.90 7 COMPLEXO HOSPITALAR E DE SAÚDE DA UNIVERSIDADE... 0.00 8 CONSELHO NACIONAL DE DESENVOLVIMENTO CIENTÍFIC... 1502789.00 9 CONSELHO NACIONAL DE JUSTIÇA 0.00 10 DEFENSORIA PÚBLICA DA UNIÃO - DPU 500000.00 ... df = ano2015.groupby("UO_Ajustada").Empenhado.sum().reset_index() df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 175 entries, 0 to 174 Data columns (total 2 columns): UO_Ajustada 175 non-null object Empenhado 175 non-null float64 dtypes: float64(1), object(1) memory usage: 2.8+ KB But I want to include in this new dataframe one more column: the count of appearances of "Empenhado" within "UO_Ajustada" - Empenhado.count() - A column called …
possible better answer: http://stackoverflow.com/a/49984297
type: Question
has comment: http://stackoverflow.com/comment/86984862
tagged with: pandas
tagged with: group-by
has answer: http://stackoverflow.com/a/49984297
has comment: http://stackoverflow.com/comment/86984826

parsing
tags question: http://stackoverflow.com/q/50010843
tags question: http://stackoverflow.com/q/49957002
tags question: http://stackoverflow.com/q/49997331
tags question: http://stackoverflow.com/q/49993754
tags question: http://stackoverflow.com/q/49917193
tags question: http://stackoverflow.com/q/49921105
tags question: http://stackoverflow.com/q/49956645
tags question: http://stackoverflow.com/q/50038691
tags question: http://stackoverflow.com/q/49954294
tags question: http://stackoverflow.com/q/49948661
tags question: http://stackoverflow.com/q/49931389
tag name: parsing
tags question: http://stackoverflow.com/q/50032258
tags question: http://stackoverflow.com/q/50036110
tags question: http://stackoverflow.com/q/50061599
tags question: http://stackoverflow.com/q/49970366
tags question: http://stackoverflow.com/q/49948029
tags question: http://stackoverflow.com/q/49974799
tags question: http://stackoverflow.com/q/50008298
tags question: http://stackoverflow.com/q/49998494
type: Tag
tags question: http://stackoverflow.com/q/49927610
tags question: http://stackoverflow.com/q/49950961

http://stackoverflow.com/comment/86948441
has text: i have gone through the database migration upgrade. but got stocked index.html.{% for post in posts %} {{ post.title }} {% include '_post.html' %} {% endfor %} also my detail.html: {% block app_content %} {{posts.title}} {{posts.body}} {% endblock %} and
comment on: http://stackoverflow.com/q/49948198
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/132183444
type: QuestionComment
has text: Can I get this code in C#
type: Comment
comment on: http://stackoverflow.com/q/49993864
score: 0

http://stackoverflow.com/a/53354250
type: Answer
answers question: http://stackoverflow.com/q/50029461
score: 0
has body: I stumbled upon the same issue. I tried various method but it looks like since Scrapy uses logging module, you have to set it at global level which result in Scrapy to print all the debug information. I've found more reliable solution to use bool flag with print statement fro DEBUG and use logger for INFO, ERROR and WARNING.

euclidean-distance
type: Tag
tags question: http://stackoverflow.com/q/50032472
tag name: euclidean-distance

http://stackoverflow.com/q/49968316
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/50075636
upvote count: 7
has comment: http://stackoverflow.com/comment/86952348
downvote count: 1
favorite count: 0
type: Question
has body: I want to sort an array within the group boundaries defined in another array. The groups are not presorted in any way and need to remain unchanged after the sorting. In numpy terms it would look like this: import numpy as np def groupwise_sort(group_idx, a, reverse=False): sortidx = np.lexsort((-a if reverse else a, group_idx)) # Reverse sorting back to into grouped order, but preserving groupwise sorting revidx = np.argsort(np.argsort(group_idx, kind='mergesort'), kind='mergesort') return a[sortidx][revidx] group_idx = np.array([3, 2, 3, 2, 2, 1, 2, 1, 1]) a = np.array([3, 2, 1, 7, 4, 5, 5, 9, 1]) groupwise_sort(group_idx, a) # &gt;&gt;&gt; array([1, 2, 3, 4, 5, 1, 7, 5, 9]) groupwise_sort(group_idx, a, reverse=True) # &gt;&gt;&gt; array([3, 7, 1, 5, 4, 9, 2, 5, 1]) How can I do the same with pandas? I saw df.groupby() and df.sort_values(), though I couldn't find a straight forward way to achieve the same sorting. And a fast one, if possible.
has comment: http://stackoverflow.com/comment/86957661
type: UnansweredQuestion
score: 6
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/86957567
has title: Groupwise sorting in pandas
has answer: http://stackoverflow.com/a/49968504

django-fsm
tags question: http://stackoverflow.com/q/49923449
tag name: django-fsm
type: Tag

http://stackoverflow.com/q/50053320
score: 1
type: AnsweredQuestion
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50053603
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50053603
has body: I'm trying to read HTTP post request stored in a file then send it via python socket, the problem is that post body is not read by the webapp, is there any trick to cosider when sending HTTP requests from a low-level ? Code snippet : f = open('req.txt', 'rb') req = f.read() f.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, 80)) s.send(req) s.close() req.txt : POST /api HTTP/1.1 Host: mywebsite.com Connection: close Cookie: nothing Content-Lenght: 11 param=value
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87123530
has comment: http://stackoverflow.com/comment/87123552
has title: Read HTTP POST request from file

http://stackoverflow.com/comment/86960080
type: Comment
has text: `from ldap3.core.exceptions import LDAPBindError`
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/49971875

http://stackoverflow.com/a/50062395
type: Answer
has body: If you just want to send http/https request using a proxy through Python you can use request library. Here is some example: import requests base_url = 'https://whatever.com' proxy = {"https":"https://user:pass@proxy_url:port"} resp = requests.get(base_url, proxies=proxy)
score: 0
has comment: http://stackoverflow.com/comment/87141475
answers question: http://stackoverflow.com/q/50062020
has comment: http://stackoverflow.com/comment/87141666

http://stackoverflow.com/comment/87110949
comment on: http://stackoverflow.com/q/50046667
type: Comment
type: QuestionComment
score: 0
has text: I put two more plots of the outputs, I don't know if you need other type of data.

python
tags question: http://stackoverflow.com/q/49982676
tags question: http://stackoverflow.com/q/49935754
tags question: http://stackoverflow.com/q/49938250
tags question: http://stackoverflow.com/q/49926504
tags question: http://stackoverflow.com/q/50049283
tags question: http://stackoverflow.com/q/50022098
tags question: http://stackoverflow.com/q/50022723
tags question: http://stackoverflow.com/q/49981224
tags question: http://stackoverflow.com/q/49943270
tags question: http://stackoverflow.com/q/50055640
tags question: http://stackoverflow.com/q/49937206
tags question: http://stackoverflow.com/q/49989653
tags question: http://stackoverflow.com/q/49951026
tags question: http://stackoverflow.com/q/49990790
tags question: http://stackoverflow.com/q/49932998
tags question: http://stackoverflow.com/q/49993578
tags question: http://stackoverflow.com/q/49963999
tags question: http://stackoverflow.com/q/50014425
tags question: http://stackoverflow.com/q/50069340
tags question: http://stackoverflow.com/q/49962067
tags question: http://stackoverflow.com/q/49951472
tags question: http://stackoverflow.com/q/49962987
tags question: http://stackoverflow.com/q/50051773
tags question: http://stackoverflow.com/q/50023430
tags question: http://stackoverflow.com/q/50042046
tags question: http://stackoverflow.com/q/50005256
tags question: http://stackoverflow.com/q/49936222
tags question: http://stackoverflow.com/q/49933982
tags question: http://stackoverflow.com/q/50001220
tags question: http://stackoverflow.com/q/49948580
tags question: http://stackoverflow.com/q/50036568
tags question: http://stackoverflow.com/q/49945288
tags question: http://stackoverflow.com/q/49967607
tags question: http://stackoverflow.com/q/49948065
tags question: http://stackoverflow.com/q/50044378
tags question: http://stackoverflow.com/q/50019825
tags question: http://stackoverflow.com/q/49993872
tags question: http://stackoverflow.com/q/49934668
tags question: http://stackoverflow.com/q/49999875
tags question: http://stackoverflow.com/q/49943309
tags question: http://stackoverflow.com/q/49930533
tags question: http://stackoverflow.com/q/49984173
tags question: http://stackoverflow.com/q/50049523
tags question: http://stackoverflow.com/q/49949874
tags question: http://stackoverflow.com/q/50020949
tags question: http://stackoverflow.com/q/49951867
tags question: http://stackoverflow.com/q/50059451
tags question: http://stackoverflow.com/q/49974936
tags question: http://stackoverflow.com/q/49969301
tags question: http://stackoverflow.com/q/49985863
tags question: http://stackoverflow.com/q/49981768
tags question: http://stackoverflow.com/q/49977810
tags question: http://stackoverflow.com/q/49971708
tags question: http://stackoverflow.com/q/49986965
tags question: http://stackoverflow.com/q/49955429
tags question: http://stackoverflow.com/q/49964453
tags question: http://stackoverflow.com/q/49952108
tags question: http://stackoverflow.com/q/49991192
tags question: http://stackoverflow.com/q/50039269
tags question: http://stackoverflow.com/q/50013561
tags question: http://stackoverflow.com/q/50041661
tags question: http://stackoverflow.com/q/50032470
tags question: http://stackoverflow.com/q/50061714
tags question: http://stackoverflow.com/q/49964558
tags question: http://stackoverflow.com/q/49993864
tags question: http://stackoverflow.com/q/49969960
tags question: http://stackoverflow.com/q/49976160
tags question: http://stackoverflow.com/q/49974918
tags question: http://stackoverflow.com/q/49985579
tags question: http://stackoverflow.com/q/50044447
tags question: http://stackoverflow.com/q/49934212
tags question: http://stackoverflow.com/q/50029527
tags question: http://stackoverflow.com/q/50058936
tags question: http://stackoverflow.com/q/49932322
tags question: http://stackoverflow.com/q/49962741
tags question: http://stackoverflow.com/q/50009478
tags question: http://stackoverflow.com/q/49991840
tags question: http://stackoverflow.com/q/50030086
tags question: http://stackoverflow.com/q/50047929
tags question: http://stackoverflow.com/q/50024764

http://stackoverflow.com/comment/87078893
has text: @AdamSmith if i was using this in a business or research setting i'd probably go with something else, but this seems to be more of a learning programming assignment, and a simple misunderstanding of how the break/printing works in the program. My solution was more towards helping OP learn then providing the best solution. Your solution and bphi's solution are both better from a technical stand point
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50031206

http://stackoverflow.com/comment/86962289
score: 0
comment on: http://stackoverflow.com/a/49973066
type: Comment
type: AnswerComment
has text: if you are using tensor, you may need to reshape it to 1D list first, then apply the technique above

dictionary
tags question: http://stackoverflow.com/q/49917996
tags question: http://stackoverflow.com/q/50063292
tags question: http://stackoverflow.com/q/49973682
tags question: http://stackoverflow.com/q/49952480
tags question: http://stackoverflow.com/q/49991429
tags question: http://stackoverflow.com/q/49922569
tags question: http://stackoverflow.com/q/50027850
tags question: http://stackoverflow.com/q/50046101
tags question: http://stackoverflow.com/q/50032339
tags question: http://stackoverflow.com/q/49971390
tags question: http://stackoverflow.com/q/50039434
tags question: http://stackoverflow.com/q/50007028
tags question: http://stackoverflow.com/q/50031627
tags question: http://stackoverflow.com/q/49935866
tags question: http://stackoverflow.com/q/49996618
tags question: http://stackoverflow.com/q/50041346
tags question: http://stackoverflow.com/q/49985574
tags question: http://stackoverflow.com/q/49929378
tags question: http://stackoverflow.com/q/49987100
tags question: http://stackoverflow.com/q/50008919
tags question: http://stackoverflow.com/q/49931836
tags question: http://stackoverflow.com/q/49966118
tags question: http://stackoverflow.com/q/50051890
tags question: http://stackoverflow.com/q/49984625
tags question: http://stackoverflow.com/q/49944111
tags question: http://stackoverflow.com/q/49963358
tags question: http://stackoverflow.com/q/49997331
tags question: http://stackoverflow.com/q/50018955
tags question: http://stackoverflow.com/q/49982970
tags question: http://stackoverflow.com/q/49991545
tags question: http://stackoverflow.com/q/50065474
tags question: http://stackoverflow.com/q/50011143
tags question: http://stackoverflow.com/q/49945187
tags question: http://stackoverflow.com/q/49919917
tags question: http://stackoverflow.com/q/49926794
tags question: http://stackoverflow.com/q/49961812
tags question: http://stackoverflow.com/q/49928154
tags question: http://stackoverflow.com/q/50068051
tags question: http://stackoverflow.com/q/50005148
tags question: http://stackoverflow.com/q/50011078
tags question: http://stackoverflow.com/q/49991280
tags question: http://stackoverflow.com/q/49929634
tags question: http://stackoverflow.com/q/49968576
tags question: http://stackoverflow.com/q/50018001
tags question: http://stackoverflow.com/q/50040923
tags question: http://stackoverflow.com/q/49984224
tags question: http://stackoverflow.com/q/50069108
tags question: http://stackoverflow.com/q/50013060
tags question: http://stackoverflow.com/q/49978646
tags question: http://stackoverflow.com/q/50004310
tags question: http://stackoverflow.com/q/50034420
tags question: http://stackoverflow.com/q/49987789
tags question: http://stackoverflow.com/q/49984546
tags question: http://stackoverflow.com/q/49930401
tags question: http://stackoverflow.com/q/50064449
tags question: http://stackoverflow.com/q/49954659
tags question: http://stackoverflow.com/q/50036453
tags question: http://stackoverflow.com/q/50070397
tags question: http://stackoverflow.com/q/50016967
tags question: http://stackoverflow.com/q/49946398
tags question: http://stackoverflow.com/q/50044447
tags question: http://stackoverflow.com/q/49991840
tags question: http://stackoverflow.com/q/50011450
tags question: http://stackoverflow.com/q/50018222
tags question: http://stackoverflow.com/q/50029127
tags question: http://stackoverflow.com/q/50049786
tags question: http://stackoverflow.com/q/49961872
tags question: http://stackoverflow.com/q/50029585
tags question: http://stackoverflow.com/q/49941717
tags question: http://stackoverflow.com/q/49969602
tags question: http://stackoverflow.com/q/49956924
tags question: http://stackoverflow.com/q/50029624
tags question: http://stackoverflow.com/q/49950188
tags question: http://stackoverflow.com/q/50044021
tags question: http://stackoverflow.com/q/50050545
tags question: http://stackoverflow.com/q/49938985
tags question: http://stackoverflow.com/q/50022529
tags question: http://stackoverflow.com/q/50017155
tags question: http://stackoverflow.com/q/49922911
tags question: http://stackoverflow.com/q/49997558

http://stackoverflow.com/q/49934648
has title: Unescape comma when reading CSV with spark
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86886567
has comment: http://stackoverflow.com/comment/86891913
favorite count: 0
has body: I have a CSV file that contains name field with comma (,) escaped with \ id,name "10","Ashraful\, Islam" I am reading the csv file from pyspark test = spark.read.format("csv").option("sep", ",").option("escape", "\\").option("inferSchema", "true").option("header", "true").load("test.csv") test.show() The name should be Ashraful, Islam, but getting output +---+----------------+ | id| name| +---+----------------+ | 10|Ashraful\, Islam| +---+----------------+
type: AnsweredQuestion
tagged with: pyspark
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49935888
has answer: http://stackoverflow.com/a/49935888
tagged with: apache-spark
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49972435
tagged with: performance
has answer: http://stackoverflow.com/a/49972563
has answer: http://stackoverflow.com/a/49972560
tagged with: python
has title: Vectorize an iterative algorithm with numpy.where or any equivalent function
tagged with: vectorization
score: -1
tagged with: numpy
answer count: 2
upvote count: 0
has body: I wish I could construct the following algorithm with np.where or some equivalent (and efficient) numpy functions: def generate_signal(r): signal = np.zeros(len(r), dtype=int) lastSignal = 0 for i in range(len(r)): if r[i] &lt;= 30: lastSignal = 1 elif r[i] &gt;= 60: lastSignal = 0 signal[i] = lastSignal return signal Here is one example with input/output: r = np.array([50, 52, 59, 69, 47, 33, 27, 26, 20, 30, 33, 35, 58, 55, 48, 60, 68, 55, 43, 49, 33, 30, 22, 28]) s = generate_signal(r) print(s) # This is the result: [0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1] print(list(zip(r, s))) # A zipped result (in case it helps): [(50, 0), (52, 0), (59, 0), (69, 0), (47, 0), (33, 0), (27, 1), (26, 1), (20, 1), (30, 1), (33, 1), (35, 1), (58, 1), (55, 1), (48, 1), (60, 0), (68, 0), (55, 0), (43, 0), (49, 0), (33, 0), (30, 1), (22, 1), (28, 1)]
tagged with: where-clause
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49972563
accepted answer: http://stackoverflow.com/a/49972560
type: AnsweredQuestion

http://stackoverflow.com/q/49957788
accepted answer: http://stackoverflow.com/a/49958165
downvote count: 0
has comment: http://stackoverflow.com/comment/86931849
has answer: http://stackoverflow.com/a/49958165
favorite count: 0
has title: python opencv bitwise_xor
type: Question
tagged with: opencv
score: 3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86932956
has body: I am trying to combine two pictures which are segments from an original one. here is an example of two segments: pic a pic b but when trying to combine them : img_to_assemble = cv2.bitwise_xor(pic_a,pic_b) I get the following error: The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function binary_op
upvote count: 3
answer count: 1

django
tags question: http://stackoverflow.com/q/50040379
tags question: http://stackoverflow.com/q/49994260
tags question: http://stackoverflow.com/q/49935601
tags question: http://stackoverflow.com/q/49924381
tags question: http://stackoverflow.com/q/49984898
tags question: http://stackoverflow.com/q/49929305
tags question: http://stackoverflow.com/q/50011943
tags question: http://stackoverflow.com/q/50031690
tags question: http://stackoverflow.com/q/50054927
tags question: http://stackoverflow.com/q/49960467
tags question: http://stackoverflow.com/q/49981485
tags question: http://stackoverflow.com/q/49928120
tags question: http://stackoverflow.com/q/50052344
tags question: http://stackoverflow.com/q/50072475
tags question: http://stackoverflow.com/q/49992636
tags question: http://stackoverflow.com/q/50064118
tags question: http://stackoverflow.com/q/49937201
tags question: http://stackoverflow.com/q/50069085
tags question: http://stackoverflow.com/q/50035681
tags question: http://stackoverflow.com/q/49934343
tags question: http://stackoverflow.com/q/49999582
tags question: http://stackoverflow.com/q/49962436
tags question: http://stackoverflow.com/q/50032423
tags question: http://stackoverflow.com/q/49954831
tags question: http://stackoverflow.com/q/49936599
tags question: http://stackoverflow.com/q/50041919
tags question: http://stackoverflow.com/q/49942090
tags question: http://stackoverflow.com/q/49992869
tags question: http://stackoverflow.com/q/49967434
tags question: http://stackoverflow.com/q/49963291
tags question: http://stackoverflow.com/q/49999665
tags question: http://stackoverflow.com/q/50066163
tags question: http://stackoverflow.com/q/49938250
tags question: http://stackoverflow.com/q/49981224
tags question: http://stackoverflow.com/q/50005256
tags question: http://stackoverflow.com/q/50009094
tags question: http://stackoverflow.com/q/49999875
tags question: http://stackoverflow.com/q/49940684
tags question: http://stackoverflow.com/q/50035862
tags question: http://stackoverflow.com/q/50029527
tags question: http://stackoverflow.com/q/50072998
tags question: http://stackoverflow.com/q/50018315
tags question: http://stackoverflow.com/q/49951987
tags question: http://stackoverflow.com/q/49970871
tags question: http://stackoverflow.com/q/49939907
tags question: http://stackoverflow.com/q/49936194
tags question: http://stackoverflow.com/q/50022443
tags question: http://stackoverflow.com/q/50062659
tags question: http://stackoverflow.com/q/49952618
tags question: http://stackoverflow.com/q/50059648
tags question: http://stackoverflow.com/q/49935603
tags question: http://stackoverflow.com/q/50073293
tags question: http://stackoverflow.com/q/50038856
tags question: http://stackoverflow.com/q/50050739
tags question: http://stackoverflow.com/q/49972502
tags question: http://stackoverflow.com/q/50070507
tags question: http://stackoverflow.com/q/49971496
tags question: http://stackoverflow.com/q/49926710
tags question: http://stackoverflow.com/q/50073668
tags question: http://stackoverflow.com/q/50044895
tags question: http://stackoverflow.com/q/49977576
tags question: http://stackoverflow.com/q/50048911
tags question: http://stackoverflow.com/q/50060764
tags question: http://stackoverflow.com/q/49955132
tags question: http://stackoverflow.com/q/49961120
tags question: http://stackoverflow.com/q/49961536
tags question: http://stackoverflow.com/q/49960589
tags question: http://stackoverflow.com/q/49978662
tags question: http://stackoverflow.com/q/50064066
tags question: http://stackoverflow.com/q/49981145
tags question: http://stackoverflow.com/q/49993067
tags question: http://stackoverflow.com/q/50064572
tags question: http://stackoverflow.com/q/50018463
tags question: http://stackoverflow.com/q/50043461
tags question: http://stackoverflow.com/q/49995017
tags question: http://stackoverflow.com/q/49982788
tags question: http://stackoverflow.com/q/49978455
tags question: http://stackoverflow.com/q/50019420
tags question: http://stackoverflow.com/q/49918978
tags question: http://stackoverflow.com/q/49994435

http://stackoverflow.com/comment/87078361
type: Comment
comment on: http://stackoverflow.com/q/50020768
score: 0
type: QuestionComment
has text: Try adding ``WSGIApplicationGroup %{GLOBAL}``. You are likely using a Python package which doesn't work in sub interpreters. http://modwsgi.readthedocs.io/en/develop/user-guides/application-issues.html#python-simplified-gil-state-api

http://stackoverflow.com/comment/86862561
has text: close any process that opened the file ....\description.rst ?
type: Comment
comment on: http://stackoverflow.com/q/49923259
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86932936
comment on: http://stackoverflow.com/q/49958308
has text: `eval` is very "bad" practice... try not to use it if you can
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/comment/87166566
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50070444
has text: Have you checked all those things: https://stackoverflow.com/questions/49021055/airflow-1-9-0-is-queuing-but-not-launching-tasks/49047832#49047832

http://stackoverflow.com/a/49959952
answers question: http://stackoverflow.com/q/49958256
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49958256
has body: Java has a static method Arrays.sort that could in principle be implemented as a radix sort for the overloads that accept integer types (https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html#sort(int[])). They chose to implement with quicksort. There's no justification given, but I imagine 1. Radix sort requires additional memory, where quicksort doesn't 2. The difference between n log n and n is blunted by the fact that quicksort has good cache locality, where radix sort, less so.

http://stackoverflow.com/a/49968643
score: 0
has body: To create a defaultdict that has the type string as the key type, you should create like my_dict = defaultdict(str). And for having a dictionary that has the websites as keys and teams as values you should do: for i in range(len(websites)): baseballdict[websites[i]] = teams[i]
has comment: http://stackoverflow.com/comment/86953210
type: Answer
answers question: http://stackoverflow.com/q/49968576

http://stackoverflow.com/a/49971725
has body: The Sublime Text "Build results" pannel (bottom of the interface): is not interactive, you cannot type input there. To solve this, I have added, in addition to the standard CTRL+B build shortcut, another shortcut (in Menu Preferences > Key Bindings - User): { "keys": ["ctrl+shift+alt+b"], "command": "python_run" } that allows to launch the current file with Python in a new terminal window (there, you can input some data). Here is the python_run.py file (to be copied in C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User): import sublime import sublime_plugin import subprocess class PythonRunCommand(sublime_plugin.WindowCommand): def run(self): command = 'cmd /k "C:\Python27\python.exe" %s' % sublime.active_window().active_view().file_name() subprocess.Popen(command)
type: Answer
accepted answer of: http://stackoverflow.com/q/49971679
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49971679
downvote count: 0

http://stackoverflow.com/q/49985181
has body: I need some help with starting and stopping the loop in this grocery list. I need to be able to pick a few items add the totals and tax, then give the user the option to end. I have included the deposit or tax separate as it would on a real check. Then you will get a grand total at the end. If you see any other errors please feel free to let me know. Thank you #Welcome user to user display product and prices print("Hello, welcome to the store") print("This is the list &amp; products") print("0,Milk,$2.39/Gallon") print("2,Eggs,$1.58/per dozen") print("4,Water,$1.00/Bottle+$.05 deposit") print("6,Soda,$.99/Can+$.05 deposit") print("8,Bread,$2.99/Loaf") print("10,Chips,$1.30/Bag") print("12,Tomato,$1.99/Pound") print("Ready-food box,$8.99/Box+$.0625 tax") #Prompt users for his product totalpurchase=0 wdeposit=.05 sdeposit=.05 rtax=.0625 gtotal=0 totwdeposit=0 totsdeposit=0 totrtax=0 while 0: choice=int(input("Enter your product code")) if choice==0: qofmilk=int(input("How many gallons do you wish to purchase?")) totmilk=qofmilk*2.39 print("Your total price for milk is", totmilk) totalpurchase=totalpurchase+totmilk if choice==2: qofeggs=int(input("How many dozen of eggs do you wish to purchase?")) toteggs=qofeggs*1.58 print("Your total price for eggs is", toteggs) totalpurchase=totalpurchase+toteggs if choice==4: qofwater=int(input("How many bottles of water do you wish to purchase?")) totwater=qofwater*1.00 print("Your total price for water is", totwater) totalpurchase=totalpurchase+totwater if choice==6: qofsoda=int(input("How many cans of soda do you wish to purchase?")) totsoda=qofsoda*.99 print("Your total price for soda is", totsoda) totalpurchase=totalpurchase+totsoda if choice==8: qofbread=int(input("How many loafs of bread do you wish to purchase?")) totbread=qofbread*2.99 print("Your total price for bread is", totbread) totalpurchase=totalpurchase+totbread if choice==10: qofchips=int(input("How many bags of chips do you wish to purchase?")) totchips=qofchips*…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86986948
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86988807
has answer: http://stackoverflow.com/a/49985494
has title: Starting and stopping while loop in python
has comment: http://stackoverflow.com/comment/86988387
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86988967
has comment: http://stackoverflow.com/comment/86986814
has comment: http://stackoverflow.com/comment/86987128
has comment: http://stackoverflow.com/comment/86987045
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86986725
has comment: http://stackoverflow.com/comment/86987250

http://stackoverflow.com/comment/87138120
type: Comment
comment on: http://stackoverflow.com/a/50060395
score: 0
type: AnswerComment
has text: Nice, thank you. Could you ellaborate on this part --> recipe.replace(ts, '{} ({}g)'.format(ts, ceil(quantity*weigt[ts]))) or a resource where I could read about it?

http://stackoverflow.com/comment/87640021
type: QuestionComment
has text: It might be JAVA PATH problem. Could you upgrade tabula-py and run `import tabula; tabula.environment_info()` ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50056785

http://stackoverflow.com/q/49979605
favorite count: 0
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49980379
has body: I have this Json, and I need a value from a rate. "_id" : ObjectId("5addb57d0043582d48ba898a"), "success" : true, "timestamp" : 1524477784, "base" : "EUR", "date" : "2018-04-23", "rates" : { "AED" : 4.492662, "AFN" : 85.576329, "ALL" : 128.39508, "AMD" : 586.837094, "ANG" : 2.177608, "AOA" : 267.092358, "ARS" : 24.678283, "AUD" : 1.602032, "AWG" : 2.177639, "AZN" : 2.079155, "BAM" : 1.958775, "BBD" : 2.446786, "BDT" : 101.517146, "BGN" : 1.943843, "BHD" : 0.460968, "NOK" : 9.626194, } And this is my Python code import pymongo uri = "mongodb://127.0.0.1:27017" client = pymongo.MongoClient(uri) database = client['db'] collection = database['currency'] collection2 = database['countries'] p = str(input('Insert the country: ')).capitalize() if p=='Norway': currency = collection.find_one({'NOK'}) print(currency) I want to print the value inside de NOK, how can I do it? Thanks in advance.
tagged with: http://stackoverflow.com/tag/json
tagged with: pymongo
type: Question
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49980379
accepted answer: http://stackoverflow.com/a/49979790
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49979790
has title: How to print a value in Python that is inside a Json in MongoDB object

http://stackoverflow.com/a/49948306
downvote count: 0
answers question: http://stackoverflow.com/q/49947942
has body: Actually there's nothing wrong with your approach. It uses ordinary language features and conveys its message pretty clear. The other approaches also work but they are somewhat more complicated to understand and probably only preferable in case you have lots (not only 3) functions that you want to check. In that case I would actually make a function to hide that complexity. import itertools from contextlib import suppress def call_functions(funcs, give_up_func): for func in itertools.chain(funcs, [give_up_func]): with suppress(WrongProcedureError): func() return # only reached when func does not raise WrongProcedureError. That assumes that give_up_func won't raise that Exception and suppress requires python 3 (i think 3.4). However there might be something fundamentally wrong in your code when you actually need this. This seems like some sort of "fallback" operation that probably should be solved using subclasses or an additional argument or a strategy/factory instead of nested try and excepts.
type: Answer
upvote count: 3
score: 3

python-3.x
tags question: http://stackoverflow.com/q/50062659
tags question: http://stackoverflow.com/q/49963449
tags question: http://stackoverflow.com/q/50070458
tags question: http://stackoverflow.com/q/49949796
tags question: http://stackoverflow.com/q/50030168
tags question: http://stackoverflow.com/q/49972053
tags question: http://stackoverflow.com/q/50003599
tags question: http://stackoverflow.com/q/50025707
tags question: http://stackoverflow.com/q/49939123
tags question: http://stackoverflow.com/q/50064945
tags question: http://stackoverflow.com/q/49959807
tags question: http://stackoverflow.com/q/49945750
tags question: http://stackoverflow.com/q/49967109
tags question: http://stackoverflow.com/q/50062125
tags question: http://stackoverflow.com/q/49968894
tags question: http://stackoverflow.com/q/49998463
tags question: http://stackoverflow.com/q/49963580
tags question: http://stackoverflow.com/q/49961872
tags question: http://stackoverflow.com/q/50025233
tags question: http://stackoverflow.com/q/50036796
tags question: http://stackoverflow.com/q/50046129
tags question: http://stackoverflow.com/q/50003003
tags question: http://stackoverflow.com/q/49993689
tags question: http://stackoverflow.com/q/50068431
tags question: http://stackoverflow.com/q/50013023
tags question: http://stackoverflow.com/q/50004573
tags question: http://stackoverflow.com/q/49991912
tags question: http://stackoverflow.com/q/49936238
tags question: http://stackoverflow.com/q/49931936
tags question: http://stackoverflow.com/q/49960589
tags question: http://stackoverflow.com/q/50032956
tags question: http://stackoverflow.com/q/49924607
tags question: http://stackoverflow.com/q/49963494
tags question: http://stackoverflow.com/q/49993067
tags question: http://stackoverflow.com/q/50074439
tags question: http://stackoverflow.com/q/49958078
tags question: http://stackoverflow.com/q/49922715
tags question: http://stackoverflow.com/q/49971629
tags question: http://stackoverflow.com/q/50019588
tags question: http://stackoverflow.com/q/50060521
tags question: http://stackoverflow.com/q/50017514
tags question: http://stackoverflow.com/q/49998198
tags question: http://stackoverflow.com/q/49997347
tags question: http://stackoverflow.com/q/50048494
tags question: http://stackoverflow.com/q/49991998
tags question: http://stackoverflow.com/q/49933970
tags question: http://stackoverflow.com/q/50036765
tags question: http://stackoverflow.com/q/49918384
tags question: http://stackoverflow.com/q/49988866
tags question: http://stackoverflow.com/q/49940292
tags question: http://stackoverflow.com/q/50063930
tags question: http://stackoverflow.com/q/50041263
tags question: http://stackoverflow.com/q/50036751
tags question: http://stackoverflow.com/q/49979122
tags question: http://stackoverflow.com/q/50002795
tags question: http://stackoverflow.com/q/49995784
tags question: http://stackoverflow.com/q/50058208
tags question: http://stackoverflow.com/q/49922911
tags question: http://stackoverflow.com/q/50030665
tags question: http://stackoverflow.com/q/49963305
tags question: http://stackoverflow.com/q/49974375
tags question: http://stackoverflow.com/q/49960582
tags question: http://stackoverflow.com/q/49991731
tags question: http://stackoverflow.com/q/50049216
tags question: http://stackoverflow.com/q/49983134
tags question: http://stackoverflow.com/q/50035262
tags question: http://stackoverflow.com/q/49923417
tags question: http://stackoverflow.com/q/50046670
tags question: http://stackoverflow.com/q/49961974
tags question: http://stackoverflow.com/q/50056356
tags question: http://stackoverflow.com/q/49932787
tags question: http://stackoverflow.com/q/49972413
tags question: http://stackoverflow.com/q/49989883
tags question: http://stackoverflow.com/q/50032339
tags question: http://stackoverflow.com/q/49981686
tags question: http://stackoverflow.com/q/50009647
tags question: http://stackoverflow.com/q/50000560
tags question: http://stackoverflow.com/q/50005048
tags question: http://stackoverflow.com/q/50027782
tags question: http://stackoverflow.com/q/50055316

http://stackoverflow.com/comment/86995861
type: Comment
type: QuestionComment
has text: Also, why is this a subclass of dict rather than either (a) a class that _has_ a dict rather than being one, or (b) just a function that returns a plain-old dict?
comment on: http://stackoverflow.com/q/49989616
score: 0

http://stackoverflow.com/q/49933172
score: 7
has body: My problem is as follows: I have a large dataframe called details containing 900K rows and the other one containing 80M rows named attributes. Both have a column A on which I would like to do a left-outer join, the left dataframe being deatils. There are only 75K unique entries in column A in the dataframe details. The dataframe attributes 80M unique entries in column A. What is the best possible way to achieve the join operation? What have I tried? The simple join i.e. details.join(attributes, "A", how="left_outer") just times out (or gives out of memory). Since there are only 75K unique entries in column A in details, we don't care about the rest in the dataframe in attributes. So, first I filter that using: uniqueA = details.select('A').distinct().collect() uniqueA = map(lambda x: x.A, uniqueA) attributes_filtered = attributes.filter(attributes.A.isin(*uniqueA)) I thought this would work out because the attributes table comes down from 80M rows to mere 75K rows. However, it still takes forever to complete the join (and it never completes). Next, I thought that there are too many partitions and the data to be joined is not on the same partition. Though, I don't know how to bring all the data to the same partition, I figured repartitioning may help. So here it goes. details_repartitioned = details.repartition("A") attributes_repartitioned = attributes.repartition("A") The above operation brings down the number of partitions in attributes from 70K to 200. The number of partitions in details are about 1100. details_attributes = details_repartitioned.join(broadcast( attributes_repartitioned), "A", how='left_outer') # tried without broadcast too After all this, the join still doesn't work. I am still learning PySpark so I might have misunderstood the fundamentals behind repartitioning. If someone could shed light on this, it would be great. P.S. I have already seen this question but that does not answer this question.
answer count: 1
tagged with: dataframe
upvote count: 7
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/53524062
tagged with: bigdata
downvote count: 0
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/49935027
has title: Joining a large and a massive spark dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49935027
linked to: http://stackoverflow.com/q/34461804
linked to: http://stackoverflow.com/q/35948714
type: AnsweredQuestion
tagged with: apache-spark

http://stackoverflow.com/comment/86949247
comment on: http://stackoverflow.com/q/49955304
has text: Yes, hopefully this will help. If I take acat1 as an example: df1 = pd.DataFrame({'bin_for_acat1':[2,0,1,0,0]}) df1.skew() 1.257788
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86980663
type: Comment
has text: What is the exact output that you want? One data frame per rank value, or a single data frame with sum per rank sorted somehow?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49982204

http://stackoverflow.com/a/50012705
has body: Python is actually freeing the memory as soon as the function is done. The problem here is that the value you're printing out, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, tells you the peak or max memory usage. To get the current memory usage, you might try the psutil package ($ pip install psutil). It's a cross platform utility for giving you info like the current memory usage. Try this modified snippet: import numpy as np import resource import os import psutil process = psutil.Process(os.getpid()) def my_function(): print('### Starting function ###') print('Max Memory usage: %s (KB)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) print('Curr Memory usage: %s (KB)' % (process.memory_info().rss / 1024)) print('doing stuff...') x = np.random.random([10000, 10000]) print('Max Memory usage: %s (KB)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) print('Curr Memory usage: %s (KB)' % (process.memory_info().rss / 1024)) print('#### Ending function ####') print('Max Memory usage: %s (KB)'% resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) print('Curr Memory usage: %s (KB)'% (process.memory_info().rss/ 1024)) my_function() print('Max Memory usage: %s (KB)'% resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) print('Curr Memory usage: %s (KB)'% (process.memory_info().rss / 1024)) On my machine, here's the output: Max Memory usage: 714588 (KB) Curr Memory usage: 26884.0 (KB) ### Starting function ### Max Memory usage: 714588 (KB) Curr Memory usage: 26884.0 (KB) doing stuff... Max Memory usage: 808380 (KB) Curr Memory usage: 808380.0 (KB) #### Ending function #### Max Memory usage: 808380 (KB) Curr Memory usage: 27132.0 (KB) By the time we get to the first memory check, it's down to 26 MB, but it's already been as high as 714 MB at some point while starting up or importing libraries. At the start of the function it's the same, but by the end of our function, we've hit a new high with help from numpy. At this point the current usage is the new max, so b…
type: Answer
answers question: http://stackoverflow.com/q/50012376
accepted answer of: http://stackoverflow.com/q/50012376
type: AcceptedAnswer
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/q/50018501
has answer: http://stackoverflow.com/a/50018545
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
favorite count: 0
has title: Django join query with related key
has body: I have this model: class Role(models.Model): role_name = models.CharField() class RolePriviledge(models.Model): role = models.ForeignKey(Role, related_name='role_priviledge' ) module_name = models.CharField() priviledge_level = models.CharField() class UserRole(models.Model): user = models.ForeignKey(User) role = models.ForeignKey(Role) What I am trying to do is to find all the priviledges for a specified user. In sql, this would be: SELECT t3.* FROM UserRole t1 JOIN Role t2 on t1.role_id = t2.id JOIN RolePriviledge t3 on t2.id = t3.role_id WHERE t1.user_id = USER_ID (I can also skip the join with Role and just do an inner join between UserRole and RolePriviledge) How would I do this join with Django ORM? UserRole.objects.filter(user_id=USER_ID).select_related('role') would join UserRole with Role. How do I join it with RolePriviledge?
tagged with: django-models
tagged with: python
type: Question
upvote count: 2
score: 2

http://stackoverflow.com/comment/87126023
type: Comment
comment on: http://stackoverflow.com/q/50054527
type: QuestionComment
has text: (Or, if you don't care about getting them in order, you can use `future`s from a `concurrent.futures.ProcessPoolExecutor` instead of `AsyncResult`s from a `multiprocessing.Pool`.)
score: 0

send
type: Tag
tag name: send
tags question: http://stackoverflow.com/q/49956239

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/49925178
tags question: http://stackoverflow.com/q/50054662
tags question: http://stackoverflow.com/q/50018501
tags question: http://stackoverflow.com/q/49991194
tags question: http://stackoverflow.com/q/49948016
tags question: http://stackoverflow.com/q/49935601
tags question: http://stackoverflow.com/q/50038856
tags question: http://stackoverflow.com/q/50073668
tags question: http://stackoverflow.com/q/49977576
tags question: http://stackoverflow.com/q/49936742
tags question: http://stackoverflow.com/q/50049973
tags question: http://stackoverflow.com/q/49932426
tags question: http://stackoverflow.com/q/50044825
tags question: http://stackoverflow.com/q/49958185
tags question: http://stackoverflow.com/q/49966732
tags question: http://stackoverflow.com/q/50009055
tags question: http://stackoverflow.com/q/49952760
tags question: http://stackoverflow.com/q/50002600
tags question: http://stackoverflow.com/q/49999029
tags question: http://stackoverflow.com/q/50049213
tags question: http://stackoverflow.com/q/49947856
tags question: http://stackoverflow.com/q/49946980
tags question: http://stackoverflow.com/q/49984898
tags question: http://stackoverflow.com/q/50054927
tags question: http://stackoverflow.com/q/49972502
tags question: http://stackoverflow.com/q/50019009
tags question: http://stackoverflow.com/q/50044895
tags question: http://stackoverflow.com/q/49978662
tags question: http://stackoverflow.com/q/49958248
tags question: http://stackoverflow.com/q/49978455
tags question: http://stackoverflow.com/q/50029795
tags question: http://stackoverflow.com/q/50047815
tags question: http://stackoverflow.com/q/49938586
tags question: http://stackoverflow.com/q/49953830
tags question: http://stackoverflow.com/q/50007474
type: Tag
tags question: http://stackoverflow.com/q/50042364
tags question: http://stackoverflow.com/q/50026427
tags question: http://stackoverflow.com/q/49938995
tags question: http://stackoverflow.com/q/50014809
tags question: http://stackoverflow.com/q/50055018

http://stackoverflow.com/a/49925306
downvote count: 0
has body: This should work: if isinstance(scene(), GameScene) ... Because you are comparing a @property decorated function to the type of an instance of whatever you return from get_scene. I am assuming self._scene_stack[...] is of GameScene. You should be careful when using the @property decorator, because it is a special decorator in that it provides extra properties (just try typing in property().getter). By nature, decorators like: @foo def bar(): ... Does essentially foo(bar()), so I'm not sure if that's your actual use case for the decorator in the first place.
has comment: http://stackoverflow.com/comment/86873421
has comment: http://stackoverflow.com/comment/86872133
answers question: http://stackoverflow.com/q/49924954
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86871153

http://stackoverflow.com/a/62818773
has body: I had the same need, you can do it this way: import cv2 import win32api import win32con def mouse_evt(event, x, y, flags, param): # Mouse is Moving if event == cv2.EVENT_MOUSEMOVE: if some_condition: win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZEALL)) cv2.namedWindow("image") cv2.setMouseCallback("image", mouse_evt) while True: cv2.imshow("image", image) cv2.waitKey(10) I personally use it to drag cropping point around, the some_condition returns true if the cursor is close to a set point on the image.
downvote count: 0
answers question: http://stackoverflow.com/q/49992372
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/87063033
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50022116
has text: You can have look at method html while coverting xml to string [here](https://stackoverflow.com/questions/12460677/python-etree-control-empty-tag-format). However I think you loose some information some xml headers.
score: 0

http://stackoverflow.com/comment/86991064
score: 0
comment on: http://stackoverflow.com/q/49987108
type: Comment
type: QuestionComment
has text: I also look for the solution before posting this question. Maybe the title of the other question do not help.

http://stackoverflow.com/a/50051695
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87120411
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50051619
answers question: http://stackoverflow.com/q/50051619
type: Answer
has body: Probably the most elegant way I could think of is to randomly shuffle your array, and then pull off the first occurrence. That should be pretty concise. So something like: np.random.shuffle(sampl) x = np.ravel(np.where(sampl==1))[0] or, like you suggested, without shuffling, that would look something like x = np.random.choice(np.ravel(np.where(sampl==1))) On second thought, I guess the choice method will be infinitely faster than shuffling. The next issue is the edge cases. How to handle this depends on what you expect the default behavior to be. If you expect that in most cases the condition will turn up at least one hit, then you should handle the case when there is not a hit with an exception: try: x = np.random.choice(np.ravel(np.where(sampl==1))) except: # TODO pass I would highly suggest doing this unless you rarely find a hit. But don't take my word for it... time it yourself. The other option would be to put in a condition that explicitly checks that np.size( np.where(sampl==1) ) &gt; 0 before continuing. However, I would guess that that approach is slower than the try...exceptapproach.
has comment: http://stackoverflow.com/comment/87120391

http://stackoverflow.com/comment/87125638
comment on: http://stackoverflow.com/q/50051606
type: Comment
score: 0
has text: Possible dupe https://stackoverflow.com/questions/10575750/python-ioerror-errno-13-permission-denied
type: QuestionComment

http://stackoverflow.com/comment/86916279
score: 1
type: Comment
type: QuestionComment
has text: As for the first question, hit something else when you get frustrated (head against the wall is a popular choice). As for the error, note that the first parameter to [`cv2.setWindowProperty`](https://docs.opencv.org/3.1.0/d7/dfc/group__highgui.html#ga66e4a6db4d4e06148bcdfe0d70a5df27) is "Name of the window.". Now, in the preceding statement you created a window named `"window"`, yet here you use a different name -- `"video.mp4"`. Also, further on, you have `cv2.imshow` using yet another window name -- `"Frame"`. The name is what's used to differentiate between multiple windows!
comment on: http://stackoverflow.com/q/49949639

http://stackoverflow.com/q/49939415
has comment: http://stackoverflow.com/comment/86896150
has answer: http://stackoverflow.com/a/53658675
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86895669
upvote count: 1
tagged with: python
has body: I have a paradoxon, that I just cannot explain. In short: I built a python script that is supposed to crack a zipped file, which is password protected. This is what I've done: (1) zip the text file: zip --password bla zip3.zip myZip So the passphrase is "bla". (2) Then I use the following Python Script: import zipfile import itertools from itertools import * import string import time That's the basic function, that is supposed to check, if a given password works or not: def crack(File, pwd): try: File.extractall(pwd=str.encode(pwd)) print("\n---- SUCCESS! {0} ----".format(pwd)) except: print("{0} did not work.".format(pwd)) pass Here I specify, which characters I want to use for trying: myLetters = string.ascii_letters Here I specify, which zip-file I want to crack: File = zipfile.ZipFile("PATH/TO/MY/zip3.zip", 'r') Here I specify, how long the password-phrase is: pwd_len = 3 here I specify, how many possible combinations of the charactes exist: all_poss = (len(myLetters)**pwd_len) Here is the procedure for concrete password cracking: count = 0 start_time = time.time() for i in range(0,pwd_len+1): for j in map(''.join, itertools.product(myLetters, repeat=i)): crack(File, j) count += 1 print(round((count/all_poss)*100, 1), end='\r') res_time = time.time() - start_time print("\n--- {} ---".format(round(res_time,2))) I use a nested loop, to try every password. If it works, I should get the Success-message. Else I should only see the "doesn't work message". However... If I type in my terminal: python3 pwdCracker.py &gt;&gt; out I get a long text file, which contains many many "does not work messages", BUT I also get a whole bunch of "Success-messages", although only ONE ("bla") should be correct. Here is a little extract: wN did not work. ---- SUCCESS! wO ---- wO did not work. wP did not work.` So apparently "wO" is working.. But why?? I set the password to "bla"! I really can open the file with "wO"... why can that happen?? Hope you can help!
has comment: http://stackoverflow.com/comment/86896046
answer count: 2
has answer: http://stackoverflow.com/a/49940569
tagged with: brute-force
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86895774
has comment: http://stackoverflow.com/comment/86895945
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/zip
tagged with: python-3.x
has title: Zip Password functionality works wrong

http://stackoverflow.com/comment/86917062
type: Comment
score: 0
type: AnswerComment
has text: But I only want to extract the content of one meta tag, where meta name="keywords"?
comment on: http://stackoverflow.com/a/49950146

http://stackoverflow.com/q/49995641
has answer: http://stackoverflow.com/a/49997959
has comment: http://stackoverflow.com/comment/87038957
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87012748
tagged with: python
type: AnsweredQuestion
upvote count: 2
score: 2
answer count: 1
downvote count: 0
has title: Splitting a Scrapy element among multiple CSV rows
tagged with: scrapy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49997959
has body: I've been working on something that I think should be relatively easy but I keep hitting my head against a wall. I've tried multiple similar solutions from stackoverflow and I've improved my code but still stuck on the basic functionality. I am scraping a web page that returns an element (genre) that is essential a list of genres: Mystery, Comedy, Horror, Drama The xpath returns perfectly. I'm using a Scrapy pipeline to output to a CSV file. What I'd like to do is create a separate row for each item in the above list along with the page url: "Mystery", "http:domain.com/page1.html" "Comedy", "http:domain.com/page1.html" No matter what I try I can only output: "Mystery, Comedy, Horror, Drama", ""http:domain.com/page1.html" Here's my code: def parse_genre (self, response): for item in [i.split (',') for i in response.xpath ('//span [contains (@class, "genre")]/text()').extract()]: sg = ItemLoader (item=ItemGenre (), response=response) sg.add_value ('url', response.url) sg.add_value ('genre', item, MapCompose(str.strip)) yield sg.load_item () This is called from the main parse routine for the spider. That all functions correctly. (I have two items on each web page. The main spider gathers the "parent" information and this function is attempting to gather "child" information. Technically not a child record, but definitely a 1 to many relationship.) I've tried a number of possible solutions. This is the only version that makes sense to me and seems like it should work. I'm sure I'm just not splitting the genre string correctly.

http://stackoverflow.com/a/50015051
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50014697
upvote count: 1
downvote count: 1
has body: It seems that those parameters are both optional, so you can just leave them out of your own code (assuming you don't need them) I understand this documentation the way that: Parameter minLineLength can only be used/only has an effect if lines is also defined Parameter maxLineGap can only be used/only has an effect if lines and minLineLength is also defined Due to this nesting, there are 3 opening [ brackets and 3 closing ] brackets, otherwise the documentation would be wrong, in my understanding. If they weren't connected/nested in a way, they would very likely (because this is common documentation syntax) be documented this way: cv2.HoughLinesP(image, rho, threshold, [lines], [minLineLength], [maxLineGap])
has comment: http://stackoverflow.com/comment/87052510
has comment: http://stackoverflow.com/comment/87052893
answers question: http://stackoverflow.com/q/50014697
type: Answer

http://stackoverflow.com/a/68061625
has body: It looks like Python doesn't parse/store the client's cert when ssl.CERT_NONE is set which is the default for SSLContext import socket import ssl dest = ("www.google.com", 443) sock = socket.socket(socket.AF_INET) ctx = ssl.SSLContext() # You will either need to add the self-signed certs to the OS cert store (varies by OS) # See https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations for loading non-defaults ctx.set_default_verify_paths() ctx.verify_mode = ssl.CERT_REQUIRED ssock = ctx.wrap_socket(sock, server_hostname=dest[0]) result = ssock.connect(dest) print(ssock.getpeercert()) See https://github.com/python/cpython/blob/main/Modules/_ssl.c#L1823 It's doing bitwise & so when verify mode is CERT_NONE (0) then the code block is skipped. CERT_OPTIONAL=1 or CERT_REQUIRED=2 is needed for the cert parsing/populating to work (otherwise it just sets an empty dict) For your self-signed certs, you should either import them into the OS certificate authority store or use the method SSLContext.load_verify_locations to load the self-signed cert (since it's self-signed, you can load the server/leaf cert as the CA cert) If you go the OS-store path, you can probably just use the default context. I think on Windows there's a per-user CA store (not positive, though). I don't think such a thing exists on Linux so you'd need to add it system-wide. Not sure about macOS or other operating systems
type: Answer
answers question: http://stackoverflow.com/q/50055935
score: 0

http://stackoverflow.com/a/49947804
type: Answer
has comment: http://stackoverflow.com/comment/86912404
accepted answer of: http://stackoverflow.com/q/49947730
type: AcceptedAnswer
score: 0
has body: That's called a "list comprehension", let's break it down here: [i for i, j in zip(a, b) if i == j] can be roughly understood as making a list of [i], where i (and j) come from zip(a, b) but only if i == j. zip(a, b) takes two arrays, a and b, and combines them in such a way that the end result looks like [(1, 9), (2, 8), ...] So effectively, you're processing the result of zip(a, b) and iterating over tuples i, j to return only if i == j is "truthy". Explaining "truthy" is a bit out of scope for this answer, but in this case, the expression i == j evaluates to True if i and j have the same value. I.e., 5 == 5 is True, where 5 == 4 is False.
answers question: http://stackoverflow.com/q/49947730
has comment: http://stackoverflow.com/comment/86912492

http://stackoverflow.com/comment/87119447
comment on: http://stackoverflow.com/q/50050744
type: QuestionComment
has text: We also tested it one 3.4.0, with the same results.
type: Comment
score: 0

http://stackoverflow.com/q/49936171
has body: Pardon me for possibly an easy question. If given a matrix U with shape [L, L], and a tensor V with shape [L, L, m, n], I want a numpy way to calculate the multiplication between the scalar in U and the matrix in tensor in the corresponding position. For example,I want the following operation U[i,j] * V[i, j, :, :] across the whole index at the same time. Noted that the U[i,j] is the scalar in the location(i, j) in matrix U, and the V[i, j, :, :] is the matrix in the location(i, j) in tensor V. Thanks in advance! Update #1 Maybe the description above isn't clear. Then I make it clearly again. Given a matrix U and a tensor V like: U = np.arange(2*2).reshape(2, 2) V = np.arange(2*2*3*4).reshape(2, 2, 3, 4) And I want the tensor result R, whose element are following: R[i,j,:,:] = U[i, j] * V[i, j, :, :] (1) e.g. U[0, 0] = 0 V[0, 0] = array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) And R[0, 0] = U[0, 0] * V[0, 0] = np.zeros((3, 4)) (for short) Another example: U[0, 1] = 1 V[0, 1] = array([[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]) And R[0, 1] = U[0, 1] * V[0, 1] = V[0, 1] (for short) The process will across the whole index. Noted that the index i and j is same in (1) So my goal is to complete the process above only with few code, instead of a loop.
type: Question
has comment: http://stackoverflow.com/comment/86890214
has comment: http://stackoverflow.com/comment/86889305
has comment: http://stackoverflow.com/comment/86888644
has title: Multiply scalar in matrix with matrix in tensor in the corresponding position by numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86888430
has comment: http://stackoverflow.com/comment/86890419
has comment: http://stackoverflow.com/comment/86890107
tagged with: python
has comment: http://stackoverflow.com/comment/86888822
has comment: http://stackoverflow.com/comment/86889081
has comment: http://stackoverflow.com/comment/86888673
tagged with: numpy
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86889257

http://stackoverflow.com/q/50065276
has comment: http://stackoverflow.com/comment/87147804
accepted answer: http://stackoverflow.com/a/50065732
upvote count: 3
downvote count: 0
has title: Clearing a MetaClass Singleton
favorite count: 0
type: Question
has body: I've created a Singleton using a MetaClass as discussed in Method 3 of this answer class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MySing(metaclass=Singleton): ... I'd like to be able to clear the Singleton in the setUp() method of a unittest.TestCase so that each test starts with a clean Singleton. I guess I don't really understand what this metaClass is doing because I can't get the correct incantation for a clear() method: def clear(self): try: del(Singleton._instances[type(self)] except KeyError: pass #Sometimes we clear before creating Any thoughts on what I'm doing wrong here? My singleton is not getting cleared. sing=MySing() sing.clear() The type call above returns Singleton not MySing.
has comment: http://stackoverflow.com/comment/87147724
score: 3
has answer: http://stackoverflow.com/a/50065732
tagged with: singleton
linked to: http://stackoverflow.com/q/6760685
has comment: http://stackoverflow.com/comment/87147497
tagged with: python
has comment: http://stackoverflow.com/comment/87147832
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50065723
possible better answer: http://stackoverflow.com/a/50065723
answer count: 2
tagged with: metaclass
has comment: http://stackoverflow.com/comment/87147825

http://stackoverflow.com/comment/86915134
has text: Please don't ask two different questions in your question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49949225
score: 3

http://stackoverflow.com/comment/86998134
type: Comment
type: AnswerComment
has text: @LampShade: that's a **list comprehension**. It's one of the most basic but powerful Python idioms, you will find it super-useful.
score: 1
comment on: http://stackoverflow.com/a/49989455

http://stackoverflow.com/a/50022834
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50020118
has body: Thanks to @Alasdair, I looked in my code what he was trying to tell me and i got the answer. The url that i was trying to pass through my action attribute was wrong. Here's what i did. &lt;form action="{% url 'studentapp:editrow' rowid=student_detail.id %}" id="editform" method="POST"&gt; Through "student_detail" i'm able to get pre-populated form as i mentioned above. i used the same to get the id and pass it to my "editrow" view. It's working for me now.
accepted answer of: http://stackoverflow.com/q/50020118
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/50028492
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
accepted answer: http://stackoverflow.com/a/50380068
has answer: http://stackoverflow.com/a/50380068
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/47023871
has title: IntraBundleParallelization in Apache Beam Python SDK
answer count: 1
has body: Does the Python SDK for Apache Beam have IntraBundleParallelization support like the Java SDK? I realize that the benefit of multithreading in Python is limited, but I was wondering if there were any efforts or plans to add support to do the same with Python.
type: Question

http://stackoverflow.com/comment/86994246
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49988866
has text: I'd like to know if what I am asking is even possible. I'm new to pandas and would like to know if it's even possible. Basically I would like a new array to be formed using the index in the arrays present in the rows of the pandas tables.

http://stackoverflow.com/q/50061786
type: Question
has body: I recently had to switch my machine at work. On the new machine, pip is not anymore. $ pip --version ... OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/virtualenv-15.0.1.dist-info' I imagine that this issue is caused by virtualenv, as I never encountered any problems on my old machine and the only difference I find, is that there was no virtualenv package installed on the old machine. However $ python -c "import pip; print pip.__version__" 10.0.1 still works. I would be grateful if anyone could provide help, how to fix this problem or trace down the real problem. Please note: I do not have root rights.
has answer: http://stackoverflow.com/a/50420921
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87140159
has title: python pip broken by virtualenv
downvote count: 0
tagged with: pip
tagged with: virtualenv
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87144926
has comment: http://stackoverflow.com/comment/87154221
has comment: http://stackoverflow.com/comment/87140182

http://stackoverflow.com/comment/87029719
type: Comment
has text: Yes --same setting locally as on Heroku
score: 0
comment on: http://stackoverflow.com/q/50006409
type: QuestionComment

http://stackoverflow.com/comment/87341601
type: Comment
has text: A suspicion: do you have files named as 'final_model' **and** 'final_model.h5'? -- If the save command is somenow adding the extension automatically, you may be loading a different model.
type: AnswerComment
comment on: http://stackoverflow.com/a/50121735
score: 1

http://stackoverflow.com/q/49945709
score: -1
has answer: http://stackoverflow.com/a/50035923
tagged with: aes
favorite count: 0
type: Question
has title: AES encryption issue: "ValueError: Input strings must be a multiple of 16 in length"
upvote count: 0
answer count: 2
type: UnansweredQuestion
downvote count: 1
tagged with: base64
tagged with: python
has comment: http://stackoverflow.com/comment/86911349
has body: I was trying to encrypt some sensitive data inside the database using AES by this python code from Crypto.Cipher import AES import base64 import pymysql import os import hashlib def encryption(self, tableName): # opening db connection db_connection = self.getMySqlConnection() cursor = db_connection.cursor() print("\tTwo Way Encryption") # hashing cursor.execute("SELECT toMask FROM " + tableName + ";") row = cursor.fetchall() for item in row: string = str(item[0]) padded = string.rjust(80) secret_key = self.key cipher = AES.new(secret_key, AES.MODE_ECB) encoded = base64.b64encode(cipher.encrypt(padded)) encoded = encoded.decode('utf-8') stmt = "update " + tableName + " set toMask = '" + encoded + "' where toMask =\"" + string + "\";" cursor.execute(stmt) db_connection.commit() # closing db connection db_connection.close() print("\tDone") But my data contains some special characters like this Å So I am getting this error: ValueError: Input strings must be a multiple of 16 in length How can I solve this? Other input string doesn't make any issues. Or do I need to convert that to any other encoding?
has answer: http://stackoverflow.com/a/49947617
has comment: http://stackoverflow.com/comment/86910990
tagged with: utf-8

http://stackoverflow.com/q/49953107
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49953200
answer count: 1
has body: I want to use python regex to find the document class in a latex document. A latex file contains \documentclass{myclass} somewhere near the top. I want to find myclass using regex. This is what I've tried so far: latex_text = "blank /documentclass{myclass} words, more text /documentclassdoc{11} more words" s=re.search(r'/documentclass{(?P&lt;class_name&gt;.*)}', latex_text) It matches: myclass} words, more text /documentclassdoc{11 How can I change it to only match myclass. It should also stop searching after it finds a match, as the document can get quite long. I know the file should only have one documentclass, but I want to handle the case where there is more than 1 as well.
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/22444
tagged with: regex
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/22444
has answer: http://stackoverflow.com/a/49953200
has title: Finding latex class name using python regex

http://stackoverflow.com/a/50032216
has comment: http://stackoverflow.com/comment/87080580
has comment: http://stackoverflow.com/comment/87080558
answers question: http://stackoverflow.com/q/50032145
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87080469
has body: Return the new value in the update method and assign it in the call to the variable. ... while running: if var == 1: print(var) var = test.update(var) ... class myClass: def update(self, _var): # _var is removable unless you will use it return 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50032145
has comment: http://stackoverflow.com/comment/87080644
score: 0
has comment: http://stackoverflow.com/comment/87080741

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50046824
tags question: http://stackoverflow.com/q/49959083
tags question: http://stackoverflow.com/q/50071406
tags question: http://stackoverflow.com/q/50066500
tags question: http://stackoverflow.com/q/50023853
tags question: http://stackoverflow.com/q/50074155
tags question: http://stackoverflow.com/q/50016989
tags question: http://stackoverflow.com/q/49920532
tags question: http://stackoverflow.com/q/49925332
tags question: http://stackoverflow.com/q/50050327
tags question: http://stackoverflow.com/q/49934033
tags question: http://stackoverflow.com/q/49986965
tags question: http://stackoverflow.com/q/50033608
tags question: http://stackoverflow.com/q/49946684
tags question: http://stackoverflow.com/q/49918670
tags question: http://stackoverflow.com/q/50022465
tags question: http://stackoverflow.com/q/49930114
tags question: http://stackoverflow.com/q/49927064
tags question: http://stackoverflow.com/q/50021175
tags question: http://stackoverflow.com/q/49929668
tags question: http://stackoverflow.com/q/49965938
tags question: http://stackoverflow.com/q/50029201
tags question: http://stackoverflow.com/q/49963656
tags question: http://stackoverflow.com/q/49968274
tags question: http://stackoverflow.com/q/49951628
tags question: http://stackoverflow.com/q/49930534
tags question: http://stackoverflow.com/q/50000548
tags question: http://stackoverflow.com/q/49951049
tag name: pyqt
tags question: http://stackoverflow.com/q/50034906
tags question: http://stackoverflow.com/q/49918307
tags question: http://stackoverflow.com/q/50019909
tags question: http://stackoverflow.com/q/49974936
tags question: http://stackoverflow.com/q/50053576
tags question: http://stackoverflow.com/q/50061518
tags question: http://stackoverflow.com/q/50070752
tags question: http://stackoverflow.com/q/49948742
tags question: http://stackoverflow.com/q/50033311
tags question: http://stackoverflow.com/q/50027687
tags question: http://stackoverflow.com/q/49965770
tags question: http://stackoverflow.com/q/50067782
tags question: http://stackoverflow.com/q/50004337
tags question: http://stackoverflow.com/q/49934867

http://stackoverflow.com/q/49945955
upvote count: 2
type: UnansweredQuestion
tagged with: seaborn
tagged with: python
linked to: http://stackoverflow.com/q/17458580
score: 2
has answer: http://stackoverflow.com/a/49981099
has comment: http://stackoverflow.com/comment/86917308
tagged with: matplotlib
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/12750355
favorite count: 0
type: Question
has title: Pyplot: leaving space for a bigger title
has body: sns.boxplot(data=df, width=0.5) plt.title(f'Distribution of scores for initial and resubmission\ \nonly among students who resubmitted at all.\ \n(n = {df.shape[0]})') I want to use a bigger font, and leave more space in the top white margin so that the title doesn't get crammed in. Surprisingly, I am totally unable to find the option despite some serious googling!

http://stackoverflow.com/a/49948041
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/49947493
has body: try this : INSTALLED_APPS = [ # Rest framework 'django_filters', 'django_apscheduler', 'rest_framework', 'corsheaders', # Project applications 'ms_vlan_failover.apps.Usecase1Config', 'maintenance_check.apps.Usecase2Config', 'reporting.apps.Usecase1Config', # Django defaults 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'usecase1', 'usecase2', 'usecase3', 'tests', ]
downvote count: 1
type: Answer

http://stackoverflow.com/q/50039355
has comment: http://stackoverflow.com/comment/87123646
tagged with: python
has comment: http://stackoverflow.com/comment/87123688
has comment: http://stackoverflow.com/comment/87139327
has title: Python flask, apache and mod_wsgi application not working
has comment: http://stackoverflow.com/comment/87183468
has body: I am trying to build an application in python which can be run from XAMPP's Apache, therefore I installed flask ($ pip install flask) and I followed the following instructions for mod_wsgi installation http://modwsgi.readthedocs.io/en/develop/user-guides/quick-installation-guide.html. I am using Apache from XAMPP, version 2.4.29, and python 3.6.4 from anaconda. I built the mod_wsgi file (version 4.6.4) by downloading from https://github.com/GrahamDumpleton/mod_wsgi/releases and using the following command : $ ./configure --with-apxs=/Applications/XAMPP/xamppfiles/bin/apxs --with-python=/Users/pauline/anaconda3/bin/python3.6 --disable-framework followed by makeand sudo make install. I also tried it with and without --disable-framework. After the installation, I checked otool -L mod_wsgi.so which gives me (looks correct): SCARLET10siMac4:modules pauline$ otool -L mod_wsgi.so mod_wsgi.so: @rpath/libpython3.6m.dylib (compatibility version 3.6.0, current version 3.6.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.50.4) /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 1452.23.0) Also, when the Apache loaded modules is checked (by running this command: /Applications/XAMPP/xamppfiles/bin/httpd -M), it shows wsgi_module (shared) as well. And the output of sys.prefix is /Users/pauline/anaconda3 and of sys.version is 3.6.4 My application (image_download.py) has the simple following code : from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' if __name__ == "__main__": app.run() And my wsgi file (image_download.wsgi) the following : import sys sys.path.insert(0,"/Users/pauline/Documents/Code/platform_projects/image_download/image_download") from image_download import app as application Finally, my http.conf virtual host part is : WSGIPythonHome /Users/pauline/anaconda3 &lt;V…
has comment: http://stackoverflow.com/comment/87216415
has comment: http://stackoverflow.com/comment/87134252
tagged with: mod-wsgi
has answer: http://stackoverflow.com/a/50062267
type: UnansweredQuestion
score: 1
tagged with: apache
has comment: http://stackoverflow.com/comment/87217155
answer count: 1
downvote count: 0
upvote count: 1
tagged with: flask
favorite count: 0
type: Question

http://stackoverflow.com/comment/86897745
type: QuestionComment
comment on: http://stackoverflow.com/q/49940129
has text: Sorry the bit I don't understand is that there is an extra b' ' and apostrophe that I am trying to remove
score: 0
type: Comment

intel-mkl
tags question: http://stackoverflow.com/q/49992243
type: Tag
tag name: intel-mkl

http://stackoverflow.com/q/49963232
tagged with: google-cloud-storage
type: AnsweredQuestion
score: 0
tagged with: stream
answer count: 1
tagged with: loops
has body: I am trying to pull frames from a remote video streaming server, images are of type mjpeg, then upload to a bucket in Google Cloud Storage. Through my testing, I am able to pull consistently ~30 images per second and save the frames in my machine. However, when I am trying to upload all individual frames to GCS with their client library, it will wait for the uploading process to finish first, then come back and upload a newly received frame. For instance, in 1s, I'm expecting to receive and upload all 0...30 images, but because my code is asynchronous, it only uploads the latest image received in the loop. Here's my code class GCStream: def __init__(self): self.client = storage.Client() self.bucket = self.client.get_bucket(BUCKET_NAME) self.frame = None self.fileName = "" self.secondCount = 0 self.startSecond = datetime.datetime.now().second self.vs = VideoStream(src=REMOTE_STREAM_MJPEG).start() def uploadFrame(self): try: blob = self.bucket.blob("{}/{}/{}".format(RPID_FOLDER, BY_DAY, self.fileName)) blob.upload_from_filename(os.path.abspath(self.fileName)) print("{} uploaded to {}/{}".format(self.fileName, RPID_FOLDER, BY_DAY)) os.remove(self.fileName) except Exception as e: print(e) def readFrame(self): while True: self.frame = self.vs.read() self.secondCount = self.secondCount + 1 if datetime.datetime.now().second != self.startSecond: self.startSecond = datetime.datetime.now().second self.secondCount = 0 if self.frame is not None: self.frame = imutils.resize(self.frame, 800) self.fileName = "{}-{}.png".format(datetime.datetime.now().strftime("%H-%M-%S"), self.secondCount) cv2.imwrite(self.fileName, self.frame) self.uploadFrame() if cv2.waitKey(1) &amp; 0xFF == ord('q'): break vs.release() cv2.destroyAllWindows() if __name__ == "__main__": stream = GCStream() stream.readFrame()
tagged with: asynchronous
has title: How to avoid code blocking in a loop
type: Question
has answer: http://stackoverflow.com/a/49976847
accepted answer: http://stackoverflow.com/a/49976847
tagged with: python

http://stackoverflow.com/comment/86877719
has text: I have tried it on the network I am wanting it for, its about 10-20 seconds, but on my home network its anywhere from 3-7 seconds. I just wonder if there is a way to lower it quite dramatically
type: Comment
comment on: http://stackoverflow.com/q/49928822
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87108020
score: 0
has text: @niko " `C` is supposed to provide the same API as `A` " this can be achieved by using composition as well by overwriting `__getattr__` in `C` for example `def __getattr__(self, item): return getattr(self.obj, item)` It works, but is it a good approach? not sure. See updated answer.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50044449

http://stackoverflow.com/q/50054406
has comment: http://stackoverflow.com/comment/87125642
tagged with: python-requests
downvote count: 1
favorite count: 0
has body: I am making a Pyqt5 app and I'm trying now to make it post a file on my django website with a button click. I can make the script login to my site using requests with no problem (using csrftoken), but when uploading the file (to "http://127.0.0.1:8000/ranking") it raises an 403 Forbidden Error ("CSRF cookie not set.") even though I sent the csrftoken with the file. Here is the code: send_file.py import requests login_url = "http://127.0.0.1:8000/accounts/login/" MAX_RETRIES = 2 client = requests.Session() adapter = requests.adapters.HTTPAdapter(max_retries=MAX_RETRIES) client.mount('http://', adapter) # I know that I should use https, but the server doesn't have it yet client.get(login_url) # Goes to login page csrftoken = client.cookies['csrftoken'] # get csrf token login_data = {'username': 'b','password':'senha123', 'csrfmiddlewaretoken': csrftoken} try: response = client.post(login_url, data=login_data) # executes login if "Logout from b" in str(response.content): # this is to confirm the user logged in print("Logged in at {}".format(response.url)) # "Logged in at http://127.0.0.1:8000/home/" response2 = client.get('http://127.0.0.1:8000/ranking/') # Goes to the uploading page print("Logged in at {}".format(response2.url)) # "Logged in at http://127.0.0.1:8000/ranking/" csrftoken1 = client.cookies['csrftoken'] # get another crsf token file_data = {'csrfmiddlewaretoken': csrftoken1} headers = {"Referer": 'http://127.0.0.1:8000/ranking/'} print(csrftoken, csrftoken1) # Both are different with open('Data\\training_data.npy', 'rb') as f: r = requests.post('http://127.0.0.1:8000/ranking/', files={'training_data.npy': f}, data=file_data, headers=headers) print("File should be sent") print(r.text) # 403 Forbidden -&gt; CSRF verification failed. Request aborted. else: print("not logged in") except Exception as e: print(e) # No errors raised If you need to see the django models, templates or anything related to the website: link
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87125331
answer count: 1
accepted answer: http://stackoverflow.com/a/50062310
has answer: http://stackoverflow.com/a/50062310
type: Question
tagged with: python-3.x
has title: How to send files to website after needing to login in another url?
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87129445
type: Comment
comment on: http://stackoverflow.com/q/50056227
score: 0
has text: Yes, I know. I want to train my network with different sizes. What do you mean by single `image which is of different size that you gave in training`
type: QuestionComment

http://stackoverflow.com/comment/86958357
score: 0
has text: Where is the bottleneck? How are you trying to achieve the concurrency? Are you using threads, multiprocessing, asyncio?? A [mcve] might be nice though if it depends on OrientDB, you'll be narrowing possible responders.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49971025

http://stackoverflow.com/comment/89036284
type: AnswerComment
score: 0
has text: You can accept the answer if this solves your problem.
type: Comment
comment on: http://stackoverflow.com/a/50019708

http://stackoverflow.com/comment/87100422
comment on: http://stackoverflow.com/a/50006588
has text: Src is iframe`s attribute that specifies the url of the document to embed in the iframe. I didnt visit your url. The src is empty because they use javascript to set it. You can`t get it with bs4. One posible solution is to use Selenium
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50000548
answer count: 1
has title: PyQt4 threading properly
favorite count: 0
accepted answer: http://stackoverflow.com/a/50007109
type: AnsweredQuestion
score: 1
tagged with: pyqt4
has body: I want to make a progressbar which runs on a thread and I want to be able to move the widget during the process: import sys from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, QLineEdit, QLabel, QComboBox, QProgressBar, QFileDialog from PyQt4.QtCore import QSize, pyqtSlot, QCoreApplication, SIGNAL, QThread class App(QMainWindow): def __init__(self): super(App, self).__init__() self.setGeometry(500, 300, 820, 350) self.setWindowTitle("Program") self.initUI() def initUI(self): #Buttons btnposx = 30 btnposy = 50 self.btn4 = QPushButton('Load', self) self.btn4.move(btnposx,btnposy+220) self.connect(self.btn4, SIGNAL("released()"), self.test) #ProgressBar self.pb = QProgressBar(self) self.pb.move(btnposx+150,btnposy+220) self.pb.resize(470,27) self.show() def load(self, val): self.pb.setValue(val) def test(self): self.workThread = WorkThread() self.connect( self.workThread, SIGNAL('pb_update'), self.load) self.workThread.start() class WorkThread(QThread): def __init__(self): super(WorkThread, self).__init__() QThread.__init__(self) def __del__(self): self.wait() @pyqtSlot() def run(self): val = 0 l = range(1000000) for i in l: if i &lt; len(l): val += 100/len(l) self.emit(SIGNAL('pb_update'), val) return if __name__ == '__main__': app = QApplication(sys.argv) ex = App() ex.show() sys.exit(app.exec_()) So far this works, but it does very poorly. The Widget does barely run on my machine, when I try to move it during the process. Is there a way to make this work better so that the Widget doesn't lag or stop responding?
tagged with: python
tagged with: qprogressbar
tagged with: qthread
has answer: http://stackoverflow.com/a/50007109
type: Question
downvote count: 0
upvote count: 1
tagged with: pyqt

http://stackoverflow.com/comment/86874333
type: QuestionComment
comment on: http://stackoverflow.com/q/49929183
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
score: 0
type: Comment

http://stackoverflow.com/q/50023814
score: 2
possible better answer: http://stackoverflow.com/a/50023970
answer count: 2
tagged with: pandas
upvote count: 2
has title: How to remove unwanted `.0` s in pandas?
downvote count: 0
accepted answer: http://stackoverflow.com/a/50023924
favorite count: 0
has answer: http://stackoverflow.com/a/50023924
type: Question
has answer: http://stackoverflow.com/a/50023970
has body: How can I convert the components of a column of my pandas DataFrame from float type to actual string? Initially when I read_csv them they display in Scientific notation: e.g. 1.04983E+13 I used this following line to change the display type to show all digits with no decimal: pd.set_option('display.float_format', lambda x: '%.0f' % x) which seems to work initially (no decimal shown!): sample_df['gpid'][0:2] 0 10498310800133 1 767838527881217 However, when I try to make a list out of it, it clearly includes the decimal .0 in front of each and every component list(sample_df['gpid'])[0:2] [10498310800133.0, 767838527881217.0] How can I avoid this unwanted .0? [this has been an annoying thing for the entire day yesterday...]
tagged with: python
tagged with: decimal
type: AnsweredQuestion

http://stackoverflow.com/q/50009435
has answer: http://stackoverflow.com/a/55622257
answer count: 2
upvote count: 2
has title: Fill missing dates pyspark
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: I have a pandas data frame like this date,userId,classification 2018-03-29,55,Large 2018-03-30,55, small 2018-03-29,55, x-small 2018-04-20,65, Large 2018-04-29,75, x-small How do I fill the missing dates but per userId for a time period of 60 days? I tried it with pandas using indexing the date and then re-indexing and filling it but it gave all null values all other fields. I am ok with any solution using spark dataframes or pandas using python or java. The code I tried import pandas as pd idx = pd.date_range('02-28-2018', '04-29-2018') df = pd.DataFrame([['Chandler Bing','55','2018-03-29',51], ['Chandler Bing','55','2018-03-29',60], ['Chandler Bing','55','2018-03-30',59], ['Harry Kane','45','2018-04-30',80], ['Harry Kane','45','2018-04-21',90]],columns=['name','accountid','timestamp','size']) df['timestamp'] = pd.to_datetime(df['timestamp']) df.set_index('timestamp', inplace=True) print (df) df= df.reindex(idx, fill_value=0) print(df) and the error I get is 'ValueError: cannot reindex from a duplicate axis' Even this version didn't work import pandas as pd idx = pd.date_range('02-28-2018', '04-29-2018') df = pd.DataFrame([['Chandler Bing','55','2018-03-29',51], ['Chandler Bing','55','2018-03-29',60], ['Chandler Bing','55','2018-03-30',59], ['Harry Kane','45','2018-04-30',80], ['Harry Kane','45','2018-04-21',90]],columns=['name','accountid','timestamp','size']) df['timestamp'] = pd.to_datetime(df['timestamp']) pd.DatetimeIndex(df['timestamp']) del(df['timestamp']) #df.set_index('timestamp', inplace=True) print (df) df= df.reindex(idx, fill_value=0) print (df) uniquaccount=df['accountid'].unique() print(uniquaccount)
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50009869
score: 1
linked to: http://stackoverflow.com/q/53699012
has comment: http://stackoverflow.com/comment/87036009
type: Question

http://stackoverflow.com/comment/86934664
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49957157
type: Comment
has text: @user3613025 i edited my answer to reflect reflect the class approach. Add a comment if you need further clarification or if you understand :)

http://stackoverflow.com/q/49995015
has comment: http://stackoverflow.com/comment/87007372
tagged with: forms
has comment: http://stackoverflow.com/comment/87007166
tagged with: post
type: Question
accepted answer: http://stackoverflow.com/a/50008917
has comment: http://stackoverflow.com/comment/87008899
has answer: http://stackoverflow.com/a/50008917
has comment: http://stackoverflow.com/comment/87008673
has title: Getting GET instead of a POST on form submit
has comment: http://stackoverflow.com/comment/87008827
has comment: http://stackoverflow.com/comment/87010009
has comment: http://stackoverflow.com/comment/87007211
has comment: http://stackoverflow.com/comment/87007047
has comment: http://stackoverflow.com/comment/87033673
tagged with: python
tagged with: get
type: AnsweredQuestion
has body: The python code starts a web server, and it has these web pages of interest: index.html : This contains an HTML Form which takes username and password configure.html : This page should be called with POST username & password when form of index.html is submitted . import ubinascii import utime import socket import select html = """ Ouroboros IoT Login Username : Password: """ # Find out the post parameters in a dictionary def get_post_params(req): print("Inside POST PARAMS : req = " + req) post_params = req.split('\r\n')[-1:][0] # Check if the post body contains the necessary fields # Split the post_params by & # params : ['username=', 'password=', 'method=POST', 'url=http%3A%2F%2Ftwig-me.com%2Fv1%2Fusergroups%2FWKMUYXELA9LCC', 'jsondata=', 'submit=submit'] print("post_params : " + post_params) params = post_params.split('&') print("Params") print(params) # Initialize the key value pair dict post_dict = {} # Iterate on each param for param in params: # Each param would be like 'method=POST', etc key_val = param.split('=') print("Key Val :") print(key_val) key = key_val[0] val = key_val[1] # Update post_dict post_dict[key] = val return post_dict # This web server takes care of the WiFi configuration # max_run_sec def web_server(max_run_sec = None): # Create server socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() # TODO : If both the wifi and sta are operating simultaneously, then bind only to WiFi s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(1) poller = select.poll() poller.register(s, select.POLLIN) startTimeEpoch = utime.time() while True: all_events = poller.poll(200) # time in milliseconds if len(all_events) > 0: try: print("Just after GC Collect!") gc.collect() #print("Just before accepting") res = s.accept() client_s = res[0] client_addr = res[1] req = '' req = client_s.recv(4096) req = req.decode() req = str(req) # Came here means that there has been some connection! # Reset the start time epoch in such…
score: 0
has comment: http://stackoverflow.com/comment/87026333
answer count: 1

http://stackoverflow.com/comment/136641092
type: QuestionComment
comment on: http://stackoverflow.com/q/49955489
score: 0
has text: The two questions (Can you recommend Kivy; what IDE to recommend) are both software recommendation questions rather than about solving a concrete issue. Needs to be more specific to say whether a solution fits. A good overview can be found here otherwise: https://wiki.python.org/moin/Android
type: Comment

http://stackoverflow.com/q/49962722
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49962903
favorite count: 0
has answer: http://stackoverflow.com/a/49962900
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49963053
has body: So I have been given this dictionary whose keys are names; which has tuples with 3 values: in the 3-tuple, a stock name, number of shares traded for that transaction (int), and price of each share (int). new_dict = { 'Carl': [('Intel', 30, 40), ('Dell' , 20, 50), ('Intel',-10, 60), ('Apple', 20, 55)], 'Barb': [('Intel', 20, 40), ('Intel',-10, 45), ('IBM', 40, 30), ('Intel',-10, 35)], 'Alan': [('Intel', 20, 10), ('Dell', 10, 50), ('Apple', 80, 80), ('Dell', -10, 55)], 'Dawn': [('Apple', 40, 80), ('Apple' ,40, 85), ('Apple',-40, 90)] } I am creating a function that returns a list of 2-tuples as a result (client, and absolute value of number of shares they sold(negative num) or bought (positive num) total. - the list is sorted in decreasing order based on the sum of the number of shares they traded; if two clients trade the same number of shares, they must appear in increasing alphabetical order. For new_dict as the dictionary, the output should be [('Alan', 120), ('Dawn', 120), ('Barb', 80), ('Carl', 80)] Here's what I have done: def most_active_clients(database :{str: (str, int, int)}) -&gt; list: result = [] t = list() for key,val in database.items(): for x in val: t.append((key,abs(x[1]))) for item in t: print(item) I can't seem to figure out how to get the sum of all x[1]'s and then sort that. Can someone help me?
type: UnansweredQuestion
tagged with: python
has title: How can i get the tuples to display the sum of each person rather than individually?
score: 2
upvote count: 2

http://stackoverflow.com/q/49973682
has answer: http://stackoverflow.com/a/49973842
has answer: http://stackoverflow.com/a/49973892
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86964732
has answer: http://stackoverflow.com/a/49973868
has comment: http://stackoverflow.com/comment/86966174
answer count: 5
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: dictionary
has answer: http://stackoverflow.com/a/49973908
has comment: http://stackoverflow.com/comment/86964790
has body: I want to read a file and convert the 1st 2 values of each row as key and the next 2 as values file_name.txt a b 1 2 d e 2 3 a c 4 6 I want to create a dictionary like this d={'a-b' :(1,2)},'d-e':(2,3)},'a-c':(4,6)}} I converted the file into a list with each row being an element of the list: v_list=['a b 1 2','d e 2 3','a c 4 6'] I can also convert the file into a list with each value in each row as an element: v_list=['a','b','1','2','d','e','2','3','a',c','4','6'] But I am not getting proper reference to convert this list into a nested dictionary with values a tuple. Can someone please suggest me how to go about it.
has title: How to make the first 2 values as key and next as values
has comment: http://stackoverflow.com/comment/86963610
has comment: http://stackoverflow.com/comment/86964316
has answer: http://stackoverflow.com/a/49973773
has comment: http://stackoverflow.com/comment/86963369

http://stackoverflow.com/a/50009869
answers question: http://stackoverflow.com/q/50009435
score: 0
has body: You can use reindex with Pandas series import pandas as pd idx = pd.date_range('02-28-2018', '04-29-2018') s = pd.Series({'2018-03-29' : 55, '2018-03-30' : 55, '2018-03-29' : 55, '2018-04-20' : 65, '2018-04-29' :75}) s.index = pd.DatetimeIndex(s.index) s = s.reindex(idx, fill_value=0) print(s) will impute all the missing dates: 2018-03-28 0 2018-03-29 55 2018-03-30 55 2018-03-31 0 2018-04-01 0 2018-04-02 0 2018-04-03 0 2018-04-04 0 ...
has comment: http://stackoverflow.com/comment/87038346
type: Answer

http://stackoverflow.com/a/49979235
type: Answer
score: 1
has body: The accepted solution by jezrael works. However, I would suggest you take advantage of the numpy representation directly, since this is a more efficient way of storing and manipulating data. It is rarely the case that a list is more useful than the numpy representation when dealing with structured data. You can do this via: res = df.values.astype(str) This returns dtype &lt;U11, while df.astype(str).values returns dtype Object. This is a significant difference in how the data is stored internally.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49978682

http://stackoverflow.com/comment/87068615
score: 0
has text: Please provide code based off of the xml above and we may be able to help out :).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50024837

http://stackoverflow.com/q/49923603
answer count: 1
tagged with: web-scraping
tagged with: python
has title: How to scrape link from div element with ng-if attribute using python?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49923756
score: 0
has answer: http://stackoverflow.com/a/49923756
has comment: http://stackoverflow.com/comment/86863959
type: Question
has body: Div element looks like this Anna Bros ==$0

http://stackoverflow.com/comment/87133438
score: 0
has text: The data above is just an example to show the format that my data is in.
comment on: http://stackoverflow.com/q/50033855
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49977036
has body: If your goal is to get acquainted with keras ImageDataGenerators: If you want your generator to always return the same image (for reproducability): from keras.preprocessing.image import ImageDataGenerator import numpy as np data_dir = 'path/to/image/directory' # path to the directory where the images are stored index = 0 # select a number here ig = ImageDataGenerator() gen = ig.flow_from_directory(data_dir, batch_size=1) # if you want batch_size &gt; 1 you need to # add as many indices as your batch_size. image, label = gen._get_batches_of_transformed_samples(np.array([index])) image_name = gen.filenames[index] # do whatever you want with your image and label If you want your generator to always return a random image but know which one it is I would suggest doing the following: index = next(gen.index_generator) image, label = gen._get_batches_of_transformed_samples(index) image_name = gen.filenames[index] If you want to see how predict_generator works, however none of these approaches will help you out. The only thing I can think of is editing the DirectoryIterator code. For example you could add a line that prints the name of the image you are passing. I would suggest adding the following statement after line 1434: print(fname)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87037425
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/49973379
has comment: http://stackoverflow.com/comment/87035654
accepted answer of: http://stackoverflow.com/q/49973379
type: Answer
has comment: http://stackoverflow.com/comment/87037364
downvote count: 0

http://stackoverflow.com/comment/87025159
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49991505
has text: Hi. What html are you referring to? The android app source under Appium GUI inspector shows Appium Source line <android.view.View resource-id="Head__master-id"> in the App source tree. Again both viewers see it, UIA1 finds it in the script, but UIA2 does not in the same exact script (except with automationName set to uiautomator2 in Appium's desired capabilities initialization).

http://stackoverflow.com/q/49930650
has title: Pandas Flat File Output
tagged with: file
tagged with: python
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49930811
has body: I'm reading in a .csv file with pandas, and after doing some minor mods to some headers and a few concatenations I need to turn the file into a flat file such that each row is separated as such: Row 1(Not Needed in output) column,value column,value column,value Row 2(Not Needed in output) column,value column,value column,value IE Name,Fred Phone,555-555-5555 Office,Jackson Name,Mary Phone,555-555-5555 Office,Gulf Port Name,Willie Phone,555-555-5555 Office,Jackson etc.... and save it to file in that format.
answer count: 1
tagged with: flat
type: Question
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50012754
score: 0
has comment: http://stackoverflow.com/comment/87043954
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/50083034
type: Question
tagged with: numpy
has body: I have some function f(list) with receives as argument a list with length 2, i.e., list = [entry_1, entry_2]. I need to do a contour plot of this function: x = np.linspace(0, 2, 1000+1) y = np.linspace(0, 2, 1000+1) X, Y = np.meshgrid(x, y) Z = ? plt.contour(X, Y, Z) plt.show() The problem is: I don't know how to pass the arguments. If the function was of the type f(x,y), then Z = f(X, Y) would do the job. But Z = f([X,Y]) fails: it receives too many arguments. How can I do this? EDIT: Here are the functions of the program: from scipy.optimize import minimize def c_Gamma_gamma_fv(cf, cv): return np.abs((4 * eta_gamma * charges**2 * a_q * cf).sum() + 4.* cf *a_tau/3. + a_w * cv)**2/Gamma_gamma def mu_fv(cf, cv): return np.array([cf**4, cf**2 * cv**2, cf**2 * c_Gamma_gamma_fv(cf, cv), cv**2 * c_Gamma_gamma_fv(cf, cv), cf**4, cv**2 * cf**2, cf**2 * cv**2, cv**4, cv**2 * cf**2, cv**4]) def chi_square_fv(clist): cf, cv = clist return ((mu_fv(cf, cv) - mu_data) @ inv_cov @ (mu_fv(cf, cv) - mu_data)) x0 = [1., 1.] res_fv = minimize(chi_square_fv, x0) print(res_fv) def delta_chi_fv(clist): return chi_square_fv(clist) - chi_square_fv([res_fv.x[0], res_fv.x[1]]) All variables not explicit are constants. The function I want to plot is delta_chi_fv.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87057714
tagged with: python
has comment: http://stackoverflow.com/comment/87041925
has comment: http://stackoverflow.com/comment/87042010
has title: Contour plot with function receiving lists
tagged with: contour

http://stackoverflow.com/q/49985035
answer count: 2
possible better answer: http://stackoverflow.com/a/55300157
has body: I need to open Chrome maximised with an experimental option to prevent a pop warning about extensions "disabled by your administrator". Using Create WebDriver, I can get this working with Open Chrome With Options ${options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver Call Method ${options} add_experimental_option useAutomationExtension ${FALSE} Call Method ${options} add_argument start-maximized Create WebDriver Chrome chrome_options=${options} Go To ${HOMEPAGE} However, when I try something equivalent with Open Browser (see below), although the "useAutomationExtension" is working, the start-maximised setting is ignored. Why is this? Open Chrome with Capabilities ${args}= Create List start-maximised ${chrome_options}= Create Dictionary ... useAutomationExtension ${FALSE} ... args ${args} ${capabilities}= Create Dictionary ... chromeOptions ${chrome_options} Open Browser ${HOMEPAGE} ${BROWSER} desired_capabilities=${capabilities}
has answer: http://stackoverflow.com/a/55300157
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/50045332
has title: Disable Chrome extensions with Robot Framework's Open Browser method
has answer: http://stackoverflow.com/a/50045332
tagged with: python
tagged with: selenium-webdriver
type: Question
tagged with: selenium-chromedriver
tagged with: robotframework

http://stackoverflow.com/q/49966917
favorite count: 0
type: Question
has body: I have a friend who uses Python and TensorFlow to build machine learning models. I want to use it in my website that has backend in nodejs. Is there a way to incorporate a TensorFlow built and trained model into a JavaScript code so that I can provide machine learning based services on my website?
has title: Is there a way to use TensorFlow models in my website from JavaScript?
upvote count: 8
tagged with: machine-learning
downvote count: 5
tagged with: python
tagged with: keras
accepted answer: http://stackoverflow.com/a/49967220
tagged with: node.js
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49967220
has comment: http://stackoverflow.com/comment/86950169
score: 3
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/136843549
comment on: http://stackoverflow.com/a/68546179
type: AnswerComment
has text: Notebooks are good for story telling. They are not production tools. Very inefficient when you have multiple files and many more.
score: 2
type: Comment

http://stackoverflow.com/comment/86935275
comment on: http://stackoverflow.com/q/49959184
type: Comment
type: QuestionComment
has text: @AleksandrBaranov You also need to pass in request to your authenticate method. It should return True if user exists, is_active and supplies correct password and false otherwise.
score: 0

http://stackoverflow.com/comment/87106417
type: Comment
comment on: http://stackoverflow.com/q/50044373
type: QuestionComment
has text: @abukaj Thanks for the tip. I guess I've got what I wanted to know.
score: 0

http://stackoverflow.com/a/50032622
answers question: http://stackoverflow.com/q/50002449
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: Theory Take a look at the Odoo Documentatio for computed fields total = fields.Float(compute='_compute_total') @api.multi @api.depends('value', 'tax') def _compute_total(self): for record in self: record.total = record.value + record.value * record.tax As you can see you need to add the dependencies to trigger the computed method and update the value. The fields value and tax are in the same model in this case. So if you are using fields from the same model or related to that model, the store=True is going to work well . So you should connect the fields by relations if it is possible. Solution In your case you need to create an one2many field to relate the tables. Check if the following code works for you: class ResPartner(models.Model): _inherit = 'res.partner' pos_order_total = fields.Float( string='POS Order Total', compute='_compute_pos_order_total', store=True ) pos_order_ids = fields.One2many( string=u'POS Orders', comodel_name='pos.order', inverse_name='partner_id', ) @api.multi @api.depends('pos_order_ids.amount_total') def _compute_pos_order_total(self): for partner in self: total = 0.0 for order in partner.pos_order_ids: total += order.amount_total partner.pos_order_total = total
score: 3
accepted answer of: http://stackoverflow.com/q/50002449
type: Answer

http://stackoverflow.com/comment/87122964
type: QuestionComment
has text: @LucaAmerio You get downvotes because you have not shown what you have tried, although the code you have does not work the same you have to place it but we assume that you want us to do your work, read [ask] and http://idownvotedbecau.se/noattempt/.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50053275

http://stackoverflow.com/q/50007960
has answer: http://stackoverflow.com/a/50008092
tagged with: orm
linked to: http://stackoverflow.com/q/33775011
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Conditional Expression in Django 1.11
tagged with: postgresql
has body: I have 3 models: Product, Brand, Shop. I want to count Products which are available for Brands in the given Shop. For example: Adidas 50 Puma 25 Now I have: queryset = Brand.objects .filter(brand_id__in=id_list) .order_by('brand_name') queryset = queryset.annotate(amount_of_products=Count('products')) But this gives me an amount of products from all shops. I have tried like here: queryset = queryset.annotate( amount_of_products=Count( Case(When(shops__shop_name__in=[shop], then=1)) )) But I get an amount_of_products = 1 for every Brand in the list. Is there a way to do this conditional expression in Django 1.11?
score: 0

http://stackoverflow.com/a/50003347
answers question: http://stackoverflow.com/q/49963153
has comment: http://stackoverflow.com/comment/87090427
has comment: http://stackoverflow.com/comment/87085198
score: 0
has comment: http://stackoverflow.com/comment/87069636
has comment: http://stackoverflow.com/comment/87090381
has body: Try this without recursion: final_list = [] desired_pattern = (words[0][-3:-1], 0, True) for word in words[1:]: if word[1:3] == desired_pattern[0]: if desired_pattern[2]: final_list.append(words[desired_pattern[1]]) final_list.append(word) desired_pattern = (word[-3:-1], words.index(word), False) else: if desired_pattern[2]: desired_pattern = (word[-3:-1], words.index(word), True) Some helps: words is your starting list final_list is your desired result desired_pattern is the expected two letters from other words Update me if you need anything.
type: Answer
has comment: http://stackoverflow.com/comment/87072865
has comment: http://stackoverflow.com/comment/87092259

http://stackoverflow.com/q/50006321
linked to: http://stackoverflow.com/q/23028664
type: UnansweredQuestion
tagged with: iframe
has body: I need scrape the contents of an iframe using python. As the web-page loads it submits a request and gets the content of the iframe in the response. When I use BeautifulSoup to get the data it just gives the initial blank iframe contents. Is there any way I can get the contents? If so, how do I do it in my case? Here is my code: import requests from bs4 import BeautifulSoup page = requests.get("https://etherscan.io/token/0x168296bb09e24a88805cb9c33356536b980d3fc5#balances" + "/token/generic-tokenholders2?a=0x168296bb09e24a88805cb9c33356536b980d3fc5&amp;amp;s=100000000000000000", headers={"content-type":"type"}, timeout=5) soup = BeautifulSoup(page.content, "html.parser") balances = soup.find(id="balances") print(balances.prettify()) table_items = balances.find_all('tr') #I'm trying to collect all the &lt;tr&gt; tags inside an &lt;iframe&gt; print(table_items) #It shows an empty list because the &lt;iframe&gt; didn't load
answer count: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50006588
type: Question
tagged with: beautifulsoup
tagged with: python-3.x
has title: Can't load contents of an iframe with Python
tagged with: python
score: 0

http://stackoverflow.com/q/50072643
type: Question
has comment: http://stackoverflow.com/comment/87163220
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87162021
has comment: http://stackoverflow.com/comment/87162012
answer count: 1
has title: Python file parsing, can't catch strings in new line
downvote count: 0
has comment: http://stackoverflow.com/comment/87162004
tagged with: python
has comment: http://stackoverflow.com/comment/87161966
has comment: http://stackoverflow.com/comment/87161987
has body: So Parsing a large text file with 56,900 book titles with authors and a etext no. Trying to find the authors. By parsing the file. The file is a like this: TITLE and AUTHOR ETEXT NO. Aspects of plant life; with special reference to the British flora, 56900 by Robert Lloyd Praeger The Vicar of Morwenstow, by Sabine Baring-Gould 56899 [Subtitle: Being a Life of Robert Stephen Hawker, M.A.] Raamatun tutkisteluja IV, mennessä Charles T. Russell 56898 [Subtitle: Harmagedonin taistelu] [Language: Finnish] Raamatun tutkisteluja III, mennessä Charles T. Russell 56897 [Subtitle: Tulkoon valtakuntasi] [Language: Finnish] Tom Thatcher's Fortune, by Horatio Alger, Jr. 56896 A Yankee Flier in the Far East, by Al Avery 56895 and George Rutherford Montgomery [Illustrator: Paul Laune] Nancy Brandon's Mystery, by Lillian Garis 56894 Nervous Ills, by Boris Sidis 56893 [Subtitle: Their Cause and Cure] Pensées sans langage, par Francis Picabia 56892 [Language: French] Helon's Pilgrimage to Jerusalem, Volume 2 of 2, by Frederick Strauss 56891 [Subtitle: A picture of Judaism, in the century which preceded the advent of our Savior] Fra Tommaso Campanella, Vol. 1, di Luigi Amabile 56890 [Subtitle: la sua congiura, i suoi processi e la sua pazzia] [Language: Italian] The Blue Star, by Fletcher Pratt 56889 Importanza e risultati degli incrociamenti in avicoltura, 56888 di Teodoro Pascal [Language: Italian] The Junior Classics, Volume 3: Tales from Greece and Rome, by Various 56887 ~ ~ ~ ~ Posting Dates for the below eBooks: 1 Mar 2018 to 31 Mar 2018 ~ ~ ~ ~ TITLE and AUTHOR ETEXT NO. The American Missionary, Volume 41, No. 1, January, 1887, by Various 56886 Morganin miljoonat, mennessä Sven Elvestad 56885 [Author a.k.a. Stein Riverton] [Subtitle: Salapoliisiromaani] [Language: Finnish] "Trip to the Sunny South" in March, 1885, by L. S. D 56884 Balaam and His Master, by Joel Chandler Harris 56883 [Subtitle: and Other Sketches and Stories] Susien saaliina, mennessä Jack London 56882 [Language:…
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87161999
accepted answer: http://stackoverflow.com/a/50073404
has answer: http://stackoverflow.com/a/50073404
upvote count: 3
favorite count: 0

http://stackoverflow.com/q/50069553
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50069622
tagged with: msvcrt
tagged with: windows
downvote count: 0
has body: Im writting a simple python code that should detect the my keystrokes but for some reason in detects space after everysingle keystroke. The code: import msvcrt print("press 'escape' to quit...") text="" while 1: char = msvcrt.getch() print(ord(char)) Sample run: Input: aaaaa Output: 97 0 97 0 97 0 97 0 97 0
has comment: http://stackoverflow.com/comment/87155587
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
tagged with: getch
answer count: 1
tagged with: python
has title: msvcrt.getch() detects space every time
accepted answer: http://stackoverflow.com/a/50069622

http://stackoverflow.com/q/50034397
type: Question
linked to: http://stackoverflow.com/q/3997525
has comment: http://stackoverflow.com/comment/87085692
has comment: http://stackoverflow.com/comment/87085063
has comment: http://stackoverflow.com/comment/87084918
has comment: http://stackoverflow.com/comment/87084895
has comment: http://stackoverflow.com/comment/87084952
score: -2
has comment: http://stackoverflow.com/comment/87085760
tagged with: python
tagged with: regex
duplicate of: http://stackoverflow.com/q/3997525
has comment: http://stackoverflow.com/comment/87084933
has comment: http://stackoverflow.com/comment/87085185
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50034476
has body: I am trying to change all strings of the type a.b to a. b. It should also work if any of the characters are capital case. Note that a. should not be changed to a.\(space). I have tried using regex to do this like so: a = "a.b" a = re.sub(r'[a-b]\.[a-b]', ' .', a) The output should be a. b, but it is ., because it replaces all the characters as well, instead of keeping the characters and just putting a space after the dot. Does anyone know how to do this in Python? Edit: I am trying to add a space when there is a period in between two sentences. However, I can't use str.replace, since it would add a space in this case also, like 1.5 becoming 1. 5, which is not what I want. I tried to do regex, but wasn't able to get it to work. Also, this has to work in all possible sentences, not just a.b
has comment: http://stackoverflow.com/comment/87085020
has title: Regex replace `a.b` to `a. b`?
upvote count: 0
has answer: http://stackoverflow.com/a/50034476
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87085756
favorite count: 0

http://stackoverflow.com/a/50005561
type: Answer
has body: Probably you should use some SQL parser for this. But you can try to solve this with regular expressions which are probably not the best tool for this type of problem. Here is an example (check the comments to see what the code is doing): import re sql = "SELECT '-' || IPC.ITEM AS ITEM, IPC.first_name||' '||ISA.last_name, IPC.NAME, '0' || IPC.BAR AS DEA " \ "FROM IpcDetails IPC JOIN IsaDetails ISA ON IPC.ItemId = ISA.ItemId;" \ "SELECT '-' || IPC.ITEM, IPC.first_name||' '||ISA.last_name, IPC.NAME, '0' || IPC.BAR, IPC.FOO || '_BAR' || 'TEST' AS DEA " \ "FROM IpcDetails IPC JOIN IsaDetails ISA ON IPC.ItemId = ISA.ItemId" # Split all selects selects = (re.findall(r'SELECT(.+?)FROM(.+?)(;|$)', sql, re.IGNORECASE)) for select in selects: origFields = select[0] fieldList = [] # Split fields : not great to use split here as there might be commas inside of strings for field in origFields.split(","): # Split the field and the alias fieldAndAlias = re.search('(.+?)(\sAS.+|$)', field, re.IGNORECASE) if fieldAndAlias.group(1).find("||") &gt; -1: # Check if we should do the transformation from || to CONCAT() concat = "CONCAT(%s)" % ",".join(fieldAndAlias.group(1).split("||")) concat += fieldAndAlias.group(2) fieldList.append(concat) else: # Field where no concat to be done fieldList.append(field) # Put everthing back again. newSQL = "SELECT %s FROM %s" % (",".join(fieldList), select[1]) print(newSQL) If you run this script you will see this printed out on the console: SELECT CONCAT( '-' , IPC.ITEM) AS ITEM,CONCAT( IPC.first_name,' ',ISA.last_name), IPC.NAME,CONCAT( '0' , IPC.BAR) AS DEA FROM IpcDetails IPC JOIN IsaDetails ISA ON IPC.ItemId = ISA.ItemId SELECT CONCAT( '-' , IPC.ITEM),CONCAT( IPC.first_name,' ',ISA.last_name), IPC.NAME,CONCAT( '0' , IPC.BAR),CONCAT( IPC.FOO , '_BAR' , 'TEST') AS DEA FROM IpcDetails IPC JOIN IsaDetails ISA ON IPC.ItemId = ISA.ItemId This solution does not deal with sub selects and also aliases without the "AS" keyword. So yes: you need a proper SQL…
score: 0
answers question: http://stackoverflow.com/q/50002258

http://stackoverflow.com/a/49996711
has comment: http://stackoverflow.com/comment/87010274
type: Answer
has body: You can use combinations from itertools, that it's a python standard library, and it will help you to to remove all those nested loops. from itertools import combinations import numpy as np n = 100 np.random.seed(2) A = np.random.rand(n,n) global_best = 1000000000000000.0 for i, j, k in combinations(range(n), 3): local_best = np.amax(np.array([A[i,:], A[j,:], A[k,:]]).min(0)) if local_best &lt; global_best: global_best = local_best save_rows = [i, j, k] print global_best, save_rows
answers question: http://stackoverflow.com/q/49993101
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/50056785
linked to: http://stackoverflow.com/q/48566577
has title: CalledProcessError in tabula -py with java 1.8
has comment: http://stackoverflow.com/comment/87640021
tagged with: tabula
answer count: 3
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/50347106
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/58497979
has answer: http://stackoverflow.com/a/50117506
linked to: http://stackoverflow.com/q/29697543
type: UnansweredQuestion
has body: I am trying to extract table from a pdf using tabula -py in python.But I am getting CalledProcessError from tabula import read_pdf df=read_pdf("table.pdf",pages="all") Error: CalledProcessError: Command '['java', '-jar', 'C:\\ProgramData\\Anaconda2\\lib\\site-packages\\tabula\\tabula-1.0.1-jar- with-dependencies.jar', '--pages', 'all', '--guess', 'table.pdf']' returned non-zero exit status 2 Java Version : 1.8.0_131 OS - windows 7 This question (tabula-py CalledProcessError: Command '['java', '-jar') suggests upgrading to java 1.8.However, I already have java 1.8, but still getting the error. Any help on this will be really appreciated. Thanks !
tagged with: python

http://stackoverflow.com/comment/87018333
type: Comment
has text: you can use separte conf file
score: 0
comment on: http://stackoverflow.com/a/49999585
type: AnswerComment

http://stackoverflow.com/q/49995592
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87007945
score: 0
has comment: http://stackoverflow.com/comment/87021938
answer count: 0
has title: Flask redirect doesn't actually take user to a different page
has comment: http://stackoverflow.com/comment/87009154
has comment: http://stackoverflow.com/comment/87007754
tagged with: flask
type: Question
has body: 'main' is just my homepage and '/' is the url. For some reason, I can't get signUp to return back to the homepage after finishing. I can also confirm 'here' and 'Registered' get printed. Also, in my terminal, i get 127.0.0.1 - - [23/Apr/2018 23:13:51] "GET / HTTP/1.1" 200 - Which means it SHOULD be going to home, because I get the same line when I just click the home link on the page through html. Clicking the link redirects too. It also is the same path '/', so I'm not sure why it works with html but not with flask when I know the redirect gets acknowledged. What happens with the flask is it just stays on the signup page. Nothing else, no errors thrown. Just sits there. I was even able to do redirect('main', code=307) and it actually ran code on the main page. So why wouldn't this simple redirect render Senty.html and take the user to the page? @app.route("/") def main(): return render_template('Senty.html') @app.route('/signUp',methods=['POST','GET']) def signUp(): # still need to create signup class and transfer below code to new file conn = mysql.connect() cur = conn.cursor() try: _name = request.form['inputName'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] # validate the received values if _name and _email and _password: cur.callproc('sp_createUser',(_name,_email,_password,)) print ("Registered") data = cur.fetchall() conn.commit() json.dumps({'message':'User created successfully !'}) print('here') return redirect(url_for('main')) #else: #return json.dumps({'html':'Enter the required fields'}) #except Exception as e: #return json.dumps({'error':str(e)}) finally: cur.close() conn.close() return redirect(url_for('main')) I'm not sure where to go. I feel like I've tried everything. Here is also the HTML Senty App Name Email address Password Sign up
tagged with: python

http://stackoverflow.com/q/49968623
has comment: http://stackoverflow.com/comment/86953189
type: Question
possible better answer: http://stackoverflow.com/a/49968929
has body: I am trying to modify (align sentences in a document) a text in a file using python. I tried the following approach with no success. I don't care if the txt is modified or I can get python to read the aligned sentences in the console. Regardless if I use w or r I get an error. The document contains the following text: "Hello world. Goodbye world." document = open("text.txt", "w") def sentence_separator(document): sentences = document.split(". ") return "\n".join(sentences) document.close() The desired output or text modification is: Hello world Goodbye world Any suggestions? Appreciate it.
accepted answer: http://stackoverflow.com/a/49968672
has answer: http://stackoverflow.com/a/49968929
has answer: http://stackoverflow.com/a/49968672
has title: Aligning sentences in a text.txt file using open() function and str.join and split method
tagged with: python
has comment: http://stackoverflow.com/comment/86953170
has comment: http://stackoverflow.com/comment/86953371
has comment: http://stackoverflow.com/comment/86953365
type: AnsweredQuestion
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/86953056

http://stackoverflow.com/a/49992422
score: 48
answers question: http://stackoverflow.com/q/49992329
type: Answer
upvote count: 48
has body: Suddenly... I found why. According to much more source code of ThreadPoolExecutor: # Workers are created as daemon threads. This is done to allow the interpreter # to exit when there are still idle threads in a ThreadPoolExecutor's thread # pool (i.e. shutdown() was not called). However, allowing workers to die with # the interpreter has two undesirable properties: # - The workers would still be running during interpreter shutdown, # meaning that they would fail in unpredictable ways. # - The workers could be killed while evaluating a work item, which could # be bad if the callable being evaluated has external side-effects e.g. # writing to a file. # # To work around this problem, an exit handler is installed which tells the # workers to exit when their work queues are empty and then waits until the # threads finish. _threads_queues = weakref.WeakKeyDictionary() _shutdown = False def _python_exit(): global _shutdown _shutdown = True items = list(_threads_queues.items()) for t, q in items: q.put(None) for t, q in items: t.join() atexit.register(_python_exit) There is an exit handler which will join all unfinished worker...
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/139961223
accepted answer of: http://stackoverflow.com/q/49992329
has comment: http://stackoverflow.com/comment/107703674
has comment: http://stackoverflow.com/comment/138327186

http://stackoverflow.com/q/49944614
answer count: 2
downvote count: 0
has body: I have followed the tutorial for installing Geodjango on my Ubuntu. I am using Django 1.11.2 and Python 2.7.6, postgres-9.3.2 and postgis 2.0.3. I have checked here and here, but found no solution. But after my installation, when I tried to run, I got error: OSError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name lgdal = CDLL(lib_path) self._handle = _dlopen(self._name, mode)
has title: OSError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name
favorite count: 0
type: Question
tagged with: postgresql
has comment: http://stackoverflow.com/comment/95475136
linked to: http://stackoverflow.com/q/41521577
tagged with: geodjango
has comment: http://stackoverflow.com/comment/86933481
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/62947475
tagged with: django
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86906235
tagged with: postgis
has answer: http://stackoverflow.com/a/76855118
upvote count: 4

http://stackoverflow.com/a/49950655
has body: If it's a class method of the same class, you have to use ClassName.factorial(), or self.factorial(...) if it is a method.
upvote count: 3
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49950649
type: Answer

http://stackoverflow.com/comment/86876886
type: Comment
has text: That makes it seem as though when calling x['name'] it is attempting to index a list rather than a dictionary.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49929796

http://stackoverflow.com/comment/87040964
has text: Count the zero-crossings of the derivative
score: 0
comment on: http://stackoverflow.com/q/50012089
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87073103
type: QuestionComment
comment on: http://stackoverflow.com/q/50028427
has text: That's why I asked! It was an example I saw somewhere else. I was just trying different things. I get the same error using `data['features']['id'][0]['properties'][0]['geocode'][0]`
score: 0
type: Comment

http://stackoverflow.com/q/49990812
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50277021
has title: Optimize three nested for-loops iterating through 2 dataframes of IP addresses?
has comment: http://stackoverflow.com/comment/86999585
tagged with: python
has answer: http://stackoverflow.com/a/49991259
linked to: http://stackoverflow.com/q/40185170
has comment: http://stackoverflow.com/comment/87000452
has comment: http://stackoverflow.com/comment/86999570
has comment: http://stackoverflow.com/comment/86998661
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/86998684
linked to: http://stackoverflow.com/q/41627920
has comment: http://stackoverflow.com/comment/86999657
linked to: http://stackoverflow.com/q/30838776
has comment: http://stackoverflow.com/comment/86999217
has comment: http://stackoverflow.com/comment/86998706
linked to: http://stackoverflow.com/q/10283703
has comment: http://stackoverflow.com/comment/86999558
possible better answer: http://stackoverflow.com/a/49991259
score: -3
upvote count: 1
tagged with: ip-address
has comment: http://stackoverflow.com/comment/86999265
has comment: http://stackoverflow.com/comment/86999670
has comment: http://stackoverflow.com/comment/86999703
has comment: http://stackoverflow.com/comment/86999135
has comment: http://stackoverflow.com/comment/86998608
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86998302
accepted answer: http://stackoverflow.com/a/50277021
has comment: http://stackoverflow.com/comment/86999778
has body: I have 2 CSV files. One with Hostnames and IPs. The second with IP information (Netmask, Cidr, Subnet Name etc..) I currently have a situation like the following. for i, ipAddress in CSV1: for j, ipNetwork in CSV2: if ipAddress in ipNetwork: append ipNetwork['Subnet Name'] Unfortunately, the first csv has 9000 IPs and the second list has 30'000 subnets. This is taking a huge amount of time to iterate through. I know this was an awful way of implementing this but I knew I could always improve. Can anyone advise how better I can solve this problem? How can I search through and compare elements in each to shorten the runtime of this script? Here is the sample data [CSV 1 - Sample IP] IP Address 144.196.86.89 56.144.25.138 3.16.101.238 123.18.128.50 19.22.2.124 78.88.241.163 144.44.200.20 27.215.172.218 124.90.163.19 [CSV 2 - Sample Subnet Information] address netmask Company Subnet Name Compartment Type cidr 10.2.1.0 255.255.255.0 UPS UPS Site 1 Desktop 10.2.1.0/24 10.2.2.0 255.255.255.0 UPS UPS Site 2 Desktop 10.2.2.0/24 10.2.3.0 255.255.255.0 UPS UPS Site 3 Desktop 10.2.3.0/24 10.2.4.0 255.255.255.0 UPS UPS Site 4 Desktop 10.2.4.0/24 10.2.5.0 255.255.255.0 UPS UPS Site 5 Desktop 10.2.5.0/24 10.2.6.0 255.255.255.0 UPS UPS Site 6 Desktop 10.2.6.0/24 10.2.7.0 255.255.255.0 UPS UPS Site 7 Desktop 10.2.7.0/24 10.2.8.0 255.255.255.0 UPS UPS Site 8 Desktop 10.2.8.0/24 10.2.10.0 255.255.254.0 UPS UPS Site 9 Desktop 10.2.10.0/23 10.2.12.0 255.255.255.0 UPS UPS Site 10 Desktop 10.2.12.0/24 10.2.13.0 255.255.255.0 UPS UPS Site 11 Desktop 10.2.13.0/24

http://stackoverflow.com/q/49990473
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49991425
type: Question
downvote count: 2
type: UnansweredQuestion
score: -2
answer count: 1
has body: "The point of this code is to input a list of integers as strings and have the output be a list of integers, thus allowing the user to find the average. I can't seem to understand why it is not working, I keep getting splitting issues" def is_integer(s): if s == s.isdigit(): return True else: return False def are_all_integers(strs): for s in strs.split(","): if s == s.isdigit: return True else: return False def strs_to_num(strs): integers = [] for s in strs: integers.append(int(s)) return integers def get_ints(): list_of_integers = [] s = input("Enter some digits: ") s = s.split() while (len(s) &lt; 2) and (are_all_integers(s) is False): s = input("invalid input, try again: ") for integer in s: strs_to_num(integer) list_of_integers.append(integer) return list_of_integers def main(): s = get_ints() avg = sum(s)/len(s) print(sum(s)) print(len(s)) print("The average of these numbers are", avg) main()
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86999161
has comment: http://stackoverflow.com/comment/86997789
has title: using a function to turn a list of strings separated by commas into integers

http://stackoverflow.com/comment/87410047
has text: hi @Dark, pls help https://stackoverflow.com/questions/50196539/finding-shortest-values-between-the-cities-in-a-dataframe
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50002385
type: AnswerComment

http://stackoverflow.com/comment/86914713
type: Comment
type: QuestionComment
has text: It is not a list in Python. Try dictionary in Python.
comment on: http://stackoverflow.com/q/49949078
score: 2

http://stackoverflow.com/comment/86914926
has text: Thank you very much, wim! That works like a charm :)
type: Comment
comment on: http://stackoverflow.com/a/49949120
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86923012
comment on: http://stackoverflow.com/q/49952933
type: Comment
type: QuestionComment
has text: I mean assigning my list to another list dude! Something like b = a
score: 0

http://stackoverflow.com/comment/86955589
has text: I think all the formatting parameters are documented. To make bigger changes you have to dig into the code, and construct modified formatters subclasses. `RawTextHelpFormatter` for example, modifies a couple of deeply buried methods to turn off line wrapping in the help lines. The code is sufficiently modular that you can make a lot of changes, but it requires some study.
type: QuestionComment
comment on: http://stackoverflow.com/q/49969605
score: 1
type: Comment

pygame
tags question: http://stackoverflow.com/q/50033695
tags question: http://stackoverflow.com/q/49952200
tag name: pygame
tags question: http://stackoverflow.com/q/49957653
tags question: http://stackoverflow.com/q/50066152
tags question: http://stackoverflow.com/q/49929284
tags question: http://stackoverflow.com/q/49991443
tags question: http://stackoverflow.com/q/50073397
tags question: http://stackoverflow.com/q/49950710
tags question: http://stackoverflow.com/q/50048841
tags question: http://stackoverflow.com/q/49957509
tags question: http://stackoverflow.com/q/50068976
tags question: http://stackoverflow.com/q/50058459
tags question: http://stackoverflow.com/q/50049642
tags question: http://stackoverflow.com/q/49966159
tags question: http://stackoverflow.com/q/50023533
tags question: http://stackoverflow.com/q/50009351
tags question: http://stackoverflow.com/q/49954039
tags question: http://stackoverflow.com/q/49987072
tags question: http://stackoverflow.com/q/49922205
tags question: http://stackoverflow.com/q/50006537
tags question: http://stackoverflow.com/q/49941881
tags question: http://stackoverflow.com/q/50013241
tags question: http://stackoverflow.com/q/50016131
tags question: http://stackoverflow.com/q/50036820
tags question: http://stackoverflow.com/q/50009478
tags question: http://stackoverflow.com/q/50043740
tags question: http://stackoverflow.com/q/50043285
type: Tag

http://stackoverflow.com/q/50064449
score: -1
tagged with: dictionary
has title: How to retreive paticular data from dictionary in python
answer count: 2
has body: I have a dictionary product_list = {'Name': ['Milk, 2 Litres', 'Bread', 'Sugar', 'Apple'], 'Price': ['2.0', '3.5', '3.0', '4.5'], 'weight': ['2', '0.6', '2.8', '4.2']} &lt;br/&gt; Now the Question is &lt;br/&gt; class Weightcheck:&lt;br/&gt; def bag_products(product_list):&lt;br/&gt; bag_list = []&lt;br/&gt; non_bag_items = []&lt;br/&gt; MAX_BAG_WEIGHT = 5.0&lt;br/&gt; for product in product_list: if product.weight &gt; MAX_BAG_WEIGHT: product_list.remove(product) non_bag_items.append(product) Whenever I pass an argument to the function as, demo = Weightcheck() demo.bag_products(product_list) I get this error: TypeError: bag_products() takes 1 positional argument but 2 were given
downvote count: 1
has answer: http://stackoverflow.com/a/50064510
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50065408
has comment: http://stackoverflow.com/comment/87148729
type: UnansweredQuestion
upvote count: 0
tagged with: python

http://stackoverflow.com/comment/87156145
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50069422
has text: @HarvIpan, for future reference if you type `[MCVE]` into the comments, it automatically creates the following link for you: [MCVE]. Might save you some typing in the future!

http://stackoverflow.com/a/50043503
type: Answer
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50043308
has body: There are several ways how to add a different quantity of numbers. First of all, you can just use a list and built-in function sum: sum([1, 2, 3]) If you wouldn't like to use a list, try to write a custom wrapper on built-in sum function (it is good practice to not override the built-in names): def my_sum(*args): return sum(args) my_sum(1, 2, 3) Also, such usage is possible: my_sum(2) # result is 2 my_sum() # result is 0 But if you want a function, that takes minimum two arguments, try following: def my_sum(num1, num2, *args): return num1 + num2 + sum(args) my_sum(1, 2, 3)

http://stackoverflow.com/comment/87156244
comment on: http://stackoverflow.com/a/50069837
type: Comment
has text: It might also be a better idea to use a `for`-loop or a generator expression in combination with `next` here. Now you need to build the entire list just to get the first match.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49932964
favorite count: 0
has body: So I couldn't find any mention of this anywhere. Maybe I'm just looking for the wrong thing or the answer is so obvious that I just somehow missed it. I started working with two-dimensional arrays, but I can't find any mention of a method to entirely remove a list element from a list. Basically, I want to remove a row from a table, this is the code I'm working with; employeeTable = [[2, 4, 3, 4, 5, 8, 8], [7, 3, 4, 3, 3, 4, 4], [3, 3, 4, 3, 3, 2, 2], [9, 3, 4, 7, 3, 4, 1], [3, 5, 4, 3, 6, 3, 8], [3, 4, 4, 6, 3, 4, 4], [3, 7, 4, 8, 3, 8, 4], [6, 3, 5, 9, 2, 7, 9]] highestValue = 0 highestEmployee = 0 while employeeTable: for i in range(len(employeeTable)) if sum(employeeTable[i]) &gt; highestValue: highestValue = sum(employeeTable[i]) highestEmployee = i print("Employee " + highestEmployee + " has " + highestValue + " hours this week.") And after each for loop finishes, I would like to remove one of the 8 rows from the list and loop again. I am aware that I can probably pop the top row from the list, but I am more trying to figure out if there is a way to remove a specific row instead.
type: Question
has comment: http://stackoverflow.com/comment/86881711
tagged with: arrays
linked to: http://stackoverflow.com/q/627435
tagged with: python
type: UnansweredQuestion
answer count: 1
has title: Can I remove a list element from a two-dimensional list?
has answer: http://stackoverflow.com/a/49933051
has comment: http://stackoverflow.com/comment/86881764
tagged with: list
duplicate of: http://stackoverflow.com/q/627435
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/49959779
upvote count: 4
has comment: http://stackoverflow.com/comment/86935861
type: Answer
has comment: http://stackoverflow.com/comment/86935884
score: 4
accepted answer of: http://stackoverflow.com/q/49959715
answers question: http://stackoverflow.com/q/49959715
type: AcceptedAnswer
downvote count: 0
has body: '\n'.join(map(str.__add__, a.split('\n'), b.split('\n'))) You can also replace .split('\n'), with .splitlines(), not sure if that will make it faster. Note that in your own code, the list(...) is not needed, join accepts any iterable.

apache
tags question: http://stackoverflow.com/q/50016673
tags question: http://stackoverflow.com/q/50048806
tag name: apache
tags question: http://stackoverflow.com/q/49926103
tags question: http://stackoverflow.com/q/49938391
tags question: http://stackoverflow.com/q/49964550
tags question: http://stackoverflow.com/q/50020768
type: Tag
tags question: http://stackoverflow.com/q/50013067
tags question: http://stackoverflow.com/q/50039355
tags question: http://stackoverflow.com/q/49975783

http://stackoverflow.com/comment/86940212
score: 0
has text: could you post the python files inside the directory containing your receipt.py
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49961974

http://stackoverflow.com/comment/86857850
has text: Could you just take the `id` of the object itself using the [`id` function](https://docs.python.org/3/library/functions.html#id)?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49921057
type: Comment

http://stackoverflow.com/q/50000520
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/87017699
tagged with: list
has answer: http://stackoverflow.com/a/50000887
tagged with: matrix
score: 1
linked to: http://stackoverflow.com/q/240178
has answer: http://stackoverflow.com/a/50000929
has comment: http://stackoverflow.com/comment/87017620
has comment: http://stackoverflow.com/comment/87017208
has comment: http://stackoverflow.com/comment/87017335
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/87017406
type: Question
has comment: http://stackoverflow.com/comment/87017754
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87017352
has comment: http://stackoverflow.com/comment/87017475
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/993984
upvote count: 1
tagged with: python
has body: For a given list of tuples L whose elements are taken from range(n), I want to create A binary matrix A of order n in the following way: If (i,j) or (j,i) in L then A[i][j]=1 otherwise A[i][j]=0. Let us consider the following example: L=[(2,3),(0,1),(1,3),(2,0),(0,3)] A=[[0]*4]*4 for i in range(4): for j in range(4): if (i,j) or (j,i) in L: A[i][j]=1 else: A[i][j]=0 print A This program does not give the accurate result. Where is the logical mistake occurred?
has title: How to create a binary matrix with some given condition below:

http://stackoverflow.com/q/50022951
answer count: 1
has comment: http://stackoverflow.com/comment/87068036
has answer: http://stackoverflow.com/a/50025348
type: AnsweredQuestion
score: 0
has title: Python curve_fit with measured data points
has comment: http://stackoverflow.com/comment/87061952
has comment: http://stackoverflow.com/comment/87062546
has comment: http://stackoverflow.com/comment/87066112
downvote count: 1
has body: I have measured data points, I want to fit against a formula to determine two entities. However I get the error : TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' produced by the following python code (I use version 3): import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def func(T, fun, Tc): return fun*np.sqrt(np.cos(np.pi/2*(T/Tc)^2)) xdata=(4.61, 4.89, 4.92, 4.95, 5.06, 5.10, 5.21, 5.38, 5.41, 5.57, 5.80, 6.14, 6.61, 7.27, 7.66, 7.90, 8.91, 8.29, 8.23, 7.30, 7.86, 8.30, 8.89, 8.99, 9.24, 9.35, 9.50, 8.77, 8.27, 8.37, 7.72, 7.57, 7.99, 8.13) # these are temperature values &lt;-&gt; T ydata=(2.85, 2.84, 2.83, 2.825, 2.82, 2.81, 2.80, 2.765, 2.76, 2.74, 2.695, 2.62, 2.50, 2.265, 2.105, 1.975, 1.23, 1.75, 1.81, 2.26, 2.005, 1.75, 1.31, 1.14, 1.015, 1.045, 1.06, 1.40, 1.75, 1.69, 2.075, 2.15, 1.93, 1.855) # these are energy values &lt;-&gt; func popt, pcov = curve_fit(func, xdata, ydata) popt #display these optimized values Here comes the above error!!! I saw a way to do it if you have a fixed formula and add some noise, but I have measured data points (they must be discrete). Thank you! Carsten
has comment: http://stackoverflow.com/comment/87062649
favorite count: 0
has comment: http://stackoverflow.com/comment/87072914
accepted answer: http://stackoverflow.com/a/50025348
has comment: http://stackoverflow.com/comment/87067908
tagged with: data-analysis
type: Question
tagged with: measurement
tagged with: curve-fitting
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87140934
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50061878
has text: ah found a better one. That said, I like this particular question. It's clear, as opposed to the questions linked. I may not have found the perfect dupe, but there _is_ one :)
type: Comment

fixed-width
tags question: http://stackoverflow.com/q/49970328
type: Tag
tag name: fixed-width
tags question: http://stackoverflow.com/q/50067957

http://stackoverflow.com/q/50065051
accepted answer: http://stackoverflow.com/a/50065108
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50065424
tagged with: python
has body: I wanna add list1=[1,2,3,4,5] and list2=[1,1,1,1,1,1,1] What I desired is like list3=[2,3,4,5,6,1,1] This is my wrong code lis1=[1,2,3,4,5] #len=5 list2=[1,1,1,1,1,1,1] #len=7 if len(list1)&gt;len(list2): for i in range(len(list1)): list2.append(0) if list2[i]=[] list3[i]=list1[i]+list2[i] else: for i in range(len(list2)): list1.append(o) if list1[i]=[] list3[i]=list1[i]+list2[i] print(list3)
type: Question
upvote count: 2
has title: Python) I wanna add two lists which are different order of len
tagged with: list
has answer: http://stackoverflow.com/a/50065108
answer count: 3
score: 1
downvote count: 1
tagged with: addition
has comment: http://stackoverflow.com/comment/87146770
favorite count: 0
has answer: http://stackoverflow.com/a/50065312
possible better answer: http://stackoverflow.com/a/50065312

http://stackoverflow.com/comment/87149111
type: QuestionComment
has text: please provide a example input, and the program's behaviour.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50066205

http://stackoverflow.com/comment/86853655
type: QuestionComment
comment on: http://stackoverflow.com/q/49917974
has text: Why are you joining back on `df`? To have the count repeated on each record?
score: 0
type: Comment

http://stackoverflow.com/comment/87077691
type: AnswerComment
has text: Thanks both (Marat and SuperStew), took that example and made some improvements
type: Comment
comment on: http://stackoverflow.com/a/50029934
score: 0

http://stackoverflow.com/comment/86863783
type: QuestionComment
has text: `return model.variables['var'][0,:,:]` ?
comment on: http://stackoverflow.com/q/49923934
score: 1
type: Comment

http://stackoverflow.com/q/49924607
has body: I'm trying to import a class from another script so I can run the class when a button is clicked in tkinter. The line of code I'm trying to run is: from tkinter import * import originalscript as desiredclass variable = desiredclass() When I try to run my code, the second line gives me an 'invalid syntax' error. The two files are in the same folder and I've looked at other threads regarding this problem, but most of them suggest this as the solution, however, this line is not working for me, so I'm wondering what I am doing wrong/what I am missing? The error code is: Syntax Error: invalid syntax: filepath.py, line 2, pos 10 import script as class
has comment: http://stackoverflow.com/comment/86865583
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49924916
tagged with: importerror
has answer: http://stackoverflow.com/a/49924916
has comment: http://stackoverflow.com/comment/86865812
answer count: 1
has comment: http://stackoverflow.com/comment/86865258
downvote count: 1
has title: Importing class from another script in tkinter GUI
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86865213
upvote count: 0
has comment: http://stackoverflow.com/comment/86865108
has comment: http://stackoverflow.com/comment/86865367
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86866146

http://stackoverflow.com/a/50053706
has comment: http://stackoverflow.com/comment/87124036
has body: The problem is that the QLabels are not showing, the main widget when displayed at the beginning makes your children show up, but after that it does not make them visible, as it is in your case, so your task is to call their method show() directly: def showObstacle(self, Obs_x, Obs_y): pixmap_obst = QtGui.QPixmap('obsta_edited.png') self.d.append("O{0}".format(self.obstCounter)) label = QtWidgets.QLabel(self) label.setPixmap(pixmap_obst) label.move(Obs_x, Obs_y) label.adjustSize() label.show() # &lt;---show QLabel self.d[self.obstCounter] = label self.obstCounter += 1 print(self.d) print("Obstacle Run")
upvote count: 2
answers question: http://stackoverflow.com/q/50053576
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87123990
has comment: http://stackoverflow.com/comment/87124011
type: Answer
has comment: http://stackoverflow.com/comment/87124081
accepted answer of: http://stackoverflow.com/q/50053576
has comment: http://stackoverflow.com/comment/87124061
score: 2

http://stackoverflow.com/a/49945849
type: Answer
answers question: http://stackoverflow.com/q/49945806
score: 3
upvote count: 3
type: AcceptedAnswer
has body: The problem seems to be that link.get('data-href) sometimes returns None. In order to catch these cases, use list_links = [link.get('data-href') for link in BSOBJ.find_all('a') if link.get('data-href') is not None] and there should be no more Nones in your list. If link itself can be None, you should of course keep filtering for this as well.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49945806

http://stackoverflow.com/comment/87038560
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50010748
type: Comment
has text: Have you tried the debugger? Also, what are we seeing? Is this the definition of `play_hand`?

http://stackoverflow.com/a/49946066
has comment: http://stackoverflow.com/comment/86909005
has comment: http://stackoverflow.com/comment/86912323
has comment: http://stackoverflow.com/comment/86912310
answers question: http://stackoverflow.com/q/49944345
has comment: http://stackoverflow.com/comment/86911285
has comment: http://stackoverflow.com/comment/86909150
has comment: http://stackoverflow.com/comment/86910365
downvote count: 0
has comment: http://stackoverflow.com/comment/86910661
has comment: http://stackoverflow.com/comment/86909016
upvote count: 1
has comment: http://stackoverflow.com/comment/86909086
has body: It would go something like this: res = df[df.Channel.isin(['A', 'B'])] for row in df[df.Channel.isin(['A', 'B'])].iterrows(): row_index = row[0]
has comment: http://stackoverflow.com/comment/86912298
has comment: http://stackoverflow.com/comment/86910841
has comment: http://stackoverflow.com/comment/86909111
has comment: http://stackoverflow.com/comment/86911122
has comment: http://stackoverflow.com/comment/86910945
has comment: http://stackoverflow.com/comment/86909321
score: 1
type: Answer

http://stackoverflow.com/comment/94345716
comment on: http://stackoverflow.com/a/49918386
has text: @MitchBuchanon you're not limited to splitting the text with `str.split()`, Counter will take any iterable as an argument. If you want to count tokens from a SpaCy doc object, then you can just call `freq = Counter(doc)`.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86886012
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49935001
has text: The error couldn't be any clearer. Have you tried `print(item)` before `num_list.append(int(item))`, or at least *Google* the error?

http://stackoverflow.com/q/49936431
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has body: I am using UBUNTU 16.04 and I have installer tensorflow and now i am trying to install the object detection API. I have cloned the API from git so it gave me a repository with the following tree: models/research/ From the research repo, i have following all the steps from the official git and i could run the test. Then after that i did: `sudo python setup.py install` I have also compiled from sources the protoc compiler to have the latest version: 3.5.1 I have collected my data and created the tf record and put them in a data repository. I put the config file in a training repository. And i copy th data, training and model file repository into the models/researches/object-detection/ then i tried to run the train.py script in order to and train with my own data but i get the following errors and i am really lost and maybe i did something wrong. Does someone has any idea? `python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_coco.config /usr/local/lib/python2.7/dist-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version. Instructions for updating: Use the retry module or similar alternatives. Traceback (most recent call last): File "train.py", line 167, in &lt;module&gt; tf.app.run() File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 126, in run _sys.exit(main(argv)) File "train.py", line 92, in main FLAGS.pipeline_config_path) File "/home/jimmy/Desktop/ObjectDetecAPI/models/research/object_detection/utils/config_util.py", line 92, in g…
tagged with: python
tagged with: object-detection
has answer: http://stackoverflow.com/a/50221164
score: 0
tagged with: deep-learning
answer count: 1
has title: tensorflow object detection API error to train

http://stackoverflow.com/q/49948198
has comment: http://stackoverflow.com/comment/87122228
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87004677
has comment: http://stackoverflow.com/comment/86995786
tagged with: slugify
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86915188
has title: How to add slug to flask blog app
tagged with: python
has comment: http://stackoverflow.com/comment/87084907
has answer: http://stackoverflow.com/a/65370107
has comment: http://stackoverflow.com/comment/86937892
has body: Recently I am trying to build a blog following Grinberg Miguel Flask mega tutorial. I got stocked when I try to slug my post title such that when it is clicked the detail will be displayed. This is my code: (models.py) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(225)) slug = db.Column(db.String(300)) body = db.Column(db.Text) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) def __repr__(self): return '&lt;Post {}&gt;'.format(self.body) @staticmethod def slugify (target, value, oldvalue, initiator): if value and (not target.slug or value != oldvalue): target.slug = slugify(value) db.event.listen(Post.title, 'set', Post.slugify, retval=False) my ROUTE code goes here: from app.models import Post @bp.route('/', methods=['GET', 'POST']) @bp.route('/index', methods=['GET', 'POST']) def index(): page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, current_app.config['POSTS_PER_PAGE'], False) next_url = url_for('main.explore', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('main.explore', page=posts.prev_num) \ if posts.has_prev else None return render_template('index.html', title=_('Home'), posts=posts.items, next_url=next_url, prev_url=prev_url) @bp.route('/explore',methods=['GET', 'POST']) @login_required def explore(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash(_('Your post is now live!')) return redirect(url_for('main.index')) return render_template('create.html', title=_('Create'),form=form) @bp.route('/&lt;slug&gt;') def detail(slug): posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, current_app.config['POSTS_PER_PAGE'], False) return render_template('detail.html', title=_('Home'), posts=posts.items, next_url=next_url, prev_url=prev_url…
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87053403
has comment: http://stackoverflow.com/comment/86953520
upvote count: 1
has comment: http://stackoverflow.com/comment/87113082
has comment: http://stackoverflow.com/comment/86948441

http://stackoverflow.com/comment/86971971
type: AnswerComment
comment on: http://stackoverflow.com/a/49975792
type: Comment
score: 0
has text: happy to help :)

http://stackoverflow.com/comment/86960610
has text: would love to hear the downvoters reason. This seems like the perfect solution.
score: 0
comment on: http://stackoverflow.com/a/49972270
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49996248
has comment: http://stackoverflow.com/comment/87008868
upvote count: 0
answer count: 2
downvote count: 3
has answer: http://stackoverflow.com/a/49996428
has answer: http://stackoverflow.com/a/49997689
has body: I have this command and need to execute my program in python curl -H 'Content-Type: application/x-ndjson' -XPOST '192.168.1.149:9200/shakespeare/doc/_bulk?pretty' --data-binary @file.json
has comment: http://stackoverflow.com/comment/87008933
has title: how execute curl command in python?
has comment: http://stackoverflow.com/comment/87008878
favorite count: 0
tagged with: python-3.x
type: Question
linked to: http://stackoverflow.com/q/89228
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87008908
score: -3
tagged with: typescript
tagged with: python-2.7

http://stackoverflow.com/q/49951072
has answer: http://stackoverflow.com/a/49951096
answer count: 3
accepted answer: http://stackoverflow.com/a/49951096
has title: How to take multiples inputs in a single line in python 3?
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/76511318
tagged with: python-3.x
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/63224091
possible better answer: http://stackoverflow.com/a/63224091
favorite count: 0
has body: I am trying to get multiple inputs in a single line in python. This are the kind of inputs I am trying to take, the first line consists of the number of lines of input I will take: 3 1 2 3 4 3 8 9 6 3 Is there any way to take that kind of input, without knowing how many inputs are going to be given per line?
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/86880602
type: QuestionComment
has text: Do not using picture here
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49932322

http://stackoverflow.com/q/49996077
score: 3
has body: I have a class for which I want to create instances through a function, but I also want to be able to name the instances with the value of a Tkinter.Entry widget. The simplified version of that I am trying to achieve is the following: class vtdiagram(): IO=0.0 IC=0.0 EO=0.0 EC=0.0 IGA=0.0 def printvtvalues(self): print self.IO print self.IC print self.EO print self.EC print self.IGA def createvtinstance(): global Nametemp Nametemp=vtdiagram() If I run this code, then I can call Nametemp.printvtvalues() and get all values printed, so it works fine. I am now trying to change the name of the instance Nametemp to the string that is on the Tkinter entry widget. Basically, if engine1 is written on the entry box when I createvtinstance(), I would like to then call the instance by: engine1.printvtvalues() and get the values. I imagine the function should look something like this: def createvtinstance(): global Nametemp Nametemp=vtdiagram() Nametemp._command_to_change_the_name_=stringinentrybox.get() Do you guys have know of a command that can do such a thing? Or is there a way that I could achieve the same effect, maybe using a dictionary? ***edit: The reason I need to name the variables is for the following (in plain English): I am creating an 'engine simulator'. The idea is that the user will enter engine parameters -plus its name- in a GUI and this is the vtdiagram class. The reason for using a class is that I have the characteristics of 'engine1, engine2...' saved as an instance of the class but I also need to have functions attached to it. This is because I want to generate graphs and diagrams of saved engines but only when called. So I can compare engine1 and engine2, but then get 'forget' engine2 from the GUI to compare 1 and 3. Please keep in mind I am quite new to python :) *** Many thanks! Juan
has comment: http://stackoverflow.com/comment/87008661
tagged with: python
has comment: http://stackoverflow.com/comment/87026997
has comment: http://stackoverflow.com/comment/87047253
upvote count: 3
duplicate of: http://stackoverflow.com/q/5036700
downvote count: 0
has answer: http://stackoverflow.com/a/49997131
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87027078
has comment: http://stackoverflow.com/comment/87008620
favorite count: 0
has title: Python: change class instance name - create class instance through function
type: Question
has comment: http://stackoverflow.com/comment/87025455

http://stackoverflow.com/q/49926684
tagged with: python
tagged with: dictionary
type: Question
score: 0
tagged with: for-loop
has title: Retrieving columns from data frames which are dict items in python
answer count: 1
accepted answer: http://stackoverflow.com/a/49959682
has answer: http://stackoverflow.com/a/49959682
type: AnsweredQuestion
has body: I need to create code able to read in multiple csv files, look for commonly titled columns among the files, and extract them in an array. I'm filling a python dictionary with .csv files imported as data frames in order to be able to call on them in a for loop. However, I don't really know what the for loop to pull columns from each item of a dict would look like. Here is my code so far: import numpy as np import matplotlib.pyplot as plt import pandas as pd r= int(input('How many files do you want to plot?: ')) l= range(r) d={} for i in l: inp= str(input('Type name of file #'+str(i+1)+': ')) d[i]= pd.read_csv(inp, sep=',') #fills dict with dataframes print(d) ##prints dict to visually check for errors Then, I need to name the column which I need to extract: freq= input('Which frequency would you like to plot at?: ') ##The desired shared column (labeled by a common string) among the dataframes After this, I'm stuck. I can only think to create a for loop which iterates over each dict item, "scans across" the first row to find the title string, and then takes that column, but I don't know how to code that. Any tips???
tagged with: dataframe

http://stackoverflow.com/a/49971194
score: 0
type: Answer
has body: I cannot be sure without your actual setup script but it looks like you just need to add numpy and numpy._methods to your packages list. build_exe_options = {"packages": ["numpy", "numpy._methods"]}
answers question: http://stackoverflow.com/q/49940816

http://stackoverflow.com/a/49946959
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49946614
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49946614
has body: Your Selenium code is almost correct. The problem is that authentication form located inside an iframe and you should switch to it to be able to handle inputs: driver.switch_to.frame(driver.find_element_by_css_selector('iframe._loadEvent')) driver.find_element_by_id('loginName').send_keys('g2387744@nwytg.com') driver.find_element_by_id('password').send_keys('123456789') driver.find_element_by_css_selector('button[type="submit"]').click()
type: AcceptedAnswer

http://stackoverflow.com/comment/86908220
type: QuestionComment
has text: The result is the same.
score: 0
comment on: http://stackoverflow.com/q/49945730
type: Comment

http://stackoverflow.com/comment/86852023
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49917951
has text: oh no there is no tab space
score: 0

http://stackoverflow.com/q/50011572
linked to: http://stackoverflow.com/q/11063292
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87039607
answer count: 2
has title: Copy each line 3 lines previous to each match
has comment: http://stackoverflow.com/comment/87040137
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87039678
tagged with: sliding-window
has comment: http://stackoverflow.com/comment/87039708
has comment: http://stackoverflow.com/comment/87039948
linked to: http://stackoverflow.com/q/2301789
has comment: http://stackoverflow.com/comment/87039903
has answer: http://stackoverflow.com/a/50011763
has body: I am trying to copy lines four lines before a line that contains a specific keyword. if line.find("keyword") == 0: f.write(line -3) I don't need the line where I found the keyword, but 4 lines before it. Since the write method doesn't work with line numbers, I got stuck
tagged with: matching
has answer: http://stackoverflow.com/a/50011671
tagged with: python
has comment: http://stackoverflow.com/comment/87039638
has comment: http://stackoverflow.com/comment/87039808

bots
tags question: http://stackoverflow.com/q/50054027
tags question: http://stackoverflow.com/q/50050194
tags question: http://stackoverflow.com/q/49996084
type: Tag
tags question: http://stackoverflow.com/q/50055068
tags question: http://stackoverflow.com/q/50065047
tag name: bots
tags question: http://stackoverflow.com/q/50072365

http://stackoverflow.com/comment/86896750
type: AnswerComment
comment on: http://stackoverflow.com/a/49927303
has text: I probably don't get the principle of generators. When I run my program with the above generater (adapted to my data), it prints out lists of indices in a continuous loop. So there my question goes, how can I know which batch was actually passed and processed during training?
score: 0
type: Comment

http://stackoverflow.com/comment/87001692
type: Comment
type: QuestionComment
score: 1
has text: You should be able to plot over 2800. I've had cases where it wouldn't render in a jupyter notebook so I had to save it then open it in a browser. Also, although those 7500 should plot, it will probably take a while. Check out FastMarkerClusters for a significant speed up
comment on: http://stackoverflow.com/q/49984575

http://stackoverflow.com/comment/87043689
comment on: http://stackoverflow.com/q/49995003
type: Comment
has text: @prabhakar Thanks for your comment, I have deleted the hpx column in the test data and it got the same error result.
type: QuestionComment
score: 0

http://stackoverflow.com/a/49969751
score: 2
accepted answer of: http://stackoverflow.com/q/49967109
type: Answer
answers question: http://stackoverflow.com/q/49967109
upvote count: 2
downvote count: 0
has body: Okay, few points before going to the solution which I got after trying quite a while: (The working code is below, if you want to skip the explanation) (i) If you look at what Thread.start() does, you will see that it is mentioned that it arranges for run() method to be invoked in a separate thread of control. So, what that means is, currently, without run() functions in your code for the thread classes, it is not going to invoke the other functions in a separate thread of control. Hence the main thread is executing all of it. To understand this, place two of the run function definitions in each of your thread class: def run(self): print(threading.current_thread()) and try running it. You will see that now, the separate threads are invoked. (ii) So how would you go about calling your custom functions from run()? When you look at Thread.run()'s definition, it says The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. So one way to do this is to you pass your arguments in the call t1 = SecondClass(args = [1,2,3,4,5]) and receive and initialize it in __init__ as: def __init__(self, args): Your run() function would then call your compute or print_itfunction like def run(self): print_it(self, self.args) (iii) But now, how are you going to call the other thread each time in the loop? You can only start a thread once and if you try giving a self.object.run for the t1 thread in the loop each time, it is not going to go back to the thread's execution. It will continue that function in the same thread t2. (iv) And also, how are you going to pass the current list value to t1, execute the cube root, and then jump back to t2 and proceed with square of the next number? For solving (iii) and (iv), you would need both a Queue (where the shared list can reside) and a synchronization mechanism that can safely execute one threa…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86977310
has comment: http://stackoverflow.com/comment/86975430

http://stackoverflow.com/a/49968504
type: Answer
has comment: http://stackoverflow.com/comment/87119269
has comment: http://stackoverflow.com/comment/86962860
answers question: http://stackoverflow.com/q/49968316
has comment: http://stackoverflow.com/comment/87132193
has comment: http://stackoverflow.com/comment/87157976
has comment: http://stackoverflow.com/comment/87195712
has comment: http://stackoverflow.com/comment/86957611
has body: Let us first set the stage: import pandas as pd import numpy as np group_idx = np.array([3, 2, 3, 2, 2, 1, 2, 1, 1]) a = np.array([3, 2, 1, 7, 4, 5, 5, 9, 1]) df = pd.DataFrame({'group': group_idx, 'values': a}) df # group values #0 3 3 #1 2 2 #2 3 1 #3 2 7 #4 2 4 #5 1 5 #6 2 5 #7 1 9 #8 1 1 To get a dataframe sorted by group and values (within groups): df.sort_values(["group", "values"]) # group values #8 1 1 #5 1 5 #7 1 9 #1 2 2 #4 2 4 #6 2 5 #3 2 7 #2 3 1 #0 3 3 To sort the values in descending order, use ascending = False. To apply different orders to different columns, you can supply a list: df.sort_values(["group", "values"], ascending = [True, False]) # group values #7 1 9 #5 1 5 #8 1 1 #3 2 7 #6 2 5 #4 2 4 #1 2 2 #0 3 3 #2 3 1 Here, groups are sorted in ascending order, and the values within each group are sorted in descending order. To only sort values for contiguous rows belonging to the same group, create a new group indicator: (I keep this in here for reference since it might be helpful for others. I wrote this in an earlier version before the OP clarified his question in the comments.) df['new_grp'] = (df.group.diff(1) != 0).astype('int').cumsum() df # group values new_grp #0 3 3 1 #1 2 2 2 #2 3 1 3 #3 2 7 4 #4 2 4 4 #5 1 5 5 #6 2 5 6 #7 1 9 7 #8 1 1 7 We can then easily sort with new_grp instead of group, leaving the original order of groups untouched. Ordering within groups but keeping the group-specifing row-positions: To sort the elements of each group but keep the group-specific positions in the dataframe, we need to keep track of the original row numbers. For instance, the following will do the trick: # First, create an indicator for the original row-number: df["ind"] = range(len(df)) # Now, sort the dataframe as before df_sorted = df.sort_values(["group", "values"]) # sort the original row-numbers within each group newindex = df.groupby("group").apply(lambda x: x.sort_values(["ind"]))["ind"].values # assign the sorted row-numbers to the sorted da…
has comment: http://stackoverflow.com/comment/87110006
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/87209753
has comment: http://stackoverflow.com/comment/86963047
downvote count: 0

http://stackoverflow.com/a/49938248
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49935645
has body: You can check db.currentOp() function lists -> it show the currently running queries with detailed information. It also shows the duration time they have been running (secs_running). Check the MongoDB console and run this function and after that analise the output, db.currentOp({"sec_srunning": {gte: 3}}) If you CPU load is 100%, you can use different values, and you can minimise the output and find that 'bad query'. The most important keys to analize: active: means the query is 'in progess' state secs_running:query's duration, in seconds ns:a collection name against you perform the query query: the query body So now we know how to find slow queries that can lead to high CPU load. This solution in this link: https://medium.com/quickblox-engineering/troubleshooting-mongodb-100-cpu-load-and-slow-queries-da622c6e1339 You can check more information in there.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49935645

http://stackoverflow.com/comment/86982054
has text: You can write decorators without it, but they tend to make getting data about the wrapped function difficult. So if you wanted to read the docstring of a wrapped function, or know its name, etc. that's very difficult without using `wraps`. It's considered good practice: you may never need that functionality, but you never know, and if you're providing these decorators for other people to use they may need it. It also doesn't hurt anything. I can't think of a downside to using `wraps`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49982537
score: 1

http://stackoverflow.com/q/50032912
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: pandas
upvote count: 2
downvote count: 2
has body: I want to order this by the column "market", but normal "sort_values" from pandas doesn't work. I want to order by set and game. Could you please help? +---+------------------------------+----------+----------+ | | market | stake | profit | +---+------------------------------+----------+----------+ | 0 | Game Winner (Set 1, Game 1) | 1605.50 | -1020.30 | | 1 | Game Winner (Set 1, Game 10) | 2825.00 | 85.42 | | 2 | Game Winner (Set 1, Game 11) | 700.00 | 100.00 | | 3 | Game Winner (Set 1, Game 12) | 2280.40 | 9.60 | | 4 | Game Winner (Set 1, Game 2) | 5688.30 | -1516.84 | | 5 | Game Winner (Set 1, Game 3) | 2604.00 | -1205.70 | | 6 | Game Winner (Set 1, Game 4) | 4638.56 | -1817.72 | | 7 | Game Winner (Set 1, Game 5) | 3600.00 | 1488.00 | | 8 | Game Winner (Set 1, Game 6) | 8851.72 | -2776.65 | | 9 | Game Winner (Set 1, Game 7) | 10477.00 | -2097.00 | +---+------------------------------+----------+----------+ This is my df. The code I used is as follow: test = df.groupby("market")"stake","profit".sum().reset_index().sort_values("market")
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50034337
accepted answer: http://stackoverflow.com/a/50033530
has title: Order by text with strings and numbers
possible better answer: http://stackoverflow.com/a/50032931
has answer: http://stackoverflow.com/a/50033530
has answer: http://stackoverflow.com/a/50032931
tagged with: python
tagged with: numpy

http://stackoverflow.com/comment/87051075
type: Comment
type: AnswerComment
has text: @jpp Thanks, you mean like `{k:sorted(v, key=int) for k,v in d.items()}` I guess?
comment on: http://stackoverflow.com/a/50017358
score: 1

http://stackoverflow.com/a/50002544
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50002465
type: Answer
has body: You're storing your data in a dict and it can only contain one key of the same name. You'll need to use a list if you want to store multiple, e.g.: data = [] for container in containers: data.append({"title": container.h2.text, "author": container.p.text, "link": "https://open.umn.edu/opentextbooks/" + container.h2.a["href"]}) with open("textbooks.json", "w") as writeJSON: json.dump(data, writeJSON, ensure_ascii=False)
downvote count: 0

http://stackoverflow.com/comment/86887432
score: 1
type: Comment
has text: You can do that while doing a spark-submit. You can do --conf spark.sql.shuffle.partitions=5000 or you can set that from spark sql. spark.sql("set spark.sql.shuffle.partitions=5000")
comment on: http://stackoverflow.com/a/49935027
type: AnswerComment

http://stackoverflow.com/q/49966596
score: 1
has comment: http://stackoverflow.com/comment/86949031
tagged with: syntactic-sugar
has comment: http://stackoverflow.com/comment/86949331
has title: python internal - how to really create a function
tagged with: types
answer count: 0
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86948955
favorite count: 0
tagged with: internals
has body: I'm Trying to learn more about python and how it works If we want to declare a function in python. We do this def bar(): print("my great bar function") bar() I'm told that under the hood of python, this corresponds to class bar(): def __call__(self, *args, **kwargs): print("my great bar function ") a =bar() a() But class bar() is only syntax sugar for bar = type("bar",(object,),{"__call__":Placeholder_for_source_code}) a= bar() a() I'm trying to replace the Placeholder_for_source_code in the body of type with the source code for printing "my great bar function". When i inspect bar.__dict__['__call__'] all i get back when i inspect the class bar above is &lt;function bar.__call__ at 0x00000000035B37B8&gt; Can somebody tell me how to this works.
type: Question
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/50007245
has comment: http://stackoverflow.com/comment/87051639
has comment: http://stackoverflow.com/comment/87073353
has body: according to the things you've tried here a small summary: The {% static %} template tag refferes to your static files, which means you should not use a variable in there to display the content. Mentioned here. Except your Post model has a img = models.CharField(...) with the static file path to your image. In your second attempt by adding a ImageField to your post model you should take the ImageFields property by calling {{ post.img.url }} as src of you img-Tag
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87056688
answers question: http://stackoverflow.com/q/50007054
has comment: http://stackoverflow.com/comment/87067597
has comment: http://stackoverflow.com/comment/87031232
has comment: http://stackoverflow.com/comment/87067028

http://stackoverflow.com/q/50065192
has answer: http://stackoverflow.com/a/50065269
upvote count: 1
type: UnansweredQuestion
downvote count: 1
has body: I am totally new to this and search did not help. This works: import rhinoscriptsyntax as rs obj = rs.GetObject("Select a curve", rs.filter.curve) if rs.IsCurve(obj): i=0 while i &lt; 100: rs.OffsetCurve( obj, [0,0,0], -i ) i += 0.2 rs.OffsetCurve( obj, [0,0,0], -i ) i += 0.7 This does not: import rhinoscriptsyntax as rs a = raw_input("Please enter first number: ") b = raw_input("Please enter second number: ") obj = rs.GetObject("Select a curve", rs.filter.curve) if rs.IsCurve(obj): i=0 while i &lt; 100: rs.OffsetCurve( obj, [0,0,0], -i ) i += a rs.OffsetCurve( obj, [0,0,0], -i ) i += b With integers it's i += int(a), but a and b must be decimals. I have no clue. Help :) Danke
has comment: http://stackoverflow.com/comment/87147061
has comment: http://stackoverflow.com/comment/87147110
tagged with: python
tagged with: rhino3d
linked to: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/87147108
favorite count: 0
has comment: http://stackoverflow.com/comment/87147150
has title: Types 'int' and 'str' are unsupported as operands for +=
type: Question
has comment: http://stackoverflow.com/comment/87147189
duplicate of: http://stackoverflow.com/q/20449427
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50065345

http://stackoverflow.com/comment/86853121
has text: Thanks for the output but only versions starting with 3 should be replaced
type: AnswerComment
comment on: http://stackoverflow.com/a/49918884
score: 0
type: Comment

httpserver
tags question: http://stackoverflow.com/q/50017205
type: Tag
tag name: httpserver

http://stackoverflow.com/a/59669615
downvote count: 0
upvote count: 1
has body: In spacy 2.1.4 version, the above ValueError for Phrase Matcher has been resolved. If you are getting such an error please update your spacy version. refer: github issue link
type: Answer
has comment: http://stackoverflow.com/comment/117187480
answers question: http://stackoverflow.com/q/50017423
score: 1

http://stackoverflow.com/q/49967995
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49968935
tagged with: api
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9845102
tagged with: python
tagged with: flask
has body: Here is what my database table schema Movie (id, movie_name, genre, time, channel) I have a MySQL table and want to return a nested json to an API, grouping them by genre and channel. For example: [ 'comedy': { [{'id': 1, 'movie_name': 'm1', 'time': 18:00, 'channel': 'c1'}, {'id': 1, 'movie_name': 'm2', 'time': 18:00, 'channel': 'c2'}] }, 'horror': { [{'id': 1, 'movie_name': 'm3', 'time': 18:00, 'channel': 'c1'}, {'id': 1, 'movie_name': 'm4', 'time': 18:00, 'channel': 'c2'}] } ] And similarly for each channels. Update: I am not using SQL-Alchemy, all I am doing now is return jsonify(cursor.fetchall())
score: 0
answer count: 2
has title: How can I return a nested json using flask.jsonify by querying a database?
has answer: http://stackoverflow.com/a/49970197
tagged with: mysql
type: Question

http://stackoverflow.com/comment/86986681
score: 0
type: AnswerComment
type: Comment
has text: why are you subtracting 1 referring to `(x-1)` from the number then applying modulo referring to `(x-1) % 9` operation and then adding 1 `(x-1) % 9 + 1` to the number? could you please explain your logic?
comment on: http://stackoverflow.com/a/49984285

http://stackoverflow.com/q/49964307
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/86944745
tagged with: pandas
has body: HOW CAN I CONVERT THIS CSV FILE TO A NESTED JSON? date model code value ================================================== 15-01-2017 00:00 EMA_EPD1_PTG_NUS_DPG 2.138 15-01-2017 00:00 EMA_EPD2_PTG_NUS_DPG 1.75 15-02-2017 00:00 EMA_EPD1_PTG_NUS_DPG 2.19 15-02-2017 00:00 EMA_EPD2_PTG_NUS_DPG 1.757 My desired Json format is like that : How can I achieve this kind of nested Json. i will use this Json to validate data by walking on dates then models and then at last the values. "date": 15-01-2017 00:00 { [ { "model_code" : EMA_EPD1_PTG_NUS_DPG [ { "value" :2.138 } ] }, { "model_code" :EMA_EPD2_PTG_NUS_DPG [ { "value" : 1.75 } ] } ] "date": 15-02-2017 00:00 { [ { "model_code" : EMA_EPD1_PTG_NUS_DPG [ { "value" :2.19 } ] }, { "model_code" :EMA_EPD2_PTG_NUS_DPG [ { "value" : 1.757 } ] } ]
tagged with: http://stackoverflow.com/tag/json
has title: CSV to nested JSON in Python
has comment: http://stackoverflow.com/comment/86963532
type: Question
tagged with: jasonette
answer count: 0
type: UnansweredQuestion
tagged with: arrays
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/86885939
type: QuestionComment
score: 0
has text: also nested lists would look like: a = [[[1,1],[0,0]], [3,4]]
type: Comment
comment on: http://stackoverflow.com/q/49935141

http://stackoverflow.com/q/49946273
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has title: python--Import module name as variable (dynamically load module from passed argument)
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/13598035
type: AnsweredQuestion
tagged with: python-3.4
has answer: http://stackoverflow.com/a/49946356
has body: Python 3.4.2... I have been trying to dynamically load a custom module from an argument. I want to load custom code to scrape specific HTML files. Example: scrape.py -m name_of_module_to_load file_to_scrape.html I have tried an number of solutions including this one: importing a module when the module name is in a variable The module loads fine when I use the actual module name instead of the variable name args.module. Code: $ cat scrape.py #!/usr/bin/env python3 from urllib.request import urlopen from bs4 import BeautifulSoup import argparse import os, sys import importlib parser = argparse.ArgumentParser(description='HTML web scraper') parser.add_argument('filename', help='File to act on') parser.add_argument('-m', '--module', metavar='MODULE_NAME', help='File with code specific to the site--must be a defined class named Scrape') args = parser.parse_args() if args.module: # from get_div_content import Scrape #THIS WORKS# sys.path.append(os.getcwd()) #EDIT--change this: #wrong# module_name = importlib.import_module(args.module, package='Scrape') #to this: module = importlib.import_module(args.module) # correct try: html = open(args.filename, 'r') except: try: html = urlopen(args.filename) except HTTPError as e: print(e) try: soup = BeautifulSoup(html.read()) except: print("Error... Sorry... not sure what happened") #EDIT--change this #wrong#scraper = Scrape(soup) #to this: scraper = module.Scrape(soup) # correct Module: $ cat get_div_content.py class Scrape: def __init__(self, soup): content = soup.find('div', {'id':'content'}) print(content) Command run and Error: $ ./scrape.py -m get_div_content.py file.html Traceback (most recent call last): File "./scrape.py", line 16, in &lt;module&gt; module_name = importlib.import_module(args.module, package='Scrape') File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2249, in _gcd_import File…
accepted answer: http://stackoverflow.com/a/49946356
downvote count: 0

http://stackoverflow.com/comment/129718823
has text: If you have Fiddler open, that might be the issue. Try closing it.
type: QuestionComment
comment on: http://stackoverflow.com/q/49979354
score: 0
type: Comment

http://stackoverflow.com/a/50018529
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103651093
has body: One way to do this is to create a new class that inherits from A, and has the expensive init_data as a class attribute. Here's a short demo derived from your code. class A: def __init__(self): self.init_data = self._initialize() # &lt;- same for each thread self.a = 0 # &lt;- private for each thread def _initialize(self): # Get data from db (high cost) print('_initialize called') return 1000 def calculate_a(self, data): # Calculate 'a' result from init_data to private 'a' variable self.a += self.init_data + data class MyA(A): # Create a single instance of the original class and store its # init_data as a class attribute of MyA init_data = A().init_data # Get rid of the inherited _initialize method _initialize = None # Override the inherited __init__ def __init__(self): self.a = 0 # Test b = MyA() b.calculate_a(10) print(b.a) c = MyA() c.calculate_a(100) print(c.a) b.calculate_a(20) print(b.a) output _initialize called 1010 1100 2030 As you can see, A._initialize() only gets called once, when the MyA class is being defined. All instances of MyA share the MyA.init_data, and any methods of MyA, including methods that it inherits from A, will use that MyA.init_data when self.init_data is referenced.
type: Answer
accepted answer of: http://stackoverflow.com/q/50017405
answers question: http://stackoverflow.com/q/50017405
has comment: http://stackoverflow.com/comment/103642848
has comment: http://stackoverflow.com/comment/103655890
downvote count: 0
has comment: http://stackoverflow.com/comment/103655787
upvote count: 1

http://stackoverflow.com/comment/87116470
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50032741
has text: Second, when I have data['products'], I have a list of dictionaries. No index is required. I then use the dictionary key, 'id', to access the value/data on each iteration. In more complex structures you may need to use an index to drill down
type: Comment

http://stackoverflow.com/a/49930086
has body: I think you can use the skiprows and nrows arguments in pandas.read_csv to pick out individual rows to read in. With skiprows, you can provide it a long list (0 indexed) of rows not to import , e.g. [0,5,6,10]. That might end up being a huge list though. If you provide it a single integer, it will skip that number of rows and start reading. Set nrows to whatever to pick up the number of rows you want at the point where you have it start. If I've misunderstood the issue, let me know.
has comment: http://stackoverflow.com/comment/86876539
has comment: http://stackoverflow.com/comment/86876329
has comment: http://stackoverflow.com/comment/86876504
answers question: http://stackoverflow.com/q/49929988
has comment: http://stackoverflow.com/comment/86876470
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/86876829
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/49929988

http://stackoverflow.com/q/50028742
has answer: http://stackoverflow.com/a/50029690
has comment: http://stackoverflow.com/comment/87075278
type: Question
has comment: http://stackoverflow.com/comment/87075288
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/50029690
has comment: http://stackoverflow.com/comment/87074917
downvote count: 0
has comment: http://stackoverflow.com/comment/87073806
has comment: http://stackoverflow.com/comment/87073702
upvote count: 1
has comment: http://stackoverflow.com/comment/87073730
favorite count: 0
has comment: http://stackoverflow.com/comment/87075465
tagged with: indexing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87073757
tagged with: list
has comment: http://stackoverflow.com/comment/87074471
score: 1
has comment: http://stackoverflow.com/comment/87074084
has title: List indexes - If too big go back to the beginning of the list
has comment: http://stackoverflow.com/comment/87073881
answer count: 1
has body: So, maybe this question will sound very beginnerish, but I just don't know how I should begin with this example: So the example is: I have a list for example 13 items long (1,2,3,4...13) There's a given number, let's say 6 The program needs to show me in a list, in what order are the numbers going to fall out. If the second number is 6, it means every time the sixth item is the next whcih is going to fall out. But my problem is that how could I tell python that if the index number goes up too high, it should start counting again from the beggining? This is what I made myself so far x = int(input("Number of items (numbers): ")) y = int(input("Fall-out number: ")) #n = 1 #id = 0 numbers = [n for n in range(x+1)] fallsout = [] numbers.remove(30) for i in numbers: if i % y == 0: fallsout.append(i) print (numbers) print (fallsout) Here's an example what should be in the input and output: Input: x = 13 y = 6 Output: 6 12 5 13 8 3 1 11 2 7 4 10 9
tagged with: python

http://stackoverflow.com/comment/86957153
score: 0
type: Comment
type: AnswerComment
has text: Sure, if it worked for you please mark as correct :)
comment on: http://stackoverflow.com/a/49970513

http://stackoverflow.com/comment/87013139
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49998309
type: Comment
has text: Yes, somehow it works like that (by adding the full path)

http://stackoverflow.com/comment/87016533
has text: @quamrana, not really, that was intentional - if you return at that point you return a dictionary of results, which is not what was intended. You could argue you can use those intermediate results later on, but that, IMO, was complicating the whole function.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49999474

http://stackoverflow.com/comment/86985465
comment on: http://stackoverflow.com/q/49984503
type: QuestionComment
score: 2
has text: `writerow` expects to be diven a single dictionary which is the data for one row. You are passing it the list of all rows. Change it to `for row in data: thewriter.writerow(row)` and you'll prob get a bit further.
type: Comment

http://stackoverflow.com/a/50004681
has comment: http://stackoverflow.com/comment/87026332
type: Answer
accepted answer of: http://stackoverflow.com/q/50003978
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87026842
type: AcceptedAnswer
has body: as @jezrael points out, the data isn't uniform. sometimes there are five pieces of information, sometimes there are 6. to clean this up and load into a dataframe you can do the following: import requests as r import pandas as pd raw = r.get('https://s3.amazonaws.com/todel162/kaggle_unicode1.txt') # the raw data has some non ascii characters which you could likely ignore. # and I ignore the last line if it is blank as that breaks the parsing. data = raw.text.encode('ascii', errors='ignore').decode() lines = [d.strip() for d in data.split('\n')] if lines[-1] == '': lines = lines[:-1] # then split out sections of data # this 1 lines replaces the following commented out for-loop more elegantly blurbs = [l.split('**') for l in '**'.join(lines).split('****')] # blurbs = [] # blurb = [] # for line in lines: # if line == '': # blurbs.append(blurb) # blurb = [] # else: # blurb.append(line) # it seems each section can either have 5 or 6 elements, write a function to return a uniform format record, and use pandas.DataFrame.from_records to load into dataframe def get_record(blurb): if len(blurb) == 6: return blurb return blurb[:3] + [''] + blurb[3:] cols = ['task_name', 'task_description', 'task_date', 'other', 'task_prize', 'task_teams'] df = pd.DataFrame.from_records([get_record(b) for b in blurbs], columns=cols) df.head() This outputs the following: Out[8]: task_name \ 0 TalkingData AdTracking Fraud Detection Challenge 1 CVPR 2018 WAD Video Segmentation Challenge 2 iMaterialist Challenge (Fashion) at FGVC5 3 iMaterialist Challenge (Furniture) at FGVC5 4 Google Landmark Retrieval Challenge task_description task_date \ 0 Can you detect fraudulent click traffic for mo... Featured13 days to go 1 Can you segment each objects within image fram... Research2 months to go 2 Image classification of fashion products. Researcha month to go 3 Image Classification of Furniture &amp; Home Goods. Researcha month to go 4 Given an image, can you find all of the same l... Researcha month to go…
answers question: http://stackoverflow.com/q/50003978
has comment: http://stackoverflow.com/comment/87026587
score: 1

http://stackoverflow.com/q/50011439
type: AnsweredQuestion
score: 0
has title: Python for loop through array creating JSON file
answer count: 1
has body: I have code to create a json object file and makes it into pretty print in a new file. Found here: # Creates a storage file for the with open('placeInfo.json', 'w') as outfile: json.dump(api.trends_place(id=location_array[1]), outfile) with open('placeInfo.json', 'r') as handle: parsed = json.load(handle) prettyFile = json.dumps(parsed, indent=4, sort_keys=True) pfFile = json.loads(prettyFile) #use for indexing print prettyFile x = 'number1' f = open(x + 'newFile.json', 'w') f.write(prettyFile) What I want to do is loop through an array (0-17 elements) and use id=location_array[x] to index each location within the array. x = 0 while x &lt; len(location_array): with open('placeInfo.json', 'w') as outfile: json.dump(api.trends_place(id=location_array[x]), outfile) with open('placeInfo.json', 'r') as handle: parsed = json.load(handle) pretty_file = json.dumps(parsed, indent = 4, sort_keys = True) print pretty_file f = open(x + 'newFile.json', 'w') f.write(pretty_file) x += 1 The first code block returns a valid new json file but this while loop does not even recognize one json file. Where am I going wrong here? Also is there any simplification of this code that can be recommended?
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/87039391
accepted answer: http://stackoverflow.com/a/50011596
has answer: http://stackoverflow.com/a/50011596

http://stackoverflow.com/q/50025233
score: 0
tagged with: twisted
answer count: 1
has answer: http://stackoverflow.com/a/50026601
has title: Buffer app using twisted/asyncio
type: Question
tagged with: python-3.x
tagged with: python-asyncio
type: UnansweredQuestion
has body: I have a simple app that receives data and must push it to another service in batches. How can I implement it using twisted or asyncio? Currently, I have next code using twisted: from twisted.internet import protocol, reactor, endpoints from twisted.protocols import basic class FirehoseProtocol(basic.LineReceiver): def __init__(self): self.data = [] def lineReceived(self, line): self.data.append(line) def push_to_firehose(self): pass # TODO class EchoFactory(protocol.ServerFactory): protocol = FirehoseProtocol endpoints.serverFromString(reactor, "tcp:5001").listen(EchoFactory()) reactor.run()
tagged with: python

http://stackoverflow.com/a/51939614
has body: import pandas as pd from prompt_toolkit import prompt filename = prompt('Enter your file name: ') df = pd.read_excel(/YOUR_DIRECTORY_PATH/%s' % filename + '.xlsx')
answers question: http://stackoverflow.com/q/50036011
has comment: http://stackoverflow.com/comment/90829864
type: Answer
score: 0

http://stackoverflow.com/q/50042350
possible better answer: http://stackoverflow.com/a/50042479
tagged with: python
has title: How to pad a 2d array with variable length per row on the left and right to form a bigger 2d array
score: 2
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50042519
answer count: 2
has comment: http://stackoverflow.com/comment/87113811
has body: I have a 2d array like small = np.arange(9).reshape((3, 3)) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) I want to apply a padding, each row to pad variable 0s on the left. And to make sure the result 2d array is of shape 3 x 8. (padding 0s on the right) offset = np.array([1, 3, 2]) So that the result looks like array([[ 0., 0., 1., 2., 0., 0., 0., 0.], [ 0., 0., 0., 3., 4., 5., 0., 0.], [ 0., 0., 6., 7., 8., 0., 0., 0.]]) What's the best way to achieve that? thanks to @Divakar solution. I ran some benchmarks on the following methods. def f1(small, offset, ncols): nrows, num_small_cols = small.shape big = np.zeros((nrows, ncols)) inner = np.empty_like(small, dtype=np.int64) for i in range(num_small_cols): inner[:, i] = offset + i big[np.arange(nrows)[:, None], inner] = small return big def f2(small, offset, ncols): n = small.shape[1] r = np.arange(ncols) offset2 = offset[:,None] # This took a lot of time mask = (offset2 &lt;= r) &amp; (offset2 + n &gt; r) out = np.zeros_like(mask, dtype=np.float64) out[mask] = small.ravel() return out def f3(small, offset, ncols): n = small.shape[1] m = ncols - n small_pad = np.zeros((len(small), n + 2*m)) small_pad[:,m:m+n] = small w = view_as_windows(small_pad, (1,ncols))[:,:,0] return w[np.arange(len(offset)), ncols-offset-n] n = 10000 offset = np.repeat(np.array([1, 3, 2]), n) small = np.random.rand(n * 3, 5) %timeit f1(small, offset, 9) # 1.32 ms %timeit f2(small, offset, 9) # 2.24 ms %timeit f3(small, offset, 9) # 1.3 ms
downvote count: 0
has comment: http://stackoverflow.com/comment/87111447
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50042519
has answer: http://stackoverflow.com/a/50042479

http://stackoverflow.com/comment/87005385
comment on: http://stackoverflow.com/q/49994132
has text: Check your labels. Where is the traceback coming from?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87092051
comment on: http://stackoverflow.com/q/50037934
type: QuestionComment
type: Comment
score: 2
has text: [CSV File Reading and Writing](https://docs.python.org/3/library/csv.html)

http://stackoverflow.com/comment/86881712
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49932756
has text: Is `tf.Variable` automatically an adjustable weight?

passwords
tags question: http://stackoverflow.com/q/50001958
tags question: http://stackoverflow.com/q/50054868
tags question: http://stackoverflow.com/q/49942003
tags question: http://stackoverflow.com/q/50010578
tags question: http://stackoverflow.com/q/50026613
type: Tag
tag name: passwords

http://stackoverflow.com/comment/86951649
score: 2
comment on: http://stackoverflow.com/q/49958474
has text: Since int is immutable, and you want a mutable class, this is not a good case for inheritance - consider composition instead ("has a" int instead of "is a" int).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87119966
has text: Have you tried finding and reading the documentation?
score: 0
comment on: http://stackoverflow.com/q/50051776
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50054926
has comment: http://stackoverflow.com/comment/87127085
has comment: http://stackoverflow.com/comment/87127099
has body: The basic difference is the fact that you can use a function decorated with staticmethod without instantiating the class, but if you make a sub-function/inner-function you can not access it from outside function where it was definned. Method Without instantiating: In [2]: Pizza.cook() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-2-4a252d4e9619&gt; in &lt;module&gt;() ----&gt; 1 Pizza.cook() TypeError: cook() missing 1 required positional argument: 'self' With instance: In [4]: Pizza('cheese', 'vegetables').cook() Out[4]: 'cheesevegetables' Static method Without instantiating: In [5]: Pizza.mix_ingredients(1,2) Out[5]: 3 Performance: Each time you call cook_pizza it defines the nested function, which causes an impact on execution time. import timeit def method(): return 'method' def method_with_inner(): def inner(): return 'inner' return inner() Execution print(timeit.timeit("method()", setup="from __main__ import method")) 0.0910306089790538 print(timeit.timeit("method_with_inner()", setup="from __main__ import method_with_inner")) 0.24090809898916632 Side note the cook_pizza could be a static method as it doesn't use any variable defined at class level or storage in self. Thanks: @Shadow @abarnert for the contributions in the discussion thread of this answer.
has comment: http://stackoverflow.com/comment/87127048
accepted answer of: http://stackoverflow.com/q/50054779
type: Answer
has comment: http://stackoverflow.com/comment/87127140
has comment: http://stackoverflow.com/comment/87126534
has comment: http://stackoverflow.com/comment/87127011
has comment: http://stackoverflow.com/comment/87126800
has comment: http://stackoverflow.com/comment/87127199
has comment: http://stackoverflow.com/comment/87126343
has comment: http://stackoverflow.com/comment/87127030
has comment: http://stackoverflow.com/comment/87126302
score: 2
has comment: http://stackoverflow.com/comment/87126961
upvote count: 2
has comment: http://stackoverflow.com/comment/87126453
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87126423
has comment: http://stackoverflow.com/comment/87126820
answers question: http://stackoverflow.com/q/50054779
has comment: http://stackoverflow.com/comment/87126430

http://stackoverflow.com/comment/86967705
has text: @Chanda Korat - version - ChromeDriver v2.27 Chrome browser- Version 66.0.3359.117 (Official Build) (64-bit)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49974265
score: 0

http://stackoverflow.com/q/49972918
downvote count: 2
has answer: http://stackoverflow.com/a/49973074
has comment: http://stackoverflow.com/comment/86962011
tagged with: python
has comment: http://stackoverflow.com/comment/86961990
linked to: http://stackoverflow.com/q/524714
linked to: http://stackoverflow.com/q/49972457
linked to: http://stackoverflow.com/q/1590608
favorite count: 0
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86962135
answer count: 1
has body: I'm trying to use global variables LAND which is an object of class Type within the class Type. The following code gives me an error: SyntaxError: invalid syntax because LAND is not defined: # Define a class named Type class Type(): def __init__(self, id, symbol): self.id = id self.symbol = symbol def is_free(self): return self.id = LAND.id # Define variables of this class LAND = Type(-1, '.') I can't just move LAND before the definition of Type, because that will also give me the error SyntaxError: invalid syntax because Type is not defined. Can somebody tell me if it is possible? Or is there any alternative way to do this? I have asked a question with a bad title Python class forward declaration, it was marked as duplicate with two questions, but as I explained in my original post, I don't think my question is the same as those two: I have seen the post Is it possible to forward-declare a function in Python?, but I don't think it's the same issue. Because the question is about forward declaration of function, while I'm asking about class. I also read this post Does Python have class prototypes (or forward declarations)?, but it was asking about refer to a class in another class, while I'm asking about refer to variables of its own type within the class. I don't see my solution in this post, or can somebody who thinks it's duplicate explain a little bit?
has comment: http://stackoverflow.com/comment/86962107
type: Question
has comment: http://stackoverflow.com/comment/86962066
accepted answer: http://stackoverflow.com/a/49973074
upvote count: 2
has title: Use global variables defined by one class within the class

http://stackoverflow.com/a/49970059
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49941105
has body: Personally I would dodge that whole bit with ssh -o StrictHostKeyChecking=no since it seems you don't care to make a decision based off of any interpretation. I'm not sure your use case for the empty string match in the list being passed to expect call, however it seems that regardless of the index, you are sending the password and expecting the prompt as if initial authentication and hostchecking is completed. The error you received shows the buffer as containing the yes/no prompt but expecting failing while expecting a &gt;. It is possible that your password is being sent to yes no prompt and then presenting "Please type 'yes' or 'no':" which doesn't contain &gt; causing you to time out.
type: Answer
has comment: http://stackoverflow.com/comment/87076099
accepted answer of: http://stackoverflow.com/q/49941105
type: AcceptedAnswer

http://stackoverflow.com/q/49964931
has comment: http://stackoverflow.com/comment/86946069
has answer: http://stackoverflow.com/a/49968563
has body: With the following code: df = pd.read_csv('chat_daniel.csv', skipinitialspace=True) On the following data field: Date,From,Content 2017-09-14 10:56 AM,"Tim X","jo" 2017-09-14 10:57 AM,"DanieY","Jow k ben thuis" 2017-09-14 10:57 AM,"Tim X","kan ik komem?" 2017-09-14 10:58 AM,"Tim X","ik heb 2 tudsejuren" etc. I get the following outcome with print(df.head()): Date From Content 0 2017-09-14 10:56 AM,"Tim X","jo" NaN NaN 1 2017-09-14 10:57 AM,"DanieY","Jow k ben thuis" NaN NaN 2 2017-09-14 10:57 AM,"Tim X","kan ik komem?" NaN NaN 3 2017-09-14 10:58 AM,"Tim X","ik heb 2 tudseju... NaN NaN 4 2017-09-14 11:00 AM,"DanieY","Ik moet 12 sxho... NaN NaN While I should get (as has been the case in some other things I've done with csv) Date From Content 0 2017-09-14 10:56 AM "Tim X" "jo" 1 2017-09-14 10:57 AM "DanieY" "Jow k ben thuis" 2 2017-09-14 10:57 AM "Tim X" "kan ik komem?" etc. So far searching everywhere I haven't found anyone who has had the same case. I can't remove all double quotes because then all commas in the double quoted fields will create seperate fields. I've already tried changing Date,From,Content to Date,"From","Content". Edit: With the following file and code: Taken away for privacy reasons. import pandas as pd import numpy as np import csv import os import re from datetime import datetime df = pd.read_csv('chat_daniel.csv', skipinitialspace=True) print(df.head()) print('-'*40) print(df.info()) I get the wrong output. Edit2 (solution): If you have this problem, to get it to function in a normal way (assuming your problem is like Jack Daniel describes for me) open an editor other than excel and you will see the problem. I used Sublime Text to easily edit my file to normal without having to do everything manually, after doing that everything should function like normal.
answer count: 2
possible better answer: http://stackoverflow.com/a/49968563
has comment: http://stackoverflow.com/comment/86946058
has comment: http://stackoverflow.com/comment/86948204
accepted answer: http://stackoverflow.com/a/49970176
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Function "pd.read_csv" does not seperate text after comma into another column if it is double-quoted in Python 3.6
has answer: http://stackoverflow.com/a/49970176
type: Question
has comment: http://stackoverflow.com/comment/86945862

http://stackoverflow.com/comment/86939193
type: Comment
comment on: http://stackoverflow.com/q/49961175
score: 0
type: QuestionComment
has text: For the same reason that `None` doesn't show up, the idea is that 99% of the time, you won't want the value, but the remainder of the time, you might...

http://stackoverflow.com/comment/86905479
comment on: http://stackoverflow.com/a/49940324
type: AnswerComment
has text: Thanks very much for your help
score: 1
type: Comment

http://stackoverflow.com/comment/86863467
type: AnswerComment
has text: I have conda installed but howerver Im not using it I guess. You are right about the env. Now it works !
comment on: http://stackoverflow.com/a/49923723
type: Comment
score: 0

http://stackoverflow.com/comment/86990341
score: 0
has text: You need to go through this link : http://selenium-python.readthedocs.io/waits.html
type: Comment
comment on: http://stackoverflow.com/a/49986145
type: AnswerComment

http://stackoverflow.com/comment/86984228
type: QuestionComment
comment on: http://stackoverflow.com/q/49967179
type: Comment
score: 0
has text: Have edited this to provide more info... hope someone can help... I suspect it's just a case of correctly writing the code to select both image urls from JSON, not just one...

http://stackoverflow.com/comment/86984821
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49984197
has text: @Aran-Fey Question is updated
score: 0

http://stackoverflow.com/a/49971841
type: Answer
answers question: http://stackoverflow.com/q/49929617
downvote count: 0
has body: Not sure if this will work, you may need to tweak it: from googleapiclient import discovery from oauth2client.client import GoogleCredentials credentials = GoogleCredentials.get_application_default() service = discovery.build('yourservicename', credentials=credentials) request = service.projects().list()[0]
score: 1
upvote count: 1

http://stackoverflow.com/comment/87065463
comment on: http://stackoverflow.com/q/50024642
score: 1
type: Comment
type: QuestionComment
has text: You have to jump through hoops to install modules? That seems like the bigger issue that needs addressing here. (I know, you probably can't help it, but that sounds insane…)

http://stackoverflow.com/a/49970402
type: Answer
answers question: http://stackoverflow.com/q/49970366
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86957196
has comment: http://stackoverflow.com/comment/86957361
has body: You can use re.split and then a final str.split: import re s = '"green lizards" like to sit "in the sun"' new_s = [[i[1:-1].split()] if i.startswith('"') else i.split() for i in re.split('(?&lt;=")\s|\s(?=")', s)] last_result = [i for b in new_s for i in b] Output: [['green', 'lizards'], 'like', 'to', 'sit', ['in', 'the', 'sun']]

http://stackoverflow.com/q/50049786
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50049888
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87115809
has body: I have two list and i would like to create dict with each list where key value is a string and then combine those two dicts in one, below are my list : list_1 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] list_2 : ['BACKUP_INFO', 'sqlite_sequence', 'BACKUP_INFO_SEARCH', 'BACKUP_INFO_SEARCH_content', 'BACKUP_INFO_SEARCH_segments', 'BACKUP_INFO_SEARCH_segdir', 'BACKUP_INFO_SEARCH_docsize', 'BACKUP_INFO_SEARCH_stat', 'FILE_INFO', 'FILE_INFO_SEARCH', 'FILE_INFO_SEARCH_content', 'FILE_INFO_SEARCH_segments', 'FILE_INFO_SEARCH_segdir', 'FILE_INFO_SEARCH_docsize', 'FILE_INFO_SEARCH_stat'] List_1 should be added with dict key value as 'id' List_2 should be added with dict key value as 'table' Then, both the above dicts should be combined into one dict to form something similar to this : { "output": { "id": 1, "table" : BACKUP_INFO } { "id": 2, "table" :sqlite_sequence } } But, i am getting the below output using table_list_out = dict(zip(list_1, list_2)) return { 'output' : {'id' : list_1, 'table_name' : list_2}}: { "output": { "id": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ], "table_name": { "1": "BACKUP_INFO", "2": "sqlite_sequence", "3": "BACKUP_INFO_SEARCH", "4": "BACKUP_INFO_SEARCH_content", "5": "BACKUP_INFO_SEARCH_segments", "6": "BACKUP_INFO_SEARCH_segdir", "7": "BACKUP_INFO_SEARCH_docsize", "8": "BACKUP_INFO_SEARCH_stat", "9": "FILE_INFO", "10": "FILE_INFO_SEARCH", "11": "FILE_INFO_SEARCH_content", "12": "FILE_INFO_SEARCH_segments", "13": "FILE_INFO_SEARCH_segdir", "14": "FILE_INFO_SEARCH_docsize", "15": "FILE_INFO_SEARCH_stat" } } }
type: AnsweredQuestion
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50049888
upvote count: 0
accepted answer: http://stackoverflow.com/a/50049858
has title: Add String to list items and then create a dict in python
has answer: http://stackoverflow.com/a/50049906
downvote count: 1
has answer: http://stackoverflow.com/a/50049858

http://stackoverflow.com/comment/86858553
has text: set comprehension: `y = {z for z in x}`
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49921345
type: QuestionComment

qstandarditemmodel
tags question: http://stackoverflow.com/q/49926599
tag name: qstandarditemmodel
type: Tag

http://stackoverflow.com/comment/86962332
score: 1
type: Comment
has text: @MarkII Could you elaborate on what's wrong? It seems to me it gives your expected result in both test cases. Also - sorry for being pedantic - `self` is not a keyword it is just used by convention.
comment on: http://stackoverflow.com/a/49973104
type: AnswerComment

http://stackoverflow.com/a/49919654
has comment: http://stackoverflow.com/comment/86898942
score: 0
has comment: http://stackoverflow.com/comment/86921487
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86944931
accepted answer of: http://stackoverflow.com/q/49918038
has comment: http://stackoverflow.com/comment/86935105
answers question: http://stackoverflow.com/q/49918038
has body: This is jus a different solution to your problem that should be much faster compared to usage of iterrows. You should always try to use as much vectorization as possible with pandas. df = pd.DataFrame({'neg': [0,0,1, 0, 1,0, 0, 1]}) indexes = df[df['neg'] == 1].index shifted = indexes + 1 values = indexes - indexes.to_series().shift().fillna(0) df.assign(dfs=pd.Series(vals, index=indexes)).fillna(0) neg dfs 0 0 0.0 1 0 0.0 2 1 3.0 3 0 0.0 4 1 2.0 5 0 0.0 6 0 0.0 7 1 3.0 if you want you can out yourself convert the dfs column to int
type: Answer
has comment: http://stackoverflow.com/comment/86945840

http://stackoverflow.com/q/49967149
score: 1
upvote count: 1
answer count: 1
has title: Cropping a surface in python for Z values greater than
favorite count: 0
type: Question
has body: So I've got a 3D surface plot of a function which represents some real data. Any values greater than 8.5 on the Z axis are a physical impossibility and therefore I would like to remove them from my plot. I've been struggling to do this, any help would be appreciated: I want to set the values above 8 (most of the red) to NaN, but the plot appears to be empty when I try this. I've done some googling and discovered that surf plots do not like NaN's (apparently) and was wondering if anyone here could help! The code: fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(1.0,101.0,1.0) Y = np.arange(1.0,4.1, 0.04) X, Y = np.meshgrid(X, Y) Z = ((0.3973473*(np.exp(np.log10(X)))) + 0.6176893) * Y surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
tagged with: python
tagged with: surface
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49999132
accepted answer: http://stackoverflow.com/a/49999132
downvote count: 0

beautifulsoup
tags question: http://stackoverflow.com/q/49969085
tags question: http://stackoverflow.com/q/49939098
tags question: http://stackoverflow.com/q/49940129
tags question: http://stackoverflow.com/q/50013902
tags question: http://stackoverflow.com/q/50035992
tags question: http://stackoverflow.com/q/50070571
tags question: http://stackoverflow.com/q/49941417
tags question: http://stackoverflow.com/q/49955795
tags question: http://stackoverflow.com/q/49991604
type: Tag
tags question: http://stackoverflow.com/q/49996084
tags question: http://stackoverflow.com/q/49923439
tags question: http://stackoverflow.com/q/49932522
tags question: http://stackoverflow.com/q/49932795
tags question: http://stackoverflow.com/q/49999168
tags question: http://stackoverflow.com/q/50022829
tags question: http://stackoverflow.com/q/49948064
tags question: http://stackoverflow.com/q/50062237
tags question: http://stackoverflow.com/q/50026544
tags question: http://stackoverflow.com/q/49957543
tags question: http://stackoverflow.com/q/50013420
tags question: http://stackoverflow.com/q/50030758
tags question: http://stackoverflow.com/q/49920035
tags question: http://stackoverflow.com/q/49956645
tags question: http://stackoverflow.com/q/49949370
tags question: http://stackoverflow.com/q/50064036
tags question: http://stackoverflow.com/q/50002465
tags question: http://stackoverflow.com/q/50006321
tags question: http://stackoverflow.com/q/49950041
tags question: http://stackoverflow.com/q/50045775
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/49925263
tags question: http://stackoverflow.com/q/49949767
tags question: http://stackoverflow.com/q/49955536
tags question: http://stackoverflow.com/q/49952518
tags question: http://stackoverflow.com/q/50026264
tags question: http://stackoverflow.com/q/49971317
tags question: http://stackoverflow.com/q/50003003
tags question: http://stackoverflow.com/q/49918734
tags question: http://stackoverflow.com/q/49964779
tags question: http://stackoverflow.com/q/50014456
tags question: http://stackoverflow.com/q/49932226
tags question: http://stackoverflow.com/q/49987479
tags question: http://stackoverflow.com/q/50067941
tags question: http://stackoverflow.com/q/49992234
tags question: http://stackoverflow.com/q/49925471
tags question: http://stackoverflow.com/q/49925460
tags question: http://stackoverflow.com/q/49961281
tags question: http://stackoverflow.com/q/50036543
tags question: http://stackoverflow.com/q/49975784
tags question: http://stackoverflow.com/q/50054116
tags question: http://stackoverflow.com/q/50014068
tags question: http://stackoverflow.com/q/49962350
tags question: http://stackoverflow.com/q/49934551
tags question: http://stackoverflow.com/q/49939449
tags question: http://stackoverflow.com/q/50006810
tags question: http://stackoverflow.com/q/49967439
tags question: http://stackoverflow.com/q/50067249
tags question: http://stackoverflow.com/q/49978532
tags question: http://stackoverflow.com/q/49949849
tags question: http://stackoverflow.com/q/50012384
tags question: http://stackoverflow.com/q/49946717
tags question: http://stackoverflow.com/q/50064601
tags question: http://stackoverflow.com/q/50023985
tags question: http://stackoverflow.com/q/50018614
tags question: http://stackoverflow.com/q/49992645
tags question: http://stackoverflow.com/q/50050343
tags question: http://stackoverflow.com/q/50049042
tags question: http://stackoverflow.com/q/50027413
tags question: http://stackoverflow.com/q/49934878
tags question: http://stackoverflow.com/q/49945963
tags question: http://stackoverflow.com/q/49968965
tags question: http://stackoverflow.com/q/49939123
tags question: http://stackoverflow.com/q/49965781

http://stackoverflow.com/a/50011879
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50009692
type: Answer
answers question: http://stackoverflow.com/q/50009692
has comment: http://stackoverflow.com/comment/87073137
score: 0
has comment: http://stackoverflow.com/comment/87041866
has body: Based on the Haskell solution I posted as a comment on the question, here is a solution using the itertools library that uses an infinite list of values. import itertools def pay(n, a, b, k): cyc = itertools.cycle([range(a, b+1, k), range(b, a-1, -k)]) chained = itertools.chain.from_iterable(cyc) return sum(itertools.islice(chained, n)) This works because the pattern we're encapsulating with this algorithm is the infinitely cyclic pattern [range(a, b+1, k), range(b, a-1, -k)] (walk by k from a to b, then walk by -k from b to a). itertools.chain.from_iterable draws from the individual range iterators, and islice makes sure we only take n of the results. cyc and chained are infinite series, and islice is doing the job of limiting to n students.
has comment: http://stackoverflow.com/comment/87075512

http://stackoverflow.com/comment/86850306
comment on: http://stackoverflow.com/q/49917360
score: 0
type: Comment
type: QuestionComment
has text: @Aran-Fey its not a duplicate as the user with that issue is looking for vowels as well as cononants. It also is hard to find what the answer was for that problem.

http://stackoverflow.com/comment/87013872
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49996860
type: AnswerComment
has text: I'm getting `TypeError: 'float' object has no attribute '__getitem__` while following this approach. And you're right about containing a list.

plotly
tags question: http://stackoverflow.com/q/50007258
tag name: plotly
tags question: http://stackoverflow.com/q/50015494
tags question: http://stackoverflow.com/q/49917313
type: Tag
tags question: http://stackoverflow.com/q/50037213
tags question: http://stackoverflow.com/q/49996057
tags question: http://stackoverflow.com/q/49991731
tags question: http://stackoverflow.com/q/50051230
tags question: http://stackoverflow.com/q/49971915
tags question: http://stackoverflow.com/q/50070432
tags question: http://stackoverflow.com/q/49944041
tags question: http://stackoverflow.com/q/50023022

http://stackoverflow.com/q/50039916
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50048379
tagged with: sage
has body: Im going to use sage module in my Django web application so in my python virtualenv v3.6 I installed sage using pip. when I run my script to use sage I get the following error: Exception Value: No module named 'sage.all' I read some posts that sage has its own python. does it mean that I can not use sage in my python virtualenv?
answer count: 3
has comment: http://stackoverflow.com/comment/115182517
has comment: http://stackoverflow.com/comment/87100851
has comment: http://stackoverflow.com/comment/87095902
has answer: http://stackoverflow.com/a/63864434
score: 6
tagged with: virtualenv
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/115207243
favorite count: 0
has answer: http://stackoverflow.com/a/75369924
type: Question
has title: No module named 'sage.all'
tagged with: importerror
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/128730055

http://stackoverflow.com/q/49962436
has answer: http://stackoverflow.com/a/50244755
tagged with: python
has title: sphinx is showing the django base views instead of my own views.py
has answer: http://stackoverflow.com/a/53783757
score: 0
answer count: 2
has body: The view being shown when using Sphinx on a Django site is: The beginning of my views.py is: import os from django.shortcuts import render, redirect from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from django.utils import timezone from . forms import PlayForm, RollForm, checkBoard, BossForm from random import randint from . templatetags.playExtras import translateDice from .models import Board, Winner, Boss def getFirstFolder(req): """ return the string between first two / - this is a hack, find out how to do it with the object """ r = req.split("'") loc = r[1].find('/',1) x = r[1][1:loc] return(x) def loadBoard(request,context,location=''): ''' Load the board from the database into context. Add a hyperlink for available squares. :param context: context for template :type context: dictionary :param location: Comma seperated string of available locations or empty string so no links included. :type location: str :return: 'not on the board' or 'all taken' or comma seperated string of location options such as 'A0,B0' :rtype: str ''' req = request.__str__() I was getting errors if I didn't show Sphinx where the Python was located. The path additions I made in the Sphinx's conf.py are: ourPaths = [ '/game/', '/game/game', '/game/play', '/game/play/templatetags' ] for p in ourPaths: abspath = os.path.abspath('.') + p print('path..................',abspath) sys.path.insert(0, abspath) # Need to point to where the Django is on this system. FIND OUT HOW TO MAKE THIS RELATIVE sys.path.insert(0,'/home/ajp/Downloads/env/lib/python3.5/site-packages') sys.path.insert(0,'/home/ajp/Downloads/env/lib/python3.5/site-packages/django') The views.rst file I'm using: views module ============== .. automodule:: views :members: :undoc-members: :show-inheritance: I searched for days but I'm afraid I do not know the right terms search for to find the answer. I'm okay with the other code showing up, but I'd need to see my code in the manual as well. T…
type: Question
tagged with: python-sphinx
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/66270059
score: 2
has comment: http://stackoverflow.com/comment/117165856
downvote count: 0
type: Answer
has body: There is now an easy way of installing ROS on OSX using conda: conda install ros-noetic-desktop -c robostack. More info on https://medium.com/robostack/cross-platform-conda-packages-for-ros-fa1974fd1de3 and https://github.com/RoboStack/ros-noetic
upvote count: 2
answers question: http://stackoverflow.com/q/50060718

http://stackoverflow.com/comment/86878655
comment on: http://stackoverflow.com/a/49929417
score: 0
has text: username1 = "ruby" username2 = "desmon" username3 = "devon" username4 = "anna"
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87225227
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50077729
has text: no, the bounty is yours for answering, that is fine. When you write `b'\x1b4a'`, this is three bytes: `1B 34 61`. You probably mean `'\x1b\x4a'`. I previously tried using these commands and do not understand how the code in this answer helps fixing the problem. Can you elaborate *why* they help? I can't access the printer right now, but will post pictures asap. The main problem is that I'm getting two slips of paper, but only want one.

http://stackoverflow.com/q/49957730
type: Question
tagged with: python-ggplot
has answer: http://stackoverflow.com/a/49959048
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49959048
tagged with: pandas
has body: I have simple series of user-events, where the is a login and logout, and in-between few activities are performed. I tried various types of graphs and kinds but no luck. I want to represent time between login and logout in some color so it represent an activity. And in Y axis the activities should be represented as a star. %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime from collections import namedtuple Event = namedtuple('Event',('event_time', 'event_type')) # event_type = 1 -&gt; Login, 2 -&gt; watch , 3 -&gt; buy , 4 -&gt; like , 5 -&gt; Logout user_events = [ Event(event_time=datetime.strptime('2018-04-20 10:00:00', "%Y-%m-%d %H:%M:%S"), event_type=1), Event(event_time=datetime.strptime('2018-04-20 12:00:00', "%Y-%m-%d %H:%M:%S"), event_type=2), Event(event_time=datetime.strptime('2018-04-20 14:00:00', "%Y-%m-%d %H:%M:%S"), event_type=3), Event(event_time=datetime.strptime('2018-04-20 16:00:00', "%Y-%m-%d %H:%M:%S"), event_type=4), Event(event_time=datetime.strptime('2018-04-20 19:00:00', "%Y-%m-%d %H:%M:%S"), event_type=5), Event(event_time=datetime.strptime('2018-04-21 07:00:00', "%Y-%m-%d %H:%M:%S"), event_type=1), Event(event_time=datetime.strptime('2018-04-21 10:00:00', "%Y-%m-%d %H:%M:%S"), event_type=2), Event(event_time=datetime.strptime('2018-04-21 14:00:00', "%Y-%m-%d %H:%M:%S"), event_type=5) ] df = pd.DataFrame(user_events, columns=['event_time','event_type']) df = df.set_index('event_time') df['event_type'].plot() I'm trying to get something around this line. Any advise is appreciated. Complete working solution based in ALollz solution import pandas as pd # Used for the legend import numpy as np import matplotlib.pyplot as plt import matplotlib.lines as mlines import matplotlib.patches as mpatches from datetime import datetime from collections import namedtuple Event = namedtuple('Event',('event_time', 'event_type')) # event_type = 1 -&gt; Login, 2 -&gt; watch , 3 -&gt; buy , 4…
tagged with: matplotlib
answer count: 1
has title: Matplot lib add session( duration ) indicator and represent y-axis as stars

http://stackoverflow.com/comment/86863424
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49922911
has text: Please add the missing `...` code in the inner-most `for` loop that you left out of question.
type: Comment

http://stackoverflow.com/comment/87134795
score: 0
type: Comment
has text: @IshaGarg does your function work in Python with the same input?
comment on: http://stackoverflow.com/a/50049937
type: AnswerComment

http://stackoverflow.com/comment/86866344
type: Comment
comment on: http://stackoverflow.com/q/49923921
has text: Your second spark submit command is run against a standalone cluster running with a master on localhost. Have you installed and started a standalone cluster?
score: 0
type: QuestionComment

http://stackoverflow.com/a/50011499
type: Answer
has comment: http://stackoverflow.com/comment/87080143
has comment: http://stackoverflow.com/comment/87039598
has comment: http://stackoverflow.com/comment/87075259
upvote count: 2
answers question: http://stackoverflow.com/q/50011031
has comment: http://stackoverflow.com/comment/87079331
downvote count: 0
has comment: http://stackoverflow.com/comment/87080828
score: 2
has body: Here the same solution as @PatricArtner suggested but with the ring buffer. It may (or may not, I didn't check) work faster with big files. The idea is quite simple: we can create a list with the required size (number of lines you should keep) and a counter of current recording position cnt. For each new line, we should increase cnt by one and make modulo by size of our buffer. Therefore cnt is looping inside the list. For example if the list size is 5 cnt = (cnt+1)%5 will give 0 1 2 3 4 0 1 2 and so on. Every step the cnt will point to the oldest data in our list, which will be substituted by new data. An example of the realization is bellow. t = """"zero line six line - surprize one line two line three line four line five line six line seven line eight line """ last5 = [None,None,None,None,None] cnt = 0 for l in t.split("\n"): last5[cnt]=l if 'six' in l: print last5[(cnt+1)%5] print last5[(cnt+2)%5] print last5[(cnt+3)%5] print last5[(cnt+4)%5] print last5[(cnt+0)%5] print cnt = (cnt+1)%5 An output is quite simple: None None None "zero line six line - surprize two line three line four line five line six line NOTE: If you read from a file, and the file is quite big and strings which you need to keep are huge (for example, gene sequences) and your condition doesn't trigger so often, be clever, do not keep strings in memory. Create a list of positions in the file where last strings start and reread them if you need. Below is an example of how to make it very fast... from numpy import random as rnd print "Creating the file ...." DNA=["G","C","T","A"] with open("bigdatafile","w") as fd: for i in xrange(5000): fd.write("".join([ DNA[rnd.randint(4)] for x in xrange(2000)])+"\n") print "DONE" print print "SEARCHING GGGGGGGGGGG" last5, cnt = [0,0,0,0,0], 1 with open("bigdatafile","r") as fd: for i,l in enumerate(fd.readlines()): last5[cnt] = last5[(cnt+4)%5]+len(l) if "GGGGGGGGGGG" in l: print "FIND!" fd.seek(last5[(cnt+1)%5]) print fd.read(last5[cnt]-last5[(cnt+1)%5]) cnt…

http://stackoverflow.com/comment/86993920
comment on: http://stackoverflow.com/a/49988613
score: 0
type: AnswerComment
has text: I tried changing this line:easily_apply.append(result.find_elements_by_xpath("//a[@href]")). Easily apply is appending session
type: Comment

http://stackoverflow.com/q/49965089
downvote count: 0
tagged with: django
favorite count: 0
accepted answer: http://stackoverflow.com/a/49965127
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49965127
tagged with: python
has body: I am looking to ban users from an action button in Django admin by setting user.is_active = False, for the selected users. class MyUserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name' , 'email') readonly_fields = ('first_name' , ('last_name') , ('email') , ('username')) actions = ['ban_users'] #USER BANNING FUNCTION def ban_users(self, request, queryset): user_obj = User.objects.get(username= 'username') user_obj.update(is_active = False) user_obj.save() admin.site.unregister(User) admin.site.register(User, MyUserAdmin) I've tried a few ways,and It either ends up banning all the users including super users or gives the error : User matching query does not exist. Its a simple function I am trying to implement I know,but any help would be appreciated.
type: Question
upvote count: 2
tagged with: django-admin
has title: Django Admin,trouble setting user.is_active to FALSE(banning) through admin action button
answer count: 1

http://stackoverflow.com/a/49999585
has comment: http://stackoverflow.com/comment/87020486
has body: HI can you try the below configuration: import os from django.core.wsgi import get_wsgi_application import sys sys.path.append('/var/www/html/DatasystemsCORE') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DatasystemsCORE.settings") application = get_wsgi_application() Apache2 python wsgi module sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 &lt;VirtualHost *:80&gt; ServerName dev.example.com #your server name ServerAlias dev.example.com #your server alias DocumentRoot #your document root WSGIProcessGroup dev.example.com WSGIPassAuthorization On WSGIDaemonProcess dev.example.com python-home=/home/robert/django/robertenv python-path=/var/www/html/DatasystemsCORE &lt;Here should be your virtual env path &gt; WSGIScriptAlias / /var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py Alias /static/ /var/www/html/DatasystemsCORE/static/Theme/ #static directory &lt;Directory /var/www/html/DatasystemsCORE/static/Theme/&gt; Require all granted &lt;/Directory&gt; &lt;Directory /var/www/html/DatasystemsCORE/DatasystemsCORE&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; &lt;/VirtualHost&gt; Use above virtual host configuration
has comment: http://stackoverflow.com/comment/87018104
has comment: http://stackoverflow.com/comment/87021655
has comment: http://stackoverflow.com/comment/87019108
has comment: http://stackoverflow.com/comment/87018880
has comment: http://stackoverflow.com/comment/87020587
type: Answer
answers question: http://stackoverflow.com/q/49998997
has comment: http://stackoverflow.com/comment/87020641
has comment: http://stackoverflow.com/comment/87020390
has comment: http://stackoverflow.com/comment/87018428
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87018333
downvote count: 0

http://stackoverflow.com/comment/87030218
type: AnswerComment
has text: @naveengullipalli Don't try to put code in comments. Add the new code at the end of the question (don't remove the original code with the problem).
score: 1
comment on: http://stackoverflow.com/a/50006604
type: Comment

http://stackoverflow.com/comment/87089004
has text: Please see my edit.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50035543
type: AnswerComment

http://stackoverflow.com/comment/135432909
score: 0
has text: Tried this, but did not work. The overlay slides out for about two seconds.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49939793

http://stackoverflow.com/q/50024764
type: Question
has title: Complex csv data mapping based on tables using python?
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have csv data like: id;12;12;13;13 company;Fox century;Fox century;Apple company;Apple company ticker;fox;fox;appl;appl industry code;2;2;3;3 indicator; Share Price; Common Shares Outstanding;Share Price;Common Shares Outstanding 2011-11-04; 2.72; 65046.232; 2.33; 3443 2012-02-06; 2.89; 65065.558; 2.44; 4242 2012-05-04; 3.04; 64788.687; 2.44; 2222 ......................................... Each row contain id,company,ticker;industrycode;indicator;2011-11-04(date);2012-02-06(date);..etc. I want to insert this data based on my db model: I have 2 tables company,Indicator company tables has 4 column:Id(primary_key),companyname,ticker,industry code and Indicator tables has 4 column:Share Price; Common Shares Outstanding,date,id(foreign key) I tried company tables and i successfully insert data into it using following code logic: with open('testss.csv', newline='') as f_input: csv_input = csv.reader(f_input, skipinitialspace=True) block = [] for row in csv_input: if len(row): if row[0] == 'id': if block: print(block) block = [row] else: block.append(row) for i in range(1,len(block[0])): print (block[0][0]+" : "+block[0][i]) print (block[1][0]+" : "+block[1][i]) print (block[2][0]+" : "+block[2][i]) print (block[3][0]+" : "+block[3][i]) I did not understand how to insert data in indicator table like this: id|date |SharePrice | Common Shares Outstanding 12|2011-11-04| 2.72 | 65046.232 13|2011-11-04|2.33 | 3443 Please give some logic(code Example) to implement this.
has answer: http://stackoverflow.com/a/50026997
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/50068042
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: add_patch is an axes method, not something directly under pyplot. Just change your commented line to: plt.gca().add_patch(rect) gca() gets the current active axes in pyplot.
accepted answer of: http://stackoverflow.com/q/50067977
has comment: http://stackoverflow.com/comment/87152836
answers question: http://stackoverflow.com/q/50067977
type: Answer

http://stackoverflow.com/comment/86913483
type: Comment
type: QuestionComment
score: 0
has text: Have you tried looking at my answer? There is example code in responses to the linked question
comment on: http://stackoverflow.com/q/49947856

http://stackoverflow.com/comment/87081335
type: Comment
has text: In your example, (samples, timesteps, features) is (120, 5, 3). Am I right?
type: AnswerComment
comment on: http://stackoverflow.com/a/50028462
score: 0

http://stackoverflow.com/a/49983901
accepted answer of: http://stackoverflow.com/q/49973060
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/87003660
has comment: http://stackoverflow.com/comment/87001590
has body: "The Bible" for tasks like this: [Python.Docs]: ctypes - A foreign function library for Python. I modified your code (found a bunch of problems, out of which some were critical). code00.py: #!/usr/bin/env python import ctypes as cts import sys import time from ctypes import wintypes as wts wts.BYTE = cts.c_ubyte class KEYBDINPUT(cts.Structure): _fields_ = ( ("wVk", wts.WORD), ("wScan", wts.WORD), ("dwFlags", wts.DWORD), ("time", wts.DWORD), ("dwExtraInfo", wts.PULONG), ) class INPUT(cts.Structure): _fields_ = ( ("type", wts.DWORD), ("ki", KEYBDINPUT), ("padding", wts.BYTE * 8) ) INPUT_KEYBOARD = 1 # Also defined by win32con if you have pywin32 installed INPUT_LEN = cts.sizeof(INPUT) LPINPUT = cts.POINTER(INPUT) user32_dll = cts.windll.user32 SendInput = user32_dll.SendInput SendInput.argtypes = (wts.UINT, LPINPUT, cts.c_int) SendInput.restype = wts.UINT def send_input(_input): return SendInput(1, cts.byref(_input), INPUT_LEN) def keyboard(code, flags=0): return INPUT(INPUT_KEYBOARD, (KEYBDINPUT(code, code, flags, 0, None))) def main(*argv): time.sleep(2) nb_cycles = 3 for _ in range(nb_cycles): time.sleep(0.5) # 3 seconds # Key "c" for debug, but ideally use 0x7E for "F15" ret = send_input(keyboard(ord("C"))) #print(ret) sys.stdout.write(".") sys.stdout.flush() if __name__ == "__main__": print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform)) rc = main(*sys.argv[1:]) print("\nDone.\n") sys.exit(rc) Notes: Initially, I defined the INPUT structure having only its 1st 2 members, but took a look at [MS.Learn]: INPUT structure (winuser.h) and noted that the union consists of: MOUSEINPUT KEYBDINPUT HARDWAREINPUT Did some tests and noted that MOUSEINPUT has the largest size out of the 3 structs, and it's 8 bytes greater than KEYBDINPUT (for both 032bit and 064bit), so I added the (dummy) (padding) member. Normally, I wouldn't expect that SendInput to go beyond KEYBDIN…
has comment: http://stackoverflow.com/comment/87017719
type: AcceptedAnswer
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/87010952
has comment: http://stackoverflow.com/comment/87018087
answers question: http://stackoverflow.com/q/49973060
has comment: http://stackoverflow.com/comment/87002500

http://stackoverflow.com/comment/86924643
has text: @Aran-Fey, That is for to find out unique in list. That is i achieved it. I am looking for How to find all values are different in list
score: 0
comment on: http://stackoverflow.com/q/49954037
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87115737
comment on: http://stackoverflow.com/q/50049487
type: Comment
type: QuestionComment
has text: `pymysql.Connection` is a function that returns a `pymysql.connections.Connection` object. Try `class database_connector(pymysql.connections.Connection):`
score: 2

http://stackoverflow.com/a/50031564
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87121063
answers question: http://stackoverflow.com/q/50031376
has comment: http://stackoverflow.com/comment/87104706
upvote count: 2
has body: For parent.pets.all(), I think you could use children as a secondary join condition, and treat it as an associative entity or junction table. It depends on your tables but that would look something like: Parent.pets = relationship( Pet, backref='parent' primaryjoin=Pet.child_id == Child.id, secondaryjoin=Child.parent_id == Parent.id ) You could also pretty reasonably make a backref parent if you so choose - this would let you access both parent_a.pets as well as pet_a.parent.
type: Answer

http://stackoverflow.com/comment/86954464
comment on: http://stackoverflow.com/q/49968493
type: Comment
type: QuestionComment
has text: @HenryM I am still a bit confused? I am using the correct path and pycharm also still allows me to import the article class(using intelisense)? Also the same method of including a class is what daveoncode does using the "from" and "import" keywords?
score: 0

http://stackoverflow.com/comment/129428885
type: Comment
type: QuestionComment
score: 0
has text: See also: [How to restore a builtin that I overwrote by accident?](https://stackoverflow.com/questions/17152760/)
comment on: http://stackoverflow.com/q/49987815

matrix
tags question: http://stackoverflow.com/q/50000574
tags question: http://stackoverflow.com/q/49959038
tags question: http://stackoverflow.com/q/50001201
tags question: http://stackoverflow.com/q/50047755
tags question: http://stackoverflow.com/q/50067153
tags question: http://stackoverflow.com/q/49926397
tags question: http://stackoverflow.com/q/49982746
tags question: http://stackoverflow.com/q/50040055
tags question: http://stackoverflow.com/q/50004158
tags question: http://stackoverflow.com/q/49922123
tags question: http://stackoverflow.com/q/49962404
tag name: matrix
tags question: http://stackoverflow.com/q/49995237
tags question: http://stackoverflow.com/q/49978496
tags question: http://stackoverflow.com/q/49995953
tags question: http://stackoverflow.com/q/49927761
tags question: http://stackoverflow.com/q/49990881
tags question: http://stackoverflow.com/q/50002669
tags question: http://stackoverflow.com/q/50000520
tags question: http://stackoverflow.com/q/50050631
tags question: http://stackoverflow.com/q/49988009
tags question: http://stackoverflow.com/q/49984553
tags question: http://stackoverflow.com/q/50033364
tags question: http://stackoverflow.com/q/49993101
tags question: http://stackoverflow.com/q/49958078
tags question: http://stackoverflow.com/q/49922674
type: Tag
tags question: http://stackoverflow.com/q/49979759
tags question: http://stackoverflow.com/q/50047749

http://stackoverflow.com/comment/87096670
has text: Flask, not *flash
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50019063
score: 0

http://stackoverflow.com/q/49946717
accepted answer: http://stackoverflow.com/a/49947352
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/49947352
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/86910759
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49948738
linked to: http://stackoverflow.com/q/1912434
has comment: http://stackoverflow.com/comment/86910696
tagged with: python
has body: I am doing a Python exercise, and it requires me to get the top news from the Google news website by web scraping and print to the console. As I was doing it, I just used the Beautiful Soup library to retrieve the news. That was my code: import bs4 from bs4 import BeautifulSoup import urllib.request news_url = "https://news.google.com/news/rss"; URLObject = urllib.request.urlopen(news_url); xml_page = URLObject.read(); URLObject.close(); soup_page = BeautifulSoup(xml_page,"html.parser"); news_list = soup_page.findAll("item"); for news in news_list: print(news.title.text); print(news.link.text); print(news.pubDate.text); print("-"*60); But it kept giving me errors by not printing the 'link' and 'pubDate'. After some research, I saw some answers here on Stack Overflow, and they said that, as the website uses Javascript, one should use the Selenium package in addition to Beautiful Soup. Despite not understanding how Selenium really works, I updated the code as following: from bs4 import BeautifulSoup from selenium import webdriver import urllib.request driver = webdriver.Chrome("C:/Users/mauricio/Downloads/chromedriver"); driver.maximize_window(); driver.get("https://news.google.com/news/rss"); content = driver.page_source.encode("utf-8").strip(); soup = BeautifulSoup(content, "html.parser"); news_list = soup.findAll("item"); print(news_list); for news in news_list: print(news.title.text); print(news.link.text); print(news.pubDate.text); print("-"*60); However, when I run it, a blank browser page opens and this is printed to the console: raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed (Driver info: chromedriver=2.38.551601 (edb21f07fc70e9027c746edd3201443e011a61ed),platform=Windows NT 6.3.9600 x86_64)
possible better answer: http://stackoverflow.com/a/49948738
type: Question
score: 0
answer count: 2
has title: Web Scraping with Python, Beautiful Soup, and Selenium not working

http://stackoverflow.com/comment/87149798
has text: So i have to write ````data = leCursor.execute('SELECT * FROM tweet WHERE texte pattern REGEXP ?',mot).fetchall()```` and ````connexion.create_function("REGEXP", 2, fonctionRegex)```` ?
comment on: http://stackoverflow.com/a/50066566
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86948202
has text: @Sylweester it does. If you write this: (s-sum '((5 2) (3 1 b) (22 2 c))), you will get (7 11 24). It does not use print function or others like that, but it returns a new list, which contains the sums of every sublist.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49964248
score: 0

http://stackoverflow.com/q/50021971
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87061654
tagged with: django
favorite count: 0
has comment: http://stackoverflow.com/comment/87059944
has comment: http://stackoverflow.com/comment/87061588
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87061395
score: 1
has body: I have two different forms in my index.html template and in both the forms i'm using csrf token. The problem that i'm facing is when I try to update my form i'm getting "CSRF verification failed. Request aborted." I've searched almost all the questions in this site and other websites and did everything still the error is shown. This is my first form which adds student entry: {% csrf_token %} Your name: Course: Roll No.: Address: This is my second form which is pre-populated when i click "edit" button on my template. when i click "update" button csrf token verification failed is displayed. {% csrf_token %} Your name: Course: Roll No.: Address: This is my ajax request: function update_entry(id) { var id = id $.ajax({ url: "{% url 'studentapp:index' %}", type: "POST", data:{ 'csrfmiddlewaretoken': '{{ csrf_token }}', 'id' : id, }, success: function(response){ $(".response").html(response.template) $("#editform").modal("show"); } }); } function update_property(id) { window.location.replace("/studentapp/editrow" + id+"/"); }
has comment: http://stackoverflow.com/comment/87064016
tagged with: python
accepted answer: http://stackoverflow.com/a/50043571
type: Question
has answer: http://stackoverflow.com/a/50043571
has comment: http://stackoverflow.com/comment/87063795
has comment: http://stackoverflow.com/comment/87061361
has title: when i click the button to update my form CSRF verification failed pop ups

argparse
tags question: http://stackoverflow.com/q/49969605
tags question: http://stackoverflow.com/q/50008913
tags question: http://stackoverflow.com/q/50071515
type: Tag
tags question: http://stackoverflow.com/q/50021282
tags question: http://stackoverflow.com/q/50014265
tags question: http://stackoverflow.com/q/50072557
tag name: argparse

http://stackoverflow.com/q/50028920
has comment: http://stackoverflow.com/comment/87905104
has comment: http://stackoverflow.com/comment/87227765
tagged with: python
has body: I have a python program that reads serial port and then acting as ModbusTCP server updates Modbus registers. I have a problem with reading Modbus registers with Modbus client, if I set time = 5 # Update delay it doesn't even show values, if I set it to 10 it does update values and I can read them with modbus client, but values are updating too slow. I do understand the problem. Reading from serial port should be separate function, it should wait for serial port to receive values and then add these values to modbus server registers. While serial port is waiting for values, modbus client should be able to read values already added to modbus server registers. When LoopingCall calls updating_writer() it executes ser_read_JB1 = ser_JB1.read(386) and I think code just stops there waiting for serial data to be received and while it waits # modbus part is not executed, so modbus client is requesting data, but modbus server is unable to respond. Code: import serial from pymodbus.server.async import StartTcpServer from pymodbus.server.async import StartUdpServer from pymodbus.device import ModbusDeviceIdentification from pymodbus.datastore import ModbusSequentialDataBlock from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer from twisted.internet.task import LoopingCall import logging # debug logging.basicConfig() log = logging.getLogger() log.setLevel(logging.DEBUG) # serial port settings ser = serial.Serial('COM3', 9600, parity=serial.PARITY_EVEN) def updating_writer(a): # serial read part # JB1 Data # read the whole package ser_read_JB1 = ser_JB1.read(386) # convert ascii to hex aTOh_JB1 = "".join("{:02x}".format(c) for c in ser_read_JB1) # convert to string iTOs_JB1 = str(aTOh_JB1) # bl_xx_JB1 location of the first byte to read # from string 2 char = 1 byte ### Momentānā jauda ### bl_MJ_JB1 = 258 b_konv_MJ_JB1 = (iTOs_JB1[bl_MJ_JB1]+iTOs_JB1[bl_MJ_JB1+1]+ iTOs_JB1[bl_MJ_JB1+2]+iTOs_JB1[bl…
tagged with: pymodbus
score: 0
answer count: 0
has title: Proper python program sequence/timing
type: Question
tagged with: pyserial
type: UnansweredQuestion

http://stackoverflow.com/comment/87289338
has text: I've used two methods for registering routes so far: (1) a function which takes the app object and registers all routes or (2) using flask_restful which separates the routes from the app object. The former tends to get a bit cluttered for bigger projects though.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50106159

http://stackoverflow.com/comment/87091972
score: 0
type: AnswerComment
has text: Ah didn't see this reply. Thanks so much, this is very close to what I need - except that eats the negative sign. Could you kindly update to fix this issue?
comment on: http://stackoverflow.com/a/50037426
type: Comment

http://stackoverflow.com/a/49970284
answers question: http://stackoverflow.com/q/49970209
has body: The histogram is correctly showing you that each value appears once. In order to show something smoother, you might want to group counts by quantiles and count, displaying the histogram of the result: testseries.groupby(pd.cut(testseries.astype(float), 10)).sum().hist() Example import pandas as pd import numpy as np testseries = pd.Series(np.random.randn(100000)) testseries.groupby(pd.cut(testseries.astype(float), 10)).sum().hist();
has comment: http://stackoverflow.com/comment/86956572
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86956675
accepted answer of: http://stackoverflow.com/q/49970209
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/87047627
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50014969
has text: Do you get form pre-populated now ?
type: Comment

django-database
type: Tag
tag name: django-database
tags question: http://stackoverflow.com/q/50016668

http://stackoverflow.com/a/50024508
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50013162
has body: Possibly the issue derives because you are pairing a pandas Series (temp1 from value_counts call) plot and a pandas DataFrame (temp2 form pivot_table call) plot. Since your pivot table results in a one-column dataframe, consider squeeze() to downcast dataframe into a 1-dimensional series. And then from there plot as usual: temp1 = df['Credit_History'].value_counts(ascending=True).sort_index() temp2 = df.pivot_table(values='Loan_Status', index='Credit_History', aggfunc=lambda x: x.map({'Y':1,'N':0}).mean()) temp2 = temp2.squeeze() Below demonstrates with random data in the hope df replicates your original data structure: import matplotlib.pyplot as plt import pandas as pd import numpy as np np.random.seed(42518) # SEED FOR RANDOM REPRODUCIBILITY df = pd.DataFrame({'Credit_History': np.random.choice(['debt', 'credit'], 50), 'Loan_Status': np.random.choice(['Y', 'N'],50), 'Amount': abs(np.random.randn(50))*1000 }, columns = ['Credit_History','Loan_Status','Amount']) temp1 = df['Credit_History'].value_counts(ascending=True).sort_index() temp2 = df.pivot_table(values='Loan_Status', index='Credit_History', aggfunc=lambda x: x.map({'Y':1,'N':0}).mean()) temp2 = temp2.squeeze() fig = plt.figure(figsize=(8,4)) ax1 = fig.add_subplot(121) temp1.plot(kind = 'bar') ax2 = fig.add_subplot(122) temp2.plot(kind = 'bar') plt.show()
type: Answer
answers question: http://stackoverflow.com/q/50013162

http://stackoverflow.com/comment/86985007
score: 0
type: Comment
type: QuestionComment
has text: Yes, I write the answer below?
comment on: http://stackoverflow.com/q/49984012

http://stackoverflow.com/a/49938773
has body: In order to have the correct result we should use df.loc[pd.IndexSlice["1955":"1956"], 'GDP'].min() As the years are string type.
score: 0
answers question: http://stackoverflow.com/q/49937866
type: Answer

http://stackoverflow.com/comment/87090611
type: Comment
has text: Worth noting that the `0`, `1` and `str()` are all optional. `print('"{}" : "{}"'.format(name, idnum))` yields the same result.
comment on: http://stackoverflow.com/a/50037243
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87150261
comment on: http://stackoverflow.com/q/50066816
score: 0
has text: if len(correct) == len(randomSecretPhrase):
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87029041
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50006285
score: 1
has text: Take a look: https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for

http://stackoverflow.com/comment/87481789
type: QuestionComment
has text: Did an answer below help? Feel free to accept an answer (green tick on left), or ask for clarification.
score: 1
comment on: http://stackoverflow.com/q/50045388
type: Comment

http://stackoverflow.com/q/50010929
upvote count: 10
accepted answer: http://stackoverflow.com/a/50048350
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/50048350
possible better answer: http://stackoverflow.com/a/55664372
downvote count: 0
has body: Let us start with an input that is a simple time series and try to build an autoencoder that simply fourier transforms then untransforms our data in keras. If we try to do this: inputs = Input(shape=(MAXLEN,1), name='main_input') x = tf.spectral.rfft(inputs) decoded = Lambda(tf.spectral.irfft)(x) Then the third line throws an error when entered: &gt;&gt; ValueError: Tensor conversion requested dtype complex64 for Tensor with dtype float32 You see, the output of tf.spectral.irfft is float32 but it looks like Lambda thinks it is complex64?? (Complex64 is the input x from the previous step) We can fix that error at model entry time with: inputs = Input(shape=(MAXLEN,1), name='main_input') x = tf.spectral.rfft(inputs) decoded = Lambda(tf.cast(tf.spectral.irfft(x),dtype=tf.float32))) This is accepted at input time but then when we try to build the model: autoencoder = Model(inputs, decoded) It generates the error: TypeError: Output tensors to a Model must be Keras tensors. Found: &lt;keras.layers.core.Lambda object at 0x7f24f0f7bbe0&gt; Which I guess is reasonable and was the reason I didn't want to cast it in the first place. Main question: how do I successfully wrap the tf.spectral.irfft function which outputs float32 ? More general question for learning: Let's assume I actually want to do something between the rfft and the irfft, how can I cast those imaginary numbers into absolute values without breaking keras so I can apply various convolutions and the like?
tagged with: keras
has answer: http://stackoverflow.com/a/55664372
has title: Can we use tf.spectral fourier functions in keras?
tagged with: tensorflow
favorite count: 0
type: Question
score: 10
has answer: http://stackoverflow.com/a/50161767
tagged with: python

http://stackoverflow.com/q/49962265
has title: C to Python via Ctypes - Wrapping Struct of Function Pointers to Static Functions
downvote count: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/c
answer count: 1
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49964860
has body: I have structs in a C library that are like this. The function pointers in DataFn point to static functions. .h struct Data { int i; int *array; }; typedef struct { bool (* const fn1) (struct Data*, const char *source); .... } DataFn; extern DataFn const DATAFUNC Using objdump, the table only contains DATAFUNC and a few other things from gcc. This is fine in C where calling fn1 would go like DATAFUNC.fn1(..., ...), but how would something like this be wrapped around so fn1 can be called in python w/ ctypes? Example python libc = ctypes.cdll.LoadLibrary("./data.so") print(libc.DATAFUNC) results in &lt;_FuncPtr object at 0x6ffffcd7430&gt; This is similar, but there isn't a factory function.
linked to: http://stackoverflow.com/q/3854388
favorite count: 0
tagged with: struct
tagged with: ctypes
type: Question
upvote count: 2
tagged with: function-pointers
accepted answer: http://stackoverflow.com/a/49964860

http://stackoverflow.com/comment/86869438
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49926710
score: 1
has text: There is way too much code here. Which part is generating the error?

http://stackoverflow.com/q/50028907
has answer: http://stackoverflow.com/a/50028954
has answer: http://stackoverflow.com/a/50028986
has comment: http://stackoverflow.com/comment/87074203
tagged with: python
has body: It's the end of my first month coding with python and I'm struggling with a piece of code that seemed simpler in my mind. I'm trying to edit array values based on the positions given by another array generated by np.argwhere. For example: a = np.arange(6).reshape(2,3) b = np.argwhere(a&gt;3) c = ([7,8,9],[10,11,12]) Now I want to change the values in c that are in the same position as the values that are greater than 3 in the array a. I'm trying to avoid a for loop because of the size of the real data I am working on. Thanks in advance!
has comment: http://stackoverflow.com/comment/87073887
score: 0
answer count: 2
type: UnansweredQuestion
has title: Edit an array value using another array with the positions that should change
type: Question

http://stackoverflow.com/a/50048262
answers question: http://stackoverflow.com/q/50046876
score: 0
type: Answer
has body: Generally when you have categorical data you try to encode them into a "numerical" value. Now in your case consider social media : twitter, facebook, google-plus. You might be tempted to encode them as twitter:0 , facebook: 1, google-plus: 2. But this encoding has problem: it is implying to machine learning algorithm google-plus is twice the facebook, which is not what you want. Enter one hot encoding: it converts categorical data into vector of bits . So you will have number of bits equal to number of categories present in your data: social media | binary vector (bits in order: is_twitter, is_facebook, is_google_plus) twitter | 1, 0, 0 facebook | 0, 1, 0 google-plus | 0, 0, 1 Now you can apply any ML algorithm, since all of your data is numerical. More here: One hot encoding in scikit

http://stackoverflow.com/a/66769723
has body: ttk.Treeview seems to split a given string by spaces to multiple values. If you don't like this behaviour you have to pass the value as a tuple. So instead of tv.insert('', 'end', text='foo', values=('Lorem ipsum dolor sit amet')) you should write tv.insert('', 'end', text='foo', values=('Lorem ipsum dolor sit amet', ))
answers question: http://stackoverflow.com/q/49935927
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86940508
type: QuestionComment
has text: @BurakÖztürk bulk create can use data from another model?...
type: Comment
comment on: http://stackoverflow.com/q/49962143
score: 0

dataframe
tags question: http://stackoverflow.com/q/50007292
tags question: http://stackoverflow.com/q/49977723
tags question: http://stackoverflow.com/q/49962361
tags question: http://stackoverflow.com/q/50002754
tags question: http://stackoverflow.com/q/49963491
tags question: http://stackoverflow.com/q/50002345
tags question: http://stackoverflow.com/q/49957164
tags question: http://stackoverflow.com/q/49950003
tags question: http://stackoverflow.com/q/49989209
tags question: http://stackoverflow.com/q/49949011
tags question: http://stackoverflow.com/q/50061600
tags question: http://stackoverflow.com/q/50068131
tags question: http://stackoverflow.com/q/50007449
tags question: http://stackoverflow.com/q/49947820
tags question: http://stackoverflow.com/q/50005565
tags question: http://stackoverflow.com/q/49984905
tags question: http://stackoverflow.com/q/49943627
tags question: http://stackoverflow.com/q/49942361
tags question: http://stackoverflow.com/q/49956302
tags question: http://stackoverflow.com/q/49966967
tags question: http://stackoverflow.com/q/49981566
tags question: http://stackoverflow.com/q/49953471
tags question: http://stackoverflow.com/q/49967364
tags question: http://stackoverflow.com/q/50049216
tags question: http://stackoverflow.com/q/49951768
tags question: http://stackoverflow.com/q/49980394
tags question: http://stackoverflow.com/q/50026089
tags question: http://stackoverflow.com/q/49944890
tags question: http://stackoverflow.com/q/49926897
tags question: http://stackoverflow.com/q/49922915
tags question: http://stackoverflow.com/q/50042441
tags question: http://stackoverflow.com/q/49926534
tags question: http://stackoverflow.com/q/50041398
tags question: http://stackoverflow.com/q/49918259
tags question: http://stackoverflow.com/q/50071669
tags question: http://stackoverflow.com/q/50002289
tags question: http://stackoverflow.com/q/49961846
tags question: http://stackoverflow.com/q/49927660
tags question: http://stackoverflow.com/q/50024431
tags question: http://stackoverflow.com/q/49954091
tags question: http://stackoverflow.com/q/50030448
tags question: http://stackoverflow.com/q/50067349
tags question: http://stackoverflow.com/q/49955567
tags question: http://stackoverflow.com/q/50045054
tags question: http://stackoverflow.com/q/50060320
tags question: http://stackoverflow.com/q/49940115
tags question: http://stackoverflow.com/q/50033724
tags question: http://stackoverflow.com/q/49971958
tags question: http://stackoverflow.com/q/50020983
tags question: http://stackoverflow.com/q/50025440
tags question: http://stackoverflow.com/q/49957002
tags question: http://stackoverflow.com/q/49927501
tags question: http://stackoverflow.com/q/49931251
tags question: http://stackoverflow.com/q/49961543
tags question: http://stackoverflow.com/q/49997683
tags question: http://stackoverflow.com/q/49988596
tags question: http://stackoverflow.com/q/49951836
tags question: http://stackoverflow.com/q/49923480
tags question: http://stackoverflow.com/q/50049823
tags question: http://stackoverflow.com/q/50012404
tags question: http://stackoverflow.com/q/50002415
tags question: http://stackoverflow.com/q/50068752
tags question: http://stackoverflow.com/q/50051684
tags question: http://stackoverflow.com/q/49961879
tags question: http://stackoverflow.com/q/50068443
tags question: http://stackoverflow.com/q/50071727
tags question: http://stackoverflow.com/q/49925598
tags question: http://stackoverflow.com/q/50030744
tags question: http://stackoverflow.com/q/49976238
tags question: http://stackoverflow.com/q/49962989
tags question: http://stackoverflow.com/q/49924634
tags question: http://stackoverflow.com/q/49942464
tags question: http://stackoverflow.com/q/49960365
tags question: http://stackoverflow.com/q/49955396
tags question: http://stackoverflow.com/q/49937866
tags question: http://stackoverflow.com/q/50071144
tags question: http://stackoverflow.com/q/49975878
tags question: http://stackoverflow.com/q/49950324
tags question: http://stackoverflow.com/q/50040847
tags question: http://stackoverflow.com/q/49981497

http://stackoverflow.com/comment/86912881
has text: @Andersson Updated original post
comment on: http://stackoverflow.com/q/49947704
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87164141
comment on: http://stackoverflow.com/a/50073557
type: AnswerComment
score: 0
has text: @JohnnyCortez check my edit, rewrited it as I think I understand your problem now.
type: Comment

http://stackoverflow.com/q/50027426
has comment: http://stackoverflow.com/comment/87071208
has comment: http://stackoverflow.com/comment/87071072
has answer: http://stackoverflow.com/a/50027463
tagged with: python
has title: How to build SQL Select statement with columns specified by user?
linked to: http://stackoverflow.com/q/10950362
score: 0
has body: I want to select columns by name specified by user, but I want to avoid SQL Injection. I think something like that isn't a good idea: column_one = input("Column one") column_two = input("Column two") column_three = input("Column three") sql.execute("Select {}, {}, {} from table;".format(column_one, column_two, column_three)) I can use something like that: con = sql.connect("example.sqlite3") select = "select ? from table;" t = ('id', ) cur = con.cursor() cur.execute(selec, t) rows = cur.fetchall() con.commit() con.close() for row in rows: for cell in row: print(cell) What I get is: id id id id id id id...
type: UnansweredQuestion
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/87073336
type: Question

http://stackoverflow.com/a/50038162
answers question: http://stackoverflow.com/q/50036183
has comment: http://stackoverflow.com/comment/101520721
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50036183
downvote count: 0
upvote count: 1
has body: After a few hours more of research and testing, it turns out that my issue was indeed due to USE_TZ, but not directly. The problem was that I didn't import my timezones correctly into my MySQL database. Firstly, I didn't have the required tables (which I found here on lines 60-72) Secondly, I didn't correctly set up my timezones. I ran mysql_tz_info_to_sql /usr/share/zoneinfo | mysql -u root where I should've ran mysql_tz_info_to_sql /usr/share/zoneinfo/ | mysql -u root mysql After correctly running that command and ensuring that I did indeed have the tables in my database, I was able to execute the Django Filter successfully. Thank you to everyone who helped, as I wouldn't have discovered the issue without your input!
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/95901344

http://stackoverflow.com/comment/87153151
has text: I use string just for clarify the string is a string, not anything else
type: AnswerComment
comment on: http://stackoverflow.com/a/50068275
score: 0
type: Comment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/50006331
tags question: http://stackoverflow.com/q/50054831
type: Tag
tags question: http://stackoverflow.com/q/50063542
tags question: http://stackoverflow.com/q/49985874
tags question: http://stackoverflow.com/q/49991670
tags question: http://stackoverflow.com/q/49937810
tags question: http://stackoverflow.com/q/49945414
tags question: http://stackoverflow.com/q/50006755
tags question: http://stackoverflow.com/q/50007028
tags question: http://stackoverflow.com/q/50007815
tags question: http://stackoverflow.com/q/50066635
tags question: http://stackoverflow.com/q/49943426
tags question: http://stackoverflow.com/q/49937891
tags question: http://stackoverflow.com/q/49940527
tags question: http://stackoverflow.com/q/49964963
tags question: http://stackoverflow.com/q/49990812
tags question: http://stackoverflow.com/q/49986115
tags question: http://stackoverflow.com/q/49949354
tags question: http://stackoverflow.com/q/50058709
tags question: http://stackoverflow.com/q/49932522
tags question: http://stackoverflow.com/q/50024085
tags question: http://stackoverflow.com/q/50045648
tag name: csv
tags question: http://stackoverflow.com/q/50039546
tags question: http://stackoverflow.com/q/49989356
tags question: http://stackoverflow.com/q/49934953
tags question: http://stackoverflow.com/q/49970810
tags question: http://stackoverflow.com/q/49994379
tags question: http://stackoverflow.com/q/50020380
tags question: http://stackoverflow.com/q/49996549
tags question: http://stackoverflow.com/q/50002053
tags question: http://stackoverflow.com/q/50071727
tags question: http://stackoverflow.com/q/49991434
tags question: http://stackoverflow.com/q/49976238
tags question: http://stackoverflow.com/q/49964340
tags question: http://stackoverflow.com/q/50060212
tags question: http://stackoverflow.com/q/50067194
tags question: http://stackoverflow.com/q/50060079
tags question: http://stackoverflow.com/q/49995641
tags question: http://stackoverflow.com/q/50070549
tags question: http://stackoverflow.com/q/49961746
tags question: http://stackoverflow.com/q/50068528
tags question: http://stackoverflow.com/q/49954294
tags question: http://stackoverflow.com/q/49960363
tags question: http://stackoverflow.com/q/50025612
tags question: http://stackoverflow.com/q/50031689
tags question: http://stackoverflow.com/q/49989902
tags question: http://stackoverflow.com/q/50037934
tags question: http://stackoverflow.com/q/49972718
tags question: http://stackoverflow.com/q/50012489
tags question: http://stackoverflow.com/q/50024764
tags question: http://stackoverflow.com/q/50033350
tags question: http://stackoverflow.com/q/49961872
tags question: http://stackoverflow.com/q/50043311
tags question: http://stackoverflow.com/q/50034477
tags question: http://stackoverflow.com/q/49970328
tags question: http://stackoverflow.com/q/50060231
tags question: http://stackoverflow.com/q/49943691
tags question: http://stackoverflow.com/q/50045353
tags question: http://stackoverflow.com/q/49927149
tags question: http://stackoverflow.com/q/49932226
tags question: http://stackoverflow.com/q/49945069
tags question: http://stackoverflow.com/q/49964998
tags question: http://stackoverflow.com/q/50007828
tags question: http://stackoverflow.com/q/50068987
tags question: http://stackoverflow.com/q/49943206
tags question: http://stackoverflow.com/q/50016607
tags question: http://stackoverflow.com/q/49953791
tags question: http://stackoverflow.com/q/49930650
tags question: http://stackoverflow.com/q/50060781
tags question: http://stackoverflow.com/q/49927557
tags question: http://stackoverflow.com/q/50065474
tags question: http://stackoverflow.com/q/49946216
tags question: http://stackoverflow.com/q/50020640
tags question: http://stackoverflow.com/q/50035827
tags question: http://stackoverflow.com/q/49951249
tags question: http://stackoverflow.com/q/50004017
tags question: http://stackoverflow.com/q/50059613
tags question: http://stackoverflow.com/q/49995728

http://stackoverflow.com/q/50069402
answer count: 1
has title: How to change stdin in jupyter notebook?
has answer: http://stackoverflow.com/a/50077618
tagged with: jupyter-notebook
favorite count: 0
type: Question
has body: I would like assign a file to sys.stdin so that I can read contents of the file with input(). The code below runs as expected as script but it is problematic when it is written in notebook. After calling function input() it shows me an input textbook, which I do not want since I reassigned stdin to a file. So, I expect that the line in the file would be read instead. import sys file = open("input.in") sys.stdin = file val = input() print(val) It seems to me notebook ignores sys.stdin. I couldn't find why this is happening and how to fix it. Thanks. Update I end up with overriding input function. It will do the job but I leave question open to see if someone has a better solution. file = open("input.in") input = file.readline
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 3
upvote count: 3

http://stackoverflow.com/comment/87085900
type: Comment
type: QuestionComment
has text: @Dan Mašek what does `glutInit()` do ?
comment on: http://stackoverflow.com/q/49979804
score: 0

http://stackoverflow.com/q/49992243
tagged with: numpy
type: Question
score: 9
has comment: http://stackoverflow.com/comment/87001231
has comment: http://stackoverflow.com/comment/87001304
answer count: 2
tagged with: intel-mkl
has title: Is numpy+mkl faster than numpy?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87001249
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/87001803
has answer: http://stackoverflow.com/a/50002267
has body: If numpy+mkl is faster, how much faster is it than numpy? I found that the numpy+mkl installation package is much larger than numpy, but I can't feel the difference in their speed.
has comment: http://stackoverflow.com/comment/87001294
has comment: http://stackoverflow.com/comment/90268016
upvote count: 10
has answer: http://stackoverflow.com/a/64773899
favorite count: 0

http://stackoverflow.com/comment/86915612
score: 0
type: Comment
has text: Engineero- About the same amount of columns to drop as to copy in my input file. So i picked copy.
type: QuestionComment
comment on: http://stackoverflow.com/q/49946758

http://stackoverflow.com/q/49959335
tagged with: python
has comment: http://stackoverflow.com/comment/86935299
linked to: http://stackoverflow.com/q/3488603
type: AnsweredQuestion
has title: Declaring path in pycharm not working
score: 0
answer count: 2
tagged with: pycharm
has comment: http://stackoverflow.com/comment/86935467
tagged with: pandas
has comment: http://stackoverflow.com/comment/86935324
has comment: http://stackoverflow.com/comment/86935520
has body: I am using Pycharm and I created the project in a folder called collaborative filtering. I have some csv in a folder called ml-latest-small that I also placed in the collaborative filtering folder that has the .py file I am working from. I am getting the following errors: Traceback (most recent call last): File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/movies.py", line 32, in &lt;module&gt; cf = CollabFilterDataset.from_csv(path, 'ratings.csv', 'userId', 'movieId', 'rating') File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/venv/lib/python3.6/site-packages/fastai/column_data.py", line 146, in from_csv df = pd.read_csv(os.path.join(path,csv)) File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/venv/lib/python3.6/site-packages/pandas/io/parsers.py", line 709, in parser_f return _read(filepath_or_buffer, kwds) File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/venv/lib/python3.6/site-packages/pandas/io/parsers.py", line 449, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/venv/lib/python3.6/site-packages/pandas/io/parsers.py", line 818, in __init__ self._make_engine(self.engine) File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/venv/lib/python3.6/site-packages/pandas/io/parsers.py", line 1049, in _make_engine self._engine = CParserWrapper(self.f, **self.options) File "/Users/usernamehere/Desktop/Machine Learning/Lesson 5/CollaborativeFiltering/venv/lib/python3.6/site-packages/pandas/io/parsers.py", line 1695, in __init__ self._reader = parsers.TextReader(src, **kwds) File "pandas/_libs/parsers.pyx", line 402, in pandas._libs.parsers.TextReader.__cinit__ File "pandas/_libs/parsers.pyx", line 718, in pandas._libs.parsers.TextReader._setup_parser_source FileNotFoundError: File b'/Users/usernamehere/Users/usernameher…
accepted answer: http://stackoverflow.com/a/49959790
has comment: http://stackoverflow.com/comment/86935282
has comment: http://stackoverflow.com/comment/86935482
type: Question
possible better answer: http://stackoverflow.com/a/49959444
has answer: http://stackoverflow.com/a/49959790
has answer: http://stackoverflow.com/a/49959444
has comment: http://stackoverflow.com/comment/86935539
has comment: http://stackoverflow.com/comment/86935321
has comment: http://stackoverflow.com/comment/86935566
has comment: http://stackoverflow.com/comment/86935246

http://stackoverflow.com/comment/90386400
score: 2
has text: This works perfectly, thanks so much! By the way, I submitted an edit for your last example to change `object_hook_pairs` to `object_pairs_hook`, got an error and spotted the mispelling.
type: Comment
comment on: http://stackoverflow.com/a/50013806
type: AnswerComment

http://stackoverflow.com/q/50050617
has title: Assign Unique Numeric Group IDs to Groups in Pandas
upvote count: 12
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50050735
has answer: http://stackoverflow.com/a/50050735
score: 12
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50050618
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
has body: I've consistently run into this issue of having to assign a unique ID to each group in a data set. I've used this when zero padding for RNN's, generating graphs, and many other occasions. This can usually be done by concatenating the values in each pd.groupby column. However, it is often the case the number of columns that define a group, their dtype, or the value sizes make concatenation an impractical solution that needlessly uses up memory. I was wondering if there was an easy way to assign a unique numeric ID to groups in pandas.
duplicate of: http://stackoverflow.com/q/45685254
favorite count: 0
possible better answer: http://stackoverflow.com/a/50050618
type: Question
linked to: http://stackoverflow.com/q/45685254

http://stackoverflow.com/comment/87012134
type: QuestionComment
type: Comment
has text: can you give a [mcve](https://stackoverflow.com/help/mcve)? `numpy.linalg` work with float64 on my machine
score: 1
comment on: http://stackoverflow.com/q/49997595

http://stackoverflow.com/comment/86990996
comment on: http://stackoverflow.com/a/49986822
has text: when i do that, it throws the following error: `TypeError: 'ItemIterator' object is not subscriptable`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49955687
has comment: http://stackoverflow.com/comment/86927924
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/97032960
downvote count: 0
tagged with: python
tagged with: paypal
has body: Im trying to create a monthly subscription payment with paypal. Im checking with paypal billing plans and agreements API https://developer.paypal.com/docs/integration/direct/billing-plans-and-agreements/ once executed, is the charge to the credit card recurring, or every billing cycle we have to do something (if so what) ?
score: 2
has comment: http://stackoverflow.com/comment/86927986
tagged with: paypal-subscriptions
has comment: http://stackoverflow.com/comment/86927807
has comment: http://stackoverflow.com/comment/86927706
has title: paypal billing plan and agreement API, does it auto charge the credit card on each cycle
has comment: http://stackoverflow.com/comment/87116835
favorite count: 0
type: Question
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/86901713
has text: this code sample is incomplete
comment on: http://stackoverflow.com/q/49942690
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86924108
type: Comment
comment on: http://stackoverflow.com/q/49953036
score: 0
type: QuestionComment
has text: Glad can help! Nice day!

http://stackoverflow.com/comment/87112970
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50048391
has text: Thanks.. Got it now
type: Comment

http://stackoverflow.com/q/50019420
has comment: http://stackoverflow.com/comment/87133654
has comment: http://stackoverflow.com/comment/87060154
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/53431231
has title: From django 1.6 to 1.11: AppRegistryNotReady exception
has comment: http://stackoverflow.com/comment/87055082
has body: In my REST-like API, I have a mechanism to allow users to customize models (add custom fields and add custom models). This relies on a set of models describing the customizations. Here is a simplified version of my code to show the concept. + myproject + customization . models.py class CustomModel(django.db.models.Model): # […] class CustomField(django.db.models.Model): # […] and + myproject + entities . models.py class RootEntityModel(django.db.models.Model): name = CharField(…) # […] from myproject import customization from myproject.customization.models import CustomField # Here apply the custom filters on the root entity type for custom_field in CustomField.objects.filter(entity__name='RootEntityModel').all(): customize.build_field_and_apply(custom_field, RootEntityModel) # Here instantiate custom models, etc # […] In Django 1.6, I have no problem making everything work. Now, transitionning to Django 1.11, I've had some cleanup to do, mainly because it's impossible to import a model inside the root package of an application. (see also this answer). I've eleminated every AppRegistryNotReady exception that I had, but for the one in myproject.entity.models module. Indeed, to build my Entities, I have to query to the CustomField and CustomModel tables, but as I'm currently building my models, Django forbids me to do so. I am stuck in this kind of circular dependency. Any thought towards a workaround are welcome. EDIT: Stack trace follows […] File "D:/Code/django-1.11/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:/Code/django-1.11/django/apps/registry.py", line 108, in populate app_config.import_models() File "D:/Code/django-1.11/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:/Python27/lib/importlib/__init__.py", line 37, in import_module __import__(name) File "D:/Code/resterserver/myproject/entities/models/__init__.py", line 369, in &lt;module&gt; for custom_fi…
linked to: http://stackoverflow.com/q/36233098
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/53431231
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50040244
has answer: http://stackoverflow.com/a/50051969
accepted answer: http://stackoverflow.com/a/50051969
tagged with: python
tagged with: kivy
has title: Kivy not showing an image
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87104242
favorite count: 0
type: Question
has body: I am trying to create a simple app that will present an image after a button is clicked. So far I have managed to create the button in the ShootButton class and bind it to the Bullet class. The problem is that after the 'Bullet' class is being called, the image does not appear. I know that the class is called because it does prints "test", but no image. from kivy.app import App from kivy.core.window import Window from kivy.uix.image import Image from kivy.uix.widget import Widget Window.size = (360, 640) class Game(Widget): pass class ShootButton(Widget): def shoot(self): shooting = Bullet() shooting.bullet_fly() class Bullet(Widget): def bullet_fly(self): img = Image(source='bullet.png') self.add_widget(img) print('test') class MyApp(App): def build(self): return Game() if __name__ == '__main__': MyApp().run() And the Kv file: &lt;Game&gt; ShootButton: &lt;ShootButton&gt; Button: text: "shoot!" size: 70,50 font_size: 20 pos: 100,100 on_press: root.shoot()
has answer: http://stackoverflow.com/a/50045334
possible better answer: http://stackoverflow.com/a/50045334

http://stackoverflow.com/a/50056102
score: 0
has comment: http://stackoverflow.com/comment/87136628
answers question: http://stackoverflow.com/q/50055848
type: AcceptedAnswer
has body: The number of steps for generating when X=1 is: N(1) = L At the recursive step, the number of steps is the number of steps at X-1, due to recursive call, plus L * N(X-1) due to the loops: N(X) = N(X-1) + L * N(X-1) Clearly L * N(X-1) dominates N(X-1), so we can disregard the N(X-1) term. The asymptotic cost will be O(L^X). LX happens to be also the number of the items in the result, so it's impossible that you have a better asymptotic cost for that using python lists.
type: Answer
has comment: http://stackoverflow.com/comment/87129820
accepted answer of: http://stackoverflow.com/q/50055848

http://stackoverflow.com/q/50023635
score: 5
has answer: http://stackoverflow.com/a/65344355
linked to: http://stackoverflow.com/q/15197673
has comment: http://stackoverflow.com/comment/87063735
linked to: http://stackoverflow.com/q/1894269
tagged with: arrays
possible better answer: http://stackoverflow.com/a/55858479
tagged with: python
has comment: http://stackoverflow.com/comment/87063685
has answer: http://stackoverflow.com/a/63780901
upvote count: 16
answer count: 4
linked to: http://stackoverflow.com/q/5387208
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87063352
has comment: http://stackoverflow.com/comment/87063442
has body: How would I convert the following string to an array with Python (this string could have an indefinite number of items)? '["Foo","Bar","Baz","Woo"]' This is definitely a string representation as well. type() gave: <class 'str'> I got it. interestedin = request.POST.get('interestedIn')[1:-1].split(',') interested = [] for element in interestedin: interested.append(element[1:-1]) Where request.POST.get('interestedIn') gave the '["Foo","Bar","Baz","Woo"]' string list "thing".
downvote count: 11
accepted answer: http://stackoverflow.com/a/50024614
has comment: http://stackoverflow.com/comment/87064716
has comment: http://stackoverflow.com/comment/87063531
has comment: http://stackoverflow.com/comment/87063383
has comment: http://stackoverflow.com/comment/104847895
has answer: http://stackoverflow.com/a/50024614
has comment: http://stackoverflow.com/comment/87063382
has comment: http://stackoverflow.com/comment/87063400
tagged with: string
has comment: http://stackoverflow.com/comment/87063406
has title: Python - convert a string to an array
has answer: http://stackoverflow.com/a/55858479
favorite count: 0
type: Question

http://stackoverflow.com/a/49985551
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: to handle corrupt files directly from Python, catch the relevant exception and skip the corrupt file: listtar=glob.glob(dataset_folder+'/*.tar') for file in listtar: try: with tarfile.open(file) as tar: tar.extractall(path=dataset_folder) except tarfile.ReadError: print("File {} is corrupt".format(file))
answers question: http://stackoverflow.com/q/49984765
accepted answer of: http://stackoverflow.com/q/49984765
type: AcceptedAnswer

http://stackoverflow.com/comment/86942521
score: 0
comment on: http://stackoverflow.com/q/49963241
has text: @dstrants ya I'm getting them, Lutz's solution solved the loop problem!
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49943011
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/96528605
has body: sort_values does not happen in place. So when you run: AB.sort_values(['geohash','timestamp']) It is not updating AB rather returning a copy AB.sort_values(['geohash','timestamp'], inplace=True) Will update AB Alternatively you can assign the sorted dataframe to a new variable AB_sorted = AB.sort_values(['geohash','timestamp']) AB_sorted geohash timestamp 0 a2a 15 2 a2b 15 1 b3a 14 3 b3b 15
type: Answer
accepted answer of: http://stackoverflow.com/q/49942912
has comment: http://stackoverflow.com/comment/105583603
upvote count: 6
answers question: http://stackoverflow.com/q/49942912
type: AcceptedAnswer

http://stackoverflow.com/q/49998999
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52306077
downvote count: 0
has title: Setting meta data tags with piexif
has body: I try to set specific meta data for jpegs with the piexif module. I get the respective dicts out of the piexif.load(). data = piexif.load(). They return {'GPS': {}, 'Exif': {}, 'Interop': {}, 'thumbnail': None, '1st': {}, '0th': {}}. (Maybe the answer is very obviouse but I am a little confused to the dicts) However, I would like to know where and what to write to set my focus length, the camera maker and model. The reason for that, I want to use the Regard3D reconstruction GUI from http://www.regard3d.org/index.php/documentation/details/picture-set. Therefore, I need to add the meta to the jpegs and the data of the camera into the camera db. This is needed for the triangulation step. Thank you very much in advance
upvote count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/jpeg
tagged with: exif
tagged with: metadata
score: 1
has answer: http://stackoverflow.com/a/49999336

http://stackoverflow.com/comment/87113590
type: QuestionComment
has text: This is not how you do validation in Django. For a start, use a form. And secondly, you must **absolutely not** write your own login mechanism, especially one as insecure as this.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50048674

http://stackoverflow.com/comment/87140249
comment on: http://stackoverflow.com/q/50051081
score: 0
type: Comment
type: QuestionComment
has text: @AmiTavory because the time info (1524771017235 in this case) is different in each file. And with my way, I have to manually choose it for each file.

http://stackoverflow.com/q/49989288
tagged with: python-2.7
tagged with: iterator
has body: class OddNum(): def __next__(x): if x%2 != 0: print x def main(): a = iter(OddNum(1)) while next(a)&lt;100: try: print(next(a)) except StopIteration: break main() Above is the code I am working with. The main code was given, so I did not write that. All this is supposed to do is print odd numbers 1-100. The error I get is: Traceback (most recent call last): line 36, in &lt;module&gt; main() line 29, in main a = iter(OddNum(1)) TypeError: this constructor takes no arguments
has comment: http://stackoverflow.com/comment/86995126
upvote count: 0
has answer: http://stackoverflow.com/a/49989428
has answer: http://stackoverflow.com/a/49989364
has comment: http://stackoverflow.com/comment/86995474
has comment: http://stackoverflow.com/comment/86995159
answer count: 3
has comment: http://stackoverflow.com/comment/86995101
has comment: http://stackoverflow.com/comment/86995229
has answer: http://stackoverflow.com/a/66933193
has comment: http://stackoverflow.com/comment/86995390
has title: Printing odd numbers using Iterators
downvote count: 1
tagged with: iteration
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86995303
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86996289
score: -1

http://stackoverflow.com/comment/87109296
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49963492
has text: is there a better tag i could use to help find some help on this?
score: 0

http://stackoverflow.com/comment/87173844
comment on: http://stackoverflow.com/a/50076430
score: 0
type: Comment
type: AnswerComment
has text: Sorry, I tried set path=/opt/local/Library/Frameworks/Python.framework/Versions/2.7 in .vimrc but after that also it didn't work

http://stackoverflow.com/comment/87115642
score: 0
comment on: http://stackoverflow.com/a/50049548
type: Comment
type: AnswerComment
has text: Thanks a bunch... makes me feel really stupid to have wasted the last hour of my life because I thought soap==soup!

http://stackoverflow.com/comment/86950060
comment on: http://stackoverflow.com/q/49960589
has text: You're not passing a `slug` parameter to the view, through the URL, so there's no `self.kwargs['slug']`.
score: 0
type: Comment
type: QuestionComment

pandas
tags question: http://stackoverflow.com/q/49938383
tags question: http://stackoverflow.com/q/49919217
tags question: http://stackoverflow.com/q/50049494
tags question: http://stackoverflow.com/q/49998613
tags question: http://stackoverflow.com/q/50025612
tags question: http://stackoverflow.com/q/49973537
tags question: http://stackoverflow.com/q/50034590
tags question: http://stackoverflow.com/q/49971160
tags question: http://stackoverflow.com/q/49984696
tags question: http://stackoverflow.com/q/50023644
tags question: http://stackoverflow.com/q/49974001
tags question: http://stackoverflow.com/q/50060194
tags question: http://stackoverflow.com/q/49970309
tags question: http://stackoverflow.com/q/49929542
tags question: http://stackoverflow.com/q/50059845
tags question: http://stackoverflow.com/q/50001852
tags question: http://stackoverflow.com/q/50040989
tags question: http://stackoverflow.com/q/50012259
tags question: http://stackoverflow.com/q/49928202
tags question: http://stackoverflow.com/q/50023814
tags question: http://stackoverflow.com/q/49996410
tags question: http://stackoverflow.com/q/50050918
tags question: http://stackoverflow.com/q/50008428
tags question: http://stackoverflow.com/q/49952307
tags question: http://stackoverflow.com/q/50045809
tags question: http://stackoverflow.com/q/50032912
tags question: http://stackoverflow.com/q/50038718
tags question: http://stackoverflow.com/q/50070789
tags question: http://stackoverflow.com/q/50045747
tags question: http://stackoverflow.com/q/49976315
tags question: http://stackoverflow.com/q/50020659
tags question: http://stackoverflow.com/q/49991785
tags question: http://stackoverflow.com/q/49951472
tags question: http://stackoverflow.com/q/49961598
tags question: http://stackoverflow.com/q/49996676
tags question: http://stackoverflow.com/q/50044250
tags question: http://stackoverflow.com/q/49972718
tags question: http://stackoverflow.com/q/50055065
tags question: http://stackoverflow.com/q/49922644
tags question: http://stackoverflow.com/q/49999550
tags question: http://stackoverflow.com/q/50045625
tags question: http://stackoverflow.com/q/50009145
tags question: http://stackoverflow.com/q/49944615
tags question: http://stackoverflow.com/q/50063089
tags question: http://stackoverflow.com/q/49995003
tags question: http://stackoverflow.com/q/49927774
tags question: http://stackoverflow.com/q/50050447
tags question: http://stackoverflow.com/q/50010257
tags question: http://stackoverflow.com/q/49994780
tags question: http://stackoverflow.com/q/49950034
tags question: http://stackoverflow.com/q/50033145
tags question: http://stackoverflow.com/q/49949796
tags question: http://stackoverflow.com/q/49989956
tags question: http://stackoverflow.com/q/50026341
tags question: http://stackoverflow.com/q/50008851
tags question: http://stackoverflow.com/q/50067957
tags question: http://stackoverflow.com/q/49931125
tags question: http://stackoverflow.com/q/50049217
tags question: http://stackoverflow.com/q/49944836
tags question: http://stackoverflow.com/q/50002738
tags question: http://stackoverflow.com/q/50066428
tags question: http://stackoverflow.com/q/50049660
tags question: http://stackoverflow.com/q/50021375
tags question: http://stackoverflow.com/q/49990758
tags question: http://stackoverflow.com/q/50062577
tags question: http://stackoverflow.com/q/50039771
tags question: http://stackoverflow.com/q/50010434
tags question: http://stackoverflow.com/q/50047844
tags question: http://stackoverflow.com/q/49924864
tags question: http://stackoverflow.com/q/49949300
tags question: http://stackoverflow.com/q/49918038
tags question: http://stackoverflow.com/q/49964307
tags question: http://stackoverflow.com/q/49961320
tags question: http://stackoverflow.com/q/50040428
tags question: http://stackoverflow.com/q/50040534
tags question: http://stackoverflow.com/q/49998457
tags question: http://stackoverflow.com/q/49993889
tags question: http://stackoverflow.com/q/50019830
tags question: http://stackoverflow.com/q/50021368
tags question: http://stackoverflow.com/q/50071281

http://stackoverflow.com/comment/87060208
score: 0
comment on: http://stackoverflow.com/q/50018614
type: Comment
has text: Just a suggestion.. But wouldn't it be easier to apply for an [API key](https://fortnitetracker.com/site-api)? Just make a request to ```https://api.fortnitetracker.com/v1/profile/psn/Rehgum``` and get the stats you need. No parsing required. It'll also be faster, since you're not loading the whole page.
type: QuestionComment

http://stackoverflow.com/a/52265346
downvote count: 0
answers question: http://stackoverflow.com/q/49929082
upvote count: 1
has body: Python connector should be use native Python types, in this case — None. Also for Ruby and Crystal I can pass nil and Tarantool is working fine. In the Python connector code I see that developers used type None. If you used None and got an error, then show you code?
score: 1
type: Answer

http://stackoverflow.com/comment/86918590
score: 0
comment on: http://stackoverflow.com/q/49950958
has text: I realized I could just pass a list to the variable `model.V = Var([1, 4, 6], within=Binary)` but it seems that passing the set should work.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50066824
score: 0
answers question: http://stackoverflow.com/q/50066608
has comment: http://stackoverflow.com/comment/87150264
has body: You actually do not need catids and marketids: finalDf['CAT_ID'] = catid finalDf['MARKET_ID'] = marketid Will work. For the rest of the script, I would probably have made things a bit simpler in that way: finalDf = pd.DataFrame() finalDf['PRODUCT'] = df['PRODUCT'].reset_index() Supposing that you are not interested in df's original index as your code implied.
type: Answer
has comment: http://stackoverflow.com/comment/87150452
has comment: http://stackoverflow.com/comment/87150431

http://stackoverflow.com/q/50066034
has comment: http://stackoverflow.com/comment/87148686
tagged with: xpath
duplicate of: http://stackoverflow.com/q/1323755
answer count: 2
has answer: http://stackoverflow.com/a/50066364
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87148805
tagged with: scrapy
has body: I am scraping a site using scrapy. There is a list of div some are display none and other are display block. I only want to fetch data from the div that are display block. But i am not able to fetch the style attribute from the div. I also checked a solution on stackoverflow ie response.xpath("//div").xpath("@style").extract() this gives me a blank list in output. It is not fetching the style attribute. Or can I get the raw HTML using scrapy then with the help of beautiful soup get the style attribute from the div? or is if i can get the raw html in string that will be also helpful. all i want is style aatribute in it. Sample html :- div content need to extract no need to extract
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50066181
has title: Nested .xpath('@attribute') gives an empty result if some tags don't have the attribute
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1323755
has comment: http://stackoverflow.com/comment/87148779
tagged with: python

http://stackoverflow.com/comment/87105708
score: 0
has text: The 'extra question' shall be asked as a separate question, and yes, there is a solution.
type: Comment
comment on: http://stackoverflow.com/q/50044373
type: QuestionComment

http://stackoverflow.com/q/50055285
score: -1
tagged with: rows
has comment: http://stackoverflow.com/comment/87126944
type: Question
upvote count: 2
has body: I have python dataframe, I want to sum across different rows, separated by number 0. E.g: i have this DF here: data= DataFrame({'A':['a','b','c','d','e','f','g','h','i'],'B':[1,2,0,3,2,0,0,3,4]}) I want to generate this DF: data2= DataFrame({'AA':'a','d','h'],'BB':[3,5,7]})
has title: Sum dataframe by conditionally defined groups
has comment: http://stackoverflow.com/comment/87127340
tagged with: pandas
type: UnansweredQuestion
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/50055639
favorite count: 0
has comment: http://stackoverflow.com/comment/87127405
tagged with: sum
has comment: http://stackoverflow.com/comment/87127068
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/50070596
score: -1
has body: You're opening files and not closing them. Whenever you use .open() without .close() there are bugs that might happen. It's always preferred to use the context manager like you did in the last example. with open('filename.ext', mode='somemodeR\W') as this automatically closes it and you don't have to worry about manually closing the file each time you open it.
type: Answer
answers question: http://stackoverflow.com/q/50070549
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/86943916
type: Comment
type: AnswerComment
has text: Please explain your answer.
comment on: http://stackoverflow.com/a/49963834
score: 0

http://stackoverflow.com/comment/87089572
type: Comment
type: QuestionComment
has text: If you are referring to manually modifying the values in the filter, I have tried that (see question: `I have also tried replacing the start__week_day=2 with values from 0-8 (inclusive, just in case) `)
score: 0
comment on: http://stackoverflow.com/q/50036183

python-imageio
type: Tag
tags question: http://stackoverflow.com/q/49958821
tag name: python-imageio
tags question: http://stackoverflow.com/q/50002135

http://stackoverflow.com/q/49970413
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49970585
has title: How to compare input and list content (and handle wrong inputs)
has answer: http://stackoverflow.com/a/49970585
tagged with: input
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
has body: This piece of code will ask for input, compare input with content of lists and, if input and content match, return input. If input is not in list user will be asked again for input. def get_input(tested_list): corect_input = False while not corect_input: try: # we are comparing input to list of lists content my_input = str.lower((input("Enter here: "))) for line in a_list: if my_input == line[2].lower(): return my_input except ValueError: print("????") else: corect_input = False Now questions (I'm very beginner. Try-Except-Else is all very new for me) : Is there any reason here to include 'except' line? Since input is converted to string, I can't see way to input anything what will cause any error. What kind of error shall I use after 'except'. How shall I write this piece of code to be better / cleaner/ more pythonic? :) . thank you
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87040001
type: Comment
score: 0
type: QuestionComment
has text: This has a cute answer using infinite lists in Haskell. `f n a b k = sum . take n . concat . cycle $ [[a, a+k..b], [b, b-k..a]]`
comment on: http://stackoverflow.com/q/50009692

http://stackoverflow.com/q/50034940
type: Question
linked to: http://stackoverflow.com/q/10561923
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87089580
tagged with: pickle
tagged with: python
has title: dill.load unicodeDecodeError
has comment: http://stackoverflow.com/comment/87089576
tagged with: dill
answer count: 0
score: 1
upvote count: 1
downvote count: 0
has body: I try to dill.load() some large pickle file that will cause momery error if I use _pickle.load(). However, I got this error UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1 What should I do?
favorite count: 0

http://stackoverflow.com/comment/87060392
type: QuestionComment
comment on: http://stackoverflow.com/q/50022220
type: Comment
score: 0
has text: Do you want to end up with a bunch of variables like `x_0`, `x_1`, `x_2` etc or are you only interested in the final value of the calculation?

http://stackoverflow.com/comment/86942391
comment on: http://stackoverflow.com/a/49963002
type: AnswerComment
type: Comment
has text: True that. Numpy is powerful and i still continue to be amazed. Will explore more on trapz
score: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/50032946
tags question: http://stackoverflow.com/q/50040496
tags question: http://stackoverflow.com/q/50008463
tags question: http://stackoverflow.com/q/50052940
tags question: http://stackoverflow.com/q/49919217
tags question: http://stackoverflow.com/q/50004159
tags question: http://stackoverflow.com/q/50021368
tags question: http://stackoverflow.com/q/49991273
tag name: merge
tags question: http://stackoverflow.com/q/49956302
tags question: http://stackoverflow.com/q/49997558
tags question: http://stackoverflow.com/q/50045805
tags question: http://stackoverflow.com/q/50068752
tags question: http://stackoverflow.com/q/49966468
tags question: http://stackoverflow.com/q/50027208
tags question: http://stackoverflow.com/q/49930533
tags question: http://stackoverflow.com/q/49977810
tags question: http://stackoverflow.com/q/50001168
tags question: http://stackoverflow.com/q/49944836
tags question: http://stackoverflow.com/q/49950003
tags question: http://stackoverflow.com/q/50045518
tags question: http://stackoverflow.com/q/49918428
tags question: http://stackoverflow.com/q/50042441

http://stackoverflow.com/comment/87033115
type: QuestionComment
comment on: http://stackoverflow.com/q/50008277
has text: Depending on your needs you can make X itself the condition, removing the need for other params. Or if the condition isn't dependent on X you can have 1 extra param that is an int, and build the if,elif clauses dependent on that.
type: Comment
score: 0

http://stackoverflow.com/comment/87692581
type: Comment
has text: Sorry it was my fault. I do my network in bad way. Now i'm looking for some optimisation of this: [link](https://gist.github.com/SzateX/d5ad41bbc355347342efc345b447b942)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50069494

http://stackoverflow.com/a/49970967
has comment: http://stackoverflow.com/comment/86958709
answers question: http://stackoverflow.com/q/49969861
has comment: http://stackoverflow.com/comment/86958543
accepted answer of: http://stackoverflow.com/q/49969861
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: The error lies with merge_sort. One important difference between numpy arrays and lists is that the former return a view when sliced while the latter return a copy. Thus collection, left_half and right_half all reference the same data when working on an array whereas in the list case left_half and right_half will be slice copies. You can fix this by forcing a copy or writing to a newly allocated output. As a result of this bug in the end some elements will have been overwritten while others occur multiple times. In fact there were lots of zeros when I ran a test. This triggers worst-case behavior in quick_sort: Of a block of equal elements the recursion will shave off one at a time which is what makes it hit the recursion limit. I don't know what the text book fix for that is but you could collect equal elements in a third group.
has comment: http://stackoverflow.com/comment/86958531

http://stackoverflow.com/q/50059295
possible better answer: http://stackoverflow.com/a/55856572
type: Question
has answer: http://stackoverflow.com/a/55856572
score: 0
answer count: 2
has title: Matplotlib Live Graph - Using Time as x-axis values
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87135235
accepted answer: http://stackoverflow.com/a/50060135
has answer: http://stackoverflow.com/a/50060135
has comment: http://stackoverflow.com/comment/87135882
tagged with: python-3.x
has body: I was just wondering if it is possible to use Time as x-axis values for a matplotlib live graph. If so, how should it be done? I have been trying many different methods but end up with errors. This is my current code : update_label(label): def getvoltage(): f=open("VoltageReadings.txt", "a+") readings = [0]*100 maxsample = 100 counter = 0 while (counter &lt; maxsample): reading = adc.read_adc(0, gain=GAIN) readings.append(reading) counter += 1 avg = sum(readings)/100 voltage = (avg * 0.1259)/100 time = str(datetime.datetime.now().time()) f.write("%.2f," % (voltage) + time + "\r\n") readings.clear() label.config(text=str('Voltage: {0:.2f}'.format(voltage))) label.after(1000, getvoltage) getvoltage() def animate(i): pullData = open("VoltageReadings.txt","r").read() dataList = pullData.split('\n') xList=[] yList=[] for eachLine in dataList: if len(eachLine) &gt; 1: y, x = eachLine.split(',') xList.append(float(x))) yList.append(float(y)) a.clear() a.plot(xList,yList) This is one of the latest method I've tried and I'm getting error that says ValueError: could not convert string to float: '17:21:55' I've tried finding ways to convert the string into a float but I can't seem to do it I'd really appreciate some help and guidance, thank you :)
type: AnsweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87135437

http://stackoverflow.com/comment/93342298
comment on: http://stackoverflow.com/q/49960269
score: 0
type: Comment
has text: Did you figure this out?
type: QuestionComment

http://stackoverflow.com/comment/87005044
comment on: http://stackoverflow.com/a/49994415
has text: The OP's file doesn't seem to be comma-separated.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87110473
has text: @palivek `['LHR', 'SYD', 'JFK', 'AAL', ['DUB'], 'LHR']`
comment on: http://stackoverflow.com/q/50046101
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87075164
score: 2
type: Comment
type: QuestionComment
has text: How long is your list? It may be as simple as checking if `sorted(L) == L`.
comment on: http://stackoverflow.com/q/50029537

http://stackoverflow.com/comment/86929283
comment on: http://stackoverflow.com/q/49956284
score: 0
type: Comment
type: QuestionComment
has text: That means that this is probably not the way to go when using a factory method?

http://stackoverflow.com/comment/86913833
comment on: http://stackoverflow.com/a/49947557
has text: I do have request.sid. I added this to my emit and it is now working correctly.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49958297
has body: clean_fieldname methods called in order of fields declaration, so at the moment clean_password is called cleaned_data does not contain confirm_password. You can perform this validation in clean_confirm_password method: def clean_confirm_password(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: print(password) print(confirm_password) raise forms.ValidationError( "Password and password confirmation does not match" ) return password or just use clean method for validation that requires access to multiple form fields.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49958248
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49958248
type: Answer
has comment: http://stackoverflow.com/comment/86933008

http://stackoverflow.com/comment/86928440
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49955557
type: Comment
has text: I think I MAY be starting to get a handle on some of the more simple approaches to Data Wrangling. I have a long way to go still - but some of the answers I see here are starting to make sense for me instead of just being complete arcane mysteries.

http://stackoverflow.com/comment/86908061
comment on: http://stackoverflow.com/a/49944855
has text: ValueError: Boolean array expected for the condition, not float64
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/132919692
has text: Can also happen if you recently added pytest-django to your local environment and forgot to rebuild your docker container :')
score: 0
type: Comment
comment on: http://stackoverflow.com/a/71924462
type: AnswerComment

http://stackoverflow.com/q/49951039
answer count: 1
has body: I have the following code, the result column has values Won or Lost: df.groupby('result')['col_A'].agg(['mean','median']).plot(kind='bar') How do I make the x-axis be mean &amp; median, and use the color for the Won/Lost group? Thanks!
has title: pandas bar chart: use aggregated output as x-axis and colors for each group
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49951593
accepted answer: http://stackoverflow.com/a/49951593
score: 1
tagged with: matplotlib
tagged with: aggregate-functions
tagged with: python
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 1
tagged with: bar-chart

http://stackoverflow.com/comment/86960053
has text: This is a great example of horrendous sample codes on the internet. ( I mean the example on python-graph-gallery.com , not this response!)
type: Comment
comment on: http://stackoverflow.com/a/49972074
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87018357
comment on: http://stackoverflow.com/a/49983909
score: 1
type: Comment
type: AnswerComment
has text: Use `/File/Param/Field[2]/Array/text()` to get it. Notice that the `Array` values in the example XML are empty.

http://stackoverflow.com/comment/86999558
comment on: http://stackoverflow.com/q/49990812
score: 0
has text: Sorry, it took so long, does anyone want the sample data?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87054964
type: QuestionComment
has text: If you have a standard folder where all your packages are in, consider creating a `.pth` text file in your `python/Lib/site-packages` folder (Windows), that contains the absolute path of your folder. This will do the `sys.path.append` for you automatically everytime you run the interpreter. See https://docs.python.org/3/library/site.html
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50019435

http://stackoverflow.com/a/50070251
answers question: http://stackoverflow.com/q/49932651
upvote count: 4
downvote count: 0
type: AcceptedAnswer
has body: You are wrong. First, built-in names are importable from builtins module (in Python 3): py::object open = py::module::import("builtins").attr("open"); Second, open also lives in io module so you can also use the following line that is equivalent to the line above: py::object open = py::module::import("io").attr("open"); This is for Python 3, but the last line works for Python 2.7 too.
score: 4
has comment: http://stackoverflow.com/comment/87336025
accepted answer of: http://stackoverflow.com/q/49932651
type: Answer
has comment: http://stackoverflow.com/comment/87157219

http://stackoverflow.com/comment/86941095
type: AnswerComment
comment on: http://stackoverflow.com/a/49955549
type: Comment
has text: Thanks, in my case I had to use a[0].url.replace(urllib.parse.unquote('%2B'),'%2B')
score: 0

http://stackoverflow.com/comment/87088228
type: Comment
score: 0
type: AnswerComment
has text: i tried this method. i've removed rowid still it is showing "TypeError at /studentapp/editrow/72/ editrow() got an unexpected keyword argument 'rowid'" What to do now?
comment on: http://stackoverflow.com/a/50030045

http://stackoverflow.com/a/49999825
accepted answer of: http://stackoverflow.com/q/49999166
score: 8
upvote count: 9
answers question: http://stackoverflow.com/q/49999166
type: AcceptedAnswer
type: Answer
downvote count: 1
has body: I like using seaborn for this kind of visualizations. I guessthe "extra level" you mean is called "hue". import seaborn as sns sns.set_style("whitegrid") tips = sns.load_dataset("tips") ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set3") and the result would be: check out this documentation: https://seaborn.pydata.org/generated/seaborn.boxplot.html
has comment: http://stackoverflow.com/comment/106025849
has comment: http://stackoverflow.com/comment/87015829

http://stackoverflow.com/q/49934926
has comment: http://stackoverflow.com/comment/86888529
has comment: http://stackoverflow.com/comment/86891778
has title: Can't load VGG16 Model Weights
downvote count: 0
upvote count: 1
answer count: 1
tagged with: keras
favorite count: 0
type: Question
has body: I am using this code to make my own VGG16 network: # build the VGG16 network model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(64, 3, 3, activation='relu', name='conv1_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2), dim_ordering="th")) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1')) model.add(ZeroPadding2D((1, 1))) model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2')) model.add(MaxPooling2D((2, 2), strides=(2, 2), dim_ordering="th")) # load the weights of the VGG16 networks f = h5py.File(weights_path) for k in range(f.attrs['nb_layers']): if k &gt;= len(model.layers): # we don't look at the last (fully-connected) layers in the savefile break g = f['layer_{}'.format(k)] weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])] model.layers[k].set_weights(weights) f.close() print('Model loaded.') But when I call my method, it crashes: ValueError: Layer weight shape (3L, 3L, 3L, 64L) not compatible with provided weight shape (64, 3, 3, 3) I have set K.set_image_dim_ordering('th') but still it crashes. Please help.
type: UnansweredQuestion
score: 1
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/55601546

http://stackoverflow.com/a/49936573
answers question: http://stackoverflow.com/q/49935754
has comment: http://stackoverflow.com/comment/86890555
has comment: http://stackoverflow.com/comment/86891331
accepted answer of: http://stackoverflow.com/q/49935754
type: Answer
has comment: http://stackoverflow.com/comment/86890836
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86891067
has body: Try to implement below code: div_nodes = driver.find_elements_by_css_selector("div.row.result.clickcard") Let me know if you need more specific selector

http://stackoverflow.com/a/50068381
accepted answer of: http://stackoverflow.com/q/50068345
type: Answer
has comment: http://stackoverflow.com/comment/87153311
has comment: http://stackoverflow.com/comment/87153222
answers question: http://stackoverflow.com/q/50068345
downvote count: 0
has comment: http://stackoverflow.com/comment/87153915
has comment: http://stackoverflow.com/comment/129400448
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87153399
has comment: http://stackoverflow.com/comment/132696089
has comment: http://stackoverflow.com/comment/87154063
has body: The default_factory parameter of the defaultdict constructor is positional-only and doesn't really have a name. If you try to pass it by name, you are just passing a completely unrelated keyword argument. Since keyword arguments to the defaultdict constructor are interpreted as its initial contents, your dict starts out having a single key "default_factory" whose value is the str type object. To understand how this works, imagine a function like this: def func(*args, **kwds): (default_factory,) = args for k, v in kwds.items(): print(k, v) # do something with keys and values If the documentation of this function were to name the positional argument default_factory, that might be a correct description of its meaning, but it would be misleading if it implied that one could pass it as a keyword argument. Some built-in functions are like that because it is very easy to define positional-only arguments in CPython C code. With defaultdict, it is by design, to allow literally any string key to be used as the part of initial content, without having an exception for a key that happens to be named default_factory.
score: 10
upvote count: 10

http://stackoverflow.com/q/49956857
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: stack
has title: Python prefix to infix notation using a stack data structure
has body: I have an assignment problem on using a stack data structure to solve problems. I am prompted to make the following stack function. Task: Using the stack you created, write the function prefix_infix that takes in a prefix expression (represented as a list) and returns the expression in fully parenthesized infix notation. Consider expressions involving only binary operators(+,-,*,/) You may find information regarding prefix here: http://en.wikipedia.org/wiki/Polish_notation def make_stack(): stack=[] def helper(*args): if args[0]=='push': stack.append(args[1]) elif args[0]=='peek': return (stack[-1]) elif args[0]=="pop": return (stack.pop()) elif args[0]=="size": return (len(stack)) return helper def prefix_infix(lst): stk=make_stack() def helper(lst): if type(lst)==int: stk('push',str(lst)) elif lst in ('+','-','*','/'): left=stk('pop') right=stk('pop') element="("+left+" "+lst+" "+right+")" stk('push',element) else: return helper(lst[2]),helper(lst[1]),helper(lst[0]) helper(lst) return stk('pop') prefix_infix(['+',['*',5,4],['-',2,1]]) #Output: "((5 * 4) + (2 - 1))" prefix_infix(['-',['*',5,4],['-',['/',1,45],['+',1,1]]]) #Output:((5 * 4) - ((1 / 45) - (1 + 1))) I somehow got my code to produce the correct output, but I’m not very confident on my approach as I did it with a recursion but I do not know what’s the right way to do it with a recursion (my recursive call with , seems haphazard). Can someone suggest some other versions of code that I can write to make it easier to comprehend? I can’t really visualise the stack, most of the time I'm just lucky with my recursive functions.
has comment: http://stackoverflow.com/comment/86929997
has comment: http://stackoverflow.com/comment/86930143
has answer: http://stackoverflow.com/a/64958126
possible better answer: http://stackoverflow.com/a/64958126
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49956978
accepted answer: http://stackoverflow.com/a/49956978
type: AnsweredQuestion

http://stackoverflow.com/comment/87077055
has text: @glibdud well actually it's not code-specific, so you can take any such chain of exceptions. I can't do this right now. If it's mandatory then I will do this a tad later.
comment on: http://stackoverflow.com/q/50030414
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49921998
has comment: http://stackoverflow.com/comment/86861022
has comment: http://stackoverflow.com/comment/86860800
has body: I would like to create multiple files with my own functions and store it as multiple script files. what is the best way to make it work. How do I call it from another python script? For example I have the files a.py, b.py, c.py and x.py in the files a.py, b.py and c.py. I would like to use functions from the other imported files. def a(): print("Function a is called") print(c()) return 1 b.py def b(): # Something print("function b is called.") return 2 c.py def c(): # de Something print("Function C is called.") print(b()) return 3 print(a()) x.py from a import * from b import * from c import * print(a()) print(b()) print(c()) Thanks.
favorite count: 0
type: Question
tagged with: python-import
tagged with: function
upvote count: 0
has comment: http://stackoverflow.com/comment/86860390
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2349991
has comment: http://stackoverflow.com/comment/86859704
tagged with: python
has comment: http://stackoverflow.com/comment/86859812
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/86861302
has comment: http://stackoverflow.com/comment/86861447
has title: Function calls to multiple different files in python
has answer: http://stackoverflow.com/a/49922186
answer count: 1
has comment: http://stackoverflow.com/comment/86859757

http://stackoverflow.com/q/49992516
has body: I am trying to write. code that will allow a user to select specific columns from a sqlite database which will then be transformed into a pandas data frame. I am using a test database titled test_database.db with a table titled test. The table has three columns, id, value_one, and value_two. The function I am showing exists within a class that establishes a connection to the database and in this function the user only needs to pass the table name and a list of columns that they would like to extract. For instance in command line sqlite I might type the command select value_one, value_two from test if I wanted only to read in the columns value_one and column_two from the table test. If I type this command into command line the method works. However, in this case I use python to build the text string which is fed into pandas.read_sql_query() and the method does not work. My code is shown below class ReadSQL: def __init__(self, database): self.database = database self.conn = sqlite3.connect(self.database) self.cur = self.conn.cursor() def query_columns_to_dataframe(table, columns): query = 'select ' for i in range(len(columns)): query = query + columns[I] + ', ' query = query[:-2] + ' from ' + table # print(query) df = pd.read_sql_query(query, self.conn) return def close_database() self.conn.close return test = ReadSQL(test_database.db) df = query_columns_to_dataframe('test', ['value_one', 'value_two']) I am assuming my problem has something to do with the way that query_columns_to_dataframe() pre-processes the information because if I uncomment the print command in query_columnes_to_dataframe() I get a text string that looks identical to what works if I just type it directly into command line. Any help is appreciated.
has title: How to extract select columns from a sqlite database with Python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49993019
tagged with: sqlite
has answer: http://stackoverflow.com/a/49992901
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49993019
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49992901

http://stackoverflow.com/q/49947242
has answer: http://stackoverflow.com/a/49947562
has answer: http://stackoverflow.com/a/49947456
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86911472
tagged with: cidr
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/49947562
downvote count: 3
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86911358
has comment: http://stackoverflow.com/comment/86911105
linked to: http://stackoverflow.com/q/44262437
has title: Using python, what's the fastest way to see which of around one million ip addresses fit into three cidrs?
has body: I have a list of ~1,000,000 ip address strings. I want to get the set of these ip addresses that are in three cidrs (each cidr is a string like this: "1.0.0.0/25"). What is the fastest way to do this? A) Convert the three cidrs into sets containing all ip addresses contained in the cidrs. For each ip address in my list, I check if the ip address is in the wanted ip address set. B) Convert each cidr into min &amp; max ip address. Convert each ip address into a tuple of ints and check if ip > min and ip &lt; max.
score: -3
has comment: http://stackoverflow.com/comment/86913948
tagged with: python
accepted answer: http://stackoverflow.com/a/49947456
tagged with: ip-address

http://stackoverflow.com/q/50037739
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87092237
downvote count: 0
upvote count: 1
tagged with: python
tagged with: blender
score: 1
has title: Using Jupyter Notebook to Blender/Adobe After-Effects
has body: I am currently using Jupyter notebook to create a program using IBM Watson Tone Analyzer service. I wanted to know if it is possible to use the notebook I'm working on to run/launch an animation I've created in something like blender or adobe aftereffects?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: after-effects
answer count: 0

http://stackoverflow.com/q/49957240
type: UnansweredQuestion
has title: Python OOP default constructor creation
tagged with: python
has body: I am creating a class in Python. I would like to set my variables equal to zero from the start, but I think using "username = none, password = none, url = none" is inefficient. Is there a way for me to instead create a new def __init__(self): method that doesn't take any arguments and sets all the attributes to none? This is how it looks currently and thanks for the help!: Class Broken(): #pulls from function which is what username = none password = none url = none job_url = none headers = none and instead, I'd like... def __init__(self):?????
has answer: http://stackoverflow.com/a/49957320
score: 0
tagged with: oop
tagged with: default-constructor
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50012481
has title: Count values for each line in text file python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87041618
accepted answer: http://stackoverflow.com/a/50012588
has answer: http://stackoverflow.com/a/50012502
has comment: http://stackoverflow.com/comment/87041323
has answer: http://stackoverflow.com/a/50012588
tagged with: file
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50012502
answer count: 2
upvote count: 0
has body: I think I am close to what I am trying to get, but I am still a begginer so don't really know if it is the best way. Let's say we have a file with hundred of lines where at the end of each one there is a value I want to count. It seems complex to me to program all in a single line of code so I prefer going step by step. Let's say we have a file with lines like the followings: Type of line 1: 10 Type of line 1: 5 Type of line 1: 15 Type of line 2: 50 Type of line 2: 25 Type of line 2: 5 Type of line 3: 1 Type of line 3: 14 Type of line 3: 2 Since there is various type of lines what I am trying to get is the sum of those values which appear in the same type of line. For instance, the output should be this: Type of line 1: 30 Type of line 2: 80 Type of line 3: 17 Type of line it is just a string. So in order to achieve this first I read the file line by line and split each line using ':' character. Then I save those splitted lines in a variable to call its elements later and sum those values with the same type of line. I know that since its a file where lines are strings in order to operate with values they must be treated as ints so it should be something like int(y[1]), but I am not sure. Any suggestion whether I am on the right path? Here is what I tried so far: with open('file.txt','r') as f: for line in f: y = line.split(':') ...
tagged with: python
score: -1

http://stackoverflow.com/a/49957739
has body: I misread the question the first time. If you want it to look exactly like: C1/C2 = None; Divide by Zero Error! You could have it: return 'None; Divide by Zero Error!' But I would not recommend this and instead would recommend my original answer below: A python method always returns None if it doesn't hit a return statement. If you don't want it to return at all, you could have it raise an exception: def __truediv__(self, other): # Overrides division function denom = other.real ** 2 + other.img ** 2 tempComp = Complex(other.real, -1 * other.img) if denom != 0: tempComp = self * tempComp return Complex(tempComp.real / denom, tempComp.img / denom) else: raise(ZeroDivisionError("Error: Cannot divide by zero")) This is the same behavior as the int type.
downvote count: 0
answers question: http://stackoverflow.com/q/49957582
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49946398
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has body: Given some arbitrary dictionary mydict = { 'first': { 'second': { 'third': { 'fourth': 'the end' } } } } I've written a small routine to flatten it in the process of writing an answer to another question. def recursive_flatten(mydict): d = {} for k, v in mydict.items(): if isinstance(v, dict): for k2, v2 in recursive_flatten(v).items(): d[k + '.' + k2] = v2 else: d[k] = v return d It works, giving me what I want: new_dict = recursive_flatten(mydict) print(new_dict) {'first.second.third.fourth': 'the end'} And should work for just about any arbitrarily structured dictionary. Unfortunately, it does not: mydict['new_key'] = mydict Now recursive_flatten(mydict) will run until I run out of stack space. I'm trying to figure out how to gracefully handle self-references (basically, ignore or remove them). To complicate matters, self-references may occur for any sub-dictionary... not just the top level. How would I handle self-references elegantly? I can think of a mutable default argument, but there should be a better way... right? Pointers appreciated, thanks for reading. I welcome any other suggestions/improvements to recursive_flatten if you have them.
favorite count: 0
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/86909694
accepted answer: http://stackoverflow.com/a/49946791
has answer: http://stackoverflow.com/a/49946747
possible better answer: http://stackoverflow.com/a/49946747
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/49945999
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49946791
has title: Handle self-references when flattening dictionary

http://stackoverflow.com/a/50001260
accepted answer of: http://stackoverflow.com/q/50001168
type: Answer
answers question: http://stackoverflow.com/q/50001168
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
has body: This is one way which does not assume a specific ordering of either list. d = dict(second_list) res = [i + [d[i[0]]] for i in first_list] [['aaa', 551, 10972, 240], ['bbb', 552, 10872, 120], ['ccc', 553, 11103, 325], ['ddd', 554, 10912, 270]]

http://stackoverflow.com/a/50004675
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87030228
answers question: http://stackoverflow.com/q/50004142
upvote count: 1
has comment: http://stackoverflow.com/comment/87029978
has comment: http://stackoverflow.com/comment/87030106
has comment: http://stackoverflow.com/comment/87031399
type: Answer
has comment: http://stackoverflow.com/comment/87030037
has comment: http://stackoverflow.com/comment/87030819
has body: Use locals or globals. import mymod if __name__ == 'main': function_list=['mymod.f1','mymod.f2','mymod.f3'] for func in function_list: try: locals()[func]() # something here? except Exception, e: print(e) or import mymod if __name__ == 'main': function_list=['mymod.f1','mymod.f2','mymod.f3'] for func in function_list: try: globals()[func]() # something here? except Exception, e: print(e) this would only work if the functions are in the same module Also, as said in the comment, you can call the functions directly if you save them without using the inverted commas in the list.
has comment: http://stackoverflow.com/comment/87030428
has comment: http://stackoverflow.com/comment/87028709
has comment: http://stackoverflow.com/comment/87030701

recursion
type: Tag
tags question: http://stackoverflow.com/q/50050906
tags question: http://stackoverflow.com/q/49949840
tags question: http://stackoverflow.com/q/49945999
tags question: http://stackoverflow.com/q/49969861
tags question: http://stackoverflow.com/q/50044407
tags question: http://stackoverflow.com/q/49984197
tags question: http://stackoverflow.com/q/49933970
tags question: http://stackoverflow.com/q/50012032
tag name: recursion
tags question: http://stackoverflow.com/q/49963487
tags question: http://stackoverflow.com/q/49996618
tags question: http://stackoverflow.com/q/50070546
tags question: http://stackoverflow.com/q/49934787
tags question: http://stackoverflow.com/q/49963421
tags question: http://stackoverflow.com/q/50050486
tags question: http://stackoverflow.com/q/50029044
tags question: http://stackoverflow.com/q/50049250
tags question: http://stackoverflow.com/q/50055570
tags question: http://stackoverflow.com/q/49963153
tags question: http://stackoverflow.com/q/49946398
tags question: http://stackoverflow.com/q/50048141
tags question: http://stackoverflow.com/q/49963492
tags question: http://stackoverflow.com/q/50053107

http://stackoverflow.com/a/50027007
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87071225
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50026529
has body: You can override get_initial if you want to set initial data dynamically. If you don't need to set it dynamically you can simply set initial. class JobCreation(LoginRequiredMixin, SuccessMessageMixin, generic.edit.CreateView): model = Job form_class = JobCreationForm def get_initial(self): initial = super().get_initial() initial['location'] = self.request.user.location return initial ...
accepted answer of: http://stackoverflow.com/q/50026529
type: AcceptedAnswer

http://stackoverflow.com/q/50026371
has answer: http://stackoverflow.com/a/50032002
answer count: 1
has comment: http://stackoverflow.com/comment/87069276
downvote count: 1
linked to: http://stackoverflow.com/q/986006
has comment: http://stackoverflow.com/comment/87069319
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87069307
has comment: http://stackoverflow.com/comment/87069192
upvote count: 0
has title: 2017 GCSE Card Trick : "Pop from empty list" IndexError
has body: import random def create_deck(): suits = ["♥","♣","♦","♠"] values = ["1","2","3","4","5","6","7","8","9","10","J","Q","K"] deck = [] card = "" for suit in suits: for value in values: card = value + suit deck.append(card) random.shuffle(deck) random.shuffle(deck) cards = deck[:21] print(cards) return cards #create the deck and keep 21 cards def create_piles(deck): pile1 = [] pile2 = [] pile3 = [] for i in range(7): pile1.append(cards.pop()) pile2.append(cards.pop()) pile3.append(cards.pop()) print("\n" *3) print(pile1) print(pile2) print(pile3) return pile1,pile2,pile3 #create the three piles def user_choice(): while True: print("What pile is your card in?") choice = input("----&gt; ") print(cards) if choice in ["1","2","3"]: return choice #select the pile def reassemble(choice,pile1,pile2,pile3): if choice == "1": cards = pile2 + pile1 + pile3 elif choice == "2": cards = pile1 + pile2 + pile3 else: cards = pile2 + pile3 + pile1 #reassemble the piles def win(create_piles): print("Your card was") #the card that the user picked def trick_compile(cards): for i in range(3): pile1,pile2,pile3 = create_piles(cards) choice = user_choice() cards = reassemble(choice,pile1,pile2,pile3) win(create_piles) quit() #framework that runs the trick cards = create_deck() trick_compile(cards) I am a GCSE Computer Science student. This code is based off last years coursework, which asks for a card trick. When I run my script, the following error is displayed: Traceback (most recent call last): File "main.py", line 71, in &lt;module&gt; trick_compile(cards) File "main.py", line 62, in trick_compile pile1,pile2,pile3 = create_piles(cards) File "main.py", line 26, in create_piles pile1.append(cards.pop()) IndexError : pop from empty List I have concluded that the "empty" list is the list cards, however, I have assigned 21 values to it (which also form the first piles that are displayed). Why is the list empty after they are appended into Pile1, 2 and 3 respectively, and what can one do to f…
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50032002
type: AnsweredQuestion

http://stackoverflow.com/comment/87087278
score: 0
has text: You have control over the system you're scanning? Configure the firewall to open the port you want to use. This is a system administration problem, not programming question. Try asking in SuperUser.com
type: Comment
comment on: http://stackoverflow.com/a/50033980
type: AnswerComment

http://stackoverflow.com/q/50034321
has title: How to Handle Pandas Operation Creating -Inf Values?
type: Question
tagged with: numpy
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87086311
score: 3
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: So I have a long table of daily return data for stocks, and I am trying to calculate their % returns by this, data['return'] = data['avg'].pct_change()/100 data.dropna(inplace=True) And the values I get are normal. However, trying to do any other operations on the data now gives me an NaN, which confused me since the original data was well-behaved and I made sure to drop any new NaN's. Turns out the pct_change()/100 operation creates a -Inf at one point, which is just infuriating. Since I am assuming the -Inf gets created bec. a certain neg. % change was too low, how do I get around pandas operations in general making the same mistake? Thanks you in advance.
has comment: http://stackoverflow.com/comment/87086777

http://stackoverflow.com/q/49928680
score: 0
has answer: http://stackoverflow.com/a/49928872
tagged with: function
accepted answer: http://stackoverflow.com/a/49928787
has answer: http://stackoverflow.com/a/49928787
type: Question
tagged with: arguments
tagged with: python
linked to: http://stackoverflow.com/q/1740726
possible better answer: http://stackoverflow.com/a/49928872
answer count: 4
has title: Writing a function in python with addition and subtraction operators as arguments
type: AnsweredQuestion
has body: I'm really confused and I don't know how to solve the following problem. Imagine that I have written a very long code and I want to transform this long code to a function to prevent repetition. The problem is that I need to give 'add sign' (+) and 'subtraction sign'(-) as function inputs. I mean that I have a very long code that I need to change two signs of add and subtraction for each time and nothing more and finally to get the output according changing these two operators (these two operators are in fact my variables!) As you know repeating this long function for four different states of changing 'add and subtraction signs', makes my code even longer and longer. I would like to know if there is any way to define just One function that gives these pair of add and subtraction operators as input and give me the output for these four different conditions? I have made a simple example to clarify the question: Imagine that I have four similar 'for loops' just different in 'minus sign' and 'plus sign': edges=set() a=60; b=40 for i in range(0,300): a+=1; b+=1 if a!=0 and b!=0: edges.add((a, b)) a=60; b=40 for i in range(0,300): a-=1; b-=1 if a&gt;=0 and b&gt;=0: edges.add((a, b)) a=60; b=40 for i in range(0,300): a+=1; b-=1 if a&gt;=0 and b&gt;=0: edges.add((a, b)) a=60; b=40 for i in range(0,300): a-=1; b+=1 if a&gt;=0 and b&gt;=0: edges.add((a, b)) print(edges) As you see, these four 'for loops' are all the same except in 'plus and minus signs'. I want to write just one function instead of these four repeated 'for loops'. Is there any other way to solve this problem? Anyone has any idea?
has answer: http://stackoverflow.com/a/49928847
has answer: http://stackoverflow.com/a/61952879

http://stackoverflow.com/comment/112617680
score: 1
comment on: http://stackoverflow.com/a/49979592
has text: @Gabriella Giordano , I think the `QObject::connect` should be placed before `process->start()`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87021659
score: 0
has text: You need to post a [mcve].
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50002362

http://stackoverflow.com/comment/87146973
score: 0
comment on: http://stackoverflow.com/a/50064510
type: Comment
type: AnswerComment
has text: product_list is a dictionary, if you iterate on it like: for product in product_list you will iterate over all the key

http://stackoverflow.com/comment/87035167
comment on: http://stackoverflow.com/q/50009178
score: 0
has text: R,G,B are supposed to be new values for red,green,blue
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87160549
comment on: http://stackoverflow.com/q/50071515
score: 0
has text: `if sys.argv[1:]:` is prettier than the `len(sys.argv)` test.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86925722
comment on: http://stackoverflow.com/q/49954262
score: 0
type: Comment
type: QuestionComment
has text: Since you're not using `from flaskext.mysql import MySQL` for now, delete the line and see if it still occurs.

http://stackoverflow.com/comment/86895049
has text: input fields are empty. The cursor starts to flash inside the field, but the .send_keys() method does not work.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49938830

http://stackoverflow.com/comment/86930106
type: AnswerComment
comment on: http://stackoverflow.com/a/49951262
has text: @amark, See update. The method still works. Please give a [mcve], the way I have in my answer, otherwise it will be impossible to confirm what's wrong with your data.
score: 0
type: Comment

http://stackoverflow.com/a/50009267
has comment: http://stackoverflow.com/comment/87035512
has body: You can using np.hstack list(map(lambda x :len(np.hstack(x)),df.Var1)) Out[10]: [5, 4, 1] df['Var2']=list(map(lambda x :len(np.hstack(x)),df.Var1)) df Out[12]: Var1 Var2 0 [X, Y, [Z, A, B]] 5 1 [A, [R, S, T]] 4 2 [B] 1
answers question: http://stackoverflow.com/q/50009143
score: 0
type: Answer

http://stackoverflow.com/comment/87070855
type: Comment
type: QuestionComment
has text: Tried. Still doesn't work. G goes to 0.0 and D keeps increasing.
score: 0
comment on: http://stackoverflow.com/q/50026996

http://stackoverflow.com/q/50035642
accepted answer: http://stackoverflow.com/a/50035755
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87087759
score: 0
has body: I'm trying to implement a function with 2 arguments and an additional 3rd arbitrary keyword argument using **kwarg formatting, as below: def build_profile(first_name, last_name, **additional_info): """ Building a user profile """ profile = {} profile['First name'] = first_name profile['Last name'] = last_name for key, value in additional_info.items(): profile[key.title()] = value.title() return profile build_profile("x", 'y', 'x', 'y', 'x', 'y') However, this produces the error: TypeError: build_profile() takes 2 positional arguments but 6 were given I managed to reproduce this error in isolation using the following code: def x(**y): print(y) Output: x(1,2,3,4,5) This generates the same response: TypeError: x() takes 0 positional arguments but 1 was given This has lead me to conclude that I either: Have an issue with my python configuration (running 3.6.4 in Spyder) or I'm missing something blindingly obvious.
answer count: 2
has title: Not recognising arbitrary keyword positional arguments using **kwarg format
tagged with: function
tagged with: keyword
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/36901
has answer: http://stackoverflow.com/a/50035668
possible better answer: http://stackoverflow.com/a/50035668
tagged with: python
has answer: http://stackoverflow.com/a/50035755

http://stackoverflow.com/a/59462226
upvote count: 9
answers question: http://stackoverflow.com/q/50015586
type: Answer
has body: DNS Python (dnspython) might be helpful. You can get the DNS server address with: import dns.resolver dns_resolver = dns.resolver.Resolver() dns_resolver.nameservers[0]
score: 9
downvote count: 0

http://stackoverflow.com/a/49954926
upvote count: 2
downvote count: 0
type: Answer
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49941466
has body: A location block with proxy_pass just passes through the path unchanged unless you rewrite it. For your case add the following rewrite rule after the proxy_pass statement. rewrite ^/mylocation/?(.*)$ /$1 break;
answers question: http://stackoverflow.com/q/49941466

http://stackoverflow.com/q/50022723
has comment: http://stackoverflow.com/comment/87061645
accepted answer: http://stackoverflow.com/a/50023209
linked to: http://stackoverflow.com/q/49729099
type: Question
has comment: http://stackoverflow.com/comment/87067261
has answer: http://stackoverflow.com/a/50023209
upvote count: 3
has title: Python 3 Escaping Quotes in System Calls
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87062268
type: AnsweredQuestion
score: 3
has body: I'm trying to convert new lines in a text file to "\n" characters in a string by running an Awk command using os.system: awk '{printf "%s\\n", $0}' /tmp/file My problem is that escaping the quotes is not working: $ replace = "awk '{printf \"%s\\n\", $0}' /tmp/file" $ print(replace) awk '{printf "%s\n", $0}' /tmp/file I've tried using shlex as well: $ import shlex $ line = "awk '{printf \"%s\\n\", $0}'" $ lexer = shlex.shlex(line, posix=True) $ lexer.escapedquotes = "'\"" $ mystring = ','.join(lexer) $ print(mystring) awk,{printf "%s\n", $0} I either need to know how to run this awk command with Python or how to convert carriage returns/new lines in a file to "\n" in a string. EDIT: Here's an example file: oneline twoline threeline A method should return the following from this file: oneline\ntwoline\n\nthreeline

http://stackoverflow.com/comment/87017771
type: Comment
type: QuestionComment
has text: https://www.facebook.com/legal/terms, 3.2: _“You will not [...] access Facebook, using automated means (such as harvesting bots, robots, spiders, or scrapers) without our prior permission.”_
score: 2
comment on: http://stackoverflow.com/q/50000321

http://stackoverflow.com/comment/87086807
comment on: http://stackoverflow.com/a/50035263
type: AnswerComment
score: 0
has text: I think it should be `result.Distance >= result.Start`, and this is my answer too.
type: Comment

http://stackoverflow.com/a/50225979
accepted answer of: http://stackoverflow.com/q/50037096
has body: I'm not sure if this is the functionality you're trying to achieve, but, try this: First grab the call id when Twilio hits your webhook and connects the incoming call (in this example CAe1644a7eed5088b159577c5802d8be38) Then when you're ready to transfer to the secondary number, make a POST request to instruct to switch to executing a new TwiML, like this: # Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) call = client.calls("CAe1644a7eed5088b159577c5802d8be38") \ .update( method="POST", url="http://example.com/transfer.xml" ) print(call.to) The transfer.xml contains the to the secondary number: <?xml version="1.0" encoding="UTF-8"?> 415-123-4567
has comment: http://stackoverflow.com/comment/111481963
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50037096
has comment: http://stackoverflow.com/comment/111469683
has comment: http://stackoverflow.com/comment/111482334
has comment: http://stackoverflow.com/comment/111478215
type: Answer
has comment: http://stackoverflow.com/comment/111480847
has comment: http://stackoverflow.com/comment/111473042

http://stackoverflow.com/comment/87096551
has text: I've tried to hash tag they others and take each in a row
comment on: http://stackoverflow.com/a/50040159
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50071304
tagged with: python
has title: Possible to start Dask in yarn-client mode?
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: hadoop-yarn
has body: I use dask_yarn (part of knit) to start a Dask Yarn cluster as follows: import dask_yarn cluster = dask_yarn.DaskYARNCluster(env='/home/hadoop/reqs/dvss.zip', lang='en_US.UTF-8') cluster.start(n_workers=4, memory=5120, cpus=3) This requests 1 vCore on core nodes for AM, and gives the rest of the vCores to workers. In Spark, I have the option to run the application in yarn-client mode, which would have the driver run on master nodes, and then all the core node resources could be free to use by workers. Is it possible to do the same with dask_yarn?
answer count: 1
tagged with: dask-distributed
has answer: http://stackoverflow.com/a/50077472
tagged with: amazon-web-services
favorite count: 0
type: Question
tagged with: dask
score: 1

http://stackoverflow.com/a/50035263
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87086807
has body: Still working on solution but here is something to start : &gt;&gt;&gt; data = [["Gold+",1,30,35],["Silver+",1,25,30],["Bronze+",1,20,25],["Gold",2,20,25],["Silver",2,15,20],["Bronze",2,10,15]] &gt;&gt;&gt; std = pd.DataFrame(data,columns=['Title','League','Start','End']) &gt;&gt;&gt; std Title League Start End 0 Gold+ 1 30 35 1 Silver+ 1 25 30 2 Bronze+ 1 20 25 3 Gold 2 20 25 4 Silver 2 15 20 5 Bronze 2 10 15 &gt;&gt;&gt; data = [["John",1,26],["Ryan",1,33],["Mike",1,9],["Jo",2,21],["Riko",2,15],["Kiven",2,13]] &gt;&gt;&gt; race = pd.DataFrame(data,columns=['Name','League','Distance']) &gt;&gt;&gt; race Name League Distance 0 John 1 26 1 Ryan 1 33 2 Mike 1 9 3 Jo 2 21 4 Riko 2 15 5 Kiven 2 13 &gt;&gt;&gt; result=pd.merge(race,std,on='League') &gt;&gt;&gt; result = result[(result.Distance &gt;= result.Start)&amp;(result.Distance &lt; result.End)]"Name","League","Distance","Title" &gt;&gt;&gt; result Name League Distance Title 1 John 1 26 Silver+ 3 Ryan 1 33 Gold+ 9 Jo 2 21 Gold 13 Riko 2 15 Silver 17 Kiven 2 13 Bronze Merge and Multiple conditions links for their tutorials and drawbacks.
accepted answer of: http://stackoverflow.com/q/50034728
type: Answer
answers question: http://stackoverflow.com/q/50034728
score: 0

http://stackoverflow.com/a/50039953
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87096802
accepted answer of: http://stackoverflow.com/q/50038585
has comment: http://stackoverflow.com/comment/87096294
answers question: http://stackoverflow.com/q/50038585
has body: tf.nn.softmax_cross_entropy_with_logits_v2 already computes softmax for you, you need to pass unbounded logits to your cross-entropy function, not the probability distribution that softmax returns. Try this: def multilayer_perceptron(x, weights, biases): # ... logits = tf.matmul(layer_3, weights['out']) + biases['out'] out_layer = tf.nn.softmax(logits) return logits, out_layer then use logits to compute cross-entropy and out_layer for inference. logits, pred = multilayer_perceptron(x, weights, biases) cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y)) optimizer is the operation that calculates gradients and applies them to variables, this operation is essentially what makes your network "learn", you have declared it but I don't see you calling it inside the loop. This should do it: _, temp_loss = sess.run([optimizer, cost], feed_dict={x: rand_x,y: rand_y}) You have a binary classification problem, I would guess your labels are either 0 or 1. You also have one output neuron, softmax of that will always return 1.0. What I would suggest is to make 2 output neurons, that way softmax will calculate probability distribution over 2 classes. Then your inference is the argmax of that distribution: correct = tf.cast(tf.equal(tf.argmax(pred, 1), y), dtype=tf.float32) accuracy = tf.reduce_mean(correct) In this case, you need to use tf.nn.sparse_softmax_cross_entropy_with_logits() to calculate cross-entropy: cost = tf.reduce_mean( tf.nn.tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y)) I would further suggest you to look at this post for more details on what I'm talking about.

http://stackoverflow.com/comment/87020866
type: Comment
has text: i simulate it for a simple time.sleep(0.001) instead REST, the thread will work but when i increase time, the thread not work and list have been empty.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50000174

numpy
tags question: http://stackoverflow.com/q/50042016
tags question: http://stackoverflow.com/q/49924164
tags question: http://stackoverflow.com/q/49944362
tags question: http://stackoverflow.com/q/50058425
tags question: http://stackoverflow.com/q/49968469
tags question: http://stackoverflow.com/q/50027430
tags question: http://stackoverflow.com/q/49993361
tags question: http://stackoverflow.com/q/49957431
tags question: http://stackoverflow.com/q/49932076
tags question: http://stackoverflow.com/q/50027783
tags question: http://stackoverflow.com/q/50047381
tags question: http://stackoverflow.com/q/49993101
tags question: http://stackoverflow.com/q/50074536
tags question: http://stackoverflow.com/q/49931993
tags question: http://stackoverflow.com/q/50043735
tags question: http://stackoverflow.com/q/50001153
tags question: http://stackoverflow.com/q/50034321
tags question: http://stackoverflow.com/q/49953627
tags question: http://stackoverflow.com/q/49972435
tags question: http://stackoverflow.com/q/49953817
tags question: http://stackoverflow.com/q/50073113
tags question: http://stackoverflow.com/q/50012376
tags question: http://stackoverflow.com/q/50066313
tags question: http://stackoverflow.com/q/50009029
tags question: http://stackoverflow.com/q/50019036
tags question: http://stackoverflow.com/q/50031731
tags question: http://stackoverflow.com/q/50011304
tags question: http://stackoverflow.com/q/50050040
tags question: http://stackoverflow.com/q/49928202
tags question: http://stackoverflow.com/q/50036522
tags question: http://stackoverflow.com/q/50044373
tags question: http://stackoverflow.com/q/49960195
tags question: http://stackoverflow.com/q/50070041
tags question: http://stackoverflow.com/q/50032912
tags question: http://stackoverflow.com/q/50020744
tags question: http://stackoverflow.com/q/49936222
tags question: http://stackoverflow.com/q/49948065
tags question: http://stackoverflow.com/q/49971708
tags question: http://stackoverflow.com/q/49946881
tags question: http://stackoverflow.com/q/50063231
tags question: http://stackoverflow.com/q/49951389
tags question: http://stackoverflow.com/q/50007232
tags question: http://stackoverflow.com/q/49964765
tags question: http://stackoverflow.com/q/50003658
tags question: http://stackoverflow.com/q/49968894
tags question: http://stackoverflow.com/q/49977723
tags question: http://stackoverflow.com/q/50020336
tags question: http://stackoverflow.com/q/49957157
tags question: http://stackoverflow.com/q/49985942
tags question: http://stackoverflow.com/q/50068431
tags question: http://stackoverflow.com/q/49949611
tags question: http://stackoverflow.com/q/50040458
tags question: http://stackoverflow.com/q/49965394
tags question: http://stackoverflow.com/q/50040428
tags question: http://stackoverflow.com/q/49950412
tags question: http://stackoverflow.com/q/49936594
tags question: http://stackoverflow.com/q/50021928
tags question: http://stackoverflow.com/q/49989805
tags question: http://stackoverflow.com/q/49949231
tags question: http://stackoverflow.com/q/50021625
tags question: http://stackoverflow.com/q/50030231
tags question: http://stackoverflow.com/q/50018595
tags question: http://stackoverflow.com/q/50034000
tags question: http://stackoverflow.com/q/50056645
tags question: http://stackoverflow.com/q/49926256
tags question: http://stackoverflow.com/q/49949428
tags question: http://stackoverflow.com/q/50005551
tags question: http://stackoverflow.com/q/49962027
tags question: http://stackoverflow.com/q/50053968
tags question: http://stackoverflow.com/q/49983134
tags question: http://stackoverflow.com/q/50028410
tags question: http://stackoverflow.com/q/49917313
tags question: http://stackoverflow.com/q/50064422
tags question: http://stackoverflow.com/q/49961043
tags question: http://stackoverflow.com/q/49981791
tags question: http://stackoverflow.com/q/49998480
tags question: http://stackoverflow.com/q/50073050
tags question: http://stackoverflow.com/q/49927172
tags question: http://stackoverflow.com/q/49938122
tags question: http://stackoverflow.com/q/49924561

http://stackoverflow.com/a/49962016
has comment: http://stackoverflow.com/comment/86940454
type: Answer
upvote count: 1
score: 1
has body: self.screen = kwargs.get("screen",self.screen) This gets the "screen" value from kwargs. If its not there, it just uses whatever happens to be in screen at the moment and stuffs it back into screen. Its the same as if "screen" in kwargs: self.screen = kwargs["screen"] In other words, update only changes values that are passed as keyword arguments. This seems like a complicated way to do a simple thing. There must be a use case for it, but, generally, yuck. Couldn't I just remove the use of kwargs seeing as I know how many parameters are needed? In the example, no. It will set zero, onem two or three attributes depending on whether they are in kwarg. You could even put other values like update(foo="bar") and it would just ignore them. So, here are two ways to set the attribute: debug.update(active = numActive) debug.active = numActive I'm leaning towards the second way. Leaning way over!
downvote count: 0
has comment: http://stackoverflow.com/comment/86940419
has comment: http://stackoverflow.com/comment/86940363
answers question: http://stackoverflow.com/q/49961997

http://stackoverflow.com/a/49977892
score: 4
has body: The id of an object in CPython is the objects memory address as seen by the process itself. The OS prevents different processes from seeing other processes memory. Gross simplification warning As far as each process is concerned, its memory space starts at 0 and goes up. Two different processes that start up and ask for a 1000-byte block of memory from the OS will both think they have memory block 0-1000, but they are not actually sharing memory. See https://en.wikipedia.org/wiki/Virtual_address_space for a good intro and better explanation.
upvote count: 4
has comment: http://stackoverflow.com/comment/86984772
answers question: http://stackoverflow.com/q/49977765
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49977765
has comment: http://stackoverflow.com/comment/86976766
has comment: http://stackoverflow.com/comment/86976222
type: Answer
has comment: http://stackoverflow.com/comment/86977706

http://stackoverflow.com/q/50074548
tagged with: python
tagged with: image-processing
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: raster
upvote count: 1
has comment: http://stackoverflow.com/comment/87171029
has title: Loop through large .tif stack (image raster) and extract positions
score: 1
has body: I want to run through a large tif stack +1500 frames and extract the coordinates of the local maxima for each frame. The code below does the job, however extremely slow for large files. When running on smaller bits (e.g. 20 frames) each frame is done almost instantly - when running on the whole dataset, each frame takes seconds. Any solutions to run a faster code? I figure it is due to the loading of the large tiff file - however it should only be necessary one time initially? I have the following code: from pims import ImageSequence from skimage.feature import peak_local_max def cmask(index,array): radius = 3 a,b = index nx,ny = array.shape y,x = np.ogrid[-a:nx-a,-b:ny-b] mask = x*x + y*y &lt;= radius*radius return(sum(array[mask])) # number of pixels images = ImageSequence('tryhard_red_small.tif') frame_list = [] x = [] y = [] int_liposome = [] BG_liposome = [] for i in range(len(images[0])): tmp_frame = images[0][i] xy = pd.DataFrame(peak_local_max(tmp_frame, min_distance=8,threshold_abs=3000)) x.extend(xy[0].tolist()) y.extend(xy[1].tolist()) for j in range(len(xy)): index = x[j],y[j] int_liposome.append(cmask(index,tmp_frame)) frame_list.extend([i]*len(xy)) print "Frame: ", i, "of ",len(images[0]) features = pd.DataFrame( {'lip_int':int_liposome, 'y' : y, 'x' : x, 'frame' : frame_list})
has answer: http://stackoverflow.com/a/50076279

http://stackoverflow.com/comment/86912119
comment on: http://stackoverflow.com/q/49947730
score: 4
type: Comment
type: QuestionComment
has text: Which part of this don't you understand? Do you know how list comprehensions work? Do you know what `zip(a, b)` does? Do you know what `i == j` does? Answering all of this would be far too broad for a single Q&A.

http://stackoverflow.com/comment/87003532
type: Comment
comment on: http://stackoverflow.com/a/49991760
score: 0
type: AnswerComment
has text: Thanks, that is a much cleaner/effective way to do that. Eventually got the connection every time. Could you explain how calling self.send_request() recursively would return `None` as it only returns on a success and would reach the recursive call on any error, until the success. Returning the recursive call would return any response from sending the request, including an error on the second. Unless I am totally missing something?

http://stackoverflow.com/a/49942337
score: 0
has body: It can be done with the help of iterrows() function. Here is the code : first table creation : value=[(0,11,10,20),(1,22,11,21),(2,33,12,22),(3,44,13,23),(4,55,14,24), (5,66,15,25),(6,77,16,26),(7,88,17,27),(8,99,18,28)] header=["index","time","vel","yaw"] df1 = pd.DataFrame.from_records(value, columns=header) second table creation: value=[(0,67,"nan","nan"),(1,75,"nan" ,"nan" ),(2,87,"nan" ,"nan" ) (3,99,"nan" ,"nan" )] header=["index","time","vel","yaw"] df2 = pd.DataFrame.from_records(value, columns=header) storing the result in df2 itself: for index, row in df2.iterrows(): min=10000000 for indexer, rows in df1.iterrows(): if abs(row['time']-rows['time'])&lt;min: min = abs(row['time']-rows['time']) #storing the position pos = indexer df2.loc[index,'vel'] = df1['vel'][pos] df2.loc[index,'yaw'] = df1['yaw'][pos]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49940527
answers question: http://stackoverflow.com/q/49940527
type: Answer

http://stackoverflow.com/q/49960061
has body: I am trying to get json data from webapp : I tried: from flask import Flask from flask import request app = Flask(__name__) @app.route('/postjson', methods = ['POST']) def postJsonHandler(): print (request.is_json) content = request.get_json() print (content) return 'JSON posted' app.run(port= 8090) and then: import requests url='http://127.0.0.1:8090/postjson' hj=requests.post(url,{ "device":"TemperatureSensor", "value":"20", "timestamp":"25/01/2017 10:10:05" }) print(hj.text) and i am getting: on server side: * Running on http://127.0.0.1:8090/ (Press CTRL+C to quit) 127.0.0.1 - - [22/Apr/2018 01:45:54] "POST /postjson/ HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 01:46:01] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 01:46:01] "GET /robots.txt HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 01:51:46] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 01:51:47] "GET /robots.txt HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 01:52:26] "GET /postjson' HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 01:52:48] "GET /postjson/ HTTP/1.1" 404 - and client output: 404 Not Found Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. I just want to post json and receive and save it to a variable at server side
has comment: http://stackoverflow.com/comment/86936668
duplicate of: http://stackoverflow.com/q/9733638
downvote count: 1
has comment: http://stackoverflow.com/comment/86936790
favorite count: 0
type: Question
has title: How parse json data in flask?
has comment: http://stackoverflow.com/comment/86936875
tagged with: python
score: -1
tagged with: flask
accepted answer: http://stackoverflow.com/a/49960205
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49960205
linked to: http://stackoverflow.com/q/9733638
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/93464990
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/53291609
has text: This answer seems incomplete. Where is the code in "Install using trusted host code as below"?
type: Comment

http://stackoverflow.com/comment/87036928
has text: @undergrad Your import is also wrong... replace it with `import matplotlib.pyplot as plt`
score: 2
type: Comment
comment on: http://stackoverflow.com/a/50010129
type: AnswerComment

http://stackoverflow.com/a/49923860
type: AcceptedAnswer
has body: Replace for x in sorted(dict_a): for y in sorted(dict_b): list= [] ... dict_b[y] = list dict_a[x] = dict_b by for x in sorted(dict_a): new_dict = dict() for y in sorted(dict_b): list= [] ... new_dict[y] = list dict_a[x] = new_dict
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49922911
answers question: http://stackoverflow.com/q/49922911

http://stackoverflow.com/comment/86876690
type: Comment
type: AnswerComment
has text: so I added the check if isinstance of a dictionary, and that part of the code works now, but now I get the error that 'list' object has no attribute 'values'. I haven't copied the code exactly.
comment on: http://stackoverflow.com/a/49929453
score: 0

http://stackoverflow.com/q/50043893
has comment: http://stackoverflow.com/comment/87174145
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: levenshtein-distance
tagged with: fuzzywuzzy
has answer: http://stackoverflow.com/a/50082814
has title: fuzzywuzzy to normalize string in pandas column
has answer: http://stackoverflow.com/a/50079056
has comment: http://stackoverflow.com/comment/87108001
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/50090800
answer count: 3
has body: I have a dataframe like this now i want to normalize the string in the 'comments' column for the word 'election' . I tried using fuzzywuzzy but wasn't able to implement it on pandas dataframe to partially match the word 'election'. The output dataframe should have the word 'election' in the 'comments' column like this Assume that i have around 100k rows and possible combinations for the word 'election' can be many. Kindly guide me on this part.
tagged with: dataframe

http://stackoverflow.com/a/49971239
score: 4
upvote count: 5
has comment: http://stackoverflow.com/comment/86958386
has comment: http://stackoverflow.com/comment/86958401
downvote count: 1
has comment: http://stackoverflow.com/comment/86958507
answers question: http://stackoverflow.com/q/49971160
has comment: http://stackoverflow.com/comment/86958519
has comment: http://stackoverflow.com/comment/86958385
has body: You appear to have mixed types in your series with dtype object. Option 1 You can first attempt to convert to numeric with errors='coerce', and then fillna with all up to the last character prior to converting to float: s = pd.Series(['34.49881N', 0], dtype=object) s = pd.to_numeric(s, errors='coerce').fillna(s.str[:-1].astype(float)) Option 2 You can also work the other way round. This is inadvisable as it is less stringent, i.e. you may find unexpected types in the result. s = s.str[:-1].astype(float).fillna(s) Result In both cases, you will find: print(s) 0 34.49881 1 0.00000 dtype: float64
type: Answer
has comment: http://stackoverflow.com/comment/86958369
has comment: http://stackoverflow.com/comment/86958429

http://stackoverflow.com/comment/86900282
score: 2
has text: i suspect this is an XY problem but impossible to know without more context...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49942050

http://stackoverflow.com/q/50004017
has answer: http://stackoverflow.com/a/50008563
has comment: http://stackoverflow.com/comment/87027749
linked to: http://stackoverflow.com/q/48427185
answer count: 1
has body: I am new to pyspark, I am trying to load CSV file which looks like this: my csv file: article_id title short_desc 33 novel findings support original asco-cap guidelines support categorization of her2 by fish status used in bcirg clinical trials my code to read the csv : from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField from pyspark.sql.types import DoubleType, IntegerType, StringType spark = SparkSession.builder.appName('Basics').getOrCreate() schema = StructType([ StructField("article_id", IntegerType()), StructField("title", StringType()), StructField("short_desc", StringType()), StructField("article_desc", StringType()) ]) peopleDF = spark.read.csv('temp.csv', header=True, schema=schema) peopleDF.show(6) why is null being added? dataset sample so that same problem can be reproduced by you: DataSet Sample
has comment: http://stackoverflow.com/comment/87071181
type: Question
accepted answer: http://stackoverflow.com/a/50008563
has comment: http://stackoverflow.com/comment/87071281
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87027174
has title: Import CSV to pyspark dataframe
has comment: http://stackoverflow.com/comment/87071318
tagged with: pyspark
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87027986
tagged with: export
type: AnsweredQuestion
score: 0

api
tags question: http://stackoverflow.com/q/50024154
tags question: http://stackoverflow.com/q/49992805
tags question: http://stackoverflow.com/q/50051919
tag name: api
tags question: http://stackoverflow.com/q/50055823
tags question: http://stackoverflow.com/q/50038843
tags question: http://stackoverflow.com/q/49986251
tags question: http://stackoverflow.com/q/50032258
tags question: http://stackoverflow.com/q/50005158
tags question: http://stackoverflow.com/q/50010601
tags question: http://stackoverflow.com/q/50028131
tags question: http://stackoverflow.com/q/50010738
tags question: http://stackoverflow.com/q/49967995
tags question: http://stackoverflow.com/q/50032423
type: Tag
tags question: http://stackoverflow.com/q/49994598
tags question: http://stackoverflow.com/q/50036071
tags question: http://stackoverflow.com/q/49982414
tags question: http://stackoverflow.com/q/49976488
tags question: http://stackoverflow.com/q/50037259

http://stackoverflow.com/a/68719621
has comment: http://stackoverflow.com/comment/122045772
score: 0
type: Answer
has body: I have successfully done this with pdf2docx : from pdf2docx import parse pdf_file = "test.pdf" word_file = "test.docx" parse(pdf_file, word_file, start=0, end=None)
answers question: http://stackoverflow.com/q/49965818
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87010009
type: QuestionComment
has text: @abarnert: I did the same thing with nc, with my original code, and it does send POST from my ubuntu chromium browser. Wonder why the code did not work when the server was running on ESP8266, and index.html was opened on this ubuntu chromium browser.. Any thoughts what may have happened?
comment on: http://stackoverflow.com/q/49995015
score: 0
type: Comment

http://stackoverflow.com/comment/87058701
score: 0
type: AnswerComment
has text: @vaultah. True, but this implies (in my opinion) an oxymoron. Indentation and style aren't exclusive. In fact, one can say *indentation is good style*!! Prefix this answer with indentation is good and I'll upvote !
type: Comment
comment on: http://stackoverflow.com/a/50020821

http://stackoverflow.com/comment/87115420
type: Comment
type: QuestionComment
has text: Please [edit] that information about the indices into the question.
comment on: http://stackoverflow.com/q/50049560
score: 2

http://stackoverflow.com/a/50072451
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50072365
has body: It looks like you are sending a message "bepis" in response to the first, then every, message "bepis" - presumably your first response will appear as an entry on the incoming feed which will trigger a second, etc.
score: 1
downvote count: 0

http://stackoverflow.com/q/49934424
type: UnansweredQuestion
has title: Import python packages slower on Windows 10 in Sublime Text
tagged with: python
has body: Today I went from Windows 7 to Windows 10, and sadly I meet troubles with Sublime Text which is my main text editor. (my main specs are Intel Core i7, 8 GBRAM, 500 GB SSD on a laptop Dell XPS 14 L421x) Running python in Spider is extremely fast (&lt;1s). But in Sublime Text 3, just importing numpy, matplotlib and scipy takes up to 4 secondes. I really don't understand what is going on. I installed the last version of python 3.6.5 through Anaconda. I tested the same version on a Windows 7 computer and it does not have this issue (~1.5s for just the import). Would you have any clue about what is going on? Thank you!
score: 0
has answer: http://stackoverflow.com/a/49951255
answer count: 1
tagged with: windows-10
tagged with: sublimetext3
type: Question

http://stackoverflow.com/comment/86942312
type: AnswerComment
score: 0
type: Comment
has text: Well, for that I would probably save the message that you receive in the webhook into a database for your site, which you can later read the messages from if you want to show them on a site. Then you can send whatever response back to the sender that you want.
comment on: http://stackoverflow.com/a/49933613

http://stackoverflow.com/comment/86983002
has text: That's exactly what I needed. I had looked at QPainter before but I had gotten the impression it would only work with the Graphics View framework and not with QWidget.
type: AnswerComment
comment on: http://stackoverflow.com/a/49982880
score: 0
type: Comment

pip
tags question: http://stackoverflow.com/q/49971577
tags question: http://stackoverflow.com/q/49928119
tags question: http://stackoverflow.com/q/49964093
tags question: http://stackoverflow.com/q/49960060
tags question: http://stackoverflow.com/q/49969308
tags question: http://stackoverflow.com/q/49956897
tags question: http://stackoverflow.com/q/49932926
tags question: http://stackoverflow.com/q/50017785
tags question: http://stackoverflow.com/q/49924237
tags question: http://stackoverflow.com/q/49942622
tags question: http://stackoverflow.com/q/50049523
tags question: http://stackoverflow.com/q/50072998
tags question: http://stackoverflow.com/q/49995624
tags question: http://stackoverflow.com/q/50025331
tags question: http://stackoverflow.com/q/50028413
tags question: http://stackoverflow.com/q/49943410
tags question: http://stackoverflow.com/q/50019187
tags question: http://stackoverflow.com/q/49951108
tags question: http://stackoverflow.com/q/50049505
tags question: http://stackoverflow.com/q/49966325
tags question: http://stackoverflow.com/q/50009682
tags question: http://stackoverflow.com/q/49974375
tags question: http://stackoverflow.com/q/49994133
tags question: http://stackoverflow.com/q/49986887
tags question: http://stackoverflow.com/q/50055316
tags question: http://stackoverflow.com/q/50026785
tags question: http://stackoverflow.com/q/49988119
tags question: http://stackoverflow.com/q/49966166
tags question: http://stackoverflow.com/q/49956985
tags question: http://stackoverflow.com/q/50061786
type: Tag
tags question: http://stackoverflow.com/q/50024617
tags question: http://stackoverflow.com/q/50023552
tags question: http://stackoverflow.com/q/49992883
tags question: http://stackoverflow.com/q/49988928
tags question: http://stackoverflow.com/q/50042040
tags question: http://stackoverflow.com/q/49996481
tags question: http://stackoverflow.com/q/49943662
tags question: http://stackoverflow.com/q/50029447
tags question: http://stackoverflow.com/q/49923671
tags question: http://stackoverflow.com/q/49985864
tags question: http://stackoverflow.com/q/50047105
tags question: http://stackoverflow.com/q/50022839
tags question: http://stackoverflow.com/q/50062505
tags question: http://stackoverflow.com/q/50038714
tags question: http://stackoverflow.com/q/49977483
tags question: http://stackoverflow.com/q/49998942
tags question: http://stackoverflow.com/q/50064950
tags question: http://stackoverflow.com/q/50014757
tags question: http://stackoverflow.com/q/49983958
tags question: http://stackoverflow.com/q/49918859
tags question: http://stackoverflow.com/q/49940684
tags question: http://stackoverflow.com/q/49940813
tag name: pip
tags question: http://stackoverflow.com/q/50033473
tags question: http://stackoverflow.com/q/49923857
tags question: http://stackoverflow.com/q/50065432
tags question: http://stackoverflow.com/q/49932759
tags question: http://stackoverflow.com/q/49986166
tags question: http://stackoverflow.com/q/49972908
tags question: http://stackoverflow.com/q/50036878
tags question: http://stackoverflow.com/q/50035634
tags question: http://stackoverflow.com/q/50025451
tags question: http://stackoverflow.com/q/49923259
tags question: http://stackoverflow.com/q/49969085
tags question: http://stackoverflow.com/q/50061458
tags question: http://stackoverflow.com/q/49934012
tags question: http://stackoverflow.com/q/50064124
tags question: http://stackoverflow.com/q/49970233
tags question: http://stackoverflow.com/q/49994721
tags question: http://stackoverflow.com/q/49969829
tags question: http://stackoverflow.com/q/50049619
tags question: http://stackoverflow.com/q/49925555
tags question: http://stackoverflow.com/q/49966547
tags question: http://stackoverflow.com/q/49979354
tags question: http://stackoverflow.com/q/49998745
tags question: http://stackoverflow.com/q/49918479
tags question: http://stackoverflow.com/q/49948638
tags question: http://stackoverflow.com/q/49920886
tags question: http://stackoverflow.com/q/49969800

http://stackoverflow.com/comment/86996190
type: Comment
type: QuestionComment
has text: By default, numpy will propagate NaNs quietly. If you've configured it to instead signal on NaNs, just don't do that.
comment on: http://stackoverflow.com/q/49989805
score: 0

http://stackoverflow.com/q/50071732
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/50071754
has answer: http://stackoverflow.com/a/50071754
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: How do you print after the code is done searching through the list and it can't find the word in the list so it replies error?
accepted answer: http://stackoverflow.com/a/50071757
tagged with: python
has answer: http://stackoverflow.com/a/50071757
has body: I have a for loop so it can go through the whole list but how do I input for like the very last line that there is no star named Bob and say that it is an error? big_str = "0.998448,0.035746,-0.042707,352,6.18,14\n0.873265,0.031968,0.486196,358,2.07,15,ALPHERATZ\n0.512379,0.020508,0.858515,432,2.28,21,CAPH\n0.883455,0.044652,-0.466383,720,5.41,34\n0.963482,0.055705,0.261913,886,2.83,39,ALGENIB\n0.752989,0.044458,0.656529,905,5.71,41" def getStarString(n): line_list = big_str.split("\n") for x in line_list: y = getStarName(x) if y == "None": continue else: if y == n: print(x) if y != n: continue if y != n: print("ERROR: No star called " + n + " could be found.") def getStarName(name): names = list(name.split(",")) for i in range(0, len(names)): if len(names) == 7: x = names[6] return x else: return "None" getStarString("ALGENIB") getStarString("BOB")

http://stackoverflow.com/comment/87070255
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50026529
type: Comment
has text: As an aside, I'm not sure what `get_object` is meant to do here - `CreateView` doesn't need a `get_object` method because the object hasn't been created yet.

http://stackoverflow.com/comment/86989539
type: AnswerComment
comment on: http://stackoverflow.com/a/49986021
score: 0
type: Comment
has text: In Python 3, you should `open` csv files and specify `newline=''` according to the [documentation](https://docs.python.org/3/library/csv.html#csv.reader) (see example code).

http://stackoverflow.com/comment/86969277
has text: Shall this datastructure have an interface that behaves like `dict`?
comment on: http://stackoverflow.com/q/49976591
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87178678
score: 4
type: Comment
has text: I understand how to web srape, it's just getting a video link from the blob
type: QuestionComment
comment on: http://stackoverflow.com/q/50054863

http://stackoverflow.com/a/49983735
type: Answer
score: 0
has body: I believe the tag that you use for each TaggedDocument is not what you expect. Doc2Vec algorithm is learning vector representations of the specified tags (some of which can be shared between the documents). So if your goal is simply to convert sentences to vectors, the recommended choice of a tag is some kind of unique sentence identifier, such as sentence index. The learned model is then stored in model.docvecs. E.g., if you use sentence index as a tag, you can then get the 1st document vector by accessing model.docvecs for the tag "0", the second document - for the tag "1", and so on. Example code: documents = [doc2vec.TaggedDocument(sentence, ['real-%d' % i]) for i, sentence in enumerate(sentences)] model = doc2vec.Doc2Vec(documents, vector_size=10) # 10 is just for illustration # Raw vectors are stored in `model.docvecs.vectors_docs`. # It's easier to access each one by the tag, which are stored in `model.docvecs.doctags`. for tag in model.docvecs.doctags.keys(): print(tag, model.docvecs[tag]) # Prints the learned numpy array for this tag By the way, to control the model randomness, use seed parameter of Doc2Vec class.
answers question: http://stackoverflow.com/q/49967931
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49967931

http://stackoverflow.com/q/50027490
score: 5
has body: i'm trying to use opencv with python and I have this problem: I have an image and a binary mask (single channel image with 0s and 255) I want to iterate each pixel of the mask and perform some operations on the original image based on the value of the masks pixel. How can I use the numpy optimization to do that? For example, suppose I want to create a new image where each pixel remains the same if its value in the mask is 0, or its set to (0,0,255) if the pixel in the mask is 255, like: def inpaint(originalImage, mask): [rows, columns, channels] = originalImage.shape result = np.zeros((rows,columns,channels)) for row in range(rows): for column in range(columns): if(mask[row,column]==0): result[row,column] = originalImage[row,column] else: result[row,column] = (0,0,255) return result How can I optimize this using numpy? Thank you very much
has title: Apply mask to image with OpenCv Python
tagged with: python
upvote count: 6
tagged with: opencv
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/50027554
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50027554
type: Question
tagged with: numpy

http://stackoverflow.com/comment/86898941
has text: Updated what the ssh login process looks like. The empty string is needed when I have the "else" in the if statement. It breaks if I have "else" without the empty string for some reason.
comment on: http://stackoverflow.com/q/49941105
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49998584
has comment: http://stackoverflow.com/comment/87013479
possible better answer: http://stackoverflow.com/a/49998843
upvote count: 1
has comment: http://stackoverflow.com/comment/87013411
downvote count: 1
has title: How to use a for loop to calculate mean of list of numbers python?
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: Trying to use a for loop to calculate the mean of a list as I want to practice. This code is returning 4, 5, and 1 with the test cases. Can someone tell me what I'm doing wrong please? def list_mean(p): total = 0 i = 0 if i &lt; len(p): for t in p: total = total + p[i] i += 1 return i mean = i / len(p) return mean print list_mean([1,2,3,4]) &gt;&gt;&gt; 2.5 print list_mean([1,3,4,5,2]) &gt;&gt;&gt; 3.0 print list_mean([2]) &gt;&gt;&gt; 2.0
has answer: http://stackoverflow.com/a/49998837
accepted answer: http://stackoverflow.com/a/49998837
tagged with: python
has comment: http://stackoverflow.com/comment/87013503
type: Question
has comment: http://stackoverflow.com/comment/87013414
answer count: 2
linked to: http://stackoverflow.com/q/9039961
tagged with: for-loop
tagged with: mean
has answer: http://stackoverflow.com/a/49998843

http://stackoverflow.com/q/49918400
has comment: http://stackoverflow.com/comment/86852485
type: Question
type: UnansweredQuestion
tagged with: process
tagged with: python
tagged with: printstream
has comment: http://stackoverflow.com/comment/86857355
tagged with: piping
score: 0
has body: I am trying to communicate between a process in my java program and an external python script that is called by the java program. The problem arises that my java program only receives the output of the python program after it has terminated. This means I cannot have a duplex "conversation" between the processes, which is my goal. Here is my python code: for i in range(3): print("hello"); #send hello to java line = sys.stdin.readline(); #read read response from java and my java code: String line; Process external = Runtime.getRuntime().exec(execStr); BufferedReader in = new BufferedReader(new InputStreamReader(external.getInputStream())); PrintStream out = new PrintStream(external.getOutputStream(),true); while ((line = in.readLine)) != null){//while python has not yet terminated if (line.length &gt; 0){ // if not a bogus line handleLine(); sendResponse(); } } The Java then hangs on the next readLine, because it never receives a next output from the python. Thanks for your help :)
has title: python send message to stdout without terminating
has answer: http://stackoverflow.com/a/49921202
answer count: 1
has comment: http://stackoverflow.com/comment/86857798

http://stackoverflow.com/q/50049363
upvote count: 1
downvote count: 0
score: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/50049438
has title: IndexError: tuple index out of range --— Python
tagged with: python
type: UnansweredQuestion
has body: I am running a simple code that will read a json file, take the inputs and generate an output. But in one of the line, I am getting error activities_obj = document.add_paragraph() activities_obj = helper.format_alignment(activities_obj) activities = helper.askForChoices(activities, "Choose extracurricular activities") activity_string = "Beside coop experience, {}. Additionally, {}. {}. Last but not least, {}." activiy_para = activity_string.format(*activities) This was the code, the last line is giving the error: activiy_para = activity_string.format(*activities) IndexError: tuple index out of range Thank you
has comment: http://stackoverflow.com/comment/87114931
has comment: http://stackoverflow.com/comment/87114889

http://stackoverflow.com/comment/86907828
type: QuestionComment
comment on: http://stackoverflow.com/q/49945539
score: 0
type: Comment
has text: and also `get_valid_filename`.

http://stackoverflow.com/q/49986992
answer count: 0
tagged with: deep-learning
has body: I am working on a transfer learning model (based off of Vgg19) with the following architecture. _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 224, 224, 3) 0 _________________________________________________________________ block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 _________________________________________________________________ block1_conv2 (Conv2D) (None, 224, 224, 64) 36928 _________________________________________________________________ block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 _________________________________________________________________ block2_conv1 (Conv2D) (None, 112, 112, 128) 73856 _________________________________________________________________ block2_conv2 (Conv2D) (None, 112, 112, 128) 147584 _________________________________________________________________ block2_pool (MaxPooling2D) (None, 56, 56, 128) 0 _________________________________________________________________ block3_conv1 (Conv2D) (None, 56, 56, 256) 295168 _________________________________________________________________ block3_conv2 (Conv2D) (None, 56, 56, 256) 590080 _________________________________________________________________ block3_conv3 (Conv2D) (None, 56, 56, 256) 590080 _________________________________________________________________ block3_conv4 (Conv2D) (None, 56, 56, 256) 590080 _________________________________________________________________ block3_pool (MaxPooling2D) (None, 28, 28, 256) 0 _________________________________________________________________ block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 _________________________________________________________________ block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 _________________________________________________________________ block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 _________________________________________________________________ block4_conv4 …
tagged with: keras
tagged with: transfer-learning
has comment: http://stackoverflow.com/comment/86990219
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/112678376
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86997802
has title: Training accuracy reaches 1.0 after the first training epoch
tagged with: python
has comment: http://stackoverflow.com/comment/86991670
score: 0

http://stackoverflow.com/comment/86944717
score: 0
type: Comment
has text: Seems an ideal case for using a heapq here especially given the two closest matches, eg: `heapq.nsmallest(2, data, lambda L: abs(9 - L))` - that way you're only retaining the two closest at any one time and applying the key only once without having to sort the entire sequence after decorating it. (oh and congrats on 10k!)
type: AnswerComment
comment on: http://stackoverflow.com/a/49964164

http://stackoverflow.com/a/49934108
upvote count: 2
downvote count: 0
has body: Just switch the 2 lines in the else. This will cause all of the recursive calls to happen before any of the print statements. Once the end of the string is reached, the recursion will unwind and all the prints will happen: def reverse(string): if not string: return else: reverse(string[1:]) print(string) reverse("abc") Output: c bc abc
answers question: http://stackoverflow.com/q/49933970
type: Answer
score: 2

multiprocessing
tags question: http://stackoverflow.com/q/49973222
tags question: http://stackoverflow.com/q/49952451
tags question: http://stackoverflow.com/q/49972470
tags question: http://stackoverflow.com/q/49921214
tags question: http://stackoverflow.com/q/49991266
tags question: http://stackoverflow.com/q/49961490
tags question: http://stackoverflow.com/q/49959255
tags question: http://stackoverflow.com/q/49978320
tags question: http://stackoverflow.com/q/50044407
tags question: http://stackoverflow.com/q/49936735
tags question: http://stackoverflow.com/q/50065913
tags question: http://stackoverflow.com/q/50029648
tags question: http://stackoverflow.com/q/50001620
tags question: http://stackoverflow.com/q/49980612
tags question: http://stackoverflow.com/q/49994840
tags question: http://stackoverflow.com/q/49963360
tags question: http://stackoverflow.com/q/50074545
tags question: http://stackoverflow.com/q/50003900
tags question: http://stackoverflow.com/q/49943309
tags question: http://stackoverflow.com/q/50013561
tags question: http://stackoverflow.com/q/49947935
tags question: http://stackoverflow.com/q/49977765
type: Tag
tags question: http://stackoverflow.com/q/49994548
tags question: http://stackoverflow.com/q/49993687
tags question: http://stackoverflow.com/q/50068403
tags question: http://stackoverflow.com/q/50044974
tags question: http://stackoverflow.com/q/50031613
tag name: multiprocessing
tags question: http://stackoverflow.com/q/50017255

http://stackoverflow.com/comment/88539269
type: Comment
comment on: http://stackoverflow.com/q/50026996
score: 0
has text: Tried. Didn't change a thing.
type: QuestionComment

http://stackoverflow.com/a/49971017
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86959462
accepted answer of: http://stackoverflow.com/q/49970716
has comment: http://stackoverflow.com/comment/86957899
type: Answer
has body: Here is one way. s = df[df['p_and_s'] &gt; 2].groupby('Event_Number')['Well'].apply(list) df['well_array'] = df['Event_Number'].map(s) Explanation Create a series mapping Event_Number to Well after applying a filter on p_and_s. Map to original dataframe via pd.Series.map. For performance, where possible lambda functions should be avoided as they represent expensive implicit loops. Result Event_Number Well p_and_s well_array 0 1 7 4.0 [7] 1 1 9 0.0 [7] 2 1 15 0.0 [7] 3 2 7 2.0 [9] 4 2 9 7.0 [9] 5 2 15 0.0 [9] 6 3 5 0.0 [7, 16] 7 3 7 8.0 [7, 16] 8 3 16 3.0 [7, 16] 9 4 7 8.0 [7] 10 4 15 0.0 [7] 11 5 7 8.0 [7, 9, 15] 12 5 9 3.0 [7, 9, 15] 13 5 15 6.0 [7, 9, 15] 14 6 5 0.0 [7] 15 6 7 8.0 [7] 16 7 7 8.0 [7] 17 7 9 0.0 [7] 18 7 15 0.0 [7] 19 8 7 8.0 [7, 15] 20 8 15 4.0 [7, 15]
has comment: http://stackoverflow.com/comment/86958926
answers question: http://stackoverflow.com/q/49970716
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86862193
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49922970
has text: `class atendance(models.Model):` this is from my models.py

http://stackoverflow.com/q/49966058
has answer: http://stackoverflow.com/a/49966398
has answer: http://stackoverflow.com/a/49966116
has body: I have a dictionary - p = {"a": [(0,1),(0,3)]} I want to fetch only the first value of each tuple i.e, 0 in this case. p["a"] gives me [(0,1),(0,3)] but I want [0,0] Can anyone suggest how to do this?
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49966088
has answer: http://stackoverflow.com/a/49966200
linked to: http://stackoverflow.com/q/10735282
has title: Python dictionary getting first value of tuple
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86947927
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/49966398
possible better answer: http://stackoverflow.com/a/49966088

http://stackoverflow.com/q/50051165
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/56357903
score: 1
has answer: http://stackoverflow.com/a/52060465
has answer: http://stackoverflow.com/a/50938359
has answer: http://stackoverflow.com/a/50052897
accepted answer: http://stackoverflow.com/a/50052897
favorite count: 0
type: Question
tagged with: attributeerror
linked to: http://stackoverflow.com/q/15891038
tagged with: seaborn
has title: AttributeError: 'float' object has no attribute 'shape' when using seaborn
has body: I created a random dataFrame simulating the dataset tips from seaborn: import numpy as np import pandas as pd time = ['day','night'] sex = ['female','male'] smoker = ['yes','no'] for t in range(0,len(time)): for s in range(0,len(sex)): for sm in range(0,len(smoker)): randomarray = np.random.rand(10)*10 if t == 0 and s == 0 and sm == 0: df = pd.DataFrame(index=np.arange(0,len(randomarray)),columns=["total_bill","time","sex","smoker"]) L = 0 for i in range(0,len(randomarray)): df.loc[i] = [randomarray[i], time[t], sex[s], smoker[sm]] L = L + 1 else: for i in range(0,len(randomarray)): df.loc[i+L] = [randomarray[i], time[t], sex[s], smoker[sm]] L = L + 1 My dataFrame df has, for each column, the same type of class as the dataFrame tips from seaborn's dataset: tips = sns.load_dataset("tips") type(tips["total_bill"][0]) type(tips["time"][0]) numpy.float64 str And so on for the other columns. Same as my dataFrame: type(df["total_bill"][0]) type(tips["time"][0]) numpy.float64 str However, when I try to use seaborn's violinplot or factorplot following the documentation: g = sns.factorplot(x="sex", y="total_bill", hue="smoker", col="time", data=df, kind="violin", split=True, size=4, aspect=.7); I have no problems if I use the dataFrame tips, but when I use my dataFrame I get: AttributeError: 'float' object has no attribute 'shape' I Imagine this is an issue with the way I pass the array into the dataFrame, but I couldn't find what is the problem since every issue I found on the internet with the same AttributeError says it's because it's not the same type of class, and as shown above my dataFrame has the same type of class as the one in seaborn's documentation. Any suggestions?
tagged with: python
possible better answer: http://stackoverflow.com/a/50938359
answer count: 4
type: AnsweredQuestion

machine-learning
tags question: http://stackoverflow.com/q/49977766
tags question: http://stackoverflow.com/q/49924058
type: Tag
tags question: http://stackoverflow.com/q/50034958
tags question: http://stackoverflow.com/q/49997685
tags question: http://stackoverflow.com/q/50004043
tags question: http://stackoverflow.com/q/49967190
tags question: http://stackoverflow.com/q/49965331
tags question: http://stackoverflow.com/q/49978307
tags question: http://stackoverflow.com/q/49946462
tags question: http://stackoverflow.com/q/50023771
tags question: http://stackoverflow.com/q/49966917
tags question: http://stackoverflow.com/q/49997883
tags question: http://stackoverflow.com/q/49980575
tags question: http://stackoverflow.com/q/50010065
tags question: http://stackoverflow.com/q/49978509
tags question: http://stackoverflow.com/q/50044974
tags question: http://stackoverflow.com/q/49958098
tags question: http://stackoverflow.com/q/49970421
tags question: http://stackoverflow.com/q/49988496
tags question: http://stackoverflow.com/q/49925374
tags question: http://stackoverflow.com/q/49944010
tags question: http://stackoverflow.com/q/49958888
tags question: http://stackoverflow.com/q/49945462
tags question: http://stackoverflow.com/q/49973379
tags question: http://stackoverflow.com/q/50051040
tags question: http://stackoverflow.com/q/50045620
tags question: http://stackoverflow.com/q/50029405
tags question: http://stackoverflow.com/q/49989128
tags question: http://stackoverflow.com/q/49929583
tags question: http://stackoverflow.com/q/50062764
tags question: http://stackoverflow.com/q/49982653
tags question: http://stackoverflow.com/q/50032197
tags question: http://stackoverflow.com/q/50037467
tags question: http://stackoverflow.com/q/49959130
tags question: http://stackoverflow.com/q/49975649
tags question: http://stackoverflow.com/q/49964995
tags question: http://stackoverflow.com/q/50004805
tags question: http://stackoverflow.com/q/49961668
tags question: http://stackoverflow.com/q/50055149
tags question: http://stackoverflow.com/q/50063093
tags question: http://stackoverflow.com/q/49932293
tags question: http://stackoverflow.com/q/50070789
tags question: http://stackoverflow.com/q/50053151
tags question: http://stackoverflow.com/q/49931965
tags question: http://stackoverflow.com/q/50011221
tags question: http://stackoverflow.com/q/49956354
tags question: http://stackoverflow.com/q/49987686
tags question: http://stackoverflow.com/q/49921839
tags question: http://stackoverflow.com/q/49986216
tags question: http://stackoverflow.com/q/49996489
tags question: http://stackoverflow.com/q/50011969
tags question: http://stackoverflow.com/q/50040238
tags question: http://stackoverflow.com/q/49965161
tags question: http://stackoverflow.com/q/49950865
tags question: http://stackoverflow.com/q/49970594
tags question: http://stackoverflow.com/q/50067558
tags question: http://stackoverflow.com/q/50072501
tags question: http://stackoverflow.com/q/49959907
tags question: http://stackoverflow.com/q/49977063
tags question: http://stackoverflow.com/q/49969087
tags question: http://stackoverflow.com/q/50004602
tags question: http://stackoverflow.com/q/49966639
tags question: http://stackoverflow.com/q/49952712
tags question: http://stackoverflow.com/q/50061393
tags question: http://stackoverflow.com/q/50061187
tags question: http://stackoverflow.com/q/50026996
tags question: http://stackoverflow.com/q/49940110
tags question: http://stackoverflow.com/q/50037674
tags question: http://stackoverflow.com/q/49964049
tags question: http://stackoverflow.com/q/49968000
tags question: http://stackoverflow.com/q/50041558
tags question: http://stackoverflow.com/q/49974030
tags question: http://stackoverflow.com/q/49971487
tags question: http://stackoverflow.com/q/50051281
tags question: http://stackoverflow.com/q/50010040
tags question: http://stackoverflow.com/q/50033014
tags question: http://stackoverflow.com/q/49936002
tags question: http://stackoverflow.com/q/49972725
tags question: http://stackoverflow.com/q/49936379

http://stackoverflow.com/a/50068004
downvote count: 0
has comment: http://stackoverflow.com/comment/87152986
upvote count: 1
answers question: http://stackoverflow.com/q/50067934
has comment: http://stackoverflow.com/comment/87153104
score: 1
type: Answer
has body: I'm not sure I understood fully your question, but I think what you need is partial function: from functools import partial my_partial = partial(return_arg, T) sub_function( 1, 2, my_partial)

http://stackoverflow.com/a/49928453
has comment: http://stackoverflow.com/comment/86872874
type: Answer
downvote count: 0
score: 7
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49928429
answers question: http://stackoverflow.com/q/49928429
has body: print automatically includes a line break. print("\n") therefore prints 2 line breaks.

http://stackoverflow.com/q/50022814
has comment: http://stackoverflow.com/comment/87062090
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has comment: http://stackoverflow.com/comment/87072396
linked to: http://stackoverflow.com/q/3768895
upvote count: 1
has body: I have three classes in my program, Processes contain Lanes. Lanes contain Tasks. The objects are stored in each other as arrays with some other string information about the class I'm trying to output the Process objects into JSON files but I keep getting the following error: Object of type 'Process' is not JSON serializable I'm fairly new to JSON processing so I don't understand why the objects are outputting this error. I'm using the following code to print the Process objects as JSON items: def outputJSON(self): for n in self.processes: print(json.dumps(n, sort_keys=True, indent=4)) And these are the class objects: class Task(object): def __init__(self, name, UiD): self.name = name self.UiD = UiD self.incoming = 'None' self.outgoing = [] self.messageFlowIn = 'None' self.messageFlowOut = 'None' def __str__(self): print(self.name +"\n") print("Incoming Connection : \n" + self.incoming + "\n") print("Outgoing Connections : ") if len(self.outgoing) &gt;= 1: for n in self.outgoing: print(n+"\n") print("MessageFlowIn : " + self.messageFlowIn) print("MessageFlowOut : " + self.messageFlowOut) class Lane(object): def __init__(self, name, associatedTasks): self.name = name self.associatedTasks = associatedTasks class Process(object): def __init__(self, name, associatedLaneNames): self.name = name self.associatedLaneNames = associatedLaneNames self.laneObjects = [] How can I correctly output this data to a JSON file?
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50023319
has comment: http://stackoverflow.com/comment/87071908
has comment: http://stackoverflow.com/comment/87066641
has title: How to write Python objects to a JSON file?
has answer: http://stackoverflow.com/a/50023090
tagged with: python
linked to: http://stackoverflow.com/q/18478287
has comment: http://stackoverflow.com/comment/87154568
accepted answer: http://stackoverflow.com/a/50103711
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50103711
has answer: http://stackoverflow.com/a/50023319
answer count: 3
has comment: http://stackoverflow.com/comment/87064296
has comment: http://stackoverflow.com/comment/87061982
score: 1

http://stackoverflow.com/q/50040093
has comment: http://stackoverflow.com/comment/87113370
has comment: http://stackoverflow.com/comment/87101302
has answer: http://stackoverflow.com/a/72044286
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87096312
tagged with: python
has answer: http://stackoverflow.com/a/72043781
answer count: 3
has title: Currency Converter in Python
upvote count: 1
has body: I am learning python and I have a task to write a program that converts currencies. It needs to support those currencies: BGN, USD, EUR, GBP with those rates: Rate USD EUR GBP 1 BGN 1.79549 1.95583 2.53405 There is automatic test engine that will input value to convert + entry currency + target currency. The output should be a number converted by the rates. I thought I could use a dictionary and do something like the code below. Would you help find why it is not working and find the elegant solution? value = float(input()) in_curr = input() out_curr = input() dict = {'BGN': 1, 'USD': 1.79549, 'EUR': 1.95583, 'GBP': 2.53405} def currency_converter (value,in_curr,out_curr): return((dict[in_curr] / dict[out_curr]) * value)
score: -6
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87096233
has comment: http://stackoverflow.com/comment/87096302
has answer: http://stackoverflow.com/a/50055876

http://stackoverflow.com/comment/86941009
has text: @EJP. Yes it can. The server is not doing anything right now. It is a dummy server just acking back the request. I looked at the server metrics and p999 response time is in < 1 ms. The network time is there which is around 7ms. So each call will take at least 7ms. That's why I am trying to do it in async mode hoping that it will scale. But it is not helping. For 10000 requests, it is taking 25 seconds. Again without considering the 13.362 sec just from the network, the rest 12 seconds is coming from the other calls. They are also part of the http lib. Can they be improved?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49959942

http://stackoverflow.com/q/50061029
score: 0
has answer: http://stackoverflow.com/a/50061213
tagged with: python
has body: I'm using tornado.websocket, where class-methods are overrides of the WebSocketHandler methods. Anyway, my code look like that: class SocketHandler(tornado.websocket.WebSocketHandler): current_ninja_pool = enumerate(return_dependency_lvl_0()) current_ninja = next(current_ninja_pool) file_to_upload = [] def check_origin(self, origin): return True def open(self): logging.info("A client connected.") self.run() def run(self): if condition: do_this() else: do_that() self.current_ninja = next(self.current_ninja_pool) self.run() def on_message(self, message): do_a_lot_of_stuff() if message == 'next one': self.current_ninja = next(self.current_ninja_pool) def on_close(self): logging.info("A client disconnected") So, what I want is to be able to iterate my enumerate, so that every element can be processed in the methods run or on_message depending on how my client-websocket will answer. The problem is that I want to iterate under particular conditions, and I don't have a clue on how to do this. Since I'm not very familiar with the way you manipulate class- and instance-variables, I'm probably missing a point here. Thank you
type: Question
type: UnansweredQuestion
answer count: 1
has title: Python : Iterate a list which is shared by several method in a class
tagged with: class

http://stackoverflow.com/a/50028051
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50019187
upvote count: 3
downvote count: 0
has body: Starting with how to use a custom package you have to define what is the purpose of that package. I mean, it is something that will be useful for everyone or only for you. If the first case, then the best way is publishing it on PyPI (In that case follow all the steps). If it is the second purpose, then omit the step 5. Then, whatever your package purpose is, the first steps are: Develop the package (try to document and test it). PyCharm it is a good IDE that can help to create unit test. I recommend you to take a look at the following link: Creating-and-running-Python_Test A Project Test folder structure that I have been working on The second step is to create a setup.py file. There are a lot of fields a setup.py file can contain. Here you have an example: from setuptools import setup setup( name='mdutils', version=1.0, license='BSD', author='Didac Coll', author_email='didaccoll_93@hotmail.com', maintainer='Dídac Coll', maintainer_email='didaccoll_93@hotmail.com', description='A package, useful to create Markdown files while executing python code.', long_description=open('README.md').read(), platforms=['Python 3.6'], packages=['mdutils', 'mdutils.tools', 'mdutils.fileutils'], include_package_data=True, zip_safe=False, classifiers=['Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities', 'License :: OSI Approved :: BSD License']) Once you have created your package, you have to test the distribution with the following command python setup.py develop If all is ok, now you can create your distribution with the following command python setup.py sdist. This will generate a new folder called dist where you will find a tar.gz file. If you are interested in creating a distribution for windows I recommend you to use the next command python setup.py sdist --format=zip. In this manner, you are going to create a zip file to dist folder. Now you have your own package d…

http://stackoverflow.com/comment/86934569
type: Comment
has text: @Aran-Fey Touche! I'll try and add a walk-through.
type: AnswerComment
comment on: http://stackoverflow.com/a/49959067
score: 0

http://stackoverflow.com/comment/86950214
comment on: http://stackoverflow.com/a/49961282
score: 0
type: Comment
type: AnswerComment
has text: You will duplicate it like the `if xml_name.lower() == 'genre': self.nodes.append(xml_name)` and `[-1]` makes sure you get the latest element data, so change needed in that. Also you need to have corresponding pop in `if xml_name.lower() in ['movie', 'genre']: self.nodes.pop()` updated as well for other tags

http://stackoverflow.com/comment/87025246
comment on: http://stackoverflow.com/q/50004087
type: Comment
has text: @leopik:your string is wrong (it uses wrong excape characters). Which python version? Python3 handles natively unicode strings. You may check https://docs.python.org/2/howto/unicode.html (there is one also for python3)
type: QuestionComment
score: 0

http://stackoverflow.com/q/50073216
has title: output shape of tensor changes when assigned to a variable
type: Question
has body: Defined a model which takes input of shape(96,96,3) and outputs shape(128) i.e. gives an embedding of 128 size for a given image of input size. Similar to facenet createmodel() is the function which returns the full model after constructing it. Since the model expects input in the form of (batch_size,96,96,3) I pass 3 images i.e. (3,96,96,3) so the output of the model will be of shape(1,3,128). Keeping that in mind consider the following: nn4_small2=createmodel() print(nn4_small2.outputs[0][2]) #prints Tensor("strided_slice_11:0", shape=(128,), dtype=float32) x=nn4_small2.outputs[0][2] print(tf.shape(x)) #prints Tensor("Shape_6:0", shape=(1,), dtype=int32) Why does the shape of the output tensor change when assigned to a variable?
score: 0
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/50073518
accepted answer: http://stackoverflow.com/a/50073518
answer count: 1
linked to: http://stackoverflow.com/q/37085430
tagged with: keras
tagged with: tensorflow
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/q/50047237
accepted answer: http://stackoverflow.com/a/50051542
has body: To reduce memory costs, I specified dtypes of my pandas dataframe using astype(),like: df['A'] = df['A'].astype(int8) then I use to_csv() to store it, but when I use read_csv() to read it again and check the dtypes, I found it still stored in int64. How can I preserve the dtypes while saving it in local storages?
has answer: http://stackoverflow.com/a/50051542
downvote count: 0
linked to: http://stackoverflow.com/q/43408621
favorite count: 0
has comment: http://stackoverflow.com/comment/87110761
score: 13
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/54422402
tagged with: pandas
has answer: http://stackoverflow.com/a/54422402
has comment: http://stackoverflow.com/comment/87124278
tagged with: python
has title: how to preserve dtypes of dataframes when using to_csv?
upvote count: 13
type: Question
answer count: 2

http://stackoverflow.com/comment/86963631
type: QuestionComment
has text: what exactly you mean by `it must count for my schedule`?
score: 0
comment on: http://stackoverflow.com/q/49973804
type: Comment

http://stackoverflow.com/a/50029953
has comment: http://stackoverflow.com/comment/87077848
type: Answer
has body: I do not really understand what you want so I cannot help you to achieve it. Hopefully I can help you to understand why your code does what it does. I added some lines to your code and annotated them with numbers #n in order to reference them in my explanations. The output of my code is prefixed with an asterisk so you can tell it apart and does not interfere with yours. Cursor.execute() returns a reference to the same cursor. Hence senRow1 and senRow2 are actually the same object as proven by #5 where this identity is asserted. And when you fetch the first row of senRow1 and the first row of senrow2 you are actually fecthing the two first rows of the same cursor, call it cur, senRow1 or senRow2, they are all different names for the same thing. Actually executing the first query is useless because before doing anything with it you execute the second one in the very same cursor and the result of the first one is lost. Changing the limit changes the number of rows but does not change the first rows. In order to demonstrate it I create two cursors in #1 and #2, execute the queries in #3 and #4 and print all the rows in #6 and #7. As you can see the number of rows returned varies with the limit, but the first rows remain the same regardless the limit. Note that I am printing the result of the first query for the shake of completeness, but as explained before only the second one is relevant to your code. Thus in each iteration of the loop you are looking at the first two rows returned by the second query. And those two rows are the same in each iteration. The modified code: countNumRows = cur.execute("SELECT count(*) FROM SEN_Table") countNumFetch = countNumRows.fetchone() countNumRowsTable = countNumFetch[0] print("Number of rows in the table: " + str(countNumRowsTable)) currLimit = 0 cursor1 = conn.cursor() #1 cursor2 = conn.cursor() #2 for x in range(0, countNumRowsTable): currLimit = currLimit + 1 currLimit1Str = str(currLimit) senRow1 = cur.execute("SELECT SenNumber…
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50022851
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50022851

http://stackoverflow.com/comment/87151874
type: Comment
type: QuestionComment
has text: If you need help with the question, you need to add more logs and show some code as in what you are trying to achieve.
score: 1
comment on: http://stackoverflow.com/q/50067618

http://stackoverflow.com/q/49954039
tagged with: python-3.x
linked to: http://stackoverflow.com/q/26831033
has body: What I want to do is assign a rect to a variable without drawing it on the screen. I was wondering how to do this. Here's my current code to assign a 20x20 white rectangle to "myRect": import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((50, 50)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() myRect = pygame.draw.rect(screen, (255, 255, 255), (0, 0, 20, 20))
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/49954131
accepted answer: http://stackoverflow.com/a/49954131
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has title: How do you create rect variables in pygame without drawing them?
answer count: 1
has comment: http://stackoverflow.com/comment/86926491
favorite count: 0
type: Question

http://stackoverflow.com/comment/139229262
has text: Please refer to Paramiko's code and see their comments: "Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls."
type: Comment
comment on: http://stackoverflow.com/a/78950326
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86933234
has text: Thanks, for your reply. The output should be: with zero index, there is no other similar row so the corresponding list should be [0] and for the index 2, row 2 and row 4 are similar, so we get the list [2,4].
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49958235

http://stackoverflow.com/comment/87001386
has text: When I open a shell it says Python Version 3.6.4, that might be wrong tho
type: AnswerComment
comment on: http://stackoverflow.com/a/49972980
type: Comment
score: 0

http://stackoverflow.com/comment/87106219
type: Comment
type: QuestionComment
has text: You don't need regex for that - split your sentence by whitespace and check if all of the words are at least 3 characters long: `if all(len(word)>2 for word in sentence.split())` ... Of course, you'll have a more difficult case if you have to account in punctuation, hyphened words etc. but even regex won't do it perfectly without post-processing.
score: 1
comment on: http://stackoverflow.com/q/50044830

http://stackoverflow.com/comment/86999539
comment on: http://stackoverflow.com/q/49991429
has text: Your document is about Python 3. The complexity of `dict.keys()` is O(n) in Python 2.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50007537
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50008686
has comment: http://stackoverflow.com/comment/87033878
has answer: http://stackoverflow.com/a/50008686
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/87032971
has comment: http://stackoverflow.com/comment/87033030
has title: emacs python Elpy auto-complete not working for all
tagged with: elpy
has comment: http://stackoverflow.com/comment/87034409
tagged with: path
has comment: http://stackoverflow.com/comment/87033185
tagged with: emacs
tagged with: python
has comment: http://stackoverflow.com/comment/87032532
type: AnsweredQuestion
has body: Using Mac OSC 10.13.4, emacs 25.3 (9.0), Python3 I could have some cases of Elpy autocompletion to work for python3, but for some reason, not always. For example, numpy. triggers autocompletion, but, pandas. does not. My intuition is that while numpy comes standard with python3, pandas does not. So I need to have emacs to point to the directory where the add-on modules are located. In short, emacs does not use the same paths as python3 ... I tried to add a path to the current emacs paths, but it always failed to append these. How can I do that?
upvote count: 3

http://stackoverflow.com/a/50067714
type: Answer
has body: You can use the random_uniform_initializer and customize it to your needs. You just need to provide it the minval and maxval that you want. If you want to set it to use the same range as a glorot uniform initializer plus a small epsilon, then just set minval and maxval to epsilon+-sqrt(6 / (fan_in + fan_out)). See the documentation for details.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50067558
score: 1

http://stackoverflow.com/a/49983508
has comment: http://stackoverflow.com/comment/86984734
has body: You can try below code to get text : element_to_hover_over = firefox.find_element_by_xpath("//span[text()='Jul-14']") hover = ActionChains(firefox).move_to_element(element_to_hover_over) hover.perform() element_to_hover_over = firefox.find_element_by_xpath("//div[@class='label value outline showOnHover hover']/span") element_to_hover_over.text Your second chart is inside frame first you need to switch into frame :- frame :- datawrapper-chart-8ZOKk then try below xpath to get value in list list &lt;webElement&gt; = (//div[@class='label series smaller' and @data-column='X.1'])[1]/span then iterate through every row and get value
score: 1
has comment: http://stackoverflow.com/comment/86984562
downvote count: 0
answers question: http://stackoverflow.com/q/49983002
has comment: http://stackoverflow.com/comment/86983312
upvote count: 1
has comment: http://stackoverflow.com/comment/86983579
has comment: http://stackoverflow.com/comment/86983473
has comment: http://stackoverflow.com/comment/86984197
has comment: http://stackoverflow.com/comment/86983518
type: Answer

http://stackoverflow.com/a/50036655
type: AcceptedAnswer
has body: Something like this should work: Basically, it splits the string when ever there's a space, making a list in which each item is a morse code letter. It then checks each letter against the dictionary and takes the english counterpart. Lastly, it puts all these into a list, turns it into a string again and prints it. Hope it helps! morse_eng_dict = {".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z"} nomorse = input("Enter your Morse code here:") nomorse_list = nomorse.split() #this splits the string up wherever there is a space not_morse = [] morse = True #The code is morse (so far) for letter in nomorse_list: eng_letter = False for key in morse_eng_dict.keys(): #for each of the morse code letters in the dictionary if letter == key: eng_letter = morse_eng_dict[key] if eng_letter: #if a letter was found that corresponds not_morse.append(eng_letter) else: print("Input is not valid morse code.") morse = False if morse == True: string = "".join(not_morse) #joining the string together (without spaces in between) print(string)
answers question: http://stackoverflow.com/q/50035978
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50035978

http://stackoverflow.com/comment/87136842
has text: @YaroslavSurzhikov: this looks nice! Thanks
comment on: http://stackoverflow.com/q/50059920
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49944443
tagged with: lxml
downvote count: 0
tagged with: python-requests
favorite count: 0
upvote count: 4
has title: Parse element's tail with requests-html
type: Question
tagged with: python-requests-html
answer count: 2
tagged with: python
type: UnansweredQuestion
has body: I want to parse an HTML document like this with requests-html 0.9.0: from requests_html import HTML html = HTML(html='important data and some rubbish') data = html.find('.data', first=True) print(data.html) # important data and some rubbish print(data.text) # important data and some rubbish I need to distinguish the text inside the tag (enclosed by it) from the tag's tail (the text that follows the element up to the next tag). This is the behaviour I initially expected: data.text == 'important data' data.tail == ' and some rubbish' But tail is not defined for Elements. Since requests-html provides access to inner lxml objects, we can try to get it from lxml.etree.Element.tail: from lxml.etree import tostring print(tostring(data.lxml)) # b' important data ' print(data.lxml.tail is None) # True There's no tail in lxml representation! The tag with its inner text is OK, but the tail seems to be stripped away. How do I extract 'and some rubbish'? Edit: I discovered that full_text provides the inner text only (so much for “full”). This enables a dirty hack of subtracting full_text from text, although I'm not positive it will work if there are any links. print(data.full_text) # important data
score: 4
has answer: http://stackoverflow.com/a/49955058
has answer: http://stackoverflow.com/a/68670598

k-means
tags question: http://stackoverflow.com/q/49971980
type: Tag
tags question: http://stackoverflow.com/q/49929912
tags question: http://stackoverflow.com/q/49961977
tag name: k-means
tags question: http://stackoverflow.com/q/49969960

http://stackoverflow.com/comment/89975128
type: Comment
has text: @Savita This has to do with the lookup-pattern. `"[0-9]{2}-[0-9]{2}-(?!0000)[0-9]{4}" ` doesnt match your example dates.
type: AnswerComment
comment on: http://stackoverflow.com/a/50009858
score: 0

http://stackoverflow.com/comment/87036642
comment on: http://stackoverflow.com/a/50009883
score: 0
type: Comment
has text: @ThirstforKnowledge Glad to help.
type: AnswerComment

http://stackoverflow.com/comment/87128816
type: Comment
score: 1
type: QuestionComment
has text: This might help: https://stackoverflow.com/a/15513483/7832176
comment on: http://stackoverflow.com/q/50054116

http://stackoverflow.com/comment/86957737
type: Comment
has text: Thank you, no genius, just pretty familiar with the pandas library. You are welcome. Happy coding.
comment on: http://stackoverflow.com/a/49970866
score: 0
type: AnswerComment

python-requests
tags question: http://stackoverflow.com/q/50032614
tags question: http://stackoverflow.com/q/50041938
tags question: http://stackoverflow.com/q/49996188
tags question: http://stackoverflow.com/q/50067315
tags question: http://stackoverflow.com/q/49991704
tags question: http://stackoverflow.com/q/49940970
tags question: http://stackoverflow.com/q/49944443
type: Tag
tags question: http://stackoverflow.com/q/50071013
tags question: http://stackoverflow.com/q/49955487
tags question: http://stackoverflow.com/q/50059693
tags question: http://stackoverflow.com/q/49964779
tags question: http://stackoverflow.com/q/50049724
tags question: http://stackoverflow.com/q/50058208
tags question: http://stackoverflow.com/q/49961974
tags question: http://stackoverflow.com/q/50035087
tags question: http://stackoverflow.com/q/50042455
tags question: http://stackoverflow.com/q/49937393
tags question: http://stackoverflow.com/q/50033646
tags question: http://stackoverflow.com/q/50033061
tags question: http://stackoverflow.com/q/50027585
tags question: http://stackoverflow.com/q/49928261
tags question: http://stackoverflow.com/q/50054406
tags question: http://stackoverflow.com/q/50059239
tags question: http://stackoverflow.com/q/49948100
tags question: http://stackoverflow.com/q/49981992
tags question: http://stackoverflow.com/q/50035708
tags question: http://stackoverflow.com/q/50002958
tags question: http://stackoverflow.com/q/50018098
tags question: http://stackoverflow.com/q/49919307
tag name: python-requests
tags question: http://stackoverflow.com/q/49944063
tags question: http://stackoverflow.com/q/49947016
tags question: http://stackoverflow.com/q/50040023
tags question: http://stackoverflow.com/q/50008091
tags question: http://stackoverflow.com/q/50012384
tags question: http://stackoverflow.com/q/49983047
tags question: http://stackoverflow.com/q/50070411
tags question: http://stackoverflow.com/q/49955536
tags question: http://stackoverflow.com/q/50073441
tags question: http://stackoverflow.com/q/50004573
tags question: http://stackoverflow.com/q/50003803
tags question: http://stackoverflow.com/q/50070256
tags question: http://stackoverflow.com/q/49973049
tags question: http://stackoverflow.com/q/49939098
tags question: http://stackoverflow.com/q/50005941
tags question: http://stackoverflow.com/q/50002974
tags question: http://stackoverflow.com/q/49920056
tags question: http://stackoverflow.com/q/50045709
tags question: http://stackoverflow.com/q/50068957
tags question: http://stackoverflow.com/q/49940443
tags question: http://stackoverflow.com/q/50049973
tags question: http://stackoverflow.com/q/49948234
tags question: http://stackoverflow.com/q/49978647
tags question: http://stackoverflow.com/q/49991581
tags question: http://stackoverflow.com/q/50003096
tags question: http://stackoverflow.com/q/49962973
tags question: http://stackoverflow.com/q/50019804

http://stackoverflow.com/comment/87128662
type: QuestionComment
has text: My question is everytime I use clf.fit(), it overwrites the clf and then I save the model. Is this making the model better with everytime I run clf.fit() if the data is the same?
score: 0
comment on: http://stackoverflow.com/q/50054189
type: Comment

http://stackoverflow.com/q/49926843
has body: I was playing around with sys's getsizeof() and found that False (or 0) consists of less bytes than True (or 1). Why is that? import sys print("Zero: " + str(sys.getsizeof(0))) print("One: " + str(sys.getsizeof(1))) print("False: " + str(sys.getsizeof(False))) print("True: " + str(sys.getsizeof(True))) # Prints: # Zero: 24 # One: 28 # False: 24 # True: 28 In fact, other numbers (also some that consist of more than one digit) are 28 bytes. for n in range(0, 12): print(str(n) + ": " + str(sys.getsizeof(n))) # Prints: # 0: 24 # 1: 28 # 2: 28 # 3: 28 # 4: 28 # 5: 28 # 6: 28 # 7: 28 # 8: 28 # 9: 28 # 10: 28 # 11: 28 Even more: sys.getsizeof(999999999) is also 28 bytes! sys.getsizeof(9999999999), however, is 32. So what's going on? I assume that the booleans True and False are internally converted to 0 and 1 respectively, but why is zero different in size from other lower integers? Side question: is this specific to how Python (3) represents these items, or is this generally how digits are presented in the OS?
downvote count: 0
favorite count: 0
type: Question
score: 31
tagged with: cpython
has comment: http://stackoverflow.com/comment/86869798
tagged with: size
has answer: http://stackoverflow.com/a/49926924
tagged with: python
has comment: http://stackoverflow.com/comment/86869904
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49926924
upvote count: 31
linked to: http://stackoverflow.com/q/16553542
has comment: http://stackoverflow.com/comment/86870130
has title: Why is a False value (0) smaller in bytes than True (1)?
tagged with: types
answer count: 1

http://stackoverflow.com/comment/90755665
has text: You can put it anywhere, in a function or method that you're calling. If you want to plot the graph as soon as the window spawns, then you'd put it into the build method for your App class. I'm actually using it in a custom method that gets called whenever I drop a file on the window. So I drop a file on the window, and it plots the data to a graph for me.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51824885

http://stackoverflow.com/a/50026051
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50011106
type: Answer
answers question: http://stackoverflow.com/q/50011106
score: 3
upvote count: 3
downvote count: 0
has body: So I figured out the reason. For some reason, passing in a datetime object into the DateField type of my models is not valid. I was not aware there was a DateTimeField which is exactly for this purpose. Django did not complain when I passed in a datetime object and it appears that it probably does implicit casting. However, the library django-reversion probably took the value before implicit conversion and tried to deserialize the object into the model which did not prove to be successful with a datetime object. As per documentation for DateTimeField: A date and time, represented in Python by a datetime.datetime instance.

http://stackoverflow.com/a/49940401
answers question: http://stackoverflow.com/q/49938766
has body: I solved it: #Locate the username field unform = browser.find_element_by_name("username") #Locate the password field pwform = browser.find_element_by_name('password') ActionChains(browser)\ .move_to_element(unform).click()\ .send_keys('test')\ .move_to_element(pwform).click()\ .send_keys('test')\ .perform() #Locate login button login_button = browser.find_element_by_xpath( '//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/span/button') #Click login button login_button.click()
type: Answer
score: 0

http://stackoverflow.com/a/49993518
has comment: http://stackoverflow.com/comment/87433636
has comment: http://stackoverflow.com/comment/87448820
score: 0
has comment: http://stackoverflow.com/comment/87314323
has body: You could at least use the full path for the repo command. That would avoid the subshell to have to know where the repo command is (meaning have the right PATH set on each os.system call).
has comment: http://stackoverflow.com/comment/87312692
has comment: http://stackoverflow.com/comment/87433464
answers question: http://stackoverflow.com/q/49993364
has comment: http://stackoverflow.com/comment/87003820
type: Answer
has comment: http://stackoverflow.com/comment/87003770

http://stackoverflow.com/comment/86988639
type: Comment
type: AnswerComment
has text: how to match until a double quotes is met ?
comment on: http://stackoverflow.com/a/49986120
score: 0

http://stackoverflow.com/comment/113392008
has text: If you get an error on converting the file: ```AttributeError: 'DiGraph' object has no attribute 'node'``` install ```pip install networkx==1.11``` [It's because Networkx v2 is somewhat non-backward compatible with smop (quite outdated)](https://github.com/victorlei/smop/issues/153#issuecomment-571826680.)
type: Comment
score: 7
comment on: http://stackoverflow.com/a/52266699
type: AnswerComment

http://stackoverflow.com/comment/87054794
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50005195
has text: the error statement doesn't indicate which line causes the crash, not even when I launch it manually

http://stackoverflow.com/q/50009634
upvote count: 0
has comment: http://stackoverflow.com/comment/87036160
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87036122
tagged with: python
tagged with: parameters
score: -1
accepted answer: http://stackoverflow.com/a/50009727
has comment: http://stackoverflow.com/comment/87036347
has body: I have a Python (2.7) file with a function. I want to call it from command line and pass optional parameters by param name. In my py file, I have this function: def split_file(source_file_path, alt_output_path='', chunk_size=2000000): and at the bottom I have this: if __name__ == '__main__': split_file(*sys.argv[1:]) How can set it up to be able to call it like this? &gt; C:\Python27\python C:\Work\file_splitter.py "C:\Work\files\myfile.txt" alt_output_path="C:\EBI\Work\files\alt" I've looked at argparser and it's a bit confusing to me.
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87035888
has answer: http://stackoverflow.com/a/50009727
has title: How to call a function from command line passing in named optional parameters
type: AnsweredQuestion

http://stackoverflow.com/q/49981791
favorite count: 0
has title: Numpy Matrix Indexing Equivalence
tagged with: numpy
tagged with: indexing
accepted answer: http://stackoverflow.com/a/49982192
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49982192
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86979789
downvote count: 0
has body: I have a matrix mat: array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]) I am wondering why mat[:3,1:2] is: array([[ 2], [ 7], [12]])` But mat[:3,1] is: array([ 2, 7, 12])
answer count: 1

http://stackoverflow.com/comment/86914913
has text: Can you paste the example header in your question as formatted text, rather than as an image?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49949146

http://stackoverflow.com/q/49962350
tagged with: python
has answer: http://stackoverflow.com/a/49963826
has comment: http://stackoverflow.com/comment/86940878
favorite count: 0
has answer: http://stackoverflow.com/a/49965411
answer count: 2
accepted answer: http://stackoverflow.com/a/49965411
has body: I'm trying to scrape text from a website and can't figure out how to remove an extraneous div tag. Code looks like: import requests from bs4 import BeautifulSoup team_urls = ['http://www.lyricsfreak.com/e/ed+sheeran/shape+of+you_21113143.html/', 'http://www.lyricsfreak.com/e/ed+sheeran/thinking+out+loud_21083784.html', 'http://www.lyricsfreak.com/e/ed+sheeran/photograph_21058341.html'] for url in team_urls: page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') for e in soup.find_all('br'): e.replace_with('\n') lyrics = soup.find(class_='dn') print(lyrics) This is giving me an output of: &lt;div class="dn" id="content_h"&gt;The club isn't the best place... I would like to remove the div tag.
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/49963826
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
has title: Removing extraneous div tags from BeautifulSoup
score: 1

http://stackoverflow.com/q/50004208
downvote count: 0
upvote count: 1
tagged with: python
has title: How to interpret the rvecs with aruco
tagged with: opencv
tagged with: aruco
has body: I have read some of your articles and they have helped me a lot to know the ins and outs of computer vision. I have a question about a vision issue and I would like to consult with you to see if you can answer me. I have calibrated my camera, and using the aruco library I try to obtain the position of them with: aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) ### parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(img, aruco_dict, parameters=parameters) if ids is not None: ids = self.__filteringWithOurList(ids, corners) localPositions = {} if ids is not None and len(ids.tolist()) &gt; 0: rvec, tvec, object_points = aruco.estimatePoseSingleMarkers(corners, markerLength, self.camera_matrix, self.dist_coeffs) My question comes in relation to that last line: the tvec (the vector of tranlation) I get it and it gives me good results regarding the position X, Y, Z of the aruco with respect to the camera, but with the rvec I do not have clear what I get. What I would like to obtain are the navigation angles (pitch, roll and yaw) with respect to the camera, but what comes out there I do not understand. I know it's in radians, so I've transformed it into degrees, but I still can not interpret it. What kind of rotation does it give me? How do I interpret it? Thank you very much
score: 1
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50034590
has comment: http://stackoverflow.com/comment/87085327
linked to: http://stackoverflow.com/q/26886653
downvote count: 0
upvote count: 1
has body: I have a time-series dataset and I need to find the difference in my field for every tick. In excel, I can accomplish this easily by writing a formula B2=A2-A1 and copying this formula down the entire B column example: Is there a straightforward way to do this with pandas? I have considered apply() but looks like it can only work on 1 element of a series My other option will be to create an Numpy array out of my column A and run a loop through it. However, that seems like a roundabout way and gets even more complicated if I need to refer elements from different The actual Excel formula that I need to translate is =IF((A3-A2)>0, (A3-A2), A3+(4294967296-A2))
has title: Is there an equivalent of an excel formula in pandas
tagged with: excel
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50034620
has comment: http://stackoverflow.com/comment/87088902
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50034620
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50048661
has answer: http://stackoverflow.com/a/50048661
tagged with: numpy
has answer: http://stackoverflow.com/a/50048304

http://stackoverflow.com/comment/86881987
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49933085
has text: Thanks for your answer! But this has a similar issue to some of the possible solutions I listed above. In my example the issue is with numpy, but in reality there are several (~10 or more) packages that I would need to remove in this way, and I would like to find a more general solution that doesn't involve hardcoding the removal of each of these packages. Thanks for the idea though! I didn't consider this as a way to remove the python package without removing the dependencies!
type: AnswerComment

http://stackoverflow.com/comment/87133436
type: Comment
comment on: http://stackoverflow.com/a/50057117
type: AnswerComment
has text: Thank you for the answer:) but unfortunately, I am unable to upvote it due to reputation. Although I am not able to retrieve the data from f.cleaned_data['choice_field'] .
score: 0

http://stackoverflow.com/comment/91245743
comment on: http://stackoverflow.com/q/49920886
type: QuestionComment
type: Comment
has text: Possible duplicate of [How to clean iPython environment so I can start over with Jupyter and Python 3.x?](https://stackoverflow.com/questions/47493806/how-to-clean-ipython-environment-so-i-can-start-over-with-jupyter-and-python-3-x)
score: 0

http://stackoverflow.com/comment/105408533
type: Comment
type: AnswerComment
score: 1
has text: How can I utilize this code chunk to produce the text labels for every feature? (Less Severe AND Severe)… The problem is that if I nest this loop over the range of all features, then the text label gets printed in the same location for all the features
comment on: http://stackoverflow.com/a/49952248

http://stackoverflow.com/q/50023796
type: AnsweredQuestion
score: 0
tagged with: datetime
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/50024103
has answer: http://stackoverflow.com/a/50024103
has title: Python datetime, html form input datetime-local
answer count: 1
type: Question
has body: I have an HTML form which receives date-time and stores it in a Django model. How can I compare this date-time with python's in build date time to check if there are equal?For example, a date-time receives from the template might look like this (Jan. 1, 2018, 1 a.m.), how can I write a script which will be able to compare html_time and python date time I have tried the following and it returns False import datetime def compare_time(time_now, html_time): if time_now == html_time: return True else: return False html_time = 'april. 26, 2018, 1 a.m.' time_now = datetime.datetime.ctime(datetime.datetime.now()) print(compare_time(time_now,html_time))

http://stackoverflow.com/q/49967434
tagged with: django
downvote count: 1
has title: Cannot resolve symbol Static
score: 0
has comment: http://stackoverflow.com/comment/86950573
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49969488
type: Question
tagged with: django-templates
type: UnansweredQuestion
answer count: 1
has body: {% load staticfiles %} &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="{% static 'search/style.css' %}"&gt; This is the code and I am getting error in loading static file in this part href="{% static 'search/style.css' %} error cannot resolve directory "{%static search
has comment: http://stackoverflow.com/comment/86951019
upvote count: 1

http://stackoverflow.com/a/50023209
has comment: http://stackoverflow.com/comment/87062930
type: Answer
answers question: http://stackoverflow.com/q/50022723
score: 2
has comment: http://stackoverflow.com/comment/87065231
upvote count: 2
has comment: http://stackoverflow.com/comment/87104772
type: AcceptedAnswer
downvote count: 0
has body: in that case you can use raw prefix + triple quoting: s = r"""awk '{printf "%s\\n", $0}' /tmp/file""" print(s) result: awk '{printf "%s\\n", $0}' /tmp/file So os.system(s) works. in pure python, replace newline by literal \n (adapted from another answer of mine): with open(file1,"rb") as f: contents = f.read().replace(b"\n",b"\\n") with open(file1+".bak","wb") as f: f.write(contents) os.remove(file1) os.rename(file1+".bak",file1)
has comment: http://stackoverflow.com/comment/87065810
accepted answer of: http://stackoverflow.com/q/50022723

http://stackoverflow.com/q/50069293
tagged with: python
answer count: 0
downvote count: 0
upvote count: 1
has title: How to allow a python script (that is called within a C# app) to access the USB port
score: 1
tagged with: can-bus
has body: Wondering if anyone has insight on the above. I have a Python script that accesses and sends messages through a USB-to-CAN converter. The script works pretty flawlessly when run from the Windows command line. I then tried to port calling this script from within a C# app. I can call the script fine. No problem there. When the script goes to connect to the USB-to-CAN converter, it throws an error similar to when the CAN converter is not plugged in to the USB port. I know this is not a lot to go on, as far as code and seeing my errors. I don't know if I can effectively give enough real code context without making a gigantic post. So just wondering if anyone has insight on a C# app giving USB access to a Python script called within the app. Thanks.
has comment: http://stackoverflow.com/comment/87155442
favorite count: 0
type: Question
tagged with: c#
type: UnansweredQuestion

avro
type: Tag
tags question: http://stackoverflow.com/q/50020868
tag name: avro

http://stackoverflow.com/q/49959546
upvote count: 3
has comment: http://stackoverflow.com/comment/86937877
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86939101
has comment: http://stackoverflow.com/comment/86936471
has comment: http://stackoverflow.com/comment/86939077
favorite count: 0
has comment: http://stackoverflow.com/comment/86935647
has comment: http://stackoverflow.com/comment/87026874
has body: I have a wonderful figure which appears excellent when working in a jupyter notebook but will not save as it appears in the notebook - the primary issue is the last xticklabel is always missing! I have tried numerous things including using tight_layout, saving with bbox_inches='tight', and adjusting the spacing with subplot_adjust - nothing seems to work! This is how it appears in juypyter lab: This is how the figure saves: Here is a snippet that re-creates the issue. import matplotlib.pyplot as plt import pandas as pd import numpy as np from matplotlib.dates import date2num, DateFormatter from datetime import timedelta ts = pd.Series(np.random.randn(len(rng)), index=pd.date_range('1/1/2011', periods=24*60, freq='min'), name='value') df = pd.DataFrame(ts, columns=['value']) fig, ax = plt.subplots(1, figsize=(8, 4)) ax.plot(df.value) ticks = ax.get_xticks() ax.set_xticks(np.linspace(date2num(df.index[0]), date2num(df.index[0] + timedelta(hours=24)), 5)) ax.set_xticks(np.linspace(date2num(df.index[0]), date2num(df.index[0] + timedelta(hours=24)), 25), minor=True) ax.xaxis.set_major_formatter(DateFormatter("%I %p")) ax.set_xlim(df.index[0], df.index[-1]) fig.savefig("tmp.png", bbox_inches='tight') How can I reliably save figures with matplotlib...? I am using matplotlib v2.2.2 with the MacOSX backend.
has comment: http://stackoverflow.com/comment/86936000
type: Question
has comment: http://stackoverflow.com/comment/86936299
has comment: http://stackoverflow.com/comment/86948492
score: 3
tagged with: matplotlib
has title: Issue with xticklabels when saving a figure with matplotlib
has comment: http://stackoverflow.com/comment/86937559
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86937576
has comment: http://stackoverflow.com/comment/86949764
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86935864

http://stackoverflow.com/q/50046738
has title: The way a 2D list is initialized changes its behavior
linked to: http://stackoverflow.com/q/240178
score: 0
has comment: http://stackoverflow.com/comment/87109695
has body: square = [[0 for i in range(3)] for j in range(3)] square &gt;&gt; [[0, 0, 0], [0, 0, 0], [0, 0, 0]] square[0][0] = 1 &gt;&gt; [[1, 0, 0], [0, 0, 0], [0, 0, 0]] This is the expected behavior. But then: square = [[0] * 3] * 3 square &gt;&gt; [[0, 0, 0], [0, 0, 0], [0, 0, 0]] square[0][0] = 1 &gt;&gt; [[1, 0, 0], [1, 0, 0], [1, 0, 0]] It seems like each list within the list is passed by reference to a list stored in memory. I found this to be weird behaviour since I didn't explicitly create the sublist as an independent variable, and I wondered if anybody had thoughts to share on this...
has comment: http://stackoverflow.com/comment/87110266
type: Question
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/87110748
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pass-by-reference
has comment: http://stackoverflow.com/comment/87109828
tagged with: list

http://stackoverflow.com/comment/87003082
comment on: http://stackoverflow.com/a/49992807
has text: Thanks very much !
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87067893
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50020130
type: Comment
has text: @BoarGules The `pink` on the left turns to `blue` on the right so basically I want to find out from which color to which color is a gradient going.

http://stackoverflow.com/comment/87033001
comment on: http://stackoverflow.com/q/50007474
score: 0
type: Comment
has text: It might be that `RadioSn` doesn't have an instance for the ForeignKey or the field had something else before you change the field in the db to something else. 1st:I suggest that you ensure that you have an instance for it, and try to save it with another instance (Just for testing) 2nd try to add `null=True,blank=True` to this field `role`, in the db leave it blank and save it (remove `role` from the `__str__`), test the form to see if the error persists, if not, go back to db, add an instance to ForeignKey, re add role to the `__str__` like it was, and test it
type: QuestionComment

http://stackoverflow.com/a/50048947
has comment: http://stackoverflow.com/comment/87114492
downvote count: 0
has body: We just need lookup (see documentation) df.lookup(df.index,df.columns[df.D-1]) Out[309]: array([2, 3, 3], dtype=int64) After assign it back df['E']=df.lookup(df.index,df.columns[df.D-1]) df Out[311]: A1 A2 A3 A4 B C D E 0 0 2 9 0 9 7 2 2 1 7 6 7 3 6 8 4 3 2 3 7 4 9 2 1 1 3 Update df.D.astype(str).map(dict(zip(df.columns.str[-1],df.columns))) Out[316]: 0 A2 1 A4 2 A1 Name: D, dtype: object Then df.lookup(df.index,df.D.astype(str).map(dict(zip(df.columns.str[-1],df.columns)))) Out[317]: array([2, 3, 3], dtype=int64)
answers question: http://stackoverflow.com/q/50048864
has comment: http://stackoverflow.com/comment/87114404
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87116390
upvote count: 2

http://stackoverflow.com/comment/87160675
comment on: http://stackoverflow.com/q/50071047
type: Comment
type: QuestionComment
has text: Python doesn't have pointers, but if you are familiar with pointers, you can think of all Python variables as Python object pointers. I second the recommendation to read https://nedbatchelder.com/text/names.html
score: 0

http://stackoverflow.com/a/49992789
type: Answer
has comment: http://stackoverflow.com/comment/87022682
accepted answer of: http://stackoverflow.com/q/49991840
answers question: http://stackoverflow.com/q/49991840
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87011427
upvote count: 1
has body: You can't easily insert variables into the local namespace (probably can but shouldn't without good cause). So use a dictionary to hold your named values. I've used the operator.itemgetter function to grab the ones you want for the various API calls, and wrapped your product function in a generator. from operator import itemgetter from itertools import product class DictCaller(dict): def __call__(self, fn, *args): fn(*map(itemgetter(self), args)) def my_product(d, *args): for xs in product(*map(itemgetter(d), args)): yield DictCaller(zip(args, xs)) for caller in my_product(*'abc'): caller(API_CALL, *'ab') caller(API_CALL1, *'bc')

http://stackoverflow.com/comment/87151136
score: 0
type: AnswerComment
has text: Thanks! And is it even possible to not even use that for-loop and just use map?
comment on: http://stackoverflow.com/a/50058330
type: Comment

http://stackoverflow.com/comment/86955707
type: Comment
comment on: http://stackoverflow.com/a/49969526
has text: Yep... you're right. I misplaced the open bracket. There are 9 possibilities three of which are 0 (no change) and the others are assigned based on the type of change. Thanks for your help!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87110997
type: Comment
has text: This is the most interesting problem i've seen all day. I'm really curious why they would be different. When converting the entire array into a boolean array and then indexing im curious if its done with np.float32 for efficiency reasons? Where as using array[index] > value might not need to be converted to a lower precision because its a single comparison. Definitely going to have to get deep in the docs to figure it out
comment on: http://stackoverflow.com/a/50047327
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86936237
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49958256
has text: Probably (just guessing) because you can apply it not just to numbers, but to any type that you decide has a finite set of items that you know how to sort in advance. Having this kind of generalization makes it cumbersome compared to writing your own implementation.

http://stackoverflow.com/comment/92163756
has text: Hey thanks for the kind word, unfortunately I didn't find a solution
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49947364
type: Comment

http://stackoverflow.com/comment/87036117
has text: I am pretty sure it is.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50007434
type: AnswerComment

http://stackoverflow.com/q/50007815
has comment: http://stackoverflow.com/comment/87123733
type: UnansweredQuestion
has title: python excel to csv conversion generating wrong output
has body: I wrote this code below where I am converting an excel sheet to csv file. It works fine if there are single line data in each excel cell but if the excel cell has multiple line data then it generates wrong output. Below is sample data from excel: Domain ; State ; Industry; Simulation ; Simulation offers public quick access to information and analysis – e.g., reports, news, data, and trends. Domain ; State ; Industry ; VT ; VR enables people to view simulation of virtual environement Dynamic visualization increases analysis capabilities Provides answers to questions such as: - Where are the biggest opportunities for scaling? - How should resources be aligned to increase performance? - How much are people are spending per transaction or on a particular virtualization? As you can see the first row of the excel sheet has single line data in each cell and so it comes correct but the second row had a multiple line data in it's last cell and when I run my code it treats each line in this cell as separate value and so each line comes in separate row in converted csv. Below is my code: import xlrd import csv def Excel2CSV(ExcelFile, SheetName, CSVFile): workbook = xlrd.open_workbook(ExcelFile) worksheet = workbook.sheet_by_name(SheetName) csvfile = open(CSVFile, 'w',newline = '',encoding='utf8') wr = csv.writer(csvfile,delimiter=';') for rownum in range(worksheet.nrows): wr.writerow(worksheet.row_values(rownum)) csvfile.close() How can I make sure multiple line data in a single cell remains together when converting excel sheet to csv(I don't care if the multiple line data from an excel cell becomes single line data in csv)?
tagged with: excel
has comment: http://stackoverflow.com/comment/87052774
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: Question
answer count: 0

http://stackoverflow.com/a/50521208
downvote count: 0
score: 2
type: Answer
has body: You can try using the following commands: $ export CFLAGS=-std=c++11 $ pip install PyICU
answers question: http://stackoverflow.com/q/49993304
upvote count: 2

http://stackoverflow.com/q/50047790
has answer: http://stackoverflow.com/a/50050271
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/87111752
tagged with: ordereddictionary
has answer: http://stackoverflow.com/a/77782852
has answer: http://stackoverflow.com/a/73556447
has answer: http://stackoverflow.com/a/50047914
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has body: I am tryinging to create a nested Json structure as follows: Example Json: { "id" : "de", "Key" : "1234567", "from" : "test@test.com", "expires" : "2018-04-25 18:45:48.3166159", "command" : "method.exec", "params" : { "method" : "cmd", "Key" : "default", "params" : { "command" : "testing 23" } } I am trying to do this from an OrderedDict. I am not sure of the correct way to structure the OrderedDict so that the correct Json is produced. Python Code: json_payload = OrderedDict( [('id', id), ('Key', keystore), ('from', 'test@test.com'), ('expires', expires), ('command', 'method.exec')] # What goes here for the params section?? ) print json.dumps(json_payload, indent=4, default=str)
has answer: http://stackoverflow.com/a/50047924
favorite count: 0
type: Question
has title: Python Json from Ordered Dict
answer count: 5
type: UnansweredQuestion
upvote count: 4

http://stackoverflow.com/comment/86941087
type: Comment
score: 0
type: AnswerComment
has text: Keep in mind: `eval()` should not be used in Python. Importing json module would be safer. Also, I still believe using a Java Kafka SMT would be the built-in solution to the problem, as this solution isn't failure proof
comment on: http://stackoverflow.com/a/49961931

http://stackoverflow.com/a/50060978
has comment: http://stackoverflow.com/comment/87141804
answers question: http://stackoverflow.com/q/50052832
has body: try h1.cmd('ifconfig h1 192.168.1.0') or xterm
type: Answer
score: 0

http://stackoverflow.com/comment/86914691
type: Comment
type: QuestionComment
has text: Irrespective of whether they are more interested in why using a reserved keyword is a syntax error or summing tuples, this has just come up many, many times.
comment on: http://stackoverflow.com/q/49948987
score: 0

http://stackoverflow.com/q/49959083
tagged with: python
score: 4
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49959467
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
upvote count: 5
has body: I have following code for my PyQt5 GUI: import sys from PyQt5.QtWidgets import QApplication, QWidget, QCalendarWidget, QMainWindow, QGridLayout, QLayout, QTableWidget, QHeaderView, QLabel, QHBoxLayout, QVBoxLayout, QLineEdit, QComboBox from PyQt5.QtCore import QDate, Qt from datetime import date, datetime class CalendarWindow(QMainWindow): def __init__(self, parent=None): super(CalendarWindow, self).__init__(parent) self.setUpUI() def setUpUI(self): self.setGeometry(50, 50, 1200, 700) # Labels self.label_events = QLabel(self) self.label_new_event = QLabel(self) self.label_event_name = QLabel(self) self.label_start_date = QLabel(self) self.label_repeat = QLabel(self) self.label_description = QLabel(self) # Labels parameters self.label_events.setAlignment(Qt.AlignCenter) self.label_events.setText("Wydarzenia danego dnia:") # self.label_new_event.setAlignment(Qt.AlignCenter) self.label_new_event.setText("Dodaj event:") self.label_event_name.setText("Nazwa eventu:") self.label_start_date.setText("Data eventu:") self.label_repeat.setText("Powtarzalność eventu:") self.label_description.setText("Opis:") # TextEdits self.text_event_name = QLineEdit(self) self.text_start_date = QLineEdit(self) self.text_description = QLineEdit(self) # TextEdits parameters # ComboBoxes self.combo_repeat = QComboBox(self) # ComboBoxes parameters self.combo_repeat.addItems( ["No", "Day", "Week", "Two weeks", "Month", "Half a year", "Year"]) # Widgets self.setWindowTitle("Python Calendar App") self.calendar_widget = QCalendarWidget(self) # User date select event self.calendar_widget.clicked[QDate].connect(self.dateChanged) self.events_list_widget = QTableWidget(self) self.events_list_widget.setColumnCount(5) self.events_list_widget.setHorizontalHeaderLabels( ["ID", "Name", "Date", "Repetition", "Description"]) # Columns stretched and fit self.events_list_widget.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.main_widget = QWidget(self) self.main_layout = QGridLayout(self.main_…
has title: PyQT5 proper layout alignment
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/49959467

http://stackoverflow.com/comment/87127068
score: 0
has text: Only I can do is using a loop to sum, when meets an 0 stops and loop next section. There should be an easier way in DataFrame.
type: QuestionComment
comment on: http://stackoverflow.com/q/50055285
type: Comment

http://stackoverflow.com/a/49957557
has body: The documentation specifies strftime on Period data type not Datetime data type; To use %q formatter, you can convert the datetime Index to Period (days as unit) and then format it: cols = pd.DatetimeIndex(['2000-01-01', '2000-04-01', '2000-07-01', '2000-10-01', '2001-01-01', '2001-04-01', '2001-07-01', '2001-10-01', '2002-01-01', '2002-04-01', '2002-07-01', '2002-10-01']) cols.to_period('D').strftime('%Yq%q') # hs.columns.to_period('D').strftime('%Yq%q') #array([u'2000q1', u'2000q2', u'2000q3', u'2000q4', u'2001q1', u'2001q2', # u'2001q3', u'2001q4', u'2002q1', u'2002q2', u'2002q3', u'2002q4'], # dtype='&lt;U6') Or simply use to_period with Q (quarter) as unit: cols.to_period('Q') # hs.columns.to_period('Q') #PeriodIndex(['2000Q1', '2000Q2', '2000Q3', '2000Q4', '2001Q1', '2001Q2', # '2001Q3', '2001Q4', '2002Q1', '2002Q2', '2002Q3', '2002Q4'], # dtype='period[Q-DEC]', freq='Q-DEC')
answers question: http://stackoverflow.com/q/49957395
upvote count: 6
type: Answer
downvote count: 0
type: AcceptedAnswer
score: 6
accepted answer of: http://stackoverflow.com/q/49957395

http://stackoverflow.com/comment/87011725
comment on: http://stackoverflow.com/q/49997560
has text: The same error ..
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/113218275
score: 0
has text: @data_addict Did you resolved this issue? I am facing the same issue. Any leads will be helpful.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49926504

http://stackoverflow.com/comment/87115841
type: Comment
comment on: http://stackoverflow.com/q/50049170
type: QuestionComment
score: 0
has text: If that solves your problem, then we can close this as a typo question. (Unless you don't understand why, in which case I can answer it by explaining that.) If, after fixing that, things are not as bad, but it's still not enough to solve the problem, please re-verify the Cython annotation and whatever benchmarking/profiling you did, so we know for sure we're looking at the right things. (Also, if you could update your question to tell us exactly which lines were annotated, that would help.)

http://stackoverflow.com/comment/86974679
has text: No, for arr=[0,0,0,0,1,1] and n=1 you get: arr[0] + arr[4] = 1, arr[1] + arr[4] = 1, arr[2] + arr[4] = 1, arr[3] + arr[4] = 1, ... That's 48
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49976191

http://stackoverflow.com/q/49936557
tagged with: pandas
has body: I have 2 dataframes in python that I would like to query for data. DF1: 4M records x 3 columns. The query function seems more efficient than the loc function. DF2: 2K records x 6 columns. The loc function seems much more efficient than the query function. Both queries return a single record. The simulation was done by running the same operation 10K times. Running python 2.7 and pandas 0.16.0 Any recommendations to improve the query speed?
has title: pandas dataframe: loc vs query performance
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49937318
answer count: 2
has comment: http://stackoverflow.com/comment/86888623
has answer: http://stackoverflow.com/a/72262060
possible better answer: http://stackoverflow.com/a/72262060
downvote count: 0
upvote count: 42
score: 42
has comment: http://stackoverflow.com/comment/86890173
accepted answer: http://stackoverflow.com/a/49937318
tagged with: indexing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86888729
tagged with: performance

http://stackoverflow.com/comment/88900900
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49983276
has text: Could you elaborate on the additional files you had to add to hiddenimport?
type: Comment

http://stackoverflow.com/comment/86878012
type: QuestionComment
type: Comment
has text: Just not possible without looking at each element in the array, so `O(N)` is as good as it gets.
score: 0
comment on: http://stackoverflow.com/q/49928609

http://stackoverflow.com/comment/86882702
type: Comment
type: AnswerComment
has text: It's giving me an syntax error for your code at file_name = f'{self.word_vocab}.mp3'
score: 0
comment on: http://stackoverflow.com/a/49932777

http://stackoverflow.com/comment/87072889
has text: I would suggest using Python's [shelve](https://docs.python.org/3/library/shelve.html#module-shelve) module which provides an dictionary-like interface to a file-based database—so doesn't require it all to be in memory.
comment on: http://stackoverflow.com/q/50028214
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49951218
has answer: http://stackoverflow.com/a/49951579
possible better answer: http://stackoverflow.com/a/49951579
has body: For the dataframe s6 shown below, I need to: 1. In s6 .iloc[:,4:] replace all cells that contain a 0 with np.nan 2. In s6 .iloc[:,4:] replace all cells that end with a number &lt; 5 with np.nan, where the value in each cell ends with an _Q and then a number. So for this example dataframe: col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | f1 f2 f3 f4 110_q9 111_q4 110_q8 111_q9 The desired output would look like this: col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | f1 f2 f3 f4 NaN Nan NaN 111_q9 I've tried many variations on the following, with no success: s6.iloc[:,4:][s6.iloc[:,4:].str.contains('0')] &lt;- np.nan s6.iloc[:,4:] = s6.iloc[:,4:].replace('*0*', np.nan) s6.iloc[:,4:] = s6.iloc[:,4:].replace('0',np.nan) s6.iloc[:,4:] = s6.iloc[:,4:].replace(0,np.nan) s6 = [out[out[f].str.split('_Q', expand=True)[1].astype(int) &gt; 5] for f in out.columns if f not in col_list] Solution: For the final solution on replacing cells that contain a 0 I altered the answer to also remove cells that did not contain a quality score (uncalled bases) and will post that here as an example of how to apply multiple filters to a subset of a pandas dataframe. import pandas as pd for chunk in pd.read_csv(self.input_csv, sep=',', header=0, chunksize=chunksize): # create id column chunk["id"] = chunk.apply(lambda x : '{}_{}_{}'.format(x[1], x[2], x[3]), axis=1) chunk.set_index("id", drop=True, inplace=True) chunk.drop(["Features", "fov","x","y"], axis=1, inplace=True) # count and remove uncalled bases cols = [x for x in chunk.columns] # coerce np array of strings to search A = chunk[cols].values.astype(str) # mask for uncalled bases on vectorized array m1 = np.core.defchararray.find(A, '0') != -1 m2 = np.core.defchararray.find(A, '_Q') == -1 # apply mask and return filtered columns to df chunk[cols] = np.where(m1|m2, '', chunk[cols]) # merge chunks into one dataframe chunks.append(chunk) csv= pd.concat(chunks, axis=0)
tagged with: replace
has answer: http://stackoverflow.com/a/49951369
has title: Pandas: replace all cells in a subset of columns that contain 0 with np.nan
accepted answer: http://stackoverflow.com/a/49951369
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/49918167
upvote count: 0
has title: Apply Regular expression on output file
answer count: 1
has answer: http://stackoverflow.com/a/49918884
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86852784
has body: I have written a python script that dumps all versions in a text file. All versions are separated by '|' symbol. I need to replace all versions starting with 3 with follwing condition e.g 1) 3.7.0E should be replaced as 03.07.00E 2) 3.17.1E should be replaced as 03.17.01E All single digit numbers should be replaced with 0 My output file looks like 3.7.0E|3.7.1E|3.7.2E|3.7.3E|3.7.4E|3.7.5E|16.2.1|16.2.2|3.8.0E|16.3.1|16.3.2|16.3.3|16.3.1a|16.4.1|16.4.2|3.17.1E|3.7.11E
has comment: http://stackoverflow.com/comment/86852271
accepted answer: http://stackoverflow.com/a/49918884
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86852530
has comment: http://stackoverflow.com/comment/86852804

http://stackoverflow.com/a/50066665
answers question: http://stackoverflow.com/q/50066500
type: Answer
has body: The problem is that you read the values before you even opened the Dialog. This will only give you the initial values. Place the readings after you opened the Dialog and you will be fine. def dialogOpen(self): self.sub = subDialog() if self.sub.exec_(): check = str(self.sub.checkbox.isChecked()) spin = str(self.sub.spinbox.value()) self.label1.setText('spinbox value is ' + spin) self.label2.setText('Checkbox is ' + check)
score: 4
accepted answer of: http://stackoverflow.com/q/50066500
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50086067
has body: Taken partially from this question, add display-name to WSGIDaemonProcess so you can grab them using a command like: ps aux | grep modwsgi Add this to your configuration: Define GROUPNAME modwsgi WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5 display-name=%{GROUPNAME} Update There are a couple of reasons why ps would not give you the DaemonProcess display-name. As shown in the docs: display-name=value Defines a different name to show for the daemon process when using the ps command to list processes. If the value is %{GROUP} then the name will be (wsgi:group) where group is replaced with the name of the daemon process group. Note that only as many characters of the supplied value can be displayed as were originally taken up by argv0 of the executing process. Anything in excess of this will be truncated. This feature may not work as described on all platforms. Typically it also requires a ps program with BSD heritage. Thus on some versions of Solaris UNIX the /usr/bin/ps program doesn’t work, but /usr/ucb/ps does. Other programs which can display this value include htop. You could: Set a display-name of smaller length: WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5 display-name=wsws And try to find them by: ps aux | grep wsws Or set it to %{GROUP} and filter using the name of the daemon process group (wsgi:group).
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49964550
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49964550
has comment: http://stackoverflow.com/comment/87189774
has comment: http://stackoverflow.com/comment/87189677
score: 2
has comment: http://stackoverflow.com/comment/87188376
downvote count: 0
has comment: http://stackoverflow.com/comment/104409128
type: Answer

http://stackoverflow.com/a/50050714
answers question: http://stackoverflow.com/q/50050440
score: 0
has body: The following code keeps track of what they pressed: choice=None def choice1(): global choice choice='Choice 1' def choice2(): global choice choice='Choice 2' def start(): global choice if choice=='Choice 1': foo1() elif choice=='Choice 2': foo2() else: #do something else since they didn't press either Pass choice1 as the command for Choice_1_Button, choice2 as the command for Choice_2_Button, and start for Start_Button. If you want to use radio buttons, it will make it easier: def start(choice): if choice=='Choice 1': foo1() elif choice=='Choice 2': foo2() else: #do something else since they didn't press either var=StringVar(root) var.set(None) Radiobutton(root, text='Choice 1', value='Choice 1', variable=var).pack() Radiobutton(root, text='Choice 2', value='Choice 2', variable=var).pack() Button(self.frame, text='Start', command=lambda: start(var.get())).pack()
type: Answer

http://stackoverflow.com/a/50012680
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/50012624
has body: Maybe try subprocess instead of os.system, so something like this: import subprocess bashCommand = "wget -O url_list_dir/wise_allsky.dat '{href_aw}' --no-check-certificate" process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate()
type: Answer
score: -1

http://stackoverflow.com/comment/87073290
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50028309
has text: Related: https://github.com/numpy/numpy/issues/10752
score: 0

http://stackoverflow.com/q/50050862
tagged with: django
upvote count: 7
favorite count: 0
type: Question
tagged with: model
has comment: http://stackoverflow.com/comment/87118342
has body: In our project we use soft delete (is_deleted attribute on a model). Before creating a new model I want to first check if it was already exist and deleted and if so - set is_deleted=False and save the already exists model. So I decided to override the model 'save' method. (not the View Create since it should work not only for requests) The problem is that 'save()' is called for all actions (create, update, delete). Is there a way I can call the overridden method only on create? class Model(BaseModel): title = models.CharField(max_length=200) identifier = models.CharField(max_length=15) def save(self, *args, **kwargs): try: existing_model = Model.objects.active_and_deleted().get( identifier=self.identifier) if self.is_deleted is False: existing_model.is_deleted = False existing_model.title = self.title existing_model.created_at = self.created_at existing_model.updated_at = self.updated_at existing_model.created_by = self.created_by existing_model.deleted_at = None super(Model, existing_model).save(args, kwargs) except Model.DoesNotExist: # in case the Nodel wasn't already exist - continue pass super(Model, self).save(*args, **kwargs)
has title: Django - Override model save()
has answer: http://stackoverflow.com/a/50052289
answer count: 3
has comment: http://stackoverflow.com/comment/87119593
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87120692
score: 7
has answer: http://stackoverflow.com/a/50051005
tagged with: python
has answer: http://stackoverflow.com/a/70432319
has comment: http://stackoverflow.com/comment/87118122
downvote count: 0

http://stackoverflow.com/comment/86928771
score: 0
type: Comment
type: QuestionComment
has text: the object `ips` Is a list. When you call `link.connect`, you end up passing a `list` as an argument, but it says that `link.connect` expects a string instead. You can fix that by iterating through your list of `ips`, for example: `for ip in ips: check(ip, "80)`
comment on: http://stackoverflow.com/q/49956156

http://stackoverflow.com/comment/86973283
score: 0
has text: Show us what you've tried?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49977495

http://stackoverflow.com/comment/87119637
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50051440
has text: The second-top-voted answer on the linked duplicate shows how to use `collections.Counter` in an idiomatic way.
type: Comment

json-rpc
tag name: json-rpc
tags question: http://stackoverflow.com/q/50047128
tags question: http://stackoverflow.com/q/49945083
type: Tag

http://stackoverflow.com/q/50049724
upvote count: 2
has answer: http://stackoverflow.com/a/53942557
has title: git review complains of requests.packages.urllib3 but the package is installed
type: UnansweredQuestion
has body: when i try to run git-review i get the below error: [root@localhost ~]# git-review Traceback (most recent call last): File "/usr/bin/git-review", line 7, in &lt;module&gt; from git_review.cmd import main File "/usr/lib/python2.7/site-packages/git_review/cmd.py", line 33, in &lt;module&gt; import requests File "/usr/lib/python2.7/site-packages/requests/__init__.py", line 58, in &lt;module&gt; from . import utils File "/usr/lib/python2.7/site-packages/requests/utils.py", line 32, in &lt;module&gt; from .exceptions import InvalidURL File "/usr/lib/python2.7/site-packages/requests/exceptions.py", line 10, in &lt;module&gt; from .packages.urllib3.exceptions import HTTPError as BaseHTTPError File "/usr/lib/python2.7/site-packages/requests/packages/__init__.py", line 95, in load_module raise ImportError("No module named '%s'" % (name,)) ImportError: No module named 'requests.packages.urllib3' but the requests package is already installed on the system: [root@localhost ~]# yum install python-requests Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: centos.mirror.net.in * epel: del-mirrors.extreme-ix.org * extras: del-mirrors.extreme-ix.org * updates: del-mirrors.extreme-ix.org Package python-requests-2.6.0-1.el7_1.noarch already installed and latest version Nothing to do This is my os config: [root@localhost ~]# uname -a Linux localhost.localdomain 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux [root@localhost ~]# cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) I tried uninstalling/installing packages from scratch but no luck. any help would be great here. EDIT: Here is the extra info asked in the comments: [root@localhost ~]# pip --version pip 8.1.2 from /usr/lib/python2.7/site-packages (python 2.7) [root@localhost ~]# python --version Python 2.7.5 [root@localhost ~]# pip freeze backports.ssl-match-hostname==3.4.0.2 blivet==0.61.15.65 Brlapi==0.6.0 certifi==2018.4.16 cffi==1.6…
tagged with: python
has comment: http://stackoverflow.com/comment/87184346
tagged with: python-requests
has comment: http://stackoverflow.com/comment/87115690
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/87183626
has comment: http://stackoverflow.com/comment/87229629
tagged with: git-review
tagged with: linux
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87195655
type: Question

global
type: Tag
tags question: http://stackoverflow.com/q/50050194
tag name: global

http://stackoverflow.com/a/49953282
has body: Do you match the training data preprocessing during testing?
answers question: http://stackoverflow.com/q/49952714
type: Answer
score: 0

http://stackoverflow.com/q/49961552
tagged with: igraph
score: 0
downvote count: 2
duplicate of: http://stackoverflow.com/q/56171211
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/56171211
tagged with: nvidia
type: Question
has body: I am new to programming in python on top of a NVIDIA GPU so have the following problem statement. I'm trying to perform social network analysis on Youtube Dataset(http://netsg.cs.sfu.ca/youtubedata/) in 2 parts using python's igraph library. In the 1st part I will be looking at degree distributions, centrality measures and computing HITS scores, page rank, clustering coefficients. In the 2nd part I will be working on link prediction between videos using supervised learning, PropFlow, proximity scoring, supervised random walks. Currently I am done with the pre-processing part but when I try to generate graphs on a part of our data set(the subset containing 5538 unique nodes) using igraph library in PyCharm IDE, the code runs for 3 hours with no end in sight. I wanted to know will running the python code on NVIDIA GPU on my machine will speed things up? Also is there any way to run code written in pycharm IDE directly on GPU using CUDA(https://developer.nvidia.com/cuda-downloads?target_os=Windows&amp;target_arch=x86_64&amp;target_version=7&amp;target_type=exelocal) without python's Anaconda distribution ? I tried searching online for the same but couldn't find any. System Configuration Windows 7(64 bit) NVIDIA GeForce 820M GPU(2 GB) RAM (8 GB) Python 2.7.14 PyCharm IDE(Community Edition)
has comment: http://stackoverflow.com/comment/100787672
type: UnansweredQuestion
tagged with: gpu
has answer: http://stackoverflow.com/a/50003147
has comment: http://stackoverflow.com/comment/86941448
has title: Run Python Code on NVIDIA GPU
tagged with: python
has comment: http://stackoverflow.com/comment/87023869
tagged with: cuda
upvote count: 2

http://stackoverflow.com/a/49943076
type: Answer
accepted answer of: http://stackoverflow.com/q/49930961
score: 0
answers question: http://stackoverflow.com/q/49930961
type: AcceptedAnswer
has body: Your question is a variation of the FAQ "Why do things work differently under systemd?. In this case, systemd is not supplying the DISPLAY environment variable that is available in your CLI. The value for DISPLAY is not always stable, and there may not always be a DISPLAY connect to. A recommended alternate solution for launching GUI apps is to use your desktop environment's "autostart" feature to automatically launch something on login.

http://stackoverflow.com/comment/87075591
has text: You could compile your regexps before using them, which makes individual calls a bit simpler.
score: 0
comment on: http://stackoverflow.com/q/49977715
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50032154
downvote count: 6
has comment: http://stackoverflow.com/comment/87080610
has body: The surface area of a rectangle is calculated with the following formula: Area = length * width It's pretty simple to do this in JavaScript: var svgWidth = ... var svgHeight = ... var svgArea = svgWidth * svgHeight; console.log("The area of the SVG is " + svgArea);
answers question: http://stackoverflow.com/q/50032122
upvote count: 2
type: Answer
score: -4
has comment: http://stackoverflow.com/comment/87085557

http://stackoverflow.com/q/50008091
type: AnsweredQuestion
tagged with: python-3.4
downvote count: 2
has body: I'm learning how to query an API programmatically using python. I'm able to authenticate against the API and get a 200 response. When I pass through parameters like this: parameters = {"q": "serial_number:actual_serial"} and then print(response.text) I get data back that I expect. When I pass through parameters like this: parameters = {"q": "serial_number:actual_serial"&amp;"rows=5"} I get: parameters = {"q": "serial_number:actual_serial"&amp;"rows=5"} TypeError: unsupported operand type(s) for &amp;: 'str' and 'str' and when I try to use a comma: parameters = {"q": "serial_number:actual_serial", "rows=5"} I get parameters = {"q": "serial_number:actual_serial", "rows=5"} ^ SyntaxError: invalid syntax So I'm not formatting the second part of the parameters properly. What am I missing? I'm using python3.4 When I query using the web API for the same query, I get an URL that is: https://.......?q=state%3APENDING_DESTRUCTION&amp;rows=5&amp;...... (sorry, obfuscating the url).
has answer: http://stackoverflow.com/a/50008164
upvote count: 1
has title: SyntaxError: invalid syntax, python, query API
accepted answer: http://stackoverflow.com/a/50008164
answer count: 1
tagged with: python-requests
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
score: -1

http://stackoverflow.com/q/49934033
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49934283
score: 0
has title: PyQt: Get menu button object name instead of menu item
answer count: 1
tagged with: pyqt5
tagged with: menu
tagged with: qpushbutton
accepted answer: http://stackoverflow.com/a/49934283
type: Question
tagged with: pyqt
has body: I have several qpushbuttons with a menus and am trying to get the specific button that has a menu item selected. Right now using the sender function I am able to get the menu item selected but I require the actual button which holds the menu (button 1 in this case). class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(400, 400)) buttons= ['button1','button2','button3'] pybutton = {} x=0 t = 0 for i in buttons: t = t + 100 x+=1 pybutton[str(x)] = QPushButton(i, self) pybutton[str(x)].setObjectName('btn' + str(x)) menu = QMenu() menu.addAction('item1',self.status) menu.addAction('item2',self.status) menu.addAction('item3',self.status) menu2 = menu.addMenu('menu2') menu2.addAction('item4') pybutton[str(x)].setMenu(menu) pybutton[str(x)].resize(100,100) pybutton[str(x)].move(400-int(t),100) pybutton[str(x)].setStyleSheet('QPushButton::menu-indicator { image: none; }') self.statusBar() def status(self): sender = self.sender() print('PyQt5 button click') self.statusBar().showMessage(sender.text() + ' was pressed')

http://stackoverflow.com/q/49955228
accepted answer: http://stackoverflow.com/a/49955266
tagged with: argv
answer count: 1
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/49955266
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Change Python 3 sys.argv when calling a function
tagged with: python
upvote count: 4
tagged with: python-3.x
has body: I have a program main.py which uses sys.argv to run functions from other modules: e.g: python main.py gui should run the main function in gui.py python main.py server start should run the main function in server.py. But if the program simply runs server.main() in this example, sys.argv is ['main.py', 'server', 'start'] when it should be [something, 'start']. Since server.py also relies on the correct argv, I need to make sure that the argv used in server.py is different from the argv recieved by main.py. How can I change these values?
tagged with: sys

http://stackoverflow.com/comment/86876649
score: 0
has text: Similarly, on Linux, the `seccomp` framework can be used to lock down which syscalls a process can make -- so one could disable `unlink()` altogether. Would of course need to prevent equivalents such as `truncate()`, `open()`, etc. as well -- the need to lock down `open()` means starting up the interpreter and loading libraries/etc. you need *before* putting the filter in place for that process.
type: Comment
comment on: http://stackoverflow.com/q/49929927
type: QuestionComment

http://stackoverflow.com/comment/130436985
comment on: http://stackoverflow.com/a/73820299
type: Comment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment
score: 0

http://stackoverflow.com/q/50008277
possible better answer: http://stackoverflow.com/a/50008329
has answer: http://stackoverflow.com/a/50008380
tagged with: function
has answer: http://stackoverflow.com/a/50008329
has comment: http://stackoverflow.com/comment/87033157
has body: I was wondering if there is a more elegant way to write following function without using if statements or less if statements. Depending on the argument I choose I want the function to return different variables. X = np.ones((3,3)) def calculate(X, output2=False, output3=False): y1=X*2 y2=X*3 y3=X*4 if (output2==False and output3==False): return y1 if (output2==True and output3==False): return y1,y2 if (output2==False and output3==True): return y1,y3 if (output2==True and output3==True): return y1,y2,y3 out1, out3=calculate(X, output3=True)
tagged with: python
has comment: http://stackoverflow.com/comment/87033114
accepted answer: http://stackoverflow.com/a/50008343
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87033115
answer count: 3
has answer: http://stackoverflow.com/a/50008343
has title: Elegant coding for optional arguments and outputs in Python
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50041551
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87103785
tagged with: encoder
type: Question
has answer: http://stackoverflow.com/a/50056670
score: 1
has comment: http://stackoverflow.com/comment/87107228
possible better answer: http://stackoverflow.com/a/60160084
tagged with: python
accepted answer: http://stackoverflow.com/a/50056670
has answer: http://stackoverflow.com/a/60160084
has body: I'm working with text data where a lot of user error has to be accounted for, eg. there are a lot of cases where upon predicting new data, new labels will occur that the encoder hasn't seen before due to typos etc. I just want to ignore these (so when I run labelencoder.transform(df_newdata['GL_Description']), I just want it to ignore anything it hasn't seen before). How can I do this? I didn't find a parameter for this in the docs, but is the only way really to check every word one-by-one "by hand" and drop them? Is there a way I can tell the encoder to ignore any new labels that are not in its dictionary?
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87104092
upvote count: 2
has comment: http://stackoverflow.com/comment/87281497
has title: Tell LabelEnocder to ignore new labels?
has comment: http://stackoverflow.com/comment/87102143
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87103602

http://stackoverflow.com/a/49999132
score: 1
type: Answer
has body: Managed to do it with a fresh pair of eyes today: qt = np.linspace(1.0, 100.0, num=100) ic = np.linspace(1.0, 4.0, num=100) qt, ic = np.meshgrid(qt, ic) Z = ((0.3973473*(np.exp(np.log10(qt)))) + 0.6176893) * ic for i in np.arange(len(qt)): for j in np.arange(len(ic)): if Z[j,i] &gt; 8: Z[j,i] = np.nan else: pass fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(qt, ic, Z) plt.show()
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49967149
has comment: http://stackoverflow.com/comment/136841825
accepted answer of: http://stackoverflow.com/q/49967149

http://stackoverflow.com/q/49992410
tagged with: runtime-error
tagged with: postgresql
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87002106
has title: Psycog2 terminating connection due to conflict with recovery DETAIL: User was holding a relation lock for too long
favorite count: 0
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/30097787
type: UnansweredQuestion
tagged with: database
upvote count: 1
tagged with: python
has body: I am using python to query through a really huge PG database. I used the server-side cursor and unfortunately when I run into 170000+ rows, it gives me the error: psycopg2.extensions.TransactionRollbackError: terminating connection due to conflict with recovery DETAIL: User was holding a relation lock for too long. HINT: In a moment you should be able to reconnect to the database and repeat your command. server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Here is a similar issue but it doesn't solve my confusion at all as I am fairly new to coding and psycog2. the sqlalchemy error. Could anyone suggest a solution and code? Many thanks! conn=pg.connect(host="XXX",database="XXX", user="XXX", password="XXX") cur = conn.cursor('my_cursor') cur.execute("select XX,XXX from XXXX") count = 0 data = [] while True: rows = cur.fetchmany(100) if not rows: break for id, xml in rows: count += 1 if count % 5000 == 0: print('processing The %d record' % count) data.append(Extract_info(id, xml, 'progressive', Dict_info)) pass cur.close() enter image description here, besides increasing this 2 parameter, is there a walk-around?
has comment: http://stackoverflow.com/comment/87010819

http://stackoverflow.com/comment/87178900
type: AnswerComment
type: Comment
has text: Sorry i was away for a while. But how can i get these values from DataFrame? I mean let's say i have assigned return array to "arr". How can i get rows equals to this array from DataFrame?
comment on: http://stackoverflow.com/a/50018704
score: 0

http://stackoverflow.com/comment/87157576
comment on: http://stackoverflow.com/a/50070467
type: AnswerComment
score: 1
has text: @What what are those class variables for?
type: Comment

http://stackoverflow.com/q/50040534
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/50040677
has body: I get an empty dataframe when I try to group values using the pivot_table. Let's first create some stupid data: import pandas as pd df = pd.DataFrame({"size":['large','middle','xsmall','large','middle','small'], "color":['blue','blue','red','black','red','red']}) When I use: df1 = df.pivot_table(index='size', aggfunc='count') returns me what I expect. Now I would like to have a complete pivot table with the color as column: df2 = df.pivot_table(index='size', aggfunc='count',columns='color') But this results in an empty dataframe. Why? How can I get a simple pivot table which counts me the number of combinations? Thank you.
upvote count: 3
answer count: 2
downvote count: 0
tagged with: pandas
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/50040854
tagged with: pivot-table
type: UnansweredQuestion
has title: pandas pivot_table returns empty dataframe

http://stackoverflow.com/a/50042327
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50042242
has comment: http://stackoverflow.com/comment/87100668
type: Answer
score: 4
has body: Python cannot unpack lambda parameters automatically. enumerate returns a tuple, so lambda has to take that tuple as sole argument You need: n = map(lambda t: t[1].upper() if t[0] % 2 else t[1], enumerate(alphabet)) Considering now the ugliness of map + lambda + manual unpacking, I'd advise the alternate generator comprehension instead: n = (value.upper() if index % 2 else value for index,value in enumerate(alphabet)) (I removed the lower() call since your input is already lowercase)
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50042242

http://stackoverflow.com/a/50067003
answers question: http://stackoverflow.com/q/50066625
type: Answer
score: 0
has body: Looks like you have a script called selenium.py. Rename that and it should work.

http://stackoverflow.com/comment/86972218
comment on: http://stackoverflow.com/a/49977885
type: Comment
has text: Yes, I'm saying you should've just loaded it with JSON and used the correct JSON formatting `\\\` double slash since python recognizes this only.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50070265
tagged with: python
tagged with: computer-vision
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87157362
has comment: http://stackoverflow.com/comment/87157201
has comment: http://stackoverflow.com/comment/87157262
tagged with: scipy
tagged with: tensorflow
type: Question
has title: Can I use scipy-approx_fprime() for tensorflow operations?
type: UnansweredQuestion
has body: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.approx_fprime.html from scipy import optimize forward_module = tf.load_op_library('./build/libforwardcu.so') f2 = tf.tanh(tf.conv2d(x1, w)+b) f1 = tf.tanh(tf.conv2d(x2, w)+b) def func(x): forward_module.forward(x,f2, disps, 1, 0) return loss optimize.approx_fprime(x, func, 1e-6) Would approx_fprime automatically detect the derivation rules from tensorflow (costs, loss)? I mean that if the function is f(x)=x^2, then the derivation would be detected by scipy f'(x)=2x. Of course by a neural network is a lot more effort and I want to avoid to do that by hand...

http://stackoverflow.com/a/51165784
type: Answer
has body: If removing trailing slashes from the environment variables don't work, please try the following. It works fine for me. I am using window 10 and python3.7.0 Advanced system settings -&gt; Environment Variables -&gt; Path Select Edit Select Move Up button for both python and Scripts directory. Finally your path will be as the following. If you are using other window version(In the case of not having move up button), put your python and Scripts directory at the beginning of the path.
score: 29
upvote count: 29
downvote count: 0
answers question: http://stackoverflow.com/q/49966547
has comment: http://stackoverflow.com/comment/105824257

http://stackoverflow.com/comment/86916105
type: Comment
score: 0
type: QuestionComment
has text: Also, recommend using `pip install -e .`, but I don't think that would change anything in this case
comment on: http://stackoverflow.com/q/49949693

http://stackoverflow.com/q/49936190
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/49936388
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49936388
has title: Adding two dictionaries in a RDD in Pyspark
downvote count: 1
score: -1
favorite count: 0
type: Question
upvote count: 0
tagged with: pyspark
has body: I have created and RDD where every element is a dictionary. (This is a sample. There are 30,000 keys rdd.take(2) [{'actor': 'brad', 'good': 1, 'bad': 0, 'average': 0,} {'actor': 'tom', 'good': 0, 'bad': 1, 'average': 1,}] I am trying to perform arithmetic operations on the data, That is 'actor': 'brad' and 'actor': 'tom', I want to add the other values having the same key I did this: d1=rdd.filter(lambda x: x['actor']=='brad').first() d2=rdd.filter(lambda x: x['actor']=='tom').first() dc={key: d1[key] + d2[key] for key in d1.keys() if key not in {'actor'} } But since there are around 30,000 [keys] this is taking me lot of time. Can I optimize this by performing the addition using Spark's distributed operations. If so how? Expected Output: [{'actor': 'brad', 'good': 1, 'bad': 1, 'average': 1,}]
tagged with: python
tagged with: rdd
answer count: 1
tagged with: optimization

http://stackoverflow.com/q/49941181
has comment: http://stackoverflow.com/comment/86899433
answer count: 0
has comment: http://stackoverflow.com/comment/86898196
type: UnansweredQuestion
tagged with: django
has body: hi I have a view in my Django project which essentially uses a search query to display a paginated list of results. In development mode, this 'querying' functionality works perfectly fine. However when deployed in production, when trying to make a query, the template returns the error Related Field got invalid lookup: name Although there is nowhere in my views.py where I use the word 'name'. The error seems to occur at the start of the pagination function according to the tracebacks interactive view. Traceback: File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/myproject/products/views.py" in results 129. def paginator_loop(arg): File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/query.py" in filter 836. return self._filter_or_exclude(False, *args, **kwargs) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/query.py" in _filter_or_exclude 854. clone.query.add_q(Q(*args, **kwargs)) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in add_q 1253. clause, _ = self._add_q(q_object, self.used_aliases) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in _add_q 1271. current_negated, allow_joins, split_subq) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in _add_q …
has title: Django - Related Field got invalid lookup: name when I have not mentioned name
has comment: http://stackoverflow.com/comment/86898721
score: 0
has comment: http://stackoverflow.com/comment/86901260
has comment: http://stackoverflow.com/comment/86898244
tagged with: python
type: Question

http://stackoverflow.com/comment/86944405
comment on: http://stackoverflow.com/q/49964188
type: QuestionComment
has text: Name all the checkboxes `filetouse`. You will get the list.
type: Comment
score: 2

http://stackoverflow.com/comment/86918782
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49926924
type: Comment
has text: @BramVanroy Yes, that's right (to understand it any deeper, you need to know about the C ["struct hack"](https://stackoverflow.com/questions/16553542)).

http://stackoverflow.com/comment/87072210
has text: forgot to comment a reshape in my code, you are right about how to make my question but unfortunately I can't really show more, it would be too complex and too long ;)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50027838

http://stackoverflow.com/q/50058144
has title: Flask context error when trying to serve a tensorflow model
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50059282
downvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87135399
has comment: http://stackoverflow.com/comment/87134876
answer count: 1
has body: I have a simple flask app to serve a tensorflow model. As far as I am aware, I have ironed out all of the other errors. But when it comes time to run the app I get this error: RuntimeError: Working outside of request context. Traceback (most recent call last): File "app.py", line 61, in &lt;module&gt; if request.args: File "/home/m0oN/.local/lib/python3.5/site-packages/werkzeug/local.py", line 347, in __getattr__ return getattr(self._get_current_object(), name) File "/home/m0oN/.local/lib/python3.5/site-packages/werkzeug/local.py", line 306, in _get_current_object return self.__local() File "/home/m0oN/.local/lib/python3.5/site-packages/flask/globals.py", line 37, in _lookup_req_object raise RuntimeError(_request_ctx_err_msg) RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. I think the main problem lies in here: if __name__ == '__main__': file_name = 'steph.jpg' model_file = 'thotornot_graph.pb' lable_file = 'retrained_labels.txt' input_height = 299 input_width = 299 input_mean = 128 input_std = 128 input_layer = "Mul" output_layer = "final_result" if request.args: file_name = request.args graph = load_graph(model_file) t = read_tensor_from_image_file(file_name, input_height=input_height, input_width=input_width, input_mean=input_mean, input_std=input_std) input_name = 'import/' + input_layer output_name = 'import/' + output_layer input_operation = graph.get_operation_by_name(input_name); output_operation = graph.get_operation_by_name(output_name); with tf.Session(graph=graph) as sess: start = time.time() results = sess.run(output_operation.outputs[0], {input_operation.outputs[0]: t}) end = time.time() results = np.squeeze(results) top_k = results.argsort()[-5:][::-1] lables = load_lables(lable_file) print('\nEvaluation time (1-image): {:.3f}s\n'.format(end-start)) for i in top_k: prin…
tagged with: python
score: -1
tagged with: flask
has comment: http://stackoverflow.com/comment/87134929
upvote count: 1
has comment: http://stackoverflow.com/comment/87134725
has comment: http://stackoverflow.com/comment/87133887

http://stackoverflow.com/a/50038279
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50037992
score: 1
has body: The same isinstance idea can be applied to a filter: f = ['filename1', 1696, 'filename2', 5809] max(filter(lambda i: isinstance(i, int), f)) Also, if you need to include more than one data type in your comparison, e.g.: floats, you can simple use a tuple to validate the the data to be compared: max(filter(lambda i: isinstance(i, (int, float)), f))

http://stackoverflow.com/comment/87090989
type: Comment
type: AnswerComment
has text: @TraceSmith was this what yo intended?
comment on: http://stackoverflow.com/a/49968908
score: 0

http://stackoverflow.com/comment/87080738
type: AnswerComment
has text: Got a list, appended it. now stuck on how to move the list of files. any suggestions.would be appreciated. still learning here. I want to delete the files in the source at the same time.
comment on: http://stackoverflow.com/a/50032090
type: Comment
score: 0

http://stackoverflow.com/comment/86969812
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49940550
has text: I want to move child widgets along a path. So the Layout needs to change the child wigdets’ positions over time.
score: 0

bayesian-networks
tag name: bayesian-networks
type: Tag
tags question: http://stackoverflow.com/q/50035005

http://stackoverflow.com/q/50000574
has comment: http://stackoverflow.com/comment/87022900
has comment: http://stackoverflow.com/comment/87017663
tagged with: matrix
has comment: http://stackoverflow.com/comment/87018423
tagged with: python
has body: I've a task to make fuction that generates matrix from non negative integers in range (0-8) Input of the function are 2 lists : sumForEveryCol sumForEveryRow Each list contains sum of the values for every rows/columns Example: sumForEveryRow should contain sums for every row by it's index ( sumForEveryRow[0] = sum of the first row ... etc.) sumForEveryColumn[0] = sum of the first column .. sumForEveryColumn[1] - second column .. etc.) Sum of every row or column is constant value of 40 Value of any cell should be in range 0, 8 I've strange ideas (code below) but there is no chance to work at all.. because of the algorithm... What is the algorithm in general to generate such matrix and what is the best way to implement it in python Example: sumsForEveryRow = [4,20,8,8] = constant 40 sumsForEveryCol = [8,8,8,8,8] = constant 40 gen_matrix(sumForEveryRow, sumForEveryCol) should produce random matrix like: [ 0 , 2 , 0 , 0 , 2 ], - sum of row 1 should be 4 [ 1 , 2 , 8 , 5 , 4 ], - sum of row 2 should be 20 [ 3 , 2 , 0 , 3 , 0 ], - sum of row 3 should be 8 [ 4 , 2 , 0 , 0 , 2 ], - sum of row 4 should be 8 sum for every column should be 8 8 8 8 8 import random import numpy sumsForEveryCol = [8,8,8,8,8] sumsForEveryRow = [4,20,8,8] def gen_matrix(sumForEveryCol, sumForEveryRow): sum = 40 max_value_cell = 8 num_of_rows = len(sumsForEveryRow) num_of_cols = len(sumsForEveryCol) matrix = numpy.zeros((num_of_rows, num_of_cols), dtype=numpy.int) for i in range(0, num_of_rows - 1): cur_row_sum = sumsForEveryRow[i] for j in range(0, num_of_cols - 1): if max_value_cell &gt;= cur_row_sum: if cur_row_sum == 0: matrix[i][j] = 0 else: # Dont generate 0 values ???? rand_digit = random.randint(1, cur_row_sum) cur_row_sum = cur_row_sum - rand_digit matrix[i][j] = rand_digit else: rand_digit = random.randint(0, max_value_cell) matrix[i][j] = rand_digit cur_row_sum = cur_row_sum - rand_digit return matrix
has title: function that should Generate matrix with sums of rows/columns defined as input lists
tagged with: random
has comment: http://stackoverflow.com/comment/87018891
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/87021853
score: 0

http://stackoverflow.com/a/49964044
has comment: http://stackoverflow.com/comment/86944318
answers question: http://stackoverflow.com/q/49963984
has comment: http://stackoverflow.com/comment/86944251
has comment: http://stackoverflow.com/comment/86947741
accepted answer of: http://stackoverflow.com/q/49963984
has comment: http://stackoverflow.com/comment/86944226
has comment: http://stackoverflow.com/comment/86944247
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86944630
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/86945013
has comment: http://stackoverflow.com/comment/86947502
has body: the format is also formatted differently, ie [1] [2] [3] instead of [1, 2, 3] that is because your loop creates a list of one variable each time: for x in range(0, l): # the '0' is redundant. You can write just "for x in range(l):" c = x * n # c is calculated mylist = [c] # mylist is now [c] print(mylist, end=' ') # print mylist Instead, declare the list before the loop, and add elements to it inside the loop: mylist = [] for x in range(l): c = x * n # c is calculated mylist.append(c) # mylist is now mylist + [c] print(mylist, end=' ') # print mylist The second part I don't really have an idea on how to do it. I thought it would be similar to what I have like above, but it returns nothing. It is kind of the same... You should initialize a number product = 1 and multiply it by every number in the list: product = 1 # no need for list, just a number for r in productlist: product = product * r # or product *= r print(product ) BTW, no need to reinvent the wheel... you can get the product of a list with: from functools import reduce # needed on Python3 from operator import mul list = [2, 4, 6, 8, 10] print(reduce(mul, list, 1))
type: Answer

http://stackoverflow.com/comment/86880420
comment on: http://stackoverflow.com/q/49932308
has text: Well I would expect the biased Variance be worse then the unbiased Variance, that is calculated using (n-1). Therefore it should be more often closer to the true population Variance (realvariance).
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/51775406
has comment: http://stackoverflow.com/comment/113863184
type: Answer
accepted answer of: http://stackoverflow.com/q/50004797
has body: Here is one possible solution that uses the data structure output by CoreNLP. All the information is provided. This is not intended as a full solution and extensions are probably required to deal with all situations, but this is a good starting point. from pycorenlp import StanfordCoreNLP nlp = StanfordCoreNLP('http://localhost:9000') def resolve(corenlp_output): """ Transfer the word form of the antecedent to its associated pronominal anaphor(s) """ for coref in corenlp_output['corefs']: mentions = corenlp_output['corefs'][coref] antecedent = mentions[0] # the antecedent is the first mention in the coreference chain for j in range(1, len(mentions)): mention = mentions[j] if mention['type'] == 'PRONOMINAL': # get the attributes of the target mention in the corresponding sentence target_sentence = mention['sentNum'] target_token = mention['startIndex'] - 1 # transfer the antecedent's word form to the appropriate token in the sentence corenlp_output['sentences'][target_sentence - 1]['tokens'][target_token]['word'] = antecedent['text'] def print_resolved(corenlp_output): """ Print the "resolved" output """ possessives = ['hers', 'his', 'their', 'theirs'] for sentence in corenlp_output['sentences']: for token in sentence['tokens']: output_word = token['word'] # check lemmas as well as tags for possessive pronouns in case of tagging errors if token['lemma'] in possessives or token['pos'] == 'PRP$': output_word += "'s" # add the possessive morpheme output_word += token['after'] print(output_word, end='') text = "Tom and Jane are good friends. They are cool. He knows a lot of things and so does she. His car is red, but " \ "hers is blue. It is older than hers. The big cat ate its dinner." output = nlp.annotate(text, properties= {'annotators':'dcoref','outputFormat':'json','ner.useSUTime':'false'}) resolve(output) print('Original:', text) print('Resolved: ', end='') print_resolved(output) This gives the following output: Original: Tom and Jane are good friends. They are coo…
upvote count: 6
answers question: http://stackoverflow.com/q/50004797
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/comment/86984798
has text: Will let you know tomorrow. Thanks
comment on: http://stackoverflow.com/a/49980664
type: Comment
score: 0
type: AnswerComment

python-2.6
type: Tag
tags question: http://stackoverflow.com/q/50028427
tag name: python-2.6
tags question: http://stackoverflow.com/q/50070256
tags question: http://stackoverflow.com/q/50007028

http://stackoverflow.com/q/50030731
favorite count: 0
has title: use one backslash and quotation marks together in string
type: Question
tagged with: replace
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/24085680
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50030767
has comment: http://stackoverflow.com/comment/87078078
has comment: http://stackoverflow.com/comment/87078524
has comment: http://stackoverflow.com/comment/87078239
has body: How can i do to represent a string with (\") inside string I tried several ways: date = 'xpto\"xpto' 'xpto"xpto' date = 'xpto\\"xpto' 'xpto\\"xpto' data='xpto\\' + '"xpto' 'xpto\\"xpto' data= r'xpto\"xpto' 'xpto\\"xpto' i need the string exactly like this 'xpto\"xpto' if someone knows how, I really appreciate the help
tagged with: string
has comment: http://stackoverflow.com/comment/87077564
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50030771
has answer: http://stackoverflow.com/a/50030767
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/50030771
linked to: http://stackoverflow.com/q/24085680
has comment: http://stackoverflow.com/comment/87078865
tagged with: python
has comment: http://stackoverflow.com/comment/87077868

http://stackoverflow.com/comment/119576205
comment on: http://stackoverflow.com/a/62343176
has text: worked on MacOS, thanks! (don't reinstall, turns out it was a conflicting installation)
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49946995
has comment: http://stackoverflow.com/comment/86910771
has body: You need to call .save() method after adding the object to ManyToManyField. Also, you should filter the stocks in one query instead of getting them one by one. def follow_stocks_post_registration(request): all_stocks = Stock.objects.all() if request.method == 'POST': stocks_user_selected = request.POST.getlist('stocks_selected') user_profile = Profile.objects.get(user=request.user) for stock in Stock.objects.filter(name__in=stocks_user_selected): user_profile.followed_stocks.add(stock) user_profile.save()
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49946980
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49946980

http://stackoverflow.com/q/49998613
has answer: http://stackoverflow.com/a/49999229
possible better answer: http://stackoverflow.com/a/49999926
answer count: 2
has answer: http://stackoverflow.com/a/49999926
has body: How to remove unused part of string used value in another Pandas column? I have: Col1 Col2 bbbb2 Hello I want to removebbbb2 Output: Hello I want to bbbb2 I want to use str.extract or any other pandas solution? EDIT: @erocoar But i want to remove in all rows, For example Col1 Col2 output bbbb2 Hello I want to removebbbb2 Hello I want to bbbb2 aaaa1 Hello I want to remaaaa1 Hello I want to aaaa1 Your solution is only for one example
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49999229
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/87013849
has comment: http://stackoverflow.com/comment/87015155
has title: How to remove unused part of string using another column
linked to: http://stackoverflow.com/q/50067780

http://stackoverflow.com/a/49948395
answers question: http://stackoverflow.com/q/49948256
has body: This can be solved with a counting approach. There are two types of boxes: small (S) and large (L). There are N different permutations of boxes, and each of them correlates with a bit string (ex: ABCDEFG is SSSSLLL or 0000111). You can find the number of permutations where the number of smalls up to and including some L letter is strictly greater than the number of larges. For example, in SSLSSLL, when you reach the first L, there are two S's and one L up to that point (so S > L), and for the last two, the number of S's is greater than the number of L's.
type: Answer
score: 0

http://stackoverflow.com/q/50049948
tagged with: taylor-series
answer count: 1
has title: Hide order of magnitude in Taylor series
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50050554
has body: I've been trying to familiarise myself with sympy and stumbled upon the series expansion. For example: series(cos(x),x, n=5) prints: 1 - x**2/2 + x**4/24 + O(x**6) I was wondering if there was a way of hiding the last part (O(x**6)) in the output, as in, it would print: 1 - x**2/2 + x**4/24
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/50050554
score: 0
tagged with: sympy

http://stackoverflow.com/comment/86912491
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49946881
type: QuestionComment
has text: Possible duplicate of [Fast outer tensor product in numpy](https://stackoverflow.com/questions/37464737/fast-outer-tensor-product-in-numpy)

http://stackoverflow.com/q/49984323
has comment: http://stackoverflow.com/comment/86985747
has title: Minimizing function with 2 arguments
has body: I'm trying to minimize a function with 2 arguments: def c_Gamma_gamma_fv(cf, cv): return np.abs((4 * eta_gamma * charges**2 * a_q * cf).sum() + 4.* cf *a_tau/3. + a_w * cv)**2/Gamma_gamma def mu_fv(cf, cv): return np.array([cf**4, cf**2 * cv**2, cf**2 * c_Gamma_gamma_fv(cf, cv), cv**2 * c_Gamma_gamma_fv(cf, cv), cf**4, cv**2 * cf**2, cf**2 * cv**2, cv**4, cv**2 * cf**2, cv**4]) def chi_square_fv(cf, cv): return ((mu_fv(cf, cv) - mu_data) @ inv_cov @ (mu_fv(cf, cv) - mu_data)) x0 = [1., 1.] res_fv = minimize(chi_square_fv, x0) but, I'm getting the error "TypeError: chi_square_fv() missing 1 required positional argument: 'cv'". But, when I do the following: print(chi_square_fv(1.,1.)) I get the output 38.8312698786 I'm not understanding this and I'm new to this type of procedure. How do I proceed? OBS: Gamma_gamma is just a constant of the code.
has answer: http://stackoverflow.com/a/49984487
tagged with: python
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
upvote count: 1
tagged with: minimize
tagged with: scipy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49984441
has comment: http://stackoverflow.com/comment/86985232
has answer: http://stackoverflow.com/a/49984441
possible better answer: http://stackoverflow.com/a/49984487

http://stackoverflow.com/comment/86859574
has text: Id is Column not index
comment on: http://stackoverflow.com/q/49921857
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49939169
has comment: http://stackoverflow.com/comment/86894311
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86894332
has body: I think best here is use map by dictionary for define catagories: df['Category'] = df['Category'].map({'Car':'C','Bike':'B'}).fillna('No match') print (df) ID Hourly Rate Category 0 0 8900 2.99 C 1 1 9904 9.99 C 2 2 6381 19.99 B 3 3 5862 2.99 B 4 4 2270 2.99 C Also for improve memory usage is possible use: df['Category'] = pd.Categorical(df['Category'].map({'Car':'C','Bike':'B'}).fillna('No match')) print (df) ID Hourly Rate Category 0 0 8900 2.99 C 1 1 9904 9.99 C 2 2 6381 19.99 B 3 3 5862 2.99 B 4 4 2270 2.99 C If categories have multiple values is possible define them in list of dict: print (df) ID Hourly Rate Category 0 0 8900 2.99 Car1 1 1 9904 9.99 Car2 2 2 6381 19.99 Bike1 3 3 5862 2.99 Bike 4 4 2270 2.99 Car d = {'C':['Car','Car1','Car2'], 'B':['Bike','Bike1','Bike2']} d1 = {k: oldk for oldk, oldv in d.items() for k in oldv} print (d1) {'Car1': 'C', 'Bike': 'B', 'Bike2': 'B', 'Car2': 'C', 'Car': 'C', 'Bike1': 'B'} df['Category'] = pd.Categorical(df['Category'].map(d1).fillna('No match')) print (df) ID Hourly Rate Category 0 0 8900 2.99 C 1 1 9904 9.99 C 2 2 6381 19.99 B 3 3 5862 2.99 B 4 4 2270 2.99 C EDIT: If need define values in loop, one possible solution is custom function: def f(x): if x == 'Car': return 'C' elif x == 'Bike': return 'B' else: return 'No match' df['Category'] = df['Category'].apply(f) print (df) ID Hourly Rate Category 0 0 8900 2.99 C 1 1 9904 9.99 C 2 2 6381 19.99 B 3 3 5862 2.99 B 4 4 2270 2.99 C
has comment: http://stackoverflow.com/comment/86894256
answers question: http://stackoverflow.com/q/49938884
has comment: http://stackoverflow.com/comment/86894622
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86894855
has comment: http://stackoverflow.com/comment/86894087
has comment: http://stackoverflow.com/comment/86894108

http://stackoverflow.com/q/49990066
has comment: http://stackoverflow.com/comment/86999324
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86997278
has comment: http://stackoverflow.com/comment/86996837
has comment: http://stackoverflow.com/comment/86996785
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86996680
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Pandas Standard Deviation Expected to be Zero
has comment: http://stackoverflow.com/comment/86997667
tagged with: excel
tagged with: statistics
has body: Generally, one would expect the standard deviation of n samples of the exact same number to be 0. However, using pandas' standard deviation tool I'm finding that there is a small (E-16) standard deviation for certain repeated values and I'm not sure what could be causing this. Interestingly enough, I notice the same error in Excel although not always for the same number of samples. hereimport pandas as pd pd.DataFrame(data=[5.1]*6).std() # 9.729507e-16 pd.DataFrame(data=[5.2]*6).std() # 0 pd.DataFrame(data=[5.3]*6).std() # 0 pd.DataFrame(data=[5.4]*6).std() # 9.729507e-16 pd.DataFrame(data=[5.1]*5).std() # 0 pd.DataFrame(data=[5.1]*6).std() # 9.729507e-16 pd.DataFrame(data=[5.1]*7).std() # 9.593423e-16 pd.DataFrame(data=[5.1]*8).std() # 0

http://stackoverflow.com/comment/87416506
comment on: http://stackoverflow.com/a/50198137
type: AnswerComment
has text: First question: Yes, if you want to use the tensorflow graph operations add them in the estimator model/graph definiton. I did this during training once. However when you recieve the dictionary you should be able to reduce it to single arrays and then save it as image e.g. with PyPNG
score: 1
type: Comment

http://stackoverflow.com/comment/126354379
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50024672
type: AnswerComment
has text: If you have arrays with more than 1 value you can convert them to tuples, which are hashable: `applymap(lambda x: tuple(x) if isinstance(x, list) else x)`

http://stackoverflow.com/comment/87002657
type: QuestionComment
has text: Are you searching for something like that? https://stackoverflow.com/a/49821744/2504700 It is not exectly the same, but getting combinations of 3 instead of 2 will probably do the trick
score: 0
comment on: http://stackoverflow.com/q/49993101
type: Comment

http://stackoverflow.com/comment/87179280
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50075917
has text: I see. So I would have to modify this code right here because dict items are not callable?

http://stackoverflow.com/q/49971911
score: 1
tagged with: matplotlib
answer count: 1
has body: I have a list of candlestick objects, each one has 6 values (open, high, low, close, volume, timestamp). I want to use matplotlib.finance.candlestick2_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75) function to plot this data. The thing is, how can i subdivide my list into opens, highs, lows and closes in order to load it to this function? Here's my candlestick class: class Candle: #Candlestick chart object def __init__(self, open, high, low, close, volume, timeStamp): self.open = open self.high = high self.low = low self.close = close self.volume = volume self.timestamp = timeStamp def __str__(self): return """ Open: %s High: %s Low: %s Close: %s Volume : %s Timestamp: %s""" %(self.open, self.high, self.low, self.close, self.volume, self.timestamp) And this is my list construction methods: def getTradeHistory(self, timeFrame, symbol, count): #Get the trade history from the API return self.client.Trade.Trade_getBucketed(binSize=timeFrame, partial=True, symbol=symbol, reverse=False, count=count).result() def constructCandles(self, th): #Iterate through list of trade history items and store them as candles in a list for candle in th : self.candles.append(Candle(candle['open'], candle['high'], candle['low'], candle['close'], candle['volume'], candle['timestamp']))
has title: Plotting OHLC charts in python with matplotlib
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49972197
has answer: http://stackoverflow.com/a/49972197
type: AnsweredQuestion

http://stackoverflow.com/q/50065474
has answer: http://stackoverflow.com/a/50066263
favorite count: 0
has title: Write a dictionary with multiple values to store data in columns in the CSV file
type: Question
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/50065689
possible better answer: http://stackoverflow.com/a/50065513
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50065689
has answer: http://stackoverflow.com/a/50065513
has body: I am trying to write following dictionary into csv file: mydict = {'k1':[1,2,3], 'k2':[4,5,6], 'k3':[6,7,8]} The result I want to achieve is to have dictionary keys as column headers is csv file and map corresponding key values to those columns: k1 k2 k3 1 4 6 2 5 7 3 6 8 I have tried following code but it's not working for me: import csv def save_output(output_file_name): global output fields = list(mydict.keys()) with open(output_file_name, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(mydict.items()) for key,items in mydict.items(): for item in items: writer.writerow(key,item) save_output('test_output.csv')
has comment: http://stackoverflow.com/comment/87147620
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 3

http://stackoverflow.com/comment/87081195
comment on: http://stackoverflow.com/q/50032481
score: 0
type: Comment
type: QuestionComment
has text: You're only calling `print` once, why would you expect it to print multiple times? You're still going to need a loop. If you can't use a `for` loop, (a silly restriction, but whatever) that only leaves `while` loops

http://stackoverflow.com/a/63065070
has body: You can do it with one compile using an optional variable. No raw statement needed since there are no escape characters. import re def regexStrip(theString, stripChar='\s'): theRegex = re.compile(f'^({stripChar})*|({stripChar})*$') stripContext = theRegex.sub('', theString) return stripContext print(regexStrip('SpamEggsSpam','Spam')) print(regexStrip('SpamSpamSpam$Eggs$SpamSpamSpam','Spam')) print(regexStrip(' Eggs ')) print(regexStrip(' $ Eggs $ '))
type: Answer
answers question: http://stackoverflow.com/q/50055600
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49989937
has body: The script references needed to be placed in front of the chartit load variable (not the highcharts script reference as previously answered in other questions). Here is the working arrangement: {% load static %} {% load chartit %} This cleared the error for chartloader/jquery error where jquery was loading after chartit. IMO this isn't clearly stated and/or stated at all in the documentation. I was still receiving an error for highcharts though until I noticed that: should instead be:
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49989280
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49989280
downvote count: 0

http://stackoverflow.com/a/49979790
has comment: http://stackoverflow.com/comment/86975592
accepted answer of: http://stackoverflow.com/q/49979605
has body: I think you can call it by : currency = collection.find_one({"NOK"}) print(currency['rates']['NOK'])
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49979605

http://stackoverflow.com/comment/87633018
comment on: http://stackoverflow.com/a/49932011
has text: @JayFresco, right, I am a total noob and this was actually my first real Python exercise at all, and I didnt think about turning count to one. This led me to thinking this one just didn't work the way I needed it too, when It only needed a super small modification. I see now that the way I handled adding counters just did the same thing as changing the initial variable to one in the first place. This solution is essentially the one I went with.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87157268
type: Comment
has text: Create a class, make these member values, and then provide a `new_game()` method that sets all of the values to their initial states.
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50070360

http://stackoverflow.com/a/49931396
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49929070
accepted answer of: http://stackoverflow.com/q/49929070
has body: The problem here is that you leave triplet_model.compile(loss=None), but keras does not know how to deal with it properly in load_model(). I understand that you have to do so, but you can load the model in a different way to solve your current issue. In short, don't load the entire model through load_model(), but just the weights through load_weights(). For example, you can do # save only weights triplet_model.save_weights('tmp.h5') # load saved weights new_embedding_model, new_triplet_model = build_model(input_shape) new_triplet_model.load_weights('tmp.h5') # load only weights
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/86897702
upvote count: 2

http://stackoverflow.com/a/50035916
score: 0
has body: When you are dealing with arrays or lists, (any mutable data structure in this regard), you are actually storing the reference to that variable. If you want your basis unchanged, you need to create a copy of basis and store it in basis_mod. &gt;&gt;&gt; import numpy &gt;&gt;&gt; basis = numpy.matrix([1, 2]) &gt;&gt;&gt; basis_mod = basis &gt;&gt;&gt; basis_mod[0] = [3, 4] &gt;&gt;&gt; basis matrix([[3, 4]]) &gt;&gt;&gt; basis_mod matrix([[3, 4]]) &gt;&gt;&gt; basis_mod = basis.copy() &gt;&gt;&gt; basis_mod[0] = [5, 6] &gt;&gt;&gt; basis matrix([[3, 4]]) &gt;&gt;&gt; basis_mod matrix([[5, 6]])
type: Answer
has comment: http://stackoverflow.com/comment/87129675
has comment: http://stackoverflow.com/comment/87129465
answers question: http://stackoverflow.com/q/50035874

http://stackoverflow.com/comment/86906128
has text: That's a good point that it can't detect BeautifulSoup, it just seems like that's what's setting it off – I'm fairly sure that requests works fine until I introduce BS4. Even though that doesn't really make sense. Also, I'm not accessing the site very often. Maybe, I dunno, 10x per minute max; just when I make a change and need to test my program (or maybe slightly more than that, since I think the program accesses the site 3 times).
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49943744

http://stackoverflow.com/comment/86884008
has text: Yes it is possible. You can use string-interpolation with dynamic code execution, e.g. the `exec` statement (or `exec` function in Python 3). But that is **not** the way one should usually approach this. You likely just want to use `getattr`, which dynamically accesses an attribute using a string.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49934205
score: 2

http://stackoverflow.com/comment/87070987
has text: This probably isn’t the best answer to your question, but it is worth knowing about: In Python, the vast majority of functions that want files will actually take any “file-like object” with the right methods (in 3.x, that means the appropriate ABC from the `io` module, although you can usually get away with less than that). You can use `io.BytesIO` to make a file-like object out of a bytes-like object, or you can build your own class if you need to generate bytes on the fly.
type: Comment
comment on: http://stackoverflow.com/q/50027327
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86893666
has text: You have uneven parentheses on line with `final =`... anyway you want `max(dictionary.items(), key = lambda x: sum(x[1]))`
type: QuestionComment
comment on: http://stackoverflow.com/q/49938985
type: Comment
score: 0

http://stackoverflow.com/q/50022282
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/87060685
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50022370
linked to: http://stackoverflow.com/q/25345770
linked to: http://stackoverflow.com/q/1982134
favorite count: 0
has title: Using list comprehension in data cubes
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50022370
accepted answer: http://stackoverflow.com/a/50022376
has body: I am currently trying to use list comprehensions to filter some values on a data cube with some images, however I got lost to make the jump from 2 (as we can see in here or here) to 3 dimensions. For a single image, the line of code that accomplishes what I want is: AM2 = [[x if x &gt; 1e-5 else 0 for x in line] for line in AM[0]] How do I take this to also consider the different images that are stacked on the top of each other? I assume I would need to add a third nested loop but so far all my attempts to do so failed. In my particular case the datacube is composed of numpy arrays having the dimensions of (100x400x900). Are lists comprehensions still advised to be used for filtering values over that volume of data? Thanks for your time.
tagged with: python
has answer: http://stackoverflow.com/a/50022376

http://stackoverflow.com/comment/87152403
type: QuestionComment
score: 0
has text: Your for loop is not indented
comment on: http://stackoverflow.com/q/50067977
type: Comment

http://stackoverflow.com/comment/87191734
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50072678
has text: Thank you very much that solved the black screen, I changed the kv file to lowercase and it worked, I never thought of that.

http://stackoverflow.com/comment/87143698
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50060424
type: QuestionComment
has text: Please tag with the programming language you're using.

http://stackoverflow.com/a/49964554
score: 0
has body: QStackedWidget.setCurrentIndex(index) This property holds the index position of the widget that is visible. Try it: from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Widget(QWidget): def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) self.currentWidgetRightFrame = 0 self.draw_layout() def draw_layout(self): main_layout = QVBoxLayout(self) #create frame of main tab tab_layout = QHBoxLayout() left_frame = QFrame(self) lbLeft = QLabel(" left_frame ", left_frame) right_frame = QFrame(self) lbRight1 = QLabel(" 1 right_frame", right_frame) right_frame2 = QFrame(self) lbRight2 = QLabel(" 2 right_frame", right_frame2) self.Stack = QStackedWidget(self) self.Stack.addWidget(right_frame) self.Stack.addWidget(right_frame2) left_frame.setFrameShape(QFrame.StyledPanel) right_frame.setFrameShape(QFrame.StyledPanel) right_frame2.setFrameShape(QFrame.StyledPanel) self.right_frame = right_frame2 # split left and right #splitter = QSplitter(SPLIT_H) splitter = QSplitter(self) splitter.addWidget(left_frame) splitter.addWidget(self.Stack) splitter.setStretchFactor(1, 10) # add to widget tab_layout.addWidget(splitter) main_layout.addLayout(tab_layout, 1) #draw left frame self.draw_left_frame(left_frame) self.setLayout(main_layout) def draw_left_frame(self, frame): main_layout = QVBoxLayout(frame) confirm_btn = QPushButton("switch right_frame", self) confirm_btn.setFixedWidth(100) main_layout.addWidget(confirm_btn, 0) #confirm_btn.clicked.connect(lambda:self.confirm(frame)) confirm_btn.clicked.connect(self.confirm) #main_layout.setAlignment(ALIGN_TOP) @pyqtSlot() #def TAB_VIEW_quote_search_code(self, req_quote): def confirm(self): #, req_quote): if self.currentWidgetRightFrame == 0: self.Stack.setCurrentIndex(1) self.currentWidgetRightFrame = 1 else: self.Stack.setCurrentIndex(0) self.currentWidgetRightFrame = 0 if __name__ == "__main__": import sys app = QApplication(sys.argv) app.setStyle("fusion") w = Widget() w.show() sys.exit(app.exec_())
answers question: http://stackoverflow.com/q/49963546
has comment: http://stackoverflow.com/comment/86952062
has comment: http://stackoverflow.com/comment/86948603
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49963546

http://stackoverflow.com/a/49994010
type: Answer
answers question: http://stackoverflow.com/q/49993743
score: 0
has body: Hexadecimal, octal and binary values can be converted from decimal using the python functions hex(), oct() and bin() respectively. The format function can output the numbers hex, oct and bin depending on the arguments you pass to it. So you could do something like def print_formatted(number): # "": decimal # x: hexadecimal # o: octal # b: binary bases = ["", "x", "o", "b"] numbers_formatted = [format(number, x).upper() for x in bases] return " ".join(numbers_formatted) when used as print(print_formatted(11)) outputs # 11 B 13 1011 You can checkout https://docs.python.org/3.5/library/string.html#formatspec for more details.

matplotlib
tags question: http://stackoverflow.com/q/50006318
tags question: http://stackoverflow.com/q/49921014
tags question: http://stackoverflow.com/q/50003629
tags question: http://stackoverflow.com/q/50038678
tags question: http://stackoverflow.com/q/49957730
tags question: http://stackoverflow.com/q/50004980
tags question: http://stackoverflow.com/q/50010957
tags question: http://stackoverflow.com/q/49977636
tags question: http://stackoverflow.com/q/49944018
tags question: http://stackoverflow.com/q/49975878
tags question: http://stackoverflow.com/q/49984445
tags question: http://stackoverflow.com/q/50040310
tags question: http://stackoverflow.com/q/49963666
tags question: http://stackoverflow.com/q/49917018
tags question: http://stackoverflow.com/q/50039928
tags question: http://stackoverflow.com/q/49944878
tags question: http://stackoverflow.com/q/49932569
tags question: http://stackoverflow.com/q/50023813
tags question: http://stackoverflow.com/q/50006186
tags question: http://stackoverflow.com/q/50011584
tags question: http://stackoverflow.com/q/50004228
tags question: http://stackoverflow.com/q/49948821
tags question: http://stackoverflow.com/q/50052336
tags question: http://stackoverflow.com/q/49957526
tags question: http://stackoverflow.com/q/50062201
tags question: http://stackoverflow.com/q/50018194
tags question: http://stackoverflow.com/q/50045809
tags question: http://stackoverflow.com/q/49945955
tags question: http://stackoverflow.com/q/49948000
tags question: http://stackoverflow.com/q/49961598
tags question: http://stackoverflow.com/q/50003272
tags question: http://stackoverflow.com/q/50025038
tags question: http://stackoverflow.com/q/49990493
tags question: http://stackoverflow.com/q/49923473
tags question: http://stackoverflow.com/q/50044378
tags question: http://stackoverflow.com/q/49981313
tags question: http://stackoverflow.com/q/49951039
tags question: http://stackoverflow.com/q/49926269
tags question: http://stackoverflow.com/q/50016961
tags question: http://stackoverflow.com/q/50024376
tags question: http://stackoverflow.com/q/49971911
tags question: http://stackoverflow.com/q/50015521
tags question: http://stackoverflow.com/q/49942180
tags question: http://stackoverflow.com/q/49942884
tags question: http://stackoverflow.com/q/50038729
tags question: http://stackoverflow.com/q/49983806
tags question: http://stackoverflow.com/q/49952574
tags question: http://stackoverflow.com/q/49992507
tags question: http://stackoverflow.com/q/50046947
tags question: http://stackoverflow.com/q/49919843
tags question: http://stackoverflow.com/q/50029418
tags question: http://stackoverflow.com/q/49988848
tags question: http://stackoverflow.com/q/49924104
tags question: http://stackoverflow.com/q/49925005
tags question: http://stackoverflow.com/q/49933626
tags question: http://stackoverflow.com/q/49971723
tags question: http://stackoverflow.com/q/50059295
tag name: matplotlib
tags question: http://stackoverflow.com/q/49917968
tags question: http://stackoverflow.com/q/50013162
tags question: http://stackoverflow.com/q/50042661
tags question: http://stackoverflow.com/q/49959546
tags question: http://stackoverflow.com/q/49957874
tags question: http://stackoverflow.com/q/49922991
tags question: http://stackoverflow.com/q/49988766
tags question: http://stackoverflow.com/q/50056073
tags question: http://stackoverflow.com/q/50011376
tags question: http://stackoverflow.com/q/50067977
tags question: http://stackoverflow.com/q/50066272
tags question: http://stackoverflow.com/q/49923960
tags question: http://stackoverflow.com/q/49947615
tags question: http://stackoverflow.com/q/49971915
tags question: http://stackoverflow.com/q/50019758
tags question: http://stackoverflow.com/q/50016979
tags question: http://stackoverflow.com/q/50012754
tags question: http://stackoverflow.com/q/49947770
tags question: http://stackoverflow.com/q/50034201
tags question: http://stackoverflow.com/q/50050810
tags question: http://stackoverflow.com/q/49985965
tags question: http://stackoverflow.com/q/49939738

http://stackoverflow.com/q/50054796
answer count: 2
possible better answer: http://stackoverflow.com/a/50055002
accepted answer: http://stackoverflow.com/a/50054826
upvote count: 1
score: 1
tagged with: output
has answer: http://stackoverflow.com/a/50054826
favorite count: 0
type: Question
has title: Python - Dictionaries displaying values through keys
has body: For the following program: spanishdays = { 'Sunday':'Domingo', 'Monday':'Lunes', \ 'Tuesday':'Martes', 'Wednesday':'Miercoles', \ 'Thursday':'Jueves', 'Friday':'Viernes', \ 'Saturday':'Sabado' } ui = input("Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday'," \ "'Thursday', 'Friday', 'Saturday': ") for ui in spanishdays: print('The word for ' + ui + ' in Spanish is ' + spanishdays[ui]) I thought the output would be: If the user entered Monday, then "The word for Monday in Spanish is Lunes" However, when I run the program I am getting the following output: Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday': Monday The word for Sunday in Spanish is Domingo The word for Monday in Spanish is Lunes The word for Tuesday in Spanish is Martes The word for Wednesday in Spanish is Miercoles The word for Thursday in Spanish is Jueves The word for Friday in Spanish is Viernes The word for Saturday in Spanish is Sabado How do I get just: The word for Monday in Spanish is Lunes
has comment: http://stackoverflow.com/comment/87126093
downvote count: 0
has answer: http://stackoverflow.com/a/50055002
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87126088
tagged with: display

http://stackoverflow.com/comment/87152681
type: Comment
has text: Thank you for looking at this - when I run the code I get the following. print link.get('href') ^ SyntaxError: invalid syntax
type: AnswerComment
comment on: http://stackoverflow.com/a/50068069
score: 0

http://stackoverflow.com/q/49939027
type: UnansweredQuestion
tagged with: django
tagged with: django-rest-framework
has title: Using perform_create to create an object that has ForeignKey in Django + django rest framework
has comment: http://stackoverflow.com/comment/86893849
has body: I have The following code snippet in models.py : class Supervisor(models.Model): emp_id = models.ForeignKey(Employee, null=True, blank=True) def __str__(self): return '%s' % (self.supervisor) In my views I have done : class SupervisorAPIView(mixins.CreateModelMixin, generics.ListAPIView): """ Add Supervisor """ # permission_classes = (permissions.DjangoObjectPermissions,) lookup_field = 'pk' # permission_classes = (permissions.DjangoObjectPermissions,) serializer_class = SupervisorSerializer def get_queryset(self): return Supervisor.objects.all() def perform_create(self, serializer): serializer.save( emp_id=self.kwargs['pk']) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) How do I use perform_create() to create the supervisor object ?
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86895877
type: Question
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/comment/86934096
comment on: http://stackoverflow.com/q/49958179
type: Comment
has text: The t values are obtained from a range of phi values which goes from 0 to 2pi. So the case is typically of a circle. In certain situations there could be two minima while in other situations there could be just one.
score: 0
type: QuestionComment

http://stackoverflow.com/a/50028155
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50027959
upvote count: 28
score: 28
has comment: http://stackoverflow.com/comment/87072624
has comment: http://stackoverflow.com/comment/87072661
answers question: http://stackoverflow.com/q/50027959
type: Answer
has body: Option 1 sklearn You see this problem time and time again, the error really should be indicative of what you need to do. You're basically missing a superfluous dimension on the input. Change df["TOTAL"] to df"TOTAL". df['SIZE'] = scaler.fit_transform(df"TOTAL") df TOTAL Name SIZE 0 3232 Jane 24.413959 1 382 Jack 10.000000 2 8291 Jones 50.000000 Option 2 pandas Preferably, I would bypass sklearn and just do the min-max scaling myself. a, b = 10, 50 x, y = df.TOTAL.min(), df.TOTAL.max() df['SIZE'] = (df.TOTAL - x) / (y - x) * (b - a) + a df TOTAL Name SIZE 0 3232 Jane 24.413959 1 382 Jack 10.000000 2 8291 Jones 50.000000 This is essentially what the min-max scaler does, but without the overhead of importing scikit learn (don't do it unless you have to, it's a heavy library).

http://stackoverflow.com/comment/86928592
has text: yes indeed, I realised it after asking the question. That's why I added the *EDIT. However I wanted to let the question stand for other people like me having the same issue that are not familiar with the reload function.
score: 0
comment on: http://stackoverflow.com/q/49955289
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50222508
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/50006973
has body: Just add app.is_idle = False: from pyrogram import Client, Filters list_account = ['001', '002'] for item in list_account: app = Client(item) @app.on_message(Filters.chat("public_link_chat") &amp; Filters.new_chat_members) def welcome(client, message): try: client.send_message( message.chat.id, 'Test', reply_to_message_id=message.message_id, disable_web_page_preview=True ) except Exception as e: print(e) # How do I go to the next account in a loop when I receive an error? app.is_idle = False app.start() app.join_chat("public_link_chat") app.idle() You should definitely check out these lines of the idle logic at the pyrogram source code: while self.is_idle: time.sleep(1) If you want an infinite loop, check out the itertools.cycle, it may be used like: for item in itertools.cycle(list_account): do_something()
type: Answer
answers question: http://stackoverflow.com/q/50006973
upvote count: 4
has comment: http://stackoverflow.com/comment/87512861
type: AcceptedAnswer

http://stackoverflow.com/q/50026412
answer count: 0
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87074284
tagged with: macos
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87074300
type: UnansweredQuestion
tagged with: smb
tagged with: python
tagged with: ubuntu
has title: From Mac & Ubuntu how to connect windows share path from python and list files and copy
has body: I want to connect to a windows share path through Python code in Mac(Dev) and Ubuntu(prod) and list the directories and traverse all directories in the path and search for files ending with *abc.html and retrieve those files alone. os.listdir isn't working. From Finder in Mac I could connect to the the windows shared path with link like (smb:// ...). Please let me know if you need more information.

http://stackoverflow.com/q/50040067
tagged with: pywin32
type: Question
tagged with: windows-7
has comment: http://stackoverflow.com/comment/87107161
has comment: http://stackoverflow.com/comment/87096468
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87142391
tagged with: python
linked to: http://stackoverflow.com/q/49799109
tagged with: visual-studio
has title: How to create a non blocking named pipe from Python?
tagged with: named-pipes
score: 0
has comment: http://stackoverflow.com/comment/87101590
has comment: http://stackoverflow.com/comment/87131910
answer count: 0
has body: Under Windows 7 I have a Python 3 application which communicates via named pipe with an executable, written in C using Visual Studio. Within Python I'm using win32pipe package. I observe that within the executable reading from pipe is blocking: readResult = ReadFile(plafParams-&gt;hrpipe_p, &amp;byte, 1, &amp;dwBytesTransferred, &amp;overlap); The pipe is opened with: ... ... overlap.hEvent = NULL; overlap.Offset = 0; overlap.OffsetHigh = 0; overlap.Pointer = NULL; ... ... plafParams-&gt;hwpipe_p = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, &amp;overlap); overlap is a static global variable and initialized as above. OVERLAPPED overlap; In Python the pipe is opened like: self._rpipe = win32pipe.CreateNamedPipe(r'\\.\pipe\wskr_%s'%(self._comport,), win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED , 0, 1, 256, 256, 0, None) After waiting for connection to the pipe, I write to it like win32file.WriteFile(self._rpipe, bytes) It works, and I get the sent bytes in the executable without problems, but I would like to have a non-blocking read. Therefore I opened the pipe with win32file.FILE_FLAG_OVERLAPPED, but that doesn't help... I would appreciate any hint ;-)

http://stackoverflow.com/comment/87011488
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49997595
score: 0
has text: Have you tried `decimal` module? Or is `numpy` a requirement?

http://stackoverflow.com/a/50012594
type: Answer
has body: In all honesty, there should probably only be one instance of asking the user for input, unless you explicitly require it for your case. resp = input() if "yes" in resp: # do stuff elif "no" in resp: # do other stuff
score: 0
accepted answer of: http://stackoverflow.com/q/50012111
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50012111

http://stackoverflow.com/q/50026359
type: Question
has title: Why is my length only half of what I want it to be?
score: 3
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87069160
has comment: http://stackoverflow.com/comment/87069161
has comment: http://stackoverflow.com/comment/87069111
has comment: http://stackoverflow.com/comment/87069068
has body: I want the length of the pattern to match the length of the data segment, where is this going wrong? data_segment = [] #an empty list data_series = [-1, 2, -2, 3, 41, 38, 22, 10, -1, 3] pattern = [40, 30, 20, 10] out_list = [] #an empty list to contain the final output length = len(pattern) #length of pattern list for i, v in enumerate(data_series): if i + length &gt; len(data_series) + 2: break data_segment.append([v, data_series[i+1]]) print(data_segment) Which prints [[-1, 2], [2, -2], [-2, 3], [3, 41], [41, 38], [38, 22], [22, 10], [10, -1], [-1, 3]] But I need it to print [[-1, 2, -2, 3], [2, -2, 3, 41], [-2, 3, 41, 38], [3, 41, 38, 22], [41, 38, 22, 10], [38, 22, 10, -1], [22, 10, -1, 3]]
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87069141
answer count: 1
has answer: http://stackoverflow.com/a/50026535
favorite count: 0

http://stackoverflow.com/a/50004557
has body: Because it's not asynchronous :) Look at your code: you do responses = await asyncio.gather(*tasks) for every file, so you basically run fetching in sync, every time paying all the price of coroutine handling. I suppose it's just an indentation error; if you unindent responses = await asyncio.gather(*tasks) so that it's past the for file in files loop, you will really start tasks in parallel.
accepted answer of: http://stackoverflow.com/q/50003803
answers question: http://stackoverflow.com/q/50003803
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/87026257
has comment: http://stackoverflow.com/comment/87028843
downvote count: 0
upvote count: 7
type: AcceptedAnswer

http://stackoverflow.com/a/50055680
type: Answer
has body: You could do it like this using re.sub import re def strip(string, chars=' \n\r\t'): return re.sub(r'(?:^[{chars}]+)|(?:[{chars}]+$)'.format(chars=re.escape(chars)), '', string) It uses re.escape, so users can enter characters like \ and [ that have meaning withing regex strings. It also uses the ^ and $ regex tokens so that only groups of matching characters at the front and end of the string are matched.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50055600
upvote count: 2

http://stackoverflow.com/comment/87148636
type: AnswerComment
has text: You could try to define some kind A* algorithm that scores the search based on the number of unique nodes and recursion depth. E.g. Unique_nodes / path length? If it's below a threshold cut if off.
score: 0
comment on: http://stackoverflow.com/a/50065407
type: Comment

http://stackoverflow.com/q/50002362
type: Question
has answer: http://stackoverflow.com/a/50002480
tagged with: conways-game-of-life
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87020996
score: -2
has comment: http://stackoverflow.com/comment/87021659
downvote count: 2
tagged with: python
has body: I am trying to run conway's game of life using the function animate_life(100, 'beacon',[0], 30, 300) But it keeps popping up errors , in its current form it says : x_start, y_start = seed_position[0], seed_position[1] IndexError: list index out of range. Originally I had used an index that looked like [0,1] but this also reported an error, namely : IndexError: too many indices for array I'm given to believe that giving it 2 values would report an issue because you're expecting data to be a 2D array. Numpy is complaining because the data is not 2D (it's either 1D or None)? My question is: what is the size of the data ? I.e What size argument is expected in my animate_life function which is generally defined as: animate_life(universe_size, seed, seed_position, n_generations=30, interval=300, save=False) Edi: this is referring to the code found at https://github.com/robertmartin8/PyGameofLife/blob/master/game_of_life.py
has comment: http://stackoverflow.com/comment/87021062
answer count: 1
tagged with: cellular-automata
has title: I don't understand what shape the array in my functions argument is
favorite count: 0

http://stackoverflow.com/comment/87054329
has text: @Ev.Kounis Yes obviously, but I'm just using OP's code not to confuse him, I'll add your suggestion in an edit
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50019034
score: 0

ethereum
type: Tag
tag name: ethereum
tags question: http://stackoverflow.com/q/50045203

http://stackoverflow.com/q/49940084
answer count: 1
accepted answer: http://stackoverflow.com/a/49941357
has answer: http://stackoverflow.com/a/49941357
downvote count: 1
favorite count: 0
type: Question
tagged with: apache-spark-sql
linked to: http://stackoverflow.com/q/23995040
upvote count: 2
tagged with: pyspark
tagged with: python
duplicate of: http://stackoverflow.com/q/23995040
has body: Currently I am using Spark (pyspark with Spark version 1.6) and I have a DataFrame like: DataFrame[clientId: bigint, clientName: string, action: string, ...] I want to dump it in S3 segregated by an attribute (e.g. clientId) in the following format s3://path/&lt;clientId&gt;/&lt;datafiles&gt;. I want the datafiles to contain the rows for the corresponding clientId in json format, so for the path s3://path/1/, the datafiles will contain: {"clientId":1, "clientName":"John Doe", "action":"foo", ...} {"clientId":1, "clientName":"John Doe", "action":"bar", ...} {"clientId":1, "clientName":"John Doe", "action":"baz", ...} I was thinking on using groupBy then a toJSON but in DataFrames you can only collect the data and the DataFrame is too big to fit in the driver (also the I/O is massive). How can I save the partial results of the group from the executors?
type: AnsweredQuestion
tagged with: apache-spark
tagged with: amazon-s3
score: 1
has title: Efficient GroupBy/CombineBy in pyspark

http://stackoverflow.com/comment/86981205
score: 0
has text: You should re-implement the paintEvent and draw the rectangles and gradients inside it (no stylesheets or unnecessary QFrames just to draw stuff). Do you know how to do this (re-implement the paintEvent)?
type: QuestionComment
comment on: http://stackoverflow.com/q/49981942
type: Comment

http://stackoverflow.com/comment/87007800
score: 0
comment on: http://stackoverflow.com/a/49995421
type: Comment
has text: Thanks, this works too. I won't know if it's efficient enough until I code it into the raspberry pi and my group tests whether or not it's fast enough for our purposes, but it's good to have options. The only thing I've noticed different so far is that your output defaulted into a float, even though I entered an integer. However, this shouldn't be an issue as I'm expecting to work in float/double anyways.
type: AnswerComment

http://stackoverflow.com/comment/87072217
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50027605
has text: You can also use the `re.fullmatch` method (since the 3.4 version).
type: QuestionComment

http://stackoverflow.com/q/49988706
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/94516929
tagged with: python
tagged with: iptables
has comment: http://stackoverflow.com/comment/87152852
has comment: http://stackoverflow.com/comment/86998870
score: 0
has title: Linux force packet to egress (and avoid local/kernel trafic)
has body: I have a 20-ports switch connected to a 20-NICs PC (1-to-1) and want to load it with traffic. Of course configuring all NICs with different IPs and start my client/server (Python3) scripts (or iperf3) will generate local traffic only unless I force the traffic out through the NICs. I found (here) the two main 'tricks' in order to achieve this: a.) Using network namespace: [+] It Will do exactly what I want by isolating (VM/docker-like) each NIC into a box [+] Python3 seem to support netns (Pyroute2) [-] Not sure how I can open a socket into a netns/python thread (10 threads x 2 (client/server) ) b.) Using a ghost IP (iptable: S/D-NAT + pre/post-routing): [+] All NICs remain in the root network namespace (still get to collect data through psutil) and configure at global level [+] Python TCP threaded script can run wihtout specific lib/support for netns [-] In case of reconfiguration of my setup (IPs, VLAN,...), IPTable script must be adapted accordingly. I would like to know if I overlook another possibility here and/or if for a.) I am getting it (all) wrong (since I can't find a decent example with a socket opened in a single Python script over different netns...)
tagged with: linux-namespaces
favorite count: 0
type: Question
tagged with: linux
tagged with: network-programming
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/87058076
has text: While true, surely there is a way to fix this without them; I'm mainly curious as to why sorted is spitting back the string represntation for each instance rather than just leaving the objects alone like one might expect.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50020949
type: QuestionComment

http://stackoverflow.com/comment/87004610
score: 0
has text: You will need a server-side solution. Please look into some web frameworks such as Django and Flask.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49994136

http://stackoverflow.com/comment/87039729
comment on: http://stackoverflow.com/a/49995485
type: Comment
type: AnswerComment
score: 0
has text: This line defines local variables `x, dotx` and unpacks the array `y` into the list of them on the left side of the assignment. The same applies to `xlist, vlist = y.T`, the `N x 2` array `y` gets transposed to an `2 x N` array that can be interpreted as a list of 2 arrays of length `N` that is then used to fill the list ov variables on the left side of the assignment.

http://stackoverflow.com/comment/86939242
score: 1
type: Comment
type: AnswerComment
has text: Ah, yes. I woukd not use a render template method on a binary file. That is creating unnecessary work. You imported send_from_directory explicitly - I thought you must have had a /static route using this. It will be an Expires issue. A good way to debug is Chrome's developer tools. Use the network timeline to inspect the headers of each request/response.
comment on: http://stackoverflow.com/a/49960451

http://stackoverflow.com/q/49991762
tagged with: python
tagged with: flask
has title: Zappa Init -- Flask UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 301: character maps to <undefined>
downvote count: 0
has comment: http://stackoverflow.com/comment/87000351
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50025568
answer count: 1
has comment: http://stackoverflow.com/comment/87000235
tagged with: aws-lambda
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87000483
has body: I am trying my hand at serverless deployment of an API... and getting annoyingly stuck at the setup stage. I'm trying to run zappa init from cmd, but I am getting a weird error. The command actually worked the first time I ran it (I cancelled at the last step, realizing I wanted to setup my S3 bucket first). When I tried it again, after installing and configuring awscli, then installing flask to my virtual environment, I got the following error: Your Zappa deployments will need to be uploaded to a private S3 bucket. If you don't have a bucket yet, we'll create one for you too. What do you want call your bucket? (default 'zappa-hohr3kxh7'): It looks like this is a Flask application. Oh no! An error occurred! :( ============== Traceback (most recent call last): File "c:\users\joshu\documents\code\machine-learning\boston-housing-price\app\env\venv\lib\site-packages\zappa\cli.py", line 2610, in handle sys.exit(cli.handle()) File "c:\users\joshu\documents\code\machine-learning\boston-housing-price\app\env\venv\lib\site-packages\zappa\cli.py", line 476, in handle self.init() File "c:\users\joshu\documents\code\machine-learning\boston-housing-price\app\env\venv\lib\site-packages\zappa\cli.py", line 1604, in init matches = detect_flask_apps() File "c:\users\joshu\documents\code\machine-learning\boston-housing-price\app\env\venv\lib\site-packages\zappa\utilities.py", line 143, in detect_flask_apps lines = f.readlines() File "c:\users\joshu\documents\code\machine-learning\boston-housing-price\app\env\venv\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 301: character maps to &lt;undefined&gt; I'm running Windows 10, Python 3.6 Anaconda distribution. Most of my code lies in an api.py file, other than that there is an index.html file. Here's the api.py code: from flask import Flask, render_template, request, jsonify from sklearn.externals import …
type: UnansweredQuestion
tagged with: package

http://stackoverflow.com/comment/86948030
type: Comment
comment on: http://stackoverflow.com/q/49965956
type: QuestionComment
has text: Have you checked [How to set proxy authentication (user & password) using python selenium](https://stackoverflow.com/q/38304253/2745495)? Also, is there a particular reason you tagged this only with `python` (and not with [`selenium`](https://stackoverflow.com/tags/selenium/info) and its other related tags)?
score: 0

http://stackoverflow.com/comment/86864749
type: QuestionComment
comment on: http://stackoverflow.com/q/49924237
score: 0
has text: Thanks, do we have any tool supporting python3.x to show the memory usage?
type: Comment

http://stackoverflow.com/comment/87126467
has text: And what is your question? How to use blas? Just use numpy - it uses blas under the hood...
type: QuestionComment
comment on: http://stackoverflow.com/q/50034761
score: 0
type: Comment

http://stackoverflow.com/a/70522734
has body: Taken from Tobias, use this updated version import pandas as pd pd.DataFrame.from_dict(history_model_1.history.history).to_csv('history.csv',index=False)
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49969006
type: Answer

http://stackoverflow.com/q/50047392
answer count: 1
has body: I am trying to scrape some information from this website http://www.dubaitrade.ae/ja-terminal-1 I have to go to the terminal code column and select 'General Cargo' Here is the HTML. General Cargo Terminal One Terminal Two Terminal Three I am unsure if the difficulty is because it is nested within this tag.Meaning it is some kind of form. I have tried Select(driver.find_element_by_xpath('//*[@id="terminal1"]')).select_by_visible_text('General Cargo') Select(driver.find_element_by_id('terminal1')).select_by_visible_text('General Cargo') Select(driver.find_element_by_css_selector("terminal1")) Select(driver.find_element_by_name('terminal1')).select_by_visible_text('General Cargo') I always get the error message unable to locate element.
tagged with: web-scraping
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/47993443
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: Selenium is not selecting an option from the dropdown
score: 1
tagged with: selenium
tagged with: webdriver
favorite count: 0
accepted answer: http://stackoverflow.com/a/50047777
type: Question
has answer: http://stackoverflow.com/a/50047777
downvote count: 0

http://stackoverflow.com/comment/86996837
score: 2
has text: If you don't understand float rounding in general, the standard document is [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf), although there may be simpler (novice-friendlier) explanations out there. If you do understand that, but want to know why exactly this error, edit your question to be more specific, and I can expand on my comment.
type: Comment
comment on: http://stackoverflow.com/q/49990066
type: QuestionComment

http://stackoverflow.com/q/49943442
has comment: http://stackoverflow.com/comment/86903424
has comment: http://stackoverflow.com/comment/86903264
has body: I would like to divide an index array in randomly sized chunks (taken from a limited range of possible sizes) which are also shuffled between each other. I tried the following I found here but it is focused on equally sized chunks. a = np.arange(1, 100) def chunk(xs, n): # to chunk the array xs in n parts ys = list(xs) random.shuffle(ys) size = len(ys) // n leftovers= ys[size*n:] for c, xtra in enumerate(leftovers): yield ys[c*size:(c+1)*size] + [ xtra ] for c in xrange(c+1,n): yield ys[c*size:(c+1)*size] In other words, how could I change the above function to have a certain number of chunks (random number and shuffled between each other) with a variable size taken random from a range, e.g. [5-10]
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49944026
accepted answer: http://stackoverflow.com/a/49944026
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86903322
answer count: 2
has comment: http://stackoverflow.com/comment/86903211
tagged with: arrays
has answer: http://stackoverflow.com/a/49944748
possible better answer: http://stackoverflow.com/a/49944748
tagged with: python
has title: Randomly sized chunking of a numpy array in python

bioinformatics
tags question: http://stackoverflow.com/q/50020640
tag name: bioinformatics
tags question: http://stackoverflow.com/q/50004223
tags question: http://stackoverflow.com/q/50059372
tags question: http://stackoverflow.com/q/50051440
type: Tag

http://stackoverflow.com/q/50027430
upvote count: 1
has comment: http://stackoverflow.com/comment/87071404
has comment: http://stackoverflow.com/comment/87071091
tagged with: nan
favorite count: 0
has answer: http://stackoverflow.com/a/50027626
type: Question
tagged with: numpy
tagged with: python
possible better answer: http://stackoverflow.com/a/50027626
has comment: http://stackoverflow.com/comment/87071528
type: AnsweredQuestion
has body: I have a numpy array which I want to copy to another numpy array and replace all values to zero except the nan values. Can you help please?
has title: Copy and replace values in numpy array.. nans will be nan but other values will be zero
answer count: 2
has comment: http://stackoverflow.com/comment/87071315
accepted answer: http://stackoverflow.com/a/50027664
score: 1
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/50027664

http://stackoverflow.com/q/50037992
has answer: http://stackoverflow.com/a/50038323
type: UnansweredQuestion
tagged with: max
score: -2
has answer: http://stackoverflow.com/a/50038021
has comment: http://stackoverflow.com/comment/87092691
tagged with: python
downvote count: 4
tagged with: combinations
has body: Looking to find max from the combine list as follows: ['filename1', 1696, 'filename2', 5809,....] I have tried following: max(['filename1', 1696, 'filename2', 5809,....]) that return me TypeError: '&gt;' not supported between instances of 'int' and 'str'. Any suggestion would help. What I want is to find the max integer value from the list above mentioned.
has title: Find maximum int value from list which contain both str and int python
tagged with: list
has comment: http://stackoverflow.com/comment/87092964
has answer: http://stackoverflow.com/a/50038084
has answer: http://stackoverflow.com/a/50038279
has comment: http://stackoverflow.com/comment/87095173
has comment: http://stackoverflow.com/comment/87094833
has answer: http://stackoverflow.com/a/50039764
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87092187
upvote count: 2
has comment: http://stackoverflow.com/comment/87092134
has comment: http://stackoverflow.com/comment/87094773
answer count: 5

http://stackoverflow.com/comment/87238703
type: AnswerComment
comment on: http://stackoverflow.com/a/50057160
type: Comment
has text: actually what i want to know is that after doing the following "from selenium import webdriver" I want to know that directly inside webdriver what classes/method etc. are present.
score: 0

http://stackoverflow.com/a/50057125
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: In your code a gets the value of b before the summation a = b &lt;---- a gets updated b = a+b &lt;--- summation In the doc version, a never gets an updated value before the summation as its done on the same line. Values of a and b are updated after this line. a,b = b, a+b
answers question: http://stackoverflow.com/q/50057047

http://stackoverflow.com/comment/87141489
score: 0
type: AnswerComment
has text: Thanks for the reply! I don't have pip installed so I can't really use the commands you mentioned or use pip at all.
comment on: http://stackoverflow.com/a/50061593
type: Comment

batch-normalization
tag name: batch-normalization
tags question: http://stackoverflow.com/q/49980978
type: Tag
tags question: http://stackoverflow.com/q/50047653

http://stackoverflow.com/q/49947770
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45267327
has title: Sum of Guassian by Multiple regression
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50200351
has comment: http://stackoverflow.com/comment/87405877
tagged with: python
has body: I have 16 guassian curves which I have to fit with one guassian curve. I was unable to imply the sum of guassian(multiple regression) in python. Here is the code I am using: import matplotlib.pyplot as plt import numpy as np a=np.array([3750.0, -250.0, 6750.0, 2750.0, -2050.0, 6350.0, 1550.0, -4050.0, 5750.0, 150.0, -6250.0, 4950.0, -1450.0, -8650.0, 3950.0, -3250.0]) v1=np.array( [2.5470357695283954, 0.1937004980283323, 0.43831655553839766, 6.07645636407398, 0.6331239135554633, 0.969937308645575, 13.38133838752005, 1.3226417845166933, 1.5531178254607325, 27.599625693090765, 2.031000233294804, 1.635762971986014, 53.83073800155456, 2.0719664311822843, 0.0, 100.0]) x=[] s=[] v5=9.9e2 for j in range(0,len(a)): for i in range(-1500,1500): v11=a[j]+i x.append(v11) z=np.exp((-4*np.log(2)*((v11-a[j])/(v5))**2))*((4.5*np.log(2)/(np.pi))**0.5) s.append(z*v1[j]) plt.plot(x,s,'--r',) plt.stem(a,v1) Which generates the following plot (with the problem circled): Instead of the desired output:
type: AnsweredQuestion
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/50200351
downvote count: 0
tagged with: linear-regression
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/87414479

http://stackoverflow.com/comment/86973382
score: 1
has text: By the way, if you intend to perform parallel processing with Python, you may also check Dask: https://dask.pydata.org/en/latest/ If you are performing embarrassingly parallel computations, then it would be a good alternative to MPI4Py.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49968647

http://stackoverflow.com/a/50005475
score: 1
has body: This should do what you want: def get_function(cmd): def change_colour(): if 'violet' == cmd: label_violet['bg'] = 'violet' if 'purple' == cmd: label_purple['bg'] = 'purple' if 'blue' == cmd: label_blue['bg'] = 'blue' if 'green' == cmd: label_green['bg'] = 'green' if 'reset' == cmd: label_violet['bg'] = 'grey' label_purple['bg'] = 'grey' label_blue['bg'] = 'grey' label_green['bg'] = 'grey' return change_colour violet_button = Button(the_window, text = 'Violet', width = button_size, font = window_font, command = get_function('violet')) purple_button = Button(the_window, text = 'Purple', width = button_size, font = window_font, command = get_function('purple')) blue_button = Button(the_window, text = 'Blue', width = button_size, font = window_font, command = get_function('blue')) green_button = Button(the_window, text = 'Green', width = button_size, font = window_font, command = get_function('green')) reset_button = Button(the_window, text = 'RESET', width = button_size, font = window_font, command = get_function('reset')) For the issue with the reset button, just specifie the columnspan argument of the grid function: reset_button.grid(row = 2, column = 1, pady = margin_size_height, columnspan = 2)
type: Answer
has comment: http://stackoverflow.com/comment/87028471
has comment: http://stackoverflow.com/comment/87029710
has comment: http://stackoverflow.com/comment/87028819
accepted answer of: http://stackoverflow.com/q/50005306
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87027502
has comment: http://stackoverflow.com/comment/87029752
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50005306

http://stackoverflow.com/a/50025085
answers question: http://stackoverflow.com/q/50024939
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50024939
has comment: http://stackoverflow.com/comment/87067243
has body: The method readlines() reads until EOF using readline() and returns a list containing the lines. f1 = open('test.txt', 'r') f2 = open('test2.txt', 'w') f1_lines = f1.readlines() f1.close() for line in f1_lines: find = input('Enter word to find: ') if find in line: print('Word Found') replace = input('Enter Word to replace with: ') replace_action = input('Are you sure you want to replace Y or N:') if replace_action.lower() == 'y': f2.write(line.replace(find.lower(), replace)) else: print('You have cancelled this operation') else: print('Word not found in file') f2.write(line) f2.close() I changed a few thinks based on what I understood of the question. if find in line checks if the input you look for is in the line. If it is, the line is written to f2 with the replace, else the line is written to f2 as it was. EDIT: You got another issue I guess. Works for me. runfile('C:/Users/mathieu.scheltienne/Desktop/test/untitled0.py', wdir='C:/Users/mathieu.scheltienne/Desktop/test') Enter word to find: hello Word Found Enter Word to replace with: good bye Are you sure you want to replace Y or N:y Enter word to find: hello Word Found Enter Word to replace with: good bye Are you sure you want to replace Y or N:y Enter word to find: hello Word Found Enter Word to replace with: good bye Are you sure you want to replace Y or N:y Input file was: test.txt hello world hello galaxy hello universe Output file: good bye world good bye galaxy good bye universe Version with only one word that is going to be replace by only one word on every line: f1 = open('test.txt', 'r') f2 = open('test2.txt', 'w') f1_lines = f1.readlines() f1.close() find = input('Enter word to find: ') replace = input('Enter Word to replace with: ') counter = 0 for line in f1_lines: if find in line: print('Word Found') f2.write(line.replace(find.lower(), replace)) counter += 1 else: f2.write(line) if counter == 0: print('Word not found in file') else: print('{} words replaced'.format(counter)) f2.close()
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87067464
has comment: http://stackoverflow.com/comment/87067217
type: Answer

http://stackoverflow.com/q/49950324
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49950416
upvote count: 0
answer count: 1
downvote count: 1
has title: Pandas create column from row entries
has body: I have a dataframe and I would like to group the url and create new columns for word where url is the same. df2 = pd.DataFrame({'url':['/pool','/refrigerators','/refrigerators','/refrigerators','/joss-and-main','/furniture','/entertainment-centers-and-tv-stands'], 'word':['pool','refrigerator','fridge','cooler','joss and main','furniture','tv stand']}) Wanted Output: Url word word1 word2 /pool pool /refrigerators refrigerator fridge cooler /joss-and-main joss and main /furniture furniture /entertainment-centers-and-tv-stands tv stand
favorite count: 0
type: Question
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/86917580
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49950416

http://stackoverflow.com/comment/86878074
type: QuestionComment
has text: Are you using the right axis?
score: 0
comment on: http://stackoverflow.com/q/49931009
type: Comment

http://stackoverflow.com/a/50065885
score: 0
has body: It seems that you need to send the question to slack in its API's desired format: https://api.slack.com/docs/message-buttons
has comment: http://stackoverflow.com/comment/87196487
answers question: http://stackoverflow.com/q/50065047
type: Answer
has comment: http://stackoverflow.com/comment/87281677

http://stackoverflow.com/q/50002600
favorite count: 0
has body: I am looking for ways to prevent user from entering past dates in in django admin page. Something like this: Django: How to set DateField to only accept Today &amp; Future dates My model looks like this: class MyModel(models.Model): date = models.DateField(null=True, blank=True, default=None)
type: Question
linked to: http://stackoverflow.com/q/4941974
has answer: http://stackoverflow.com/a/50002681
accepted answer: http://stackoverflow.com/a/50002664
score: 3
has title: django models.DateField prevent past
has answer: http://stackoverflow.com/a/50002664
has answer: http://stackoverflow.com/a/78331848
tagged with: django-models
tagged with: python
type: AnsweredQuestion
answer count: 3
upvote count: 3
downvote count: 0
tagged with: django
possible better answer: http://stackoverflow.com/a/50002681

http://stackoverflow.com/q/50038520
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87095112
has title: How to compare two subprocess output values in python?
has answer: http://stackoverflow.com/a/50038559
score: 2
has body: Python code: filename = open("file.txt", "r") subprocess.call(["./a.out" , "0-9"]), stdin= fin) #1 subprocess.call(["./a.out, "0123456789"], stdin = fin) #2 Here I wanted to compare the both commands by using if statement. 1) I have assigned to different variables and tried to compare it and it doesnt work. 2) I have also tried comparing on if statement (subprocess... == subprocess). Please suggest me some solution Thanks inadvance
tagged with: python
has comment: http://stackoverflow.com/comment/87095937
favorite count: 0
type: Question
tagged with: subprocess
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/86954777
type: AnswerComment
has text: Wen is a Python Guru.
comment on: http://stackoverflow.com/a/49961921
score: 0
type: Comment

http://stackoverflow.com/comment/86867150
comment on: http://stackoverflow.com/q/49925595
score: 0
has text: Did you try to "write a python script that automates calling this service"? Did it work? If not, did it produce an error mesage?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50001958
tagged with: python
tagged with: passwords
score: 0
tagged with: msvcrt
has answer: http://stackoverflow.com/a/50002187
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: getch
has title: "print" after "msvcrt.getch" doesn't work
has body: So, I am using python and I wrote a code to scan a password. So, as password should not be displayed openly, I scan one character using msvcrt.getch() and then do print('*', end=''). Here's the code: if __name__ == '__main__': string = '' ch = msvcrt.getch() while ch != b'\r': print('*', end='') string += ch.decode('utf-8') ch = msvcrt.getch() print('\nEntered string is: ', string) The problem here is, the *'s are getting printed after I type the whole "password". But, what I was expecting is a * getting printed every time I enter a character. I am running the code in terminal. I think I structured the code properly so why doesn't it work? (Also, if there are any others ways of scanning passwords, please do mention them)

http://stackoverflow.com/q/50056946
tagged with: django
tagged with: python
has body: I am trying to give a drop-down menu from Django, from a dynamic list. For example, every time I run the model it should take columns names of a dataset and these names shall appear on the drop-down menu. Previously, I have used a text box from Django which looks something like this: Forms.py from django import forms class LinearForm(forms.Form): Column_name1 = forms.CharField() I have seen forms.ModelMultipleChoiceField() and forms.ChoiceField() which takes choices as a list of values, since I need to generate a dynamic list from my Views.py. How do I proceed with this?
has title: Dropdowns Django with dynamic list
type: AnsweredQuestion
tagged with: django-views
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50057117
upvote count: 1
accepted answer: http://stackoverflow.com/a/50057117
tagged with: django-forms
favorite count: 0
type: Question

http://stackoverflow.com/a/49919442
upvote count: 1
has body: It's a feature indeed, see here. Encoded Data? Requests automatically decompresses gzip-encoded responses, and does its best to decode response content to unicode when possible. You can get direct access to the raw response (and even the socket), if needed as well.
downvote count: 0
has comment: http://stackoverflow.com/comment/86956337
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49919307

http://stackoverflow.com/comment/86917249
type: Comment
has text: Oh, sorry, I missed that.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49949960

http://stackoverflow.com/comment/86880185
has text: @Alexander - Perhaps. But I think having `dict.get()` return a default callable makes the code more readable.
type: Comment
comment on: http://stackoverflow.com/a/49931865
score: 0
type: AnswerComment

http://stackoverflow.com/q/49938137
has answer: http://stackoverflow.com/a/49943845
tagged with: python-2.7
score: 0
has body: I'm using celery == 4.1.0 (latentcall) [cqlsh 5.0.1 | Cassandra 3.11.2 | CQL spec 3.4.4 | Native protocol v4] Python 2.7.14 I'm trying to execute Cassandra Query in Celery worker function. But Celery worker received task but not execute Query. tasks.py from cassandra.cluster import Cluster from celery import Celery app = Celery('&lt;workername&gt;', backend="rpc://", broker='redis://localhost:6379/0') dbSession = Cluster().connect() @app.tasks() def get_data(): query = "SELECT * FROM customers" CustomerObj = dbSession.execute(dbSession.prepare(query)) return CustomerObj get_data.delay() I start worker using : $ celery worker -A &lt;worker_name&gt; -l INFO -c 1 -------------- celery@ubuntu v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.13.0-21-generic-x86_64-with-Ubuntu-17.10-artful 2018-04-20 14:31:41 -- * - **** --- - ** ---------- [config] - ** ---------- .&gt; app: Woker:0x7fa4a0e6f310 - ** ---------- .&gt; transport: redis://localhost:6379/0 - ** ---------- .&gt; results: rpc:// - *** --- * --- .&gt; concurrency: 1 (prefork) -- ******* ---- .&gt; task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .&gt; celery exchange=celery(direct) key=celery [tasks] . Worker.get_data [2018-04-20 14:31:41,271: INFO/MainProcess] Connected to redis://localhost:6379/0 [2018-04-20 14:31:41,285: INFO/MainProcess] mingle: searching for neighbors [2018-04-20 14:31:42,315: INFO/MainProcess] mingle: all alone ............. [2018-04-20 14:31:42,332: INFO/MainProcess] celery@ubuntu ready. [2018-04-20 14:31:43,823: INFO/MainProcess] Received task: &lt;worker_name&gt;.get_data[8de91fdf-1388-4d5c-bb22-8cb00c1c065e] Worker process is just stopped there.It will not execute that SELECT query and give any data. Anyone suggest me How can I run this code to execute Cassandra Queries.
answer count: 2
has title: Celery Worker don't execute cassandra queries
has answer: http://stackoverflow.com/a/55362044
tagged with: celery
type: Question
linked to: http://stackoverflow.com/q/14526249
tagged with: cassandra
tagged with: redis
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51796933
answers question: http://stackoverflow.com/q/49968002
has comment: http://stackoverflow.com/comment/90550971
has body: Working code: import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio import requests import random bottoken = "snip" commandprefix = "#" bot = commands.Bot(command_prefix=commandprefix) @bot.event async def on_ready(): print ("Starting up") print ("My username is " + bot.user.name + " and i am running with the ID: " + bot.user.id) await bot.change_presence(game=discord.Game(name="Test", type=1)) print ("Started") @bot.command(pass_context=True) async def hello(ctx): await bot.say("hi") print ("hi Posted") bot.run(bottoken)
score: -2
downvote count: 2
type: Answer
upvote count: 0

http://stackoverflow.com/a/50024374
accepted answer of: http://stackoverflow.com/q/50024085
score: 1
type: AcceptedAnswer
downvote count: 0
has body: By the looks of it, you can read line-by-line, remove any trailing commas and split on the : and ast.literal_eval the dict part, eg: import ast with open('yourfile') as fin: rows = (line.rstrip('\n,').partition(' : ') for line in fin) data = {r[0]: ast.literal_eval(r[2]) for r in rows} Which give you data of: {'ABB': {'Code': 'adr', 'Volume': 2238117, 'Sector': 'Industrials', 'Market_Cap': 'No Data', 'Industry': 'Industrial Products', 'List_Date': '2001-04-06'}, 'ABEV': {'Code': 'adr', 'Volume': 19348239, 'Sector': 'Consumer Defensive', 'Market_Cap': 'No Data', 'Industry': 'Beverages - Alcoholic', 'List_Date': '2013-11-11'}}
answers question: http://stackoverflow.com/q/50024085
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87064889

http://stackoverflow.com/a/50023042
has body: I tried to modify as minimal as possible in your code, so that you could understand properly. I just added a for loop with step 2 so that you wouldn't end up with index out of range. And for the final character in case of odd length string, I handled separately. def skyline (str1): result = '' length = len(str1) for index in range(0, length - 1, 2): result += str1[index].upper() + str1[index + 1].lower() if length % 2 == 1: result += str1[length - 1].upper() return result
answers question: http://stackoverflow.com/q/50022591
score: 0
has comment: http://stackoverflow.com/comment/87062978
has comment: http://stackoverflow.com/comment/87062876
type: Answer

http://stackoverflow.com/comment/87438417
comment on: http://stackoverflow.com/q/50008200
type: QuestionComment
score: 0
has text: @idfah Can you please asnwer, the same comment? I have to accept it. Thanks :)
type: Comment

http://stackoverflow.com/q/49958881
tagged with: iterator
type: Question
linked to: http://stackoverflow.com/q/49965611
has body: I'm trying to parse a huge XML file containing list of Directories_name, Files_name, permissions, creation_date_time, username, file_size, dir_size The structure of the xml is as follow : <parent_dir> <file_1> <sub-dir_1> <file_2> <sub-dir_2> .... ..... An actual file looks like this: <file date="2017-03-18 22:01:11" internal="0" group="unknown" protection="-rwxrwxr-x" name="desktop.ini" size="174" links="0" user="Administrators" /> <file date="2017-02-09 14:58:53" internal="0" group="None" protection="----------" name="26.avi" size="13263184" links="0" user="srt" /> <file date="2016-11-01 00:31:40" internal="0" group="None" protection="----------" name="6.avi" size="13569536" links="0" user="srt" /> <file date="2017-12-12 14:35:36" internal="0" group="None" protection="----------" name=".suo" size="5120" links="0" user="srt" /> <file date="2017-12-14 03:06:03" internal="0" group="None" protection="-rwx------" name="Current_Frame1 (2).mp4" size="321612800" links="0" user="Administrators" /> <file date="2018-04-16 21:35:17" internal="0" group="None" protection="-rwx------" name="Current_Frame1.avi" size="94102" links="0" user="Administrators" /> <file date="2017-12-12 21:35:13" internal="0" group="None" protection="----------" name="Fire_Detected_02_05_12.bmp" size="921654" links="0" user="srt" /> <file date="2017-12-12 21:35:13" internal="0" group="None" protection="----------" name="Fire_Detected_02_05_13.bmp" size="921654" links="0" user="srt" /> <file date="2017-12-12 21:35:50" internal="0" group="None" protection="----------" name="Smoke_Detected_02_05_50.bmp" size="921654" links="0" user="srt" /> <file date="2017-12-12 21:39:17" internal="0" group="None" protection="----------" name="Smoke_Detected_02_09_17.bmp" size="921654" links="0" user="srt" /> <file date="2017-12-12 21:39:18" internal="0" group="None" protection="----------" name="Smoke_Detected_02_09_18.bmp" size="921654" links="0" user="srt" /> <file date="2017-12-12 21:42:29" internal="0" group="None" …
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/86942093
tagged with: lxml
type: AnsweredQuestion
has title: Parse XML using LXML and build a SQLITE structure using Python
score: 0
tagged with: sqlite
accepted answer: http://stackoverflow.com/a/49996044
has answer: http://stackoverflow.com/a/49996044
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/a/50042705
has body: You can use literal_eval method from ast module s="[{'Name':'key','Values':['data']}],6,True,'somestring'" list(ast.literal_eval(s)) Out [[{'Name': 'key', 'Values': ['data']}], 6, True, 'somestring']
answers question: http://stackoverflow.com/q/50042583
score: 0
type: Answer

http://stackoverflow.com/a/50016565
has comment: http://stackoverflow.com/comment/87052491
has body: Note that (?:W|$) is consuming the W in the next match and thus you used [W]*. Actually, this is the case where lookarounds should be used since they do not consume text, just check if there is a match or not without putting the matched text into the match value. You may use \bWordcap([^|=]*=.*?)(?=\s*\bWordcap|$) See the regex demo Details \bWordcap - a word boundary followed with Wordcap ([^|=]*=[^|]*?) - Group 1: [^|=]* - any 0+ chars other than | and =, as many as possible = - an = sign .*? - any 0+ chars other than a newline, as few as possible (?=\s*\bWordcap|$) - a positive lookahead that requires 0+ whitespaces, a word boundary and Wordcap string immediately to the right of the current location, or end of string. See the Python demo: import re rx = r"\bWordcap([^|=]*=.*?)(?=\s*\bWordcap|$)" s = "Tue Apr 24 22:35:48 2018 53/e33 \nhello:55|Wordcap|abc|abc generate|6|Wordcapdata_proto_req=WINTER Wordcapdata_sample_resp=summer 2.4.5 WordcapTotal_reject=56 WordcapAddition_sum=TEA CUP ONE" print(re.findall(rx, s)) # =&gt; ['data_proto_req=WINTER', 'data_sample_resp=summer 2.4.5', 'Total_reject=56', 'Addition_sum=TEA CUP ONE']
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50016381
has comment: http://stackoverflow.com/comment/87050845
type: Answer
has comment: http://stackoverflow.com/comment/87050742
has comment: http://stackoverflow.com/comment/87052184
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50016381

http://stackoverflow.com/q/50052421
possible better answer: http://stackoverflow.com/a/50058436
downvote count: 0
accepted answer: http://stackoverflow.com/a/56417948
has comment: http://stackoverflow.com/comment/87122415
has answer: http://stackoverflow.com/a/50052660
tagged with: python
score: 4
tagged with: mixed-models
linked to: http://stackoverflow.com/q/39152729
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
tagged with: statsmodels
has title: mixed-models with two random effects - statsmodels
answer count: 3
has body: import pandas as pd import statsmodels.formula.api as smf df = pd.read_csv('http://www.bodowinter.com/tutorial/politeness_data.csv') df = df.drop(38) In R I would do: lmer(frequency ~ attitude + (1|subject) + (1|scenario), data=df) which in R gives me: Random effects: Groups Name Variance Std.Dev. scenario (Intercept) 219 14.80 subject (Intercept) 4015 63.36 Residual 646 25.42 Fixed effects: Estimate Std. Error t value (Intercept) 202.588 26.754 7.572 attitudepol -19.695 5.585 -3.527 I tried to do the same with statsmodels: model = smf.mixedlm("frequency ~ attitude", data=df, groups=df"subject","scenario").fit() But model.summary() gives me a different output: Mixed Linear Model Regression Results ======================================================= Model: MixedLM Dependent Variable: frequency No. Observations: 83 Method: REML No. Groups: 2 Scale: 0.0000 Min. group size: 1 Likelihood: inf Max. group size: 1 Converged: Yes Mean group size: 1.0 ------------------------------------------------------- Coef. Std.Err. z P&gt;|z| [0.025 0.975] ------------------------------------------------------- Intercept 204.500 attitude[T.pol] 8.800 groups RE 0.000 =======================================================
has comment: http://stackoverflow.com/comment/87157933
has answer: http://stackoverflow.com/a/56417948
has comment: http://stackoverflow.com/comment/87122278
has comment: http://stackoverflow.com/comment/87139634
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50058436

http://stackoverflow.com/a/50020946
accepted answer of: http://stackoverflow.com/q/50020917
has comment: http://stackoverflow.com/comment/87058756
type: Answer
has comment: http://stackoverflow.com/comment/87058685
answers question: http://stackoverflow.com/q/50020917
downvote count: 0
has body: Function to_datetime working only with Series (column of DataFrame), so possible solution are: df = df.apply(pd.to_datetime) #alternative #df = df.apply(lambda x: pd.to_datetime(x)) Or: for c in df.columns: df[c] = pd.to_datetime(df[c]) For convert column names: df.columns = pd.to_datetime(df.columns)
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49978383
answers question: http://stackoverflow.com/q/49977723
has body: Approach #1 Here's one with type-conversion and scaling - df['weight'] = (df['B'] &gt;= 6)*19+1 Approach #2 Another possibly faster one with using the underlying array data - df['weight'] = (df['B'].values &gt;= 6)*19+1 Approach #3 Leverage multi-cores with numexpr module - import numexpr as ne val = df['B'].values df['weight'] = ne.evaluate('(val &gt;= 6)*19+1') Timings on 500k rows as commented by OP for a random data in range [0,9) for the vectorized methods posted thus far - In [149]: np.random.seed(0) ...: df = pd.DataFrame({'B' : np.random.randint(0,9,(500000))}) # @jpp's soln In [150]: %timeit df['weight1'] = np.where(df['B'] &gt;= 6, 20, 1) 100 loops, best of 3: 3.57 ms per loop # @jpp's soln with array data In [151]: %timeit df['weight2'] = np.where(df['B'].values &gt;= 6, 20, 1) 100 loops, best of 3: 3.27 ms per loop In [154]: %timeit df['weight3'] = (df['B'] &gt;= 6)*19+1 100 loops, best of 3: 2.73 ms per loop In [155]: %timeit df['weight4'] = (df['B'].values &gt;= 6)*19+1 1000 loops, best of 3: 1.76 ms per loop In [156]: %%timeit ...: val = df['B'].values ...: df['weight5'] = ne.evaluate('(val &gt;= 6)*19+1') 1000 loops, best of 3: 1.14 ms per loop One last one ... With the output being 1 or 20, we could safely use lower precision : uint8 for a turbo speedup over already discussed ones, like so - In [208]: %timeit df['weight6'] = (df['B'].values &gt;= 6)*np.uint8(19)+1 1000 loops, best of 3: 428 µs per loop
type: AcceptedAnswer
downvote count: 0
upvote count: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/49977723
score: 4

http://stackoverflow.com/comment/86897766
type: Comment
comment on: http://stackoverflow.com/q/49940129
score: 0
type: QuestionComment
has text: So I want to be able to swap it in plain text. But the output seems to be binary or bytes data

http://stackoverflow.com/comment/86946069
type: QuestionComment
comment on: http://stackoverflow.com/q/49964931
type: Comment
has text: I could not either
score: 0

http://stackoverflow.com/a/50444972
answers question: http://stackoverflow.com/q/49940813
has comment: http://stackoverflow.com/comment/94599989
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: Its probably due to a version conflict, try to run this, it will remove the older pip somehow. sudo apt remove python pip

http://stackoverflow.com/comment/87179216
comment on: http://stackoverflow.com/a/50076430
type: AnswerComment
score: 0
type: Comment
has text: All I show is built-in functionality and Vim (thankfully) doesn't have autocompletion. If you want autocompletion, use an autocompletion plugin, as per the other answer.

http://stackoverflow.com/q/50019588
has comment: http://stackoverflow.com/comment/87055252
has title: doing "nothing" in else command of if-else clause
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/87055212
linked to: http://stackoverflow.com/q/32954481
has answer: http://stackoverflow.com/a/50019919
possible better answer: http://stackoverflow.com/a/50019919
duplicate of: http://stackoverflow.com/q/12199757
has comment: http://stackoverflow.com/comment/87055260
has comment: http://stackoverflow.com/comment/87055384
tagged with: python
has body: Code: for i in range(1000): print(i) if i%10==0 else pass Error: File "&lt;ipython-input-117-6f18883a9539&gt;", line 2 print(i) if i%10==0 else pass ^ SyntaxError: invalid syntax Why isn't 'pass' working here?
linked to: http://stackoverflow.com/q/394809
has comment: http://stackoverflow.com/comment/87055431
has comment: http://stackoverflow.com/comment/87055726
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87056025
tagged with: if-statement
has comment: http://stackoverflow.com/comment/87055967
has comment: http://stackoverflow.com/comment/87055236
has comment: http://stackoverflow.com/comment/87055892
upvote count: 10
has answer: http://stackoverflow.com/a/50019778
accepted answer: http://stackoverflow.com/a/50019778
linked to: http://stackoverflow.com/q/14474168
has comment: http://stackoverflow.com/comment/87055213
has comment: http://stackoverflow.com/comment/87055248
score: 8
favorite count: 0
linked to: http://stackoverflow.com/q/7818992
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86852797
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49918038
has text: Do you need to count just the null values? I see from your desired output that you count the 1 also. one count for 0(first row), another for 0 (second row) and a third count for 1 (3 row where neg = 1) ?

http://stackoverflow.com/q/50045620
tagged with: statistics
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50048756
tagged with: chi-squared
answer count: 3
possible better answer: http://stackoverflow.com/a/51207376
tagged with: python
has answer: http://stackoverflow.com/a/75503242
type: Question
score: 0
has answer: http://stackoverflow.com/a/51207376
tagged with: machine-learning
has title: p value generated by scipy.stats.chi2_contingency for independence testing
accepted answer: http://stackoverflow.com/a/50048756
has body: For testing if two features are independent or not, H0: A and B are independent H1: A and B are dependent p &lt; 0.05, then A and B are dependent Upon trying the following code, where it is very clear that the two arrays are dependent(they are the same arrays) obs = np.array([[10, 10, 10], [10, 10, 10]]) scipy.stats.chi2_contingency(obs) I get the following result: (0.0, 1.0, 2, array([[10., 10., 10.], [10., 10., 10.]])) i.e. p value is 1.0 > 0.05, So we accept the null hypothesis that the two arrays are independent of each other. Is there an assumption I got wrong or is it generating 1-p values?

http://stackoverflow.com/comment/86852731
has text: I have made changes suggested by you and getting error: [root@10 nix_bsd_mac_inventory-master]# python s2.py File "s2.py", line 43 for password in passwords: ^ IndentationError: expected an indented block
type: Comment
comment on: http://stackoverflow.com/a/49917161
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87109143
has text: Do i have an option to run existing data pipeline with python in order my whole scrpty will be automatically?
type: Comment
comment on: http://stackoverflow.com/q/50043330
score: 0
type: QuestionComment

http://stackoverflow.com/q/50052295
tagged with: python
has answer: http://stackoverflow.com/a/51698037
accepted answer: http://stackoverflow.com/a/51698037
type: AnsweredQuestion
upvote count: 24
favorite count: 0
score: 24
has title: How do you load MNIST images into Pytorch DataLoader?
type: Question
tagged with: pytorch
possible better answer: http://stackoverflow.com/a/50052355
has body: The pytorch tutorial for data loading and processing is quite specific to one example, could someone help me with what the function should look like for a more generic simple loading of images? Tutorial: http://pytorch.org/tutorials/beginner/data_loading_tutorial.html My Data: I have the MINST dataset as jpg's in the following folder structure. (I know I can just use the dataset class, but this is purely to see how to load simple images into pytorch without csv's or complex features). The folder name is the label and the images are 28x28 png's in greyscale, no transformations required. data train 0 3.png 5.png 13.png 23.png ... 1 3.png 10.png 11.png ... 2 4.png 13.png ... 3 8.png ... 4 ... 5 ... 6 ... 7 ... 8 ... 9 ...
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50052355

http://stackoverflow.com/a/50058718
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87134661
accepted answer of: http://stackoverflow.com/q/50058425
type: Answer
answers question: http://stackoverflow.com/q/50058425
has body: You are using row and column slicing in numpy.matrix wrong. Change your if statement to this: if u in matrix[ix, :] or u in matrix[:, iy]: By the way, this seems more elegant with quick fixes. import numpy as np from random import randint def genRandomMatrix(): matrix = np.zeros((5,5)) for ix in range(5): for iy in range(5): while True: # random int u = randint(1,5) # test if random int already in indexed row or indexed column if u in matrix[ix, :] or u in matrix[:, iy]: continue else: matrix[ix][iy] = u break print matrix genRandomMatrix()
has comment: http://stackoverflow.com/comment/87134498
score: 0

http://stackoverflow.com/q/49917249
has body: I have a boolean list a such as the following Time Value 2017-09-02 11:00:00 False 2017-09-02 11:30:00 False 2017-09-02 12:00:00 True 2017-09-02 12:30:00 True 2017-09-02 13:00:00 True 2017-09-02 13:30:00 True 2017-09-02 14:00:00 False 2017-09-02 14:30:00 False 2017-09-02 15:00:00 False 2017-09-02 15:30:00 False Next I would like to check for False values which are preceded by True Values. result = (a == 0) &amp; (a.shift(-1) == 1) The issue is that this condition should be dynamic, which means that I might want to check for values which are False and preceded in N positions by a True value, for instance N = 2 result = (a == 0) &amp; ( (a.shift(-1) == 1) | a.shift(-2) == 1) ) N = 3 result = (a == 0) &amp; ( (a.shift(-1) == 1) | a.shift(-2) == 1) | a.shift(-3) == 1) ) How can I dynamically define this conditional using N as an input parameter in a nice (pythonic?) way?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49917331
answer count: 1
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49917331
tagged with: python
linked to: http://stackoverflow.com/q/20528328
has title: Creating a dynamic condition based on input parameter
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86895502
comment on: http://stackoverflow.com/q/49938731
type: Comment
type: QuestionComment
has text: Explicitly select nextval first and pass it along with the new objects? As an aside `nullable=False` and `index=True` are redundant on a primary key column.
score: 1

http://stackoverflow.com/a/50044981
has body: I don't think you need regex for this. You could do something like: s = 'this is a sentence of some sort' words = s.split() test = [w for w in words if len(w) &gt; 3] print(len(test) == len(words)) # False Or equivalently: s = 'this is a sentence of some sort' words = s.split() acceptable = lambda x: len(x) &gt; 3 print(len(words) == len(list(filter(acceptable, words)))) Or even: s = 'this is a sentence of some sort' words = s.split() res = all(len(word) &gt; 3 for word in words) print(res) Or, as @pault suggests: s = 'this is a sentence of some sort' all(len(w) &gt; 3 and w.islower() for w in s.split())
has comment: http://stackoverflow.com/comment/87106160
downvote count: 1
has comment: http://stackoverflow.com/comment/87106218
type: Answer
answers question: http://stackoverflow.com/q/50044830
has comment: http://stackoverflow.com/comment/87106184
score: 2
upvote count: 3

cisco
type: Tag
tags question: http://stackoverflow.com/q/49977032
tag name: cisco
tags question: http://stackoverflow.com/q/50015532

http://stackoverflow.com/q/50031690
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/87080210
has body: This is the JSON response I am getting from the server : { "0": { "pk": 41, "fields": { "heading": "Empty Lecture Slot", "notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00", "date": "2018-04-25", "priority": 1, "has_read": false, "action": "/dashboard/set_substitute/91959" }, "model": "Dashboard.specificnotification" } } Here is the Java code used for parsing this JSON object : JSONObject jsonObject = new JSONObject(response); This is the error I am getting in the catch block : org.json.JSONException: No value for {"0": {"pk": 41, "fields": {"heading": "Empty Lecture Slot", "notification": "There is a free lecture available right now for TE B on 2018-05-02 8:00-9:00", "date": "2018-04-25", "priority": 1, "has_read": false, "action": "/dashboard/set_substitute/91959"}, "model": "Dashboard.specificnotification"}} How do I parse this object in Android.
score: 3
upvote count: 3
has title: Django JsonResponse parsing error in Android
tagged with: android
has answer: http://stackoverflow.com/a/50031822
tagged with: java
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86993677
score: 4
comment on: http://stackoverflow.com/q/49988624
type: QuestionComment
has text: Post the code that you have so far and explain where you are stuck specifically.
type: Comment

http://stackoverflow.com/comment/87086230
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169821/discussion-between-spencer-and-eyllanesc).
comment on: http://stackoverflow.com/q/50034906
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50061724
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50061536
score: 1
has body: Well, you are close. Except for the last line. Here's what I did, following along with your code: import pandas as pd import numpy as np df = pd.DataFrame({"Date": ["9/26/17 2:33 PM", "9/26/17 2:23 PM", "9/26/17 2:22 PM"], "Receipt number": ["1-1002","1-1001","1-1000"], "Description": ["1 x Capacino, 2 x Americano","1 x Americano","1 x Latte"]}) df2 = df['Description'].str.split(',').apply(pd.Series, 1).stack() df2.index = df2.index.droplevel(-1) df2.name = 'Product' df = df.join(df2) # Here is where I diverge df['Units'] = df['Product'].apply(lambda x: int(x.split(' x ')[0])) df['Product'] = df['Product'].apply(lambda x: x.split(' x ')[-1]) df = df.drop('Description', axis=1) Result Date Receipt number Product Units 0 9/26/17 2:33 PM 1-1002 Capacino 1 0 9/26/17 2:33 PM 1-1002 Americano 2 1 9/26/17 2:23 PM 1-1001 Americano 1 2 9/26/17 2:22 PM 1-1000 Latte 1
accepted answer of: http://stackoverflow.com/q/50061536
type: AcceptedAnswer

http://stackoverflow.com/comment/86925192
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49952469
type: AnswerComment
has text: @SharvariGc - Can you explain more? The best is create new question or modify old with sample data and expected output. thanks.

http://stackoverflow.com/q/49959206
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49959272
has answer: http://stackoverflow.com/a/49959272
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
type: AnsweredQuestion
has title: Can Not Load Static Files in Django
upvote count: 0
answer count: 1
tagged with: django
has body: I am trying to add an image to a very basic html template. I am able to render the html file, but unfortunately the image will not display. Here is my error: Not Found: /exapp/pic.jpg [21/Apr/2018 18:43:49] "GET /exapp/pic.jpg HTTP/1.1" 404 2145 I noticed that django was looking for the file with a path of /exapp/pic.jpg, so I created a folder in my static directory called exapp, and put the image in there. Still no image :( the file structure is as follows: ─ db.sqlite3 ├── exapp │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-35.pyc │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-35.pyc │ │ ├── __init__.cpython-35.pyc │ │ ├── models.cpython-35.pyc │ │ ├── urls.cpython-35.pyc │ │ └── views.cpython-35.pyc │ ├── static │ │ └── exapp │ │ └── pic.jpg │ ├── templates │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── mysite ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-35.pyc │ ├── settings.cpython-35.pyc │ ├── urls.cpython-35.pyc │ └── wsgi.cpython-35.pyc ├── settings.py ├── urls.py └── wsgi.py Here is the HTML file in question: Hello world Look it worked {% load static %} Here is the settings file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tie19%e+ri*g3#54b)axh&!8rentwx)xnsjbk&kx09(10le%7a' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'exapp', ] MIDDLEWARE = [ 'django…
downvote count: 1

http://stackoverflow.com/q/49940759
type: Question
has title: VScode output displays paths, then code
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87219529
tagged with: python
has comment: http://stackoverflow.com/comment/87108428
has comment: http://stackoverflow.com/comment/87161103
has body: New to VScode and while I like it, I feel I may have either set something up wrong or its just slower than Atom or sublime3. When running simple code it takes around 5 seconds for this simple "Hello World" to display. Why does it display all the path nonsense and is that why it sees so slow? Any ways to tune this? Thanks! Visual studio Output: user_dev@DESKTOP-131452 MINGW64 ~/Documents/VSCODE/Python/BeautifulSoup $ cd "C:\Users\user_dev\Documents\VSCODE\Python\BeautifulSoup" ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" C:/Python3/python.exe "C:\Users\user_dev\. vscode\extensions\ms-python.python-2018.3.1\pythonFiles\PythonTools\visualstudio_py_launcher_nodebug.py" "C:\Users\user_dev\Documents\VSCODE\Python\BeautifulSou p" 55240 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput "c:\Users\user_dev\Documents\VSCODE\Python\BeautifulSoup\Training\example.py" Hello World Tried the same thing in Atom and its blazing fast, ATOM output: Hello World [Finished in 0.662s] Update: Code run above to get output: print("Hello World!") Python version: $ python --version Python 3.6.4
has comment: http://stackoverflow.com/comment/87161175
score: 0
tagged with: visual-studio-code
answer count: 0
has comment: http://stackoverflow.com/comment/87161088
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50012032
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
has title: Chaining together Python Iterators
answer count: 2
tagged with: iterator
downvote count: 0
type: UnansweredQuestion
has body: Trying to see if I can recursively generate an iterator of file paths. Essentially for a list of base paths and an ordered list of subdirs, I want to generate all child paths as a combination of the two inputs. i.e base_path = ["/a", "/b"], subdir_lists = [ ["1", "2"], ["c", "d"] ] then the output should be [ "/a", "/a/1", "/a/1/c", "/a/1/d", "a/2", "/a/2/c", "/a/2/d", "/b", "/b/1", ... "/b/2/d" ] My python code looks something like this. I'm calling appendpaths() recursively. def appendpaths(subdir_lists, base_path): if not subdir_lists or len(subdir_lists) == 0: return base_path if len(subdir_lists) == 1: return starmap(os.path.join, product(base_path, subdir_lists[0])) right = subdir_lists[1:] iter_list = [base_path, appendpaths(right, starmap(os.path.join, product(base_path, subdir_lists[0])))] return chain(*iter_list) def main(): subdir_lists = [["1", "2"], ["c", "d"]] it = appendpaths(subdir_lists, ["/a", "/b"]) for x in it: print(x) main() My output is missing a few permutations: /a /b /a/1/c /a/1/d /a/2/c /a/2/d /b/1/c /b/1/d /b/2/c /b/2/d You can see that I'm missing /a/1, /a/2, /b/1 and /b/2. I'm guessing it's because somewhere in my code I've already exhausted the generators that iterate through those permutations?
has comment: http://stackoverflow.com/comment/87040565
has comment: http://stackoverflow.com/comment/87040590
tagged with: recursion
tagged with: python-itertools
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/51413206
has answer: http://stackoverflow.com/a/50012814

http://stackoverflow.com/comment/86917275
type: Comment
type: QuestionComment
has text: Usual problem: You are plotting strings. If you want to show real dates, plot dates instead of strings. There are enough examples on that around.
score: 0
comment on: http://stackoverflow.com/q/49947615

http://stackoverflow.com/comment/87051205
comment on: http://stackoverflow.com/q/50017514
score: 0
type: QuestionComment
type: Comment
has text: Can you add Todo model?

http://stackoverflow.com/a/50020826
answers question: http://stackoverflow.com/q/50020504
downvote count: 0
type: Answer
score: 2
has body: Using regex : &gt;&gt;&gt; [re.sub('(?&lt;=\d)+ (?=\d)+', '', ele) for ele in l] This uses the concept of lookahead and lookbehind in regex. #driver functions : IN : ['2 47, Philiproad, London, uk', '12 4, Northhall, London, uk'] OUT : ['247, Philiproad, London, uk', '124, Northhall, London, uk']
upvote count: 2

http://stackoverflow.com/q/49942361
has title: Need help turning pandas dataframe into multiindex by grouping just one column.
tagged with: pandas
has body: I have a pandas dataframe df that looks like this: &gt;&gt;&gt;df group A B C 1 1 2 3 1 2 3 6 1 4 9 9 2 8 1 2 2 5 6 4 3 6 5 7 I would like it multi-indexed so it looks like group A B C 1 1 2 3 2 3 6 4 9 9 2 8 1 2 5 6 4 3 6 5 7 I'd like to access each group number gives me a dataframe of just the values for that group index. What I mean is if I type df[0] then I get &gt;&gt;&gt;df[0] A B C 1 2 3 2 3 6 4 9 9 and I can do the usual functions, like take the mean via df[0].mean() I'm sure this is possible but reading the pandas help pages and looking through forums seems to have solutions for people who already created multi-indexed dataframes with tuples.
score: 1
tagged with: dataframe
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49942407

http://stackoverflow.com/comment/87148746
comment on: http://stackoverflow.com/a/50064444
type: Comment
has text: what could I do to improve the way I composed the question?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87154268
type: Comment
comment on: http://stackoverflow.com/a/50068924
type: AnswerComment
has text: This cuts off YZ since the strings are of different lengths.
score: 0

http://stackoverflow.com/a/53651084
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/128535275
type: Answer
has body: To access an Ip Camera, first, I recommend you to install it like you are going to use for the standard application, without any code, using normal software. After this, you have to know that for different cameras, we have different codes. There is a website where you can see what code you can use to access them: https://www.ispyconnect.com/sources.aspx But be careful, for my camera (Intelbras S3020) it does not work. The right way is to ask the company of your camera, and if they are a good company they will provide it. When you know your code just add it like: cap = cv2.VideoCapture("http://LOGIN:PASSWORD@IP/cgi-bin/mjpg/video.cgi?&amp;subtype=1") Instead LOGIN you will put your login, and instead PASSWORD you will put your password. To find out camera's IP address there is many softwares that you can download and provide the Ip address to you. I use the software from Intelbras, but I also recommend EseeCloud because they work for almost all cameras that I've bought: https://eseecloud.software.informer.com/1.2/ In this example, it shows the protocol http to access the Ip camera, but you can also use rstp, it depends on the camera, as I said. If you have any further questions just let me know.
downvote count: 0
answers question: http://stackoverflow.com/q/49978705

keras
tags question: http://stackoverflow.com/q/49944010
tags question: http://stackoverflow.com/q/49931623
tags question: http://stackoverflow.com/q/49982438
tags question: http://stackoverflow.com/q/49920288
tags question: http://stackoverflow.com/q/49973379
tags question: http://stackoverflow.com/q/50065555
tags question: http://stackoverflow.com/q/49957659
tags question: http://stackoverflow.com/q/50023967
tags question: http://stackoverflow.com/q/50073924
tags question: http://stackoverflow.com/q/50010929
tags question: http://stackoverflow.com/q/50034754
tags question: http://stackoverflow.com/q/50019036
tags question: http://stackoverflow.com/q/49956945
tags question: http://stackoverflow.com/q/49985191
tags question: http://stackoverflow.com/q/49946681
tags question: http://stackoverflow.com/q/50031553
tags question: http://stackoverflow.com/q/50066396
tags question: http://stackoverflow.com/q/50013640
tags question: http://stackoverflow.com/q/49946942
tags question: http://stackoverflow.com/q/50036892
tags question: http://stackoverflow.com/q/49988950
tags question: http://stackoverflow.com/q/49945857
tags question: http://stackoverflow.com/q/49935778
tags question: http://stackoverflow.com/q/50033600
tags question: http://stackoverflow.com/q/49968105
tags question: http://stackoverflow.com/q/49926256
tags question: http://stackoverflow.com/q/49950865
tags question: http://stackoverflow.com/q/50005092
tags question: http://stackoverflow.com/q/50028127
tags question: http://stackoverflow.com/q/49959907
tags question: http://stackoverflow.com/q/49952712
tags question: http://stackoverflow.com/q/49986992
tags question: http://stackoverflow.com/q/49952714
tags question: http://stackoverflow.com/q/50061393
tags question: http://stackoverflow.com/q/50061187
tags question: http://stackoverflow.com/q/49964049
tags question: http://stackoverflow.com/q/49968000
tags question: http://stackoverflow.com/q/50041558
tags question: http://stackoverflow.com/q/50073216
tags question: http://stackoverflow.com/q/50033312
tags question: http://stackoverflow.com/q/49956664
tags question: http://stackoverflow.com/q/50010040
tags question: http://stackoverflow.com/q/49936002
tags question: http://stackoverflow.com/q/49926696
tags question: http://stackoverflow.com/q/49969398
tags question: http://stackoverflow.com/q/49937159
tags question: http://stackoverflow.com/q/49990882
tags question: http://stackoverflow.com/q/50054700
tags question: http://stackoverflow.com/q/50027424
tags question: http://stackoverflow.com/q/50073095
tags question: http://stackoverflow.com/q/50065411
tags question: http://stackoverflow.com/q/50007424
tags question: http://stackoverflow.com/q/50029027
tags question: http://stackoverflow.com/q/49960412
tags question: http://stackoverflow.com/q/49969006
tags question: http://stackoverflow.com/q/50033178
tags question: http://stackoverflow.com/q/49936467
tags question: http://stackoverflow.com/q/49977839
tags question: http://stackoverflow.com/q/49987631
tags question: http://stackoverflow.com/q/49998456
tags question: http://stackoverflow.com/q/50033090
tag name: keras
tags question: http://stackoverflow.com/q/50069725
tags question: http://stackoverflow.com/q/50047605
tags question: http://stackoverflow.com/q/50040056
tags question: http://stackoverflow.com/q/49930518
tags question: http://stackoverflow.com/q/50013714
tags question: http://stackoverflow.com/q/50050021
tags question: http://stackoverflow.com/q/50022256
tags question: http://stackoverflow.com/q/49947878
tags question: http://stackoverflow.com/q/50054419
tags question: http://stackoverflow.com/q/50054740
tags question: http://stackoverflow.com/q/49998364
tags question: http://stackoverflow.com/q/50023592
tags question: http://stackoverflow.com/q/49944822
tags question: http://stackoverflow.com/q/50049691
tags question: http://stackoverflow.com/q/50056356
tags question: http://stackoverflow.com/q/49924058
type: Tag
tags question: http://stackoverflow.com/q/50011999

http://stackoverflow.com/comment/87186409
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50026997
has text: If the indicator are same for individuals id then it's work fine.But my case indicator filed not for the same as their id.e.g.(id 14 has no indicator filed like' Common Shares Outstanding'. in this case it's will show Keyerror.ok it's fine if i set data[i]['Common Shares Outstanding'] =0 in try block .it set to zero and stop the iteration.How to handle this plz some suggestion.
type: Comment

algorithm
tags question: http://stackoverflow.com/q/50028327
type: Tag
tags question: http://stackoverflow.com/q/49956178
tag name: algorithm
tags question: http://stackoverflow.com/q/50029031
tags question: http://stackoverflow.com/q/49958256
tags question: http://stackoverflow.com/q/49948256
tags question: http://stackoverflow.com/q/50071280
tags question: http://stackoverflow.com/q/49923695
tags question: http://stackoverflow.com/q/50017494
tags question: http://stackoverflow.com/q/49963421
tags question: http://stackoverflow.com/q/50055848
tags question: http://stackoverflow.com/q/50049170
tags question: http://stackoverflow.com/q/50013311
tags question: http://stackoverflow.com/q/50069470
tags question: http://stackoverflow.com/q/49994216
tags question: http://stackoverflow.com/q/50030521
tags question: http://stackoverflow.com/q/49998457
tags question: http://stackoverflow.com/q/49923299
tags question: http://stackoverflow.com/q/49954197
tags question: http://stackoverflow.com/q/50009692
tags question: http://stackoverflow.com/q/49923960
tags question: http://stackoverflow.com/q/50001620
tags question: http://stackoverflow.com/q/50066757
tags question: http://stackoverflow.com/q/50064875

http://stackoverflow.com/comment/87045476
comment on: http://stackoverflow.com/a/49991933
has text: Thank you so much Peter I will follow up on the links and do some extra reading before approving your answer. Thanks again
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49990408
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/49990269
type: Answer
has comment: http://stackoverflow.com/comment/86997545
has body: Try using subplots. import matplotlib.pyplot as plt # Init subplots fig, axes = plt.subplots(1,1); # Init ax with the first plot. ax = df['Market Cap'].plot() # Plot second df using ax from the first plot. _ = df2['Market Cap'].plot(ax = ax) plt.show()

http://stackoverflow.com/q/50004209
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I have a python script that I want to be executed when I click a button on html page. I am using JQuery to do so. For some reason, it just doesn't do anything. Am I missing any permissions or some syntax? Not sure. I am using WebApp2 framework for my application. Here is the code. My python file is in same html directory where the template is. I am pretty new to coding, Any suggestions or help please.
has title: Run a python script in HTML button using JQuery
has comment: http://stackoverflow.com/comment/87200042
has comment: http://stackoverflow.com/comment/87025096
type: Question
tagged with: webapp2
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87033834
tagged with: javascript
tagged with: jquery
has comment: http://stackoverflow.com/comment/87024833

http://stackoverflow.com/comment/87093051
type: QuestionComment
has text: have you tried the `and` keyword, as in `if len(password) > 8 and password[0].isuuper() and hasNumbers(password):`
comment on: http://stackoverflow.com/q/50038442
score: 3
type: Comment

neural-network
tags question: http://stackoverflow.com/q/50063237
tags question: http://stackoverflow.com/q/49942873
tags question: http://stackoverflow.com/q/49977063
tags question: http://stackoverflow.com/q/50064333
type: Tag
tags question: http://stackoverflow.com/q/49968000
tags question: http://stackoverflow.com/q/50061579
tags question: http://stackoverflow.com/q/50014365
tags question: http://stackoverflow.com/q/49959727
tags question: http://stackoverflow.com/q/49932756
tags question: http://stackoverflow.com/q/49988496
tags question: http://stackoverflow.com/q/49982438
tags question: http://stackoverflow.com/q/49973379
tags question: http://stackoverflow.com/q/50008097
tags question: http://stackoverflow.com/q/50004805
tags question: http://stackoverflow.com/q/49951795
tags question: http://stackoverflow.com/q/50051988
tags question: http://stackoverflow.com/q/49998456
tags question: http://stackoverflow.com/q/49956945
tags question: http://stackoverflow.com/q/50023592
tags question: http://stackoverflow.com/q/50037172
tags question: http://stackoverflow.com/q/49969957
tags question: http://stackoverflow.com/q/50026996
tags question: http://stackoverflow.com/q/49940110
tags question: http://stackoverflow.com/q/50065484
tags question: http://stackoverflow.com/q/49978307
tags question: http://stackoverflow.com/q/50041558
tags question: http://stackoverflow.com/q/50051281
tags question: http://stackoverflow.com/q/49958888
tags question: http://stackoverflow.com/q/49937159
tags question: http://stackoverflow.com/q/50010847
tags question: http://stackoverflow.com/q/49990882
tags question: http://stackoverflow.com/q/50023967
tags question: http://stackoverflow.com/q/49988009
tags question: http://stackoverflow.com/q/50027652
tags question: http://stackoverflow.com/q/49944362
tags question: http://stackoverflow.com/q/49971092
tag name: neural-network
tags question: http://stackoverflow.com/q/49993776
tags question: http://stackoverflow.com/q/49987614
tags question: http://stackoverflow.com/q/50042925
tags question: http://stackoverflow.com/q/50040056
tags question: http://stackoverflow.com/q/49947878
tags question: http://stackoverflow.com/q/49951492

http://stackoverflow.com/a/50011709
type: AcceptedAnswer
score: 0
has body: Based on @DisneylandSC's response- below is the updated working template: &lt;div class="card"&gt; &lt;div class="card-body"&gt; {% regroup object.rate_set.order_by by frequency as frequency_list %} &lt;ul class="collapsible popout"&gt; {% for frequency in frequency_list %} &lt;li&gt; &lt;div class="collapsible-header"&gt; &lt;i class="material-icons"&gt;view_day&lt;/i&gt;{{ frequency.grouper }}&amp;nbsp;Frequency Rate &lt;/div&gt; &lt;div class="collapsible-body"&gt; &lt;div class="table-responsive card-text"&gt; &lt;table class="table highlight"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Product&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for item in frequency.list %} &lt;tr&gt; &lt;td&gt; &lt;a class="nav-link" href="#"&gt; {{ item.product }} &lt;/a&gt; &lt;/td&gt; &lt;td&gt;${{ item.price }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt;
accepted answer of: http://stackoverflow.com/q/50008337
type: Answer
answers question: http://stackoverflow.com/q/50008337

http://stackoverflow.com/q/50014126
tagged with: imagenet
tagged with: python
type: UnansweredQuestion
score: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/90097244
has answer: http://stackoverflow.com/a/67129268
has comment: http://stackoverflow.com/comment/107265599
answer count: 2
downvote count: 0
has body: I compiled the files with the following command. protoc object_detection/protos/*.proto --python_out=. and as a result compiled into .py files. However, I received the following error code. ~/Documents/imgmlreport/inception/classification_inception/models/research/object_detection/utils/label_map_util.py in () 20 import tensorflow as tf 21 from google.protobuf import text_format ---&gt; 22 from object_detection.protos import string_int_label_map_pb2 23 24 ImportError: cannot import name 'string_int_label_map_pb2' so i checked utils and i already had a string_int_label_map_pb2.py why can't import string_int_label_map_pb2.py ?
has title: ImportError: cannot import name 'string_int_label_map_pb2'
upvote count: 7
tagged with: tensorflow
has answer: http://stackoverflow.com/a/75279018
type: Question
has comment: http://stackoverflow.com/comment/93027660

http://stackoverflow.com/q/50068613
tagged with: flask
tagged with: flask-sqlalchemy
linked to: http://stackoverflow.com/q/10325683
has comment: http://stackoverflow.com/comment/87154030
has comment: http://stackoverflow.com/comment/87153879
has comment: http://stackoverflow.com/comment/87166793
answer count: 0
has comment: http://stackoverflow.com/comment/87153966
has comment: http://stackoverflow.com/comment/87169357
score: 1
has comment: http://stackoverflow.com/comment/87153644
has comment: http://stackoverflow.com/comment/87170023
has title: flask sqlalchemy OperationalError: unable to open database file
has body: I have a flask rest API. there is a function which repeats every minute and updates the database(sqlite3). It works for a while but after some time API gets unresponsive and won't respond to requests. I think this function makes the API unresponsive. I can see the error mentioned in the question title. Am I doing anything wrong here? Any help is appreciated. from flask import Flask from flask_sqlalchemy import SQLAlchemy import threading app = Flask(__name__) db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True . . . def UpdateStatus(): threading.Timer(60, UpdateStatus).start() messages = Message.query.filter((Message.status != 'Seen')).all() for msg in messages: try: messageid= msg.messageid wamessageid= msg.wamessageid timestamp= datetime.now() result= driver.get_message_status(wamessageid) if result==1: status='Sent' api_response= 'OK: Message sent' elif result==2: status= 'Delivered' api_response= 'OK: Message Delivered' elif result==3: status= 'Seen' api_response= 'OK: Message Seen' message = Message.query.filter_by(messageid = messageid).first() if message.status!= status: message.status= status message.apiresponse= api_response if status== 'Delivered': message.timestamp_delivered= timestamp if status== 'Seen': if message.timestamp_delivered is None: message.timestamp_delivered= timestamp message.timestamp_seen= timestamp db.session.commit() except: traceback.print_exc() continue
favorite count: 0
has comment: http://stackoverflow.com/comment/87153696
type: Question
has comment: http://stackoverflow.com/comment/87153932
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87169508
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87170687

http://stackoverflow.com/comment/87087047
score: 0
type: Comment
type: QuestionComment
has text: Please show the complete code of LR with cross-validation.
comment on: http://stackoverflow.com/q/50031733

http://stackoverflow.com/q/49957335
score: 4
has comment: http://stackoverflow.com/comment/86930976
tagged with: caching
has body: I am trying to figure out a good way to cache the results of a method call across different instances of an object. I can modify the memoize decorator to remove the first argument (which is always self) of the method call, or I can remove the core of the method from the class and create a new function and then have the method call the new function (and memoize that function). I'm looking for guidance on this. Maybe there is something I have missed or another solution. In this example expensive_calc() is a static method, but in my application it is not. Assume that it will always return the same data regardless of the object properties as long as the function parameters are the same. Also given how my application is designed, it is much more convenient to keep it as a class function. from time import sleep class Test(object): def expensive_calc(self, arg, kwarg1): sleep(5) obj1 = Test() obj2 = Test() obj1.expensive_calc(1, kwarg1=1) obj2.expensive_calc(1, kwarg1=1) # Would like this use the cache
tagged with: function
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/93820216
has title: cache/memoize method call across different instances objects python
has comment: http://stackoverflow.com/comment/86932096
favorite count: 0
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/86934428
type: UnansweredQuestion
tagged with: memoization
has comment: http://stackoverflow.com/comment/86932396
tagged with: python
has answer: http://stackoverflow.com/a/62706472

http://stackoverflow.com/comment/86967997
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49975388
has text: Ah yes you are right! Didn't though of negation. It would definitely suffer the readability.
score: 0

http://stackoverflow.com/q/49999610
accepted answer: http://stackoverflow.com/a/49999849
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87015372
upvote count: 2
score: 2
answer count: 2
downvote count: 0
tagged with: pandas
has body: I have 2 simple DataFrames I need to merge. Both have one column in common and I want to use this column as index. &gt;&gt;&gt; df1 A B a b 0 0 3 1 1 4 2 2 5 &gt;&gt;&gt; df2 A C a c 0 2 6 1 1 7 2 0 8 And I want something like &gt;&gt;&gt; df A B C a b c 0 0 3 6 1 1 4 7 2 2 5 8 This does not work df1.merge(df2, left_on=(('A','a')), right_on=(('A','a')))
favorite count: 0
has title: Merge DataFrame by Mutliindex column
type: Question
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50012939
has answer: http://stackoverflow.com/a/50012939
has comment: http://stackoverflow.com/comment/87015257
has answer: http://stackoverflow.com/a/49999849

http://stackoverflow.com/a/49997887
type: Answer
has body: Special method for == and !=: class Obj: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, Object): """ == comparison method.""" return self.x == Object.x and self.y == Object.y def __ne__(self, Object): """ != comparison method.""" return not self.__eq__(self, Object)
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87012137
downvote count: 1
has comment: http://stackoverflow.com/comment/87012048
answers question: http://stackoverflow.com/q/49997804

http://stackoverflow.com/q/50038805
has title: Python SQLite - Update Not running
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87094100
score: 1
tagged with: sqlite
tagged with: python
has body: I'm running a python script to run a SQLite code, which is successful until I get a specific Update query (create, inserts, drops run successfully). Please note that this same code runs successfully in SQLiteExpert and when I run it in python there is no error message, the scripts simply does not pass that line and runs indefinitely. I've looked into the documentation and searched for answers but I had no success. Wonder if anyone might help me with this one. import sqlite3 # Some more code conn.commit() c.execute("""UPDATE TABEL_A SET FIELD_2 = (SELECT FIELD_X FROM TABEL_B B WHERE B.FIELD_Y = FIELD_1) WHERE FIELD_3 = "A";""") conn.commit() Thanks in advance!
has answer: http://stackoverflow.com/a/50139021
has comment: http://stackoverflow.com/comment/87111620
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87093849

http://stackoverflow.com/q/49943410
linked to: http://stackoverflow.com/q/49324802
has answer: http://stackoverflow.com/a/50159539
has answer: http://stackoverflow.com/a/74963866
has answer: http://stackoverflow.com/a/72465693
has comment: http://stackoverflow.com/comment/86903626
has comment: http://stackoverflow.com/comment/86903292
type: AnsweredQuestion
answer count: 14
linked to: http://stackoverflow.com/q/25981703
possible better answer: http://stackoverflow.com/a/63182788
has answer: http://stackoverflow.com/a/67653437
has answer: http://stackoverflow.com/a/67234195
has answer: http://stackoverflow.com/a/52286163
downvote count: 0
has answer: http://stackoverflow.com/a/70958933
score: 23
has answer: http://stackoverflow.com/a/65637839
tagged with: pip
has answer: http://stackoverflow.com/a/49944070
has comment: http://stackoverflow.com/comment/86903334
upvote count: 23
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53291609
linked to: http://stackoverflow.com/q/49768770
has title: Pip SSL Error on Windows
has answer: http://stackoverflow.com/a/63182788
has answer: http://stackoverflow.com/a/64085327
has body: I use Python 3.x on Windows 7 64 bit in an environment without full control of inbound/outbound traffic processing. Up till this week I've been able to use the --trusted-host pypi.python.org flag with pip and everything worked. This week I have started getting the following error even with the --trusted-host flag. Could not fetch URL https://pypi.python.org/simple/pytubes/: There was a probl em confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:720) - skipping I tried changing the --trusted-host flag to https://files.pythonhosted.org/packages/ in light of the pypi change this week, but that didn't seem to help. I also tried downloading and installing the wheels of certifi, wincerstore and win32 certifi as well as other stackoverflow suggestions for this kind of issue such as the digistore .pem cert and pip.ini file without any success. pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)" Finally I tried upgrading pip to pip 10 from pip 9.0.3 following the instructions here: https://pip.pypa.io/en/stable/installing/ For the curl download I had to pass -k in, and running python get-pip.py fails with a similar ssl error to pip: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)': /simple/pip/ Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)) - skipping Could not find a version that satisfies the requirement pip (from versions: ) No matching distribution found for pip Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certif…
tagged with: windows
has answer: http://stackoverflow.com/a/75910496
tagged with: ssl
tagged with: python
accepted answer: http://stackoverflow.com/a/50159539
has answer: http://stackoverflow.com/a/78476739

http://stackoverflow.com/q/49941467
type: UnansweredQuestion
tagged with: odoo
tagged with: python
has body: When I Import xlwt directly just Example , try: import xlwt from xlwt import Borders except ImportError: xlwt = None then working fine with workbook = xlwt.Workbook() But when I used the python lib for xlwt :~ https://pypi.org/project/xlwt/#files and put into custom like this from odoo.addons.inventory.python_lib import xlwt and calling the workbook = xlwt.Workbook() That time error popup AttributeError: 'NoneType' object has no attribute 'Workbook' So how to solve this
tagged with: odoo-11
has answer: http://stackoverflow.com/a/49942037
tagged with: xlwt
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Give the Attribute Error while importing xlwt

http://stackoverflow.com/comment/87031756
comment on: http://stackoverflow.com/a/50007397
type: Comment
score: 0
type: AnswerComment
has text: ‘list.remove(x)’ works well both on strings and integers. So if-else clause here is redundant.

http://stackoverflow.com/comment/87150890
type: Comment
type: QuestionComment
has text: you can remove your kron - looks like it is taken care off by broadcasting: `aux = np.abs(selectedInput - np.array(w[N - 2]))`
score: 0
comment on: http://stackoverflow.com/q/50066194

http://stackoverflow.com/a/50025373
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87089024
has comment: http://stackoverflow.com/comment/87122927
has body: There are many ways to do this. Assuming you want to do this all the time, the easiest way to do this might be to annotate the test module with: # turns all warnings into errors for this module pytestmark = pytest.mark.filterwarnings('error') Reference: https://docs.pytest.org/en/latest/warnings.html#pytest-mark-filterwarnings
type: Answer
answers question: http://stackoverflow.com/q/50025165

http://stackoverflow.com/a/49978612
has comment: http://stackoverflow.com/comment/86986687
answers question: http://stackoverflow.com/q/49971317
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86990882
has body: Going down the Tree Suggestion, please review quickly the Official BeautifulSoup Documentation HERE from bs4 import BeautifulSoup xml = ''' person head 337 2 382 66 334 1 436 373 ''' soup = BeautifulSoup(xml, 'lxml') print(soup.find('name')) # or # only string > print(soup.find('name').text) print(soup.part.bndbox.xmin) # we traverse through the tree >part>bndbox>xmin print(soup.xmin) Will return the same because it gives back the first occurrence of the tag print(soup.find('xmin')) # is the same as soup.xmin To find multiple same tag, specifically the second one: bnxboxes = soup.find_all('bndbox') # # we can either iterate through it or print(bnxboxes[1]) # the Second occurence of tag (computer counting 0,1,2..) We can also Go up the Tree Continuing the “family tree” analogy, every tag and every string has a parent: the tag that contains it. the_xmin_tag = soup.xmin # we find the xmin tag print(the_xmin_tag.parent) We can also Go sideways using `.next_sibling` and `.previous_sibling`
score: 1
type: Answer

http://stackoverflow.com/q/49928463
has answer: http://stackoverflow.com/a/49928647
accepted answer: http://stackoverflow.com/a/49928776
has answer: http://stackoverflow.com/a/49928720
has answer: http://stackoverflow.com/a/49928776
has answer: http://stackoverflow.com/a/49928660
answer count: 10
favorite count: 0
upvote count: 72
score: 72
has answer: http://stackoverflow.com/a/49929147
type: Question
possible better answer: http://stackoverflow.com/a/49928647
has answer: http://stackoverflow.com/a/61902959
has title: Python Pandas update a dataframe value from another dataframe
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49928542
has body: I have two dataframes in python. I want to update rows in first dataframe using matching values from another dataframe. Second dataframe serves as an override. Here is an example with same data and code: DataFrame 1 : DataFrame 2: I want to update update dataframe 1 based on matching code and name. In this example Dataframe 1 should be updated as below: Note : Row with Code =2 and Name= Company2 is updated with value 1000 (coming from Dataframe 2) import pandas as pd data1 = { 'Code': [1, 2, 3], 'Name': ['Company1', 'Company2', 'Company3'], 'Value': [200, 300, 400], } df1 = pd.DataFrame(data1, columns= ['Code','Name','Value']) data2 = { 'Code': [2], 'Name': ['Company2'], 'Value': [1000], } df2 = pd.DataFrame(data2, columns= ['Code','Name','Value']) Any pointers or hints?
has answer: http://stackoverflow.com/a/63196845
has answer: http://stackoverflow.com/a/61418863
has answer: http://stackoverflow.com/a/62871265
tagged with: pandas
type: AnsweredQuestion
downvote count: 0

network-programming
tags question: http://stackoverflow.com/q/49988706
tag name: network-programming
tags question: http://stackoverflow.com/q/50034650
tags question: http://stackoverflow.com/q/50060219
tags question: http://stackoverflow.com/q/50033944
tags question: http://stackoverflow.com/q/49956275
tags question: http://stackoverflow.com/q/50041089
tags question: http://stackoverflow.com/q/50058209
tags question: http://stackoverflow.com/q/50031699
tags question: http://stackoverflow.com/q/50055935
tags question: http://stackoverflow.com/q/49959942
type: Tag
tags question: http://stackoverflow.com/q/49979354
tags question: http://stackoverflow.com/q/50062020
tags question: http://stackoverflow.com/q/50040023

http://stackoverflow.com/comment/87042413
has text: It should work under Python 2. What is the error you're getting?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50012848
type: QuestionComment

http://stackoverflow.com/comment/86943184
comment on: http://stackoverflow.com/a/49963520
type: AnswerComment
has text: @prabhakar - There is no `NaN`, so no replace. But maybe missing, what you think. Can you explain more?
score: 0
type: Comment

http://stackoverflow.com/q/49926751
has answer: http://stackoverflow.com/a/49926823
has body: I recently started coding in Python. In the beginning of my scripts I always have the following import: import numpy as np. In one of my scripts, I use np.matlib.repmat function. It used to work ok, however recently it fails to run showing the following error: AttributeError: module 'numpy' has no attribute 'matlib' I searched SO for this problem, and it looks like the error like this arises if one has a script called numpy.py in his working directory or if the installed version is different and does not contain the called module. I didn't name any file numpy.py. I also found out that after I call: from numpy import matlib as mb I can use mb.repmat. Therefore, my numpy module does contain matlib module. Can someone hint me, why I cannot call np.matlib?
score: 10
duplicate of: http://stackoverflow.com/q/41818379
tagged with: python
tagged with: module
has title: AttributeError: module 'numpy' has no attribute 'matlib'
upvote count: 11
tagged with: numpy
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/49926823
downvote count: 1
linked to: http://stackoverflow.com/q/41818379
favorite count: 0
type: Question

http://stackoverflow.com/comment/136935032
score: 0
comment on: http://stackoverflow.com/a/59208661
type: Comment
type: AnswerComment
has text: What about passing global_var as a parameter, if only read is needed? Like `delayed(populate)(idx, global_var)`

http://stackoverflow.com/comment/87107915
has text: It worked! didnt need the data, so deleting the data in the db was alright. thanks yall
type: Comment
comment on: http://stackoverflow.com/a/50045097
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86964029
type: Comment
type: AnswerComment
score: 0
has text: Thank you @Nazkter. Now I want upload two different types files for above edited html.Now,Help me with this html to upload two different type of file
comment on: http://stackoverflow.com/a/49973935

http://stackoverflow.com/comment/86868383
type: Comment
score: 1
type: AnswerComment
has text: Frankly, `[:]`, which is a list slice with all parameters set to default, is a shallow copy; for more difficult cases, module `copy` exists with `deepcopy` function. (Treating structures as immutable is generally even better.)
comment on: http://stackoverflow.com/a/49925634

http://stackoverflow.com/q/50007512
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50007555
upvote count: 2
has answer: http://stackoverflow.com/a/50007555
answer count: 1
downvote count: 0
has title: Getting all groups when using pd.Grouper in Pandas
type: Question
tagged with: pandas
tagged with: grouping
tagged with: python
has body: I have a dataframe like that: zone date a b AL 2014-01-31 8.88 3286.6 AL 2014-01-31 0.61 1047.105 BS 2014-01-27 1.59 145.283 RF 2014-01-31 2.67 2842.35 RF 2014-01-31 3.4 0.26 I want to group by month and zone df.iloc[:, 1] = pd.to_datetime(df.iloc[:, 1]) g = df.groupby(['zone', pd.Grouper(key='date', freq='M')]) If I use pd.Grouper there's just one zone &gt;&gt;&gt; g.groups.keys() dict_keys([('AL', Timestamp('2014-01-31 00:00:00'))]) If I don't use pd.Grouper all the zones are there: g = df.groupby('zone') &gt;&gt;&gt;&gt; g.groups.keys() dict_keys(['AL', 'BS', 'RF']) I would like to get all the zones grouped by month so that the result would be something like: &gt;&gt;&gt;&gt; g.groups.keys() dict_keys([('AL', Timestamp('2014-01-31 00:00:00')), ('BS', Timestamp('2014-01-31 00:00:00')), ('RF', Timestamp('2014-01-31 00:00:00'))]) It's my very first question in here so if I can make it better please tell me how.
favorite count: 0

http://stackoverflow.com/a/50018977
has comment: http://stackoverflow.com/comment/87054161
has body: Using an iteration. You can use map to convert all elements of list to float. Ex: res = [] with open(filename2) as infile: for line in infile: line = line.strip() res.append(map(float, line.split())) print(res) Output: [[1.0, 2.0, 3.0, 4.0], [3.0, 5.0, 6.0, 7.0], [2.0, 8.0, 9.0, 10.0]]
has comment: http://stackoverflow.com/comment/87054200
has comment: http://stackoverflow.com/comment/87053995
score: 1
has comment: http://stackoverflow.com/comment/87060080
answers question: http://stackoverflow.com/q/50018857
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/50045061
has title: TensorFlow not playing nicely with IPython
favorite count: 0
has answer: http://stackoverflow.com/a/50047139
score: 1
has body: I'm trying to use TensorFlow from an IPython notebook. I've created a function that defines a placeholder an a variable. Since I'm a TensorFlow newbie, I did not initialize the variable properly and got an error saying I did not initialize a placeholder. I have two cells, one with the function and one with a function call. No matter how much I fix the function (and rerun both cells, of course) I keep getting initialization errors even after I fix the bug. The only way to get it to work is to restart the kernel, which pretty much beats the purpose of a notebook, I can just write a Python script.
tagged with: ipython
tagged with: tensorflow
tagged with: jupyter-notebook
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

mode
tags question: http://stackoverflow.com/q/49944615
tag name: mode
type: Tag

http://stackoverflow.com/q/50050235
has comment: http://stackoverflow.com/comment/88191380
favorite count: 0
has title: How to setup python project using pybuilder and behave
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88191279
has comment: http://stackoverflow.com/comment/88191341
tagged with: python-behave
tagged with: python
tagged with: pybuilder
score: 2
upvote count: 2
has body: I'm new to python and I'm kind of lost here, I have a gherkins project in lettuce but I found i am creating a project using behave. I created these files and folders: features features &gt; steps features &gt; steps &gt; example.py features &gt; environment.pys features &gt; example.feature Then while I was running it, I found it didn't had the dependencies needed, because I'm getting this error: ModuleNotFoundError: No module named 'pynput' So, I looked for a build tool for python and found pybuilder that seems like a good choice, so I created a build.py like this: from pybuilder.core import init, use_plugin, task from subprocess import call use_plugin("python.core") use_plugin("python.install_dependencies") default_task = "behave" @init def initialize(project): project.depends_on("pynput") @task def behave(project): call(["behave"]) But the problem persists it doesn't pick the dependency on "pynput" and I'm still getting the same error, and I found that other sites use a file requirements.txt for dependencies instead, and I'm not sure if its possible but I would prefer to use the pybuild structure for a project and that's the reason nothing is working, something like this: src src &gt; test src &gt; test &gt; python src &gt; test &gt; python &gt; example.py src &gt; test &gt; features src &gt; test &gt; features &gt; example.feature Is this possible? or should I use a different build tool for behave? and why haven't I been able to import dependencies? Thanks
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/86999778
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49990812
score: 0
has text: Updated question. I appreciate the help.

http://stackoverflow.com/comment/87056797
comment on: http://stackoverflow.com/q/50020436
score: 0
has text: vmonteco Thanks for your comment. I have edited and added the result
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87237197
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50072756
type: Comment
has text: I still can't figure out how to match the files with the given regex if -name is called. It works when I call it like `./find.py ../directory` but when I do `./find.py ../directory -name [a-z]` its telling me `./find.py: No match.`

http://stackoverflow.com/q/50017017
type: Question
has title: what if i have only one document and i want to get vectors of all sentences using doc2vec
has comment: http://stackoverflow.com/comment/87050317
has comment: http://stackoverflow.com/comment/87050376
has body: I am new to python and machine learning. I have a file(kkk.csv). this has 101 sentences 1 sentence per line . I want to get each sentence's vector using Doc2vec in gensim. After that i want to use those vectors to perform clustering so that same sentences will group together. Can someone please provide me code for this(getting vectors for each sentence and clustring them)? i tried with this code: import matplotlib.pyplot as plt from sklearn.cluster import KMeans #from sklearn.feature_extraction.text import TfidfVectorizer import gensim,logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from os import listdir docLabels = [] docLabels = [f for f in listdir('''C:/Users/rekhasharma/new''') if f.endswith('.csv')] import pandas as pd df = pd.read_csv('''C:/Users/rekhasharma/kkk.csv''',names = ['comments']) rows = 100 df = df.iloc[:rows] list1 = df.values.tolist() del list1[0] class LabeledLineSentence(object): def __init__(self, doc_list, labels_list): self.labels_list = labels_list self.doc_list = doc_list def __iter__(self): for idx,doc in enumerate(self.doc_list): yield gensim.models.doc2vec.LabeledSentence(doc,self.labels_list) it = LabeledLineSentence(list1, docLabels) model = gensim.models.Doc2Vec(vector_size=50, min_count=0, alpha=0.025, min_alpha=0.025) model.build_vocab(it) for epoch in range(100): print ('iteration' + str(epoch+1)) model.train(it,total_examples=49, total_words=None, epochs=1) model.alpha = 0.002 model.min_alpha = model.alpha model.save('doc2vec.model') d2v_model = gensim.models.doc2vec.Doc2Vec.load('doc2vec.model') docvec = d2v_model.docvecs[0] print (docvec)
has answer: http://stackoverflow.com/a/50018250
upvote count: 0
answer count: 1
downvote count: 3
tagged with: machine-learning
tagged with: python
type: UnansweredQuestion
score: -3
favorite count: 0
has comment: http://stackoverflow.com/comment/87053169

http://stackoverflow.com/q/49972718
tagged with: types
downvote count: 0
has answer: http://stackoverflow.com/a/64205401
has comment: http://stackoverflow.com/comment/87000836
favorite count: 0
has body: I have a large Pandas dataframe that I've imported from a SQL database. The whole process takes several hours. As I work on the data, inevitably the dataframe gets altered and I regularly want to go back to 'a known good dataset' and re-run various functions. Instead of importing the data from the database, I want to save the data at various points of the analysis process as CSV files which can then be used to restore the data as required; CSV is the format of choice because, for some reason, I haven't had much luck with pickling the dataframes. Simply importing the CSV data using pd.read_csv() alters the datatypes of the columns. As a result, I want to create a dictionary of dtypes which can be used to restore the data types when importing the CSV back into a dataframe. As an example, a simple dataframe may be defined as shown below: df = pd.DataFrame({'A':[1,2,3,4,5],'B':['a','b','c','d','e'],'C':[1.2,3.4,5.6,7.8,9.0]},index=[0,2,4,6,8]) which looks like: A B C 0 1 a 1.2 2 2 b 3.4 4 3 c 5.6 6 4 d 7.8 8 5 e 9.0 A dictionary of dtypes can be created using: dtypesDict = df.dtypes.to_dict() which produces: {'B': dtype('O'), 'C': dtype('float64'), 'A': dtype('int64')} If I try to use this output to define a dictionary in hard-code so it can be used to set the data types for the columns which are imported using pd.read_csv(), it fails as follows: dtypesDict = {'B': dtype('O'), 'C': dtype('float64'), 'A': dtype('int64')} NameError: name 'dtype' is not defined However, defining the dictionary as: dtypesDict = {'B': 'O', 'C': 'float64', 'A': 'int64'} allows the CSV file to be imported with no problems. I thought a dictionary comprehension was the way to go but I can't make that work: dtypesDict = {k:bit_in_brackets_of_v for k,v in df.dtypes.to_dict().items()} How can I automatically produce a dictionary of the correct format that can be defined in hard-code using cut a simple cut-and-paste process and will allow dtypes of columns imported from a CSV to be set correctly?
upvote count: 4
has title: Get dictionary of dtypes as read in by Pandas read_csv()
type: Question
answer count: 2
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49972764
has answer: http://stackoverflow.com/a/49972764
score: 4
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/64205401
type: AnsweredQuestion

http://stackoverflow.com/q/49927690
possible better answer: http://stackoverflow.com/a/49927814
has comment: http://stackoverflow.com/comment/86871827
has comment: http://stackoverflow.com/comment/86872649
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86872585
has title: How do I print multiple lines after a for loop matches an if statement?
has answer: http://stackoverflow.com/a/49928130
has answer: http://stackoverflow.com/a/49927840
has comment: http://stackoverflow.com/comment/86872031
tagged with: python
has comment: http://stackoverflow.com/comment/86871435
has comment: http://stackoverflow.com/comment/86871854
answer count: 4
has body: I am trying to parse a large text document. I am wanting to extract information from this document by using this code, enumerated_journal = "" with open('journal.0028.txt', 'r') as file_object: for line in enumerate(file_object.readlines()): enumerated_journal += str(line) + "\n" for line in enumerated_journal.splitlines(): if "jrn." in line.lower() and "username" in line.lower(): print(line) This code is finding the line in the text document that contains the two strings that I am using as filters. I am wanting to know how to print the lines that precede or follow this line for a set number of lines. For example, if print(line) returns, "Username: Christian" I would like to print the lines before and after this line. "User Data:" "Username: Christian" "Age: 23" "Location: Texas" I appreciate the help in advance! Let me know if I need to clarify anything.
has comment: http://stackoverflow.com/comment/86871475
has comment: http://stackoverflow.com/comment/86872028
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86871399
has comment: http://stackoverflow.com/comment/86871517
has comment: http://stackoverflow.com/comment/86872270
has comment: http://stackoverflow.com/comment/86872382
has comment: http://stackoverflow.com/comment/86871434
has answer: http://stackoverflow.com/a/49927730
accepted answer: http://stackoverflow.com/a/49928130
has answer: http://stackoverflow.com/a/49927814

http://stackoverflow.com/a/49968114
has comment: http://stackoverflow.com/comment/87001736
accepted answer of: http://stackoverflow.com/q/49961977
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49961977
has body: You don't need to reformat anything. Each row is a 60 dimensional vector of continous values with a comparable scale (coordinates), as needed for k-means. You can just run k-means on this. But assuming that the measurements were taken in sequence, you may observe a strong correlation between rows, so I wouldn't expect the data to cluster extremely well, unless you set up the use to do and hold certain poses.
type: Answer

http://stackoverflow.com/q/49998519
tagged with: image
has title: which imresize is fastest in Python
tagged with: interpolation
score: 0
has comment: http://stackoverflow.com/comment/87013244
has answer: http://stackoverflow.com/a/52720246
answer count: 1
has body: Currently, we need a interpolation in a Image. I have used the scipy.misc.imresize. This function has two drawback: it can only output interger matrix, but I need a float result. the speed of scipy.misc.imresize is a little slow
type: Question
tagged with: performance
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87027559
tagged with: python

http://stackoverflow.com/comment/93027660
type: QuestionComment
comment on: http://stackoverflow.com/q/50014126
has text: Did you fix this?
score: 0
type: Comment

http://stackoverflow.com/comment/87132055
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50057604
type: AnswerComment
has text: be careful with this `eval()`. It has really great potential!

http://stackoverflow.com/q/50042925
tagged with: classification
tagged with: neural-network
downvote count: 0
tagged with: softmax
tagged with: machine-learning
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/87105193
type: UnansweredQuestion
tagged with: python
has title: Softmax neural net works with error in implementation, does not work with correct implementation
has body: I have been trying to fix this problem for several days, with no luck. I have been implementing a simple neural net with a single hidden layer from scratch, just for my own understanding. I have successfully implemented it with sigmoid, tanh and relu activations for binary classifications, and am now attempting to use softmax at the output for multi-class classifications. In every tutorial I have come across for a softmax implementation, including my lecturer's notes, the derivative of the softmax cross entropy error at the output layer is simplified down to just predictions - labels, thus essentially subtracting 1 from the predicted value at the position of the true label. However, I found that if this was used, then the error of my network would continuosuly increase until it converged to always predicting one random class with 100%, and the other with 0%. Interestingly, if I change this to labels - predictions, it works perfectly on my simple test of learning the binary XOR function below. Unfortunately, if I then attempt to the apply the same network to a more complex problem (hand-written letters - 26 classes), it again converges to outputting one class with 100% probability very quickly when either labels - predictions or predictions - labels is used. I have no idea why this incorrect line of code works for the simple binary classification, but not for a classification with many classes. I assume that I have something else backwards in my code, and this incorrect change is essentially reversing this other error, but I cannot find where this may be. import numpy as np class MLP: def __init__(self, numInputs, numHidden, numOutputs): # MLP architecture sizes self.numInputs = numInputs self.numHidden = numHidden self.numOutputs = numOutputs # MLP weights self.IH_weights = np.random.rand(numInputs, numHidden) # Input -&gt; Hidden self.HO_weights = np.random.rand(numHidden, numOutputs) # Hidden -&gt; Output # Gradients corresponding to weight matrices computed durin…
answer count: 0
has comment: http://stackoverflow.com/comment/87105097
upvote count: 3

http://stackoverflow.com/q/49990758
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86998130
score: 0
has comment: http://stackoverflow.com/comment/87042530
tagged with: pandas
has comment: http://stackoverflow.com/comment/86999179
has comment: http://stackoverflow.com/comment/87002460
answer count: 1
has answer: http://stackoverflow.com/a/49991698
type: Question
has comment: http://stackoverflow.com/comment/87041408
has body: I'm trying to calculate the crime rate per 100,000 population using values from two separate pivot table dataframes. Crime Total Year 2010 2011 2012 2013 2014 2015 2016 CountyName Alameda 12115 11971 13412 12327 10944 10463 11410 Alpine 355 481 200 174 125 202 165 Amador 2572 3033 2525 2390 2087 1856 2064 Butte 5966 5988 5459 5533 5085 6542 6324 Calaveras 3236 4606 4586 4162 4055 3276 3012 Colusa 1219 1325 1322 1406 817 763 850 Contra Costa 966 1032 1100 857 759 775 7553 Del Norte 1923 2388 2229 1791 2140 2190 2048 El Dorado 10259 11126 10305 10173 9938 9956 10394 Fresno 688 654 698 803 470 693 20858 Glenn 841 769 1130 1862 1203 876 775 Humboldt 7087 5684 5428 5649 4582 4278 4308 Imperial 3805 3405 4011 3930 3453 3658 2706 Inyo 833 858 1061 999 997 697 1061 Kern 52636 52164 59685 55531 47718 51277 54088 Kings 3161 3573 3056 3309 2396 2450 2413 Lake 5117 4123 4646 4655 4086 4265 3296 Lassen 767 837 1021 969 1019 1130 1104 Los Angeles 4 11 0 5 24 4 96929 Madera 6620 8080 8179 6855 6243 6395 6058 Marin 4112 3768 3630 3531 3092 3550 3412 Mariposa 1502 1796 1749 1651 1495 1572 1284 Mendocino 3714 3589 3633 4076 3634 3245 3523 Merced 11111 12008 10650 9678 8123 8189 8423 Modoc 313 506 506 584 402 394 270 Mono 392 353 314 362 362 252 309 Monterey 6734 6635 6645 6973 6964 6366 7023 Napa 2021 1898 1779 1896 570 438 1478 Nevada 3031 2984 3632 3801 3096 3629 3261 Orange 6309 6645 7035 6328 6178 6410 5618 Placer 10059 10132 8756 9256 8560 8912 8151 Plumas 1990 2011 2198 1985 1604 1492 1928 Riverside 46050 39713 36571 34312 30229 34105 33843 Sacramento 12848 12649 14790 13039 13045 14709 53793 San Benito 1620 1273 1320 1048 1153 888 679 San Bernardino 28350 31145 31297 29480 25899 27084 24922 San Diego 31015 30472 34700 30709 26191 25877 25908 San Francisco 158588 158741 182747 228175 213410 242800 219601 San Joaquin 22005 23620 22615 20859 19080 18623 16330 San Luis Obispo 397 324 603 1200 1283 1479 7646 San Mateo 8060 9019 11958 13008 11485 13037 13387 Santa Barbara 8106 8173 …
has title: Combining two dataframes into one dataframe w/ condtional
tagged with: pivot-table
type: UnansweredQuestion

http://stackoverflow.com/comment/87062210
score: 0
comment on: http://stackoverflow.com/q/50022116
type: Comment
has text: It's irrelevant how I change the file. That would be a very long code. It's only about when I'm opening the file with an xml parser and creating an xml file again, that there are changes in the file, even I haven't actually made any changes to the xml.
type: QuestionComment

http://stackoverflow.com/a/50030186
answers question: http://stackoverflow.com/q/50002990
has body: You don't need a process.stop() there, it's used with CrawlerRunner and you are using CrawlerProcess. The difference is that the former supposes you application already has a reactor loop to attach to, and the latter sets up a new reactor process.
score: 0
type: Answer

http://stackoverflow.com/comment/87140873
type: QuestionComment
has text: Sets are unordered datastructures. You have to use OrderedSets.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50062125

http://stackoverflow.com/comment/118261239
comment on: http://stackoverflow.com/a/59208661
type: Comment
has text: Thanks, bro. you've saved my day.
type: AnswerComment
score: 1

http://stackoverflow.com/q/50070571
has title: Get first td value
has answer: http://stackoverflow.com/a/50070642
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87157993
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/50070645
has comment: http://stackoverflow.com/comment/87162402
has comment: http://stackoverflow.com/comment/87157862
type: UnansweredQuestion
has body: I'm new to Beautifulsoup and Python, trying to figure how to get the first th tag of an HTML page. Can someone tell me what is wrong with my code? HTML 1365 m Rating 25-0 12h45 I would like to retrieve only the first width which has value 1365. Below is my code print('Track '+soup.findAll('th',{'width':'10%'})[3]) I tried find('th',{'width':'10%'})[3]) but it is throwing indexbound exception. Any help? With my code i'm getting the second th tag which is 12h45
tagged with: python

http://stackoverflow.com/comment/136809997
type: QuestionComment
has text: What kind of data is this? As mentioned by @Primusa, the signal at t - 1 doesn't look like affecting the signal at t.
comment on: http://stackoverflow.com/q/50054419
score: 0
type: Comment

http://stackoverflow.com/a/50015713
answers question: http://stackoverflow.com/q/50015472
has comment: http://stackoverflow.com/comment/87048216
has comment: http://stackoverflow.com/comment/87047901
has comment: http://stackoverflow.com/comment/87048126
has comment: http://stackoverflow.com/comment/87047928
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87047935
has comment: http://stackoverflow.com/comment/87047890
has body: First create Series by shift column names, split by first whitespace and append Date, last filter only Unnamed index values and rename columns names: s = df.columns.to_series().shift(-1).str.split(n=1).str[0] + ' Date' s = s[s.index.str.startswith('Unnamed')] print (s) Unnamed: 0 233740 Date Unnamed: 2 233160 Date dtype: object df = df.rename(columns=s) print (df) 233740 Date 233740 KS Equity 233160 Date 233160 KS Equity 0 2015-12-17 10330.0 2017-08-31 10460.0 1 2015-12-18 10710.0 2017-09-01 10815.0 2 2015-12-21 10720.0 2017-09-04 10835.0 3 2015-12-22 10495.0 2017-09-05 10660.0 4 2015-12-23 10425.0 2017-09-06 10535.0 If need create 2 or 3 columns from all data first create MultiIndex by split and then call unstack: df.columns = df.columns.str.split(n=1, expand=True) df = df.stack(0).reset_index(level=0, drop=True).rename_axis('val').reset_index() print (df) val Date KS Equity 0 233160 2017-08-31 10460.0 1 233740 2015-12-17 10330.0 2 233160 2017-09-01 10815.0 3 233740 2015-12-18 10710.0 4 233160 2017-09-04 10835.0 5 233740 2015-12-21 10720.0 6 233160 2017-09-05 10660.0 7 233740 2015-12-22 10495.0 8 233160 2017-09-06 10535.0 9 233740 2015-12-23 10425.0 EDIt: Solution for multiple different headers: #create dummy data df1 = df.copy() df1.columns = ['Unnamed: 4','233 JP Equity','Unnamed: 6','235 JP Equity'] df = df.join(df1) print (df) Unnamed: 0 233740 KS Equity Unnamed: 2 233160 KS Equity Unnamed: 4 \ 0 2015-12-17 10330.0 2017-08-31 10460.0 2015-12-17 1 2015-12-18 10710.0 2017-09-01 10815.0 2015-12-18 2 2015-12-21 10720.0 2017-09-04 10835.0 2015-12-21 3 2015-12-22 10495.0 2017-09-05 10660.0 2015-12-22 4 2015-12-23 10425.0 2017-09-06 10535.0 2015-12-23 233 JP Equity Unnamed: 6 235 JP Equity 0 10330.0 2017-08-31 10460.0 1 10710.0 2017-09-01 10815.0 2 10720.0 2017-09-04 10835.0 3 10495.0 2017-09-05 10660.0 4 10425.0 2017-09-06 10535.0 s = df.columns.to_series().shift(-1) + ' Date' s = s[s.index.str.startswith('Unnamed')] print (s) Unnamed: 0 233740 KS Equity Date Unnamed…
score: 1
has comment: http://stackoverflow.com/comment/87050008
accepted answer of: http://stackoverflow.com/q/50015472
type: Answer
has comment: http://stackoverflow.com/comment/87050283

http://stackoverflow.com/a/50018563
has comment: http://stackoverflow.com/comment/87361944
has comment: http://stackoverflow.com/comment/87109133
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/87356409
answers question: http://stackoverflow.com/q/49957228
has comment: http://stackoverflow.com/comment/87201585
has comment: http://stackoverflow.com/comment/87355070
has comment: http://stackoverflow.com/comment/87187997
type: Answer
has comment: http://stackoverflow.com/comment/87355728
has comment: http://stackoverflow.com/comment/87361795
has comment: http://stackoverflow.com/comment/87188006
upvote count: 6
has comment: http://stackoverflow.com/comment/87362061
has body: Paypal will automatically try to keep the billing date the same for every month (where applicable, as stated in the linked resource). You can state the starting date of a billing agreement as stated in this example, by specifying a start_datefield. Here I use the arrow module, to conveniently calculate the first day of the next month: import arrow billing_plan = paypalrestsdk.BillingPlan({ "name": "Monthly Billing Plan", "description": "Monthly Plan", "start_date": arrow.utcnow().shift(months=+1).replace(day=1).isoformat(), "merchant_preferences": { ... "setup_fee": { "currency": "USD", "value": "100" } } ... }) The initial subscription fee should be handled by the setup_fee field! EDIT after question update: On the merchant_preferences field of your plan, you are setting auto_bill_amount to yes. By taking a look at the documentation on merchant_preferences we can see that: auto_bill_amount enum Indicates whether PayPal automatically bills the outstanding balance in the next billing cycle. The outstanding balance is the total amount of any previously failed scheduled payments. Value is: NO. PayPal does not automatically bill the customer the outstanding >balance. YES. PayPal automatically bills the customer the outstanding balance. Possible values: YES, NO. Default: NO.
has comment: http://stackoverflow.com/comment/87209713
has comment: http://stackoverflow.com/comment/87187889
has comment: http://stackoverflow.com/comment/87187885

http://stackoverflow.com/q/50029803
accepted answer: http://stackoverflow.com/a/50030221
type: Question
has answer: http://stackoverflow.com/a/50030221
answer count: 2
tagged with: python
has title: MultiIndex DataFrame - Getting only the possible values of a lower level index given an upper level index value
has body: When I slice into a MultiIndex DataFrame by a level 0 index value, I want to know the possible level 1+ index values that fall under that initial value. If my wording doesn't make sense, here's an example: &gt;&gt;&gt; arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ... ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'], ... ['a','b','a','b','b','b','b','b']] &gt;&gt;&gt; tuples = list(zip(*arrays)) &gt;&gt;&gt; index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second','third']) &gt;&gt;&gt; s = pd.Series(np.random.randn(8), index=index) &gt;&gt;&gt; s first second third bar one a -0.598684 two b 0.351421 baz one a -0.618285 two b -1.175418 foo one b -0.093806 two b 1.092197 qux one b -1.515515 two b 0.741408 dtype: float64 s's index looks like: &gt;&gt;&gt; s.index MultiIndex(levels=[[u'bar', u'baz', u'foo', u'qux'], [u'one', u'two'], [u'a', u'b']], labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 1, 1, 1]], names=[u'first', u'second', u'third']) When I take just the section of s whose first index value is foo, and look up the index of that I get: &gt;&gt;&gt; s_foo = s.loc['foo'] &gt;&gt;&gt; s_foo second third one b -0.093806 two b 1.092197 dtype: float64 &gt;&gt;&gt; s_foo.index MultiIndex(levels=[[u'one', u'two'], [u'a', u'b']], labels=[[0, 1], [1, 1]], names=[u'second', u'third']) I want the index of s_foo to act as if the higher level of s does not exist, yet we can see in s_foo.index's levels attribute that a is still considered a potential value of index third, despite the fact that s_foo only has b as a possible value. Essentially, what I want to find are all the possible third values of foo_s, i.e. b and only b. Right now I do set(s_foo.reset_index()['third']), but I was hoping for a more elegant solution
possible better answer: http://stackoverflow.com/a/50030050
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50030050
tagged with: pandas

http://stackoverflow.com/comment/87073535
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50028539
has text: Thats a great idea @eagle! Where I'm not sure is how to read the file from the remote machine using a solution like this. I will play with it some more trying this route. I guess instead of using just `open` I could establish the ssh connection and read the file that way. Thanks for the response!
type: AnswerComment

http://stackoverflow.com/comment/86876543
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49923479
has text: Are these input data stored in a file?
type: QuestionComment

http://stackoverflow.com/q/50040601
linked to: http://stackoverflow.com/q/49850472
has body: I have to edit this code i have in python of a chatServer so that you can send private messages to a receiver and if the recevier isnt logged in it outputs an error to the sender. Also any message sent by the server to the client must be provided with the name of the original sender. chatClient.py import socket import struct import sys import threading from datetime import datetime PORT = 8888 HEADER_LENGTH = 2 def receive_fixed_length_msg(sock, msglen): message = b'' while len(message) &lt; msglen: chunk = sock.recv(msglen - len(message)) if chunk == b'': raise RuntimeError("socket connection broken") message = message + chunk return message def receive_message(sock): header = receive_fixed_length_msg(sock, HEADER_LENGTH) message_length = struct.unpack("!H", header)[0] message = None if message_length &gt; 0: message = receive_fixed_length_msg(sock, message_length) message = message.decode("utf-8") return message def send_message(sock, message): encoded_message = message.encode("utf-8") header = struct.pack("!H", len(encoded_message)) message = header + encoded_message sock.sendall(message); def message_receiver(): while True: msg_received = receive_message(sock) if len(msg_received) &gt; 0: # ce obstaja sporocilo current_time = datetime.now().strftime('%H:%M:%S') print("[RKchat][" + current_time + "] " + name + ": " + msg_received) print("[system] connecting to chat server ...") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("localhost", PORT)) print("[system] connected!") thread = threading.Thread(target=message_receiver) thread.daemon = True thread.start() name = input("Vpiši ime: ") while True: try: msg_send = input("") send_message(sock, msg_send) except KeyboardInterrupt: sys.exit() chatServer.py import signal signal.signal(signal.SIGINT, signal.SIG_DFL) import socket import struct import threading PORT = 8888 HEADER_LENGTH = 2 def receive_fixed_length_msg(sock, msglen): message = b'' while len(message) &lt; msglen: chunk = sock.recv(m…
has title: Python Socket Message Exchange
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87103405
type: Question
tagged with: sockets
has comment: http://stackoverflow.com/comment/87103582
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50045596

http://stackoverflow.com/a/50028716
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50028407
type: Answer
has body: The command cur.execute('SELECT * FROM Counts ORDER BY count DESC') does not reorder the database itself, it just orders the results of the select statement. More fundamentally, a SELECT statement does not modify anything. It just returns a list of the rows you ask for. If you want to change the order of the rows in the database, you need to use UPDATE or INSERT commands to do so, but in your case, you probably don't actually want to do this. It is better to just order the results every time using ORDER BY. Because of how sqlite works, it is usually not a good idea to rely on the order the results are stored in the database. More information about how rows are ordered in sqlite can be found in the docs: https://www.sqlite.org/rowidtable.html sqlite tables use 'rowid' for order by default.

http://stackoverflow.com/a/50066459
has body: The problem is that when show_image is true, but 1024 &gt;= cursor[0] &gt;= 760 and 450 &gt;= cursor[1] &gt;= 250 is satisfied, then win.blit(images[num], 0, 0) gets executed BEFORE num is defined (because num is defined in the first if statement). A way to fix this is by declaring num outside the function and then executing global num inside the if function. Corrected code: num = random.randint(0, 17) def draw(): global show_image global num win.fill([255,255,255]) pygame.draw.rect(win, [0,0,0], (760, 250, 264 , 200), 1) if 1024 &gt;= cursor[0] &gt;= 760 and 450 &gt;= cursor[1] &gt;= 250: pygame.draw.rect(win, [128,128,128], (761, 251, 262 , 198)) if click[0]: num = random.randint(0,17) show_image = True if show_image == True: win.blit(images[num], (0,0)) win.blit(font.render(captions[num], True, [0,190,0]), (660,550)) win.blit(button_text, (780,270)) pygame.display.update()
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50066152
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50066152

http://stackoverflow.com/q/49970249
tagged with: flask-sqlalchemy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86956449
accepted answer: http://stackoverflow.com/a/49971702
answer count: 1
has title: Printing out the results of a join in flask
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86956483
tagged with: flask-wtforms
has answer: http://stackoverflow.com/a/49971702
downvote count: 0
tagged with: python
upvote count: 4
has body: I'm making a flask app in which every user can add his employees to a list. I have two Tables: User and Employee and they look like this: class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) emps = db.relationship('Employee', backref = 'boss', lazy = 'dynamic') def __repr__(self): return '&lt;User {}'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) class Employee(db.Model): __tablename__ = 'Employees' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(64), index=True) last_name = db.Column(db.String(64), index=True) User_id = db.Column(db.Integer, db.ForeignKey(User.id)) def __repr__(self): return '&lt;Employee {0} {1}&gt;'.format(self.first_name, self.last_name) I tried adding this to my User class so I can join these two tables: def user_employees(self): user_emps = User.query.join(Employee, User.id == Employee.User_id).filter(User.id == Employee.User_id) return user_emps And in my html file I have this: {% block content %} {% for employee in employees %} &lt;div&gt;{{ employee }}&lt;/div&gt; {% endfor %} {% endblock %} And this is the view function: def Show_Employees(): employees = current_user.user_employees() return render_template('emps.html', employees = employees) However this doesn't work. I only get this written on my page: &lt;User test The expected output would be first name and last name of the employee. I guess the problem is with the join but I can't figure it out. Has anyone encountered anything similar?
score: 4
tagged with: flask

http://stackoverflow.com/q/49935141
has comment: http://stackoverflow.com/comment/86885888
has answer: http://stackoverflow.com/a/49935353
favorite count: 0
has comment: http://stackoverflow.com/comment/86886078
type: Question
tagged with: nested-lists
has body: Sorry for for the potentially silly question. But this seems to be a stumping problem I just can't find the answer to. Say I have the following mixed nested list in python: a = [((1,1),(0,0)), (3,4)] I'd like to check if the following tuples b, c and d appear in a: b = (1,1) c = (0,0) d = (3,4) print(b in a) # &lt;- False ? print(c in a) # &lt;- False ? print(d in a) # &lt;- True I'd like to replace the code in each print statement in such away that the search finds the tuple in the list and as such returns True Any help at all would be much appreciated. Apologies if this question has already been asked before.
has comment: http://stackoverflow.com/comment/86885754
has answer: http://stackoverflow.com/a/49937220
has comment: http://stackoverflow.com/comment/86885809
linked to: http://stackoverflow.com/q/952914
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/86885945
has answer: http://stackoverflow.com/a/49935439
has comment: http://stackoverflow.com/comment/86885939
accepted answer: http://stackoverflow.com/a/49935439
has comment: http://stackoverflow.com/comment/86885849
type: AnsweredQuestion
score: 3
tagged with: list
has comment: http://stackoverflow.com/comment/86885763
answer count: 3
has title: Python: Check if a nested list is in a nested list
possible better answer: http://stackoverflow.com/a/49935353
downvote count: 1

tensorflow
tags question: http://stackoverflow.com/q/49986522
tags question: http://stackoverflow.com/q/49997499
tags question: http://stackoverflow.com/q/50028868
tags question: http://stackoverflow.com/q/50052728
tags question: http://stackoverflow.com/q/49922674
tags question: http://stackoverflow.com/q/49969957
type: Tag
tags question: http://stackoverflow.com/q/49919304
tags question: http://stackoverflow.com/q/49967600
tags question: http://stackoverflow.com/q/50061393
tags question: http://stackoverflow.com/q/50031701
tags question: http://stackoverflow.com/q/49959545
tags question: http://stackoverflow.com/q/49940110
tags question: http://stackoverflow.com/q/50065484
tags question: http://stackoverflow.com/q/50045061
tags question: http://stackoverflow.com/q/49954014
tags question: http://stackoverflow.com/q/49953379
tags question: http://stackoverflow.com/q/49971318
tags question: http://stackoverflow.com/q/50042421
tags question: http://stackoverflow.com/q/50015121
tags question: http://stackoverflow.com/q/50073216
tags question: http://stackoverflow.com/q/50051281
tags question: http://stackoverflow.com/q/49975549
tags question: http://stackoverflow.com/q/50010040
tags question: http://stackoverflow.com/q/50071124
tags question: http://stackoverflow.com/q/49957862
tags question: http://stackoverflow.com/q/49962076
tags question: http://stackoverflow.com/q/50054989
tags question: http://stackoverflow.com/q/49926696
tags question: http://stackoverflow.com/q/49918271
tags question: http://stackoverflow.com/q/49944010
tags question: http://stackoverflow.com/q/49958888
tags question: http://stackoverflow.com/q/49931055
tags question: http://stackoverflow.com/q/50056923
tags question: http://stackoverflow.com/q/50065550
tags question: http://stackoverflow.com/q/49920288
tags question: http://stackoverflow.com/q/49951422
tags question: http://stackoverflow.com/q/49957659
tags question: http://stackoverflow.com/q/50035713
tags question: http://stackoverflow.com/q/49933056
tags question: http://stackoverflow.com/q/50044985
tags question: http://stackoverflow.com/q/49916921
tags question: http://stackoverflow.com/q/50037467
tags question: http://stackoverflow.com/q/49959130
tags question: http://stackoverflow.com/q/49995079
tags question: http://stackoverflow.com/q/49975649
tags question: http://stackoverflow.com/q/49948231
tags question: http://stackoverflow.com/q/50007424
tags question: http://stackoverflow.com/q/49943278
tags question: http://stackoverflow.com/q/49951795
tags question: http://stackoverflow.com/q/50071752
tags question: http://stackoverflow.com/q/50027652
tags question: http://stackoverflow.com/q/49975340
tags question: http://stackoverflow.com/q/49939018
tags question: http://stackoverflow.com/q/50010929
tags question: http://stackoverflow.com/q/50033178
tags question: http://stackoverflow.com/q/49928337
tags question: http://stackoverflow.com/q/49960875
tags question: http://stackoverflow.com/q/49969349
tags question: http://stackoverflow.com/q/49962323
tags question: http://stackoverflow.com/q/49977236
tags question: http://stackoverflow.com/q/49927619
tags question: http://stackoverflow.com/q/49969484
tags question: http://stackoverflow.com/q/49984317
tags question: http://stackoverflow.com/q/50071522
tags question: http://stackoverflow.com/q/50066396
tags question: http://stackoverflow.com/q/50022168
tags question: http://stackoverflow.com/q/50066313
tags question: http://stackoverflow.com/q/49935491
tags question: http://stackoverflow.com/q/49987631
tags question: http://stackoverflow.com/q/50031553
tags question: http://stackoverflow.com/q/49923429
tags question: http://stackoverflow.com/q/50046505
tags question: http://stackoverflow.com/q/50053151
tags question: http://stackoverflow.com/q/49934606
tags question: http://stackoverflow.com/q/50007085
tags question: http://stackoverflow.com/q/49950186
tags question: http://stackoverflow.com/q/50053272
tags question: http://stackoverflow.com/q/49972992
tags question: http://stackoverflow.com/q/49921839

http://stackoverflow.com/comment/87079193
comment on: http://stackoverflow.com/q/50031506
has text: The thing to understand is that in `egrep "sbin|lib"` passed to a shell, those double quotes are syntactic, not literal -- ie. they're serving the exact same purpose that the single quotes do in the Python, and aren't actually passed to `egrep`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87118473
type: AnswerComment
has text: @roganjosh Your correct. I botched the arrangement. I'm trying to show that you can plug in the values [1, 2, .., 9] and return an array of the strings of those integers.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50050894

http://stackoverflow.com/q/49931186
downvote count: 0
tagged with: iterable-unpacking
has answer: http://stackoverflow.com/a/49931236
possible better answer: http://stackoverflow.com/a/49931236
favorite count: 0
type: Question
has title: Unpacking generator which yields a dictionary
has answer: http://stackoverflow.com/a/49932978
tagged with: python
tagged with: generator
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49931273
answer count: 3
has comment: http://stackoverflow.com/comment/86878274
accepted answer: http://stackoverflow.com/a/49931273
has body: I cannot understand the output of the following sample code: def g1(): d = {'a':1, 'b':2, 'c':3} yield d for a,b,c in g1(): print a,b,c In Python 2.7.14, the above would print out a c b There are two interesting aspects of this behavior: That it prints out a c b intead of the sorted a b c, which is supposed to be the case since we are talking about dictionary keys. If you just define the dictionary without writing the generator d = {'a':1, 'b':2, 'c':3}, and then for a,b,c in d:, this will be a valueError.
upvote count: 2
has comment: http://stackoverflow.com/comment/86878357

http://stackoverflow.com/q/49963322
has comment: http://stackoverflow.com/comment/86942736
has title: Displaying rows where condition matches some part of string in pandas
linked to: http://stackoverflow.com/q/11350770
tagged with: pandas-loc
duplicate of: http://stackoverflow.com/q/11350770
has comment: http://stackoverflow.com/comment/86942705
tagged with: python
has body: We use fund_data.loc[fund_data['SubVertical']=="Data Analytics platform"] to display all details of the columns containing these('Data Analytics platform') strings in the condition of a column in pandas, but suppose we want to display rows containing even some part of the string like all rows having the word 'Data' in the 'SubVertical' column. fund_data.loc[fund_data['SubVertical']=="%Data%"] #or something like this should return the following c1 c2 1 A Data Analysis 2 B Data Analytics 3 C Big Data 4 D Consumer Data platfrom 5 E Data platforms etc....
type: Question
score: 0
answer count: 0
tagged with: pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86942587

http://stackoverflow.com/a/49918072
upvote count: 1
has body: you are looking for the zorder keyword argument plt.figure(1) plt.scatter(x, y, c='r', zorder=1) plt.hist(x, bins = 100, normed=True, zorder=0) plt.show()
type: Answer
answers question: http://stackoverflow.com/q/49917748
score: 1
downvote count: 0

http://stackoverflow.com/comment/87129544
score: 1
has text: It's definitely possible Odoo might treat them different if returned as strings. I would see it primarily being an issue for integers and floats since those have mathematical operations done on them during manipulation of the pivot table. I would have to try it though to know for sure.
type: Comment
comment on: http://stackoverflow.com/a/50056077
type: AnswerComment

http://stackoverflow.com/comment/87065782
type: Comment
comment on: http://stackoverflow.com/a/50023090
score: 0
type: AnswerComment
has text: Pickling *might* be what the OP actually wants, but that's not (yet) indicated by the question.

http://stackoverflow.com/q/50051492
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87119469
has answer: http://stackoverflow.com/a/50051693
accepted answer: http://stackoverflow.com/a/50051693
type: AnsweredQuestion
has body: How can I write a file to the filesystem whose filename isn't encoded? Currently, writing /myfolder/my file.csv becomes /myfolder/my%20file.csv. I want the filename to be my file.csv. Code snippet: rs = (grequests.get(u, headers=headers, stream=True, hooks={'response': addFilenameToResponse}) for u in urls) sp_results = grequests.map(rs) for res in sp_results: byteStream = io.BytesIO(res.content) result_df = pd.read_csv(byteStream, sep=",", encoding='utf8') outputloc = downloads_folder + res.filePathFull + '/' + res.filename outputloc = outputloc.replace('/', '\\') # switching for Windows 10 result_df.to_csv(outputloc, index=False, encoding=None) ... I've tried outputting to_csv as encoding=None but this doesn't work. Beyond this, the docs do not show any other methods it seems. The problem is, there's another legacy tool we're then reading in the filename from, and the tool re-encodes the encoded filename, resulting in /myfolder/my%2520file.csv (% encodes to %25).
downvote count: 0
answer count: 1
has title: pandas to_csv — do not encode filename or path
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87119367
tagged with: pandas

http://stackoverflow.com/comment/86979733
score: 0
comment on: http://stackoverflow.com/q/49971915
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest thanks for pointing me towards that meta thread. I wasn't aware. How is the question now?

http://stackoverflow.com/a/49985196
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49985012
has body: You can do something like this \b(?:\w*?(?:big|nice))?cat\b Put the \w* into the optional group.
score: 1
downvote count: 0

http://stackoverflow.com/q/49977839
tagged with: deep-learning
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/87007449
has body: The shape of sensor data is (1,200,9),the number of channel is 9,but i want to convert it to a 2-D data which the channel is 1, and the final shape is (9,200,1). I have test keras.layers.core.Reshape((9,200,1)), but there has error. So i don't know what should i do, i hope someone can help me,thank you very much.
type: Question
has title: How can i use python to convert sensor data (1,200,9) to (9,200,1)?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86971752
tagged with: python
has answer: http://stackoverflow.com/a/49977902
score: 0

http://stackoverflow.com/q/50054863
answer count: 0
has comment: http://stackoverflow.com/comment/87178678
type: UnansweredQuestion
tagged with: web
favorite count: 0
type: Question
has body: So I'm trying to get the video link from a the video found at https://www.cnn.com/2018/04/25/cnn10/ten-content-thurs/index.html, specifically However, the src of the video is blob:https://www.cnn.com/bfa3b957-ef83-4a88-8865-bcdfcedce7a5, which after some research, could not find a clear answer on how to extract a video link out of the blob. I don't know if you can get the video url from a blob or not.
upvote count: 5
has comment: http://stackoverflow.com/comment/87178474
has title: Web Scraping Get Video From Blob
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 5
downvote count: 0

http://stackoverflow.com/comment/87091412
type: QuestionComment
has text: @khelwood this looks like a subtly different question. Why does the `is` operator change result when the same operations are performed but with different contents of the strings.
comment on: http://stackoverflow.com/q/50037548
score: 1
type: Comment

http://stackoverflow.com/q/49949224
score: 1
tagged with: memory
accepted answer: http://stackoverflow.com/a/49950913
has comment: http://stackoverflow.com/comment/86916470
tagged with: traceback
type: Question
has answer: http://stackoverflow.com/a/49950913
has body: I am trying to test my logistic regression model but I get a memory error and cannot solve it. Is it because my sentences take too much space? I will appreciate any help. From Line 267 in my code: self.X, self.y = self.transform_to_dataset(training_sentences,_pos__sentences) self.clf = Pipeline([ ('vectorizer', DictVectorizer(sparse=False)), ('classifier', LogisticRegression())]) self.clf.fit(self.X, self.y) And the error I get after running this: Traceback (most recent call last): File "tagger_lr_chunk.py", line 342, in &lt;module&gt; tagger.train(data_dir + 'train.txt') File "tagger_lr_chunk.py", line 271, in train self.clf.fit(self.X, self.y) File "/home/selub/anaconda2/lib/python2.7/site-packages/sklearn/pipeline.py", line 248, in fit Xt, fit_params = self._fit(X, y, **fit_params) File "/home/selub/anaconda2/lib/python2.7/site-packages/sklearn/pipeline.py", line 213, in _fit **fit_params_steps[name]) File "/home/selub/anaconda2/lib/python2.7/site-packages/sklearn/externals/joblib/memory.py", line 362, in __call__ return self.func(*args, **kwargs) File "/home/selub/anaconda2/lib/python2.7/site-packages/sklearn/pipeline.py", line 581, in _fit_transform_one res = transformer.fit_transform(X, y, **fit_params) File "/home/selub/anaconda2/lib/python2.7/site-packages/sklearn/feature_extraction/dict_vectorizer.py", line 230, in fit_transform return self._transform(X, fitting=True) File "/home/selub/anaconda2/lib/python2.7/site-packages/sklearn/feature_extraction/dict_vectorizer.py", line 204, in _transform result_matrix = result_matrix.toarray() File "/home/selub/anaconda2/lib/python2.7/site-packages/scipy/sparse/compressed.py", line 943, in toarray out = self._process_toarray_args(order, out) File "/home/selub/anaconda2/lib/python2.7/site-packages/scipy/sparse/base.py", line 1130, in _process_toarray_args return np.zeros(self.shape, dtype=self.dtype, order=order) MemoryError
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
tagged with: python
favorite count: 0
type: AnsweredQuestion
has title: Memory error in Python while using sklearn

http://stackoverflow.com/a/50006748
answers question: http://stackoverflow.com/q/50001278
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: The discussion and duplicate dance around a simple solution: In [177]: np.arange(Decimal('-2.0'), Decimal('2.0'), Decimal('0.1')) Out[177]: array([Decimal('-2.0'), Decimal('-1.9'), Decimal('-1.8'), Decimal('-1.7'), Decimal('-1.6'), Decimal('-1.5'), Decimal('-1.4'), Decimal('-1.3'), Decimal('-1.2'), Decimal('-1.1'), Decimal('-1.0'), Decimal('-0.9'), Decimal('-0.8'), Decimal('-0.7'), Decimal('-0.6'), Decimal('-0.5'), Decimal('-0.4'), Decimal('-0.3'), Decimal('-0.2'), Decimal('-0.1'), Decimal('0.0'), Decimal('0.1'), Decimal('0.2'), Decimal('0.3'), Decimal('0.4'), Decimal('0.5'), Decimal('0.6'), Decimal('0.7'), Decimal('0.8'), Decimal('0.9'), Decimal('1.0'), Decimal('1.1'), Decimal('1.2'), Decimal('1.3'), Decimal('1.4'), Decimal('1.5'), Decimal('1.6'), Decimal('1.7'), Decimal('1.8'), Decimal('1.9')], dtype=object) Giving float values to Decimal does not work well: In [180]: np.arange(Decimal(-2.0), Decimal(2.0), Decimal(0.1)) Out[180]: array([Decimal('-2'), Decimal('-1.899999999999999994448884877'), Decimal('-1.799999999999999988897769754'), Decimal('-1.699999999999999983346654631'), because Decimal(0.1) just solidifies the floating point inprecision of 0.1: In [178]: Decimal(0.1) Out[178]: Decimal('0.1000000000000000055511151231257827021181583404541015625') Suggested duplicate: How to use a decimal range() step value?

http://stackoverflow.com/q/49924561
has comment: http://stackoverflow.com/comment/86867104
linked to: http://stackoverflow.com/q/49281459
has comment: http://stackoverflow.com/comment/86881268
answer count: 0
has body: Pardon me for possibly an easy question. Is there an elegant, numpy way to apply the dot product matrix-wise in tensor? e.g. import numpy as np M = np.array(range(12)).reshape(2,2,3) N = np.array(range(12)).reshape(2,3,2) And then I'll have following result array([[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]]) array([[[ 0, 3], [ 1, 4], [ 2, 5]], [[ 6, 9], [ 7, 10], [ 8, 11]]]) And then I want the matrix-element dot operation, np.dot(M[0], N[0]), np.dot(M[1], N[1]) Is there a elegant, numpy way to apply the operation at the same time? Thanks in advance! Update #1 I'm sorry I didn't make it clear! I actually want the cross product of the matrix-element of two tensor. I aim to get an another tensor with the element like result = (M[0].dot(N[0]) M[1].dot(N[1])) That means if I got a tensor M with shape [L, u, v], and a tensor N with shape [L, v, w]. I hope got the result with shape [L, u, w]. Finally getting the matrix-element cross product operation. I have found the question np.dot product between two 3D matrices along specified axis but I think that's not the answer I want. But I found the question Numpy elementwise product of 3d array is exactly what I want. Thanks a lot for @Brenlla, @Divakar, @hpaulj answering.
has comment: http://stackoverflow.com/comment/86881263
has title: Numpy matrix-wise dot product
has comment: http://stackoverflow.com/comment/86881250
linked to: http://stackoverflow.com/q/31957364
type: Question
linked to: http://stackoverflow.com/q/36072042
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86865372
has comment: http://stackoverflow.com/comment/86865143
has comment: http://stackoverflow.com/comment/86866666
duplicate of: http://stackoverflow.com/q/31957364
tagged with: python
tagged with: numpy
score: 0

http://stackoverflow.com/comment/86937182
score: 0
type: Comment
type: QuestionComment
has text: As a general rule, concatenating as you go along is slowest, because it makes a new array each time. Appending to a list is relatively fast, because a list just collects pointers. Insertion into a preallocated array is also good.
comment on: http://stackoverflow.com/q/49960195

http://stackoverflow.com/comment/87058690
comment on: http://stackoverflow.com/a/50016223
has text: can you try response.xpath('//nav[@id="mmenu"]//ul/li[contains(@class,"level0")]/a[contains(@class,"level-top")]/@href').extract()
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87091634
comment on: http://stackoverflow.com/q/50037548
has text: @deceze: that first one is also using comparison chaining, fun! The expression *in the first line* produces `False`, not `True`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86952062
type: Comment
comment on: http://stackoverflow.com/a/49964554
type: AnswerComment
has text: It depends on what you're going to do there. Look at some examples here: https://www.tutorialspoint.com/pyqt/pyqt_tutorial.pdf
score: 0

http://stackoverflow.com/comment/87112794
type: AnswerComment
has text: Thus, this is exactly the same syntax you're using with `[1,2,3] + [4,5,6] + [7,8,9]`, just where the `[4,5,6]` is what's returned by the `glob()` call.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50048132

http://stackoverflow.com/q/50066468
has body: I have the following situation: I have a single master_function that I wish to pass a sub_function into. The function that I wish to pass into this changes (for example 1 and 2). The arguments of each function also vary in their number and type. def sub_function_1( x, y, z): return x + y + z def sub_function_2( x, y ): return x + y def master_function( x, y, z, F ): return x*y + F() Quick fix The simple fix to this would be to write the function callback with all possible arguments, whether they are used or not: def master_function( x, y, z, F ): return x*y + F(x,y,z) Then we can call master_function( x, y, z, sub_function_1) or master_function( x, y, z, sub_function_2) as desired. Unfortunately, I have many functions that I wish to pass into the master function; so this approach is not suitable! Is there a way to write F in master_function without reference to the arguments required? How can I generalise this?
has comment: http://stackoverflow.com/comment/87149770
downvote count: 0
upvote count: 1
tagged with: callback
possible better answer: http://stackoverflow.com/a/50066839
has title: Passing variables into a function Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50066839
linked to: http://stackoverflow.com/q/919680
tagged with: python
accepted answer: http://stackoverflow.com/a/50066592
has answer: http://stackoverflow.com/a/50066592
type: AnsweredQuestion
answer count: 2
score: 1

http://stackoverflow.com/comment/86971856
score: 0
comment on: http://stackoverflow.com/q/49973060
type: QuestionComment
type: Comment
has text: @Tim I tried to remove the class `MOUSEINPUT` but nothing happened when launching. I have updated the question to indicate what I tried. The link is interesting but it does mention an union for `INPUTunion` so I don't know whether the code can be trimmed.

http://stackoverflow.com/a/70791565
type: Answer
answers question: http://stackoverflow.com/q/49992805
score: 1
has body: Your output is a dictionary, which can be directly turned into a pandas dataframe by df = pd.DataFrame([response]) - NOTICE, I am passing this dictionary as a list to the pandas DataFrame constructor. Or you can tailor your url to get the desired information. In the example below, I am getting data from the specified dataset and date ranges which are easily gleaned/edited. It seems that NOAA has updated their api formats at some time, and a lot of the material out there is not quite working anymore, so others may be receiving errors with this example code. If you are just getting started, this format will return a json file with results, and hopefully you can adapt it from there: import requests import pandas as pd import json from datetime import datetime token = 'yourtoken' url = "http://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCNDMS&startdate=1776-07-04&enddate=1776-09-04" headers = {"token":token} r = requests.get(url, "dataset", headers = headers).text response = json.loads(r) response = response['results'] response = response[0] print(response) df=pd.DataFrame([response])
upvote count: 1
downvote count: 0

sql
tags question: http://stackoverflow.com/q/50057603
tags question: http://stackoverflow.com/q/49958396
tags question: http://stackoverflow.com/q/49976315
tags question: http://stackoverflow.com/q/50059009
tags question: http://stackoverflow.com/q/49998457
tags question: http://stackoverflow.com/q/50058020
tags question: http://stackoverflow.com/q/50041727
tags question: http://stackoverflow.com/q/49983853
tags question: http://stackoverflow.com/q/49925982
tags question: http://stackoverflow.com/q/49966065
tags question: http://stackoverflow.com/q/50047077
tags question: http://stackoverflow.com/q/49916861
tags question: http://stackoverflow.com/q/49987271
tags question: http://stackoverflow.com/q/49974069
tags question: http://stackoverflow.com/q/50039546
tags question: http://stackoverflow.com/q/50022574
tags question: http://stackoverflow.com/q/49953310
tags question: http://stackoverflow.com/q/49974551
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/50073606
tags question: http://stackoverflow.com/q/50063834
tags question: http://stackoverflow.com/q/49931307
tags question: http://stackoverflow.com/q/50020683
tags question: http://stackoverflow.com/q/50063058
tags question: http://stackoverflow.com/q/49918095

http://stackoverflow.com/q/50029986
type: Question
accepted answer: http://stackoverflow.com/a/50030619
possible better answer: http://stackoverflow.com/a/77456564
answer count: 2
has answer: http://stackoverflow.com/a/50030619
has answer: http://stackoverflow.com/a/77456564
downvote count: 0
tagged with: python
has body: I am trying to write a openCV program where i am breaking down the video into frames and comparing two frames one after the other if both are the same i reject the frame else append the frame to a output file. How can i achieve it? OpenCV 2.4.13 Python 2.7
tagged with: opencv
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Removing frames with no motion in openCV
favorite count: 0

http://stackoverflow.com/a/49921063
upvote count: 4
has body: Use brew list to see what you've installed with Brew. And Brew Uninstall as needed. Likewise, review the logs from wget to see where it installed things. Keep in mind that MacOS uses Python 2.7 for system critical tasks; it's baked-into the OS so don't touch it. Anything you installed with pip is saved to the /site-packages directory of the Python version in which you installed it so it will disappear when you remove that version of Python. The .pkg files installed directly into your Applications folder and can be deleted safely like any normal app.
downvote count: 0
answers question: http://stackoverflow.com/q/49920886
type: Answer
score: 4

http://stackoverflow.com/q/50038103
score: 0
has body: I want to insert records of data from local Odoo server to another remote odoo server using web service like xmlrpc pr erppeek how can I do that
type: Question
has answer: http://stackoverflow.com/a/64836111
answer count: 2
type: UnansweredQuestion
has title: How to connect local Odoo server with remote odoo server
tagged with: python
has answer: http://stackoverflow.com/a/50707801
has comment: http://stackoverflow.com/comment/87092788

watson
tags question: http://stackoverflow.com/q/50074188
type: Tag
tags question: http://stackoverflow.com/q/50008200
tag name: watson

http://stackoverflow.com/a/49989803
answers question: http://stackoverflow.com/q/49986522
has body: I resolved the issue by decoding the data as jpeg with tf.image.decode_jpeg. Instead of: def read_and_decode(filename_queue): # ... image = tf.decode_raw(features['image/encoded'], tf.uint8) # ... I did: def read_and_decode(filename_queue): # ... image = tf.image.decode_jpeg(features['image/encoded']) # ... This explains the reason for why the difference between the expected size and the given size were so big: the given (read) bytes were "only" compressed JPEG data, and not a "complete" bitmap image of full size.
score: 3
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/q/49959715
favorite count: 0
type: Question
tagged with: python-3.x
has title: Combining text as blocks
has answer: http://stackoverflow.com/a/49959779
accepted answer: http://stackoverflow.com/a/49959779
tagged with: python
possible better answer: http://stackoverflow.com/a/49959794
type: AnsweredQuestion
has body: Let's start two blocks of text, for example a = """CAC ABA CAC""" b = """AAA BBB CCC""" If we add these two strings, we will end up with &gt;&gt;&gt; print(a+b) CAC ABA CACAAA BBB CCC &gt;&gt;&gt; I was wondering if there is a fast way to add large blocks of text so that they print side by side, like so: &gt;&gt;&gt; print(a+b) CACAAA ABABBB CACCCC &gt;&gt;&gt; I know that one can do &gt;&gt;&gt; print('\n'.join(list(a.split('\n')[x]+b.split('\n')[x] for x in range(3)))) CACAAA ABABBB CACCCC &gt;&gt;&gt; but is there a faster method?
answer count: 2
has answer: http://stackoverflow.com/a/49959794
downvote count: 0
upvote count: 1
score: 1
tagged with: string

http://stackoverflow.com/q/50013117
has body: I am in the process of creating a Python script to collect CSV data from a web URL. I've had no issue setting this up with: request.urlretrieve("www.RandomWebsiteInfo.com", "my output info") However, one of the web URLs I wish to retrieve includes an edit date in the naming convention. Example: ftp://ftp.ncdc.noaa.gov/pub/data/swdi/stormevents/csvfiles/StormEvents_details-ftp_v1.0_d2018_c20180418.csv.gz The portion of the string with "_c20180418" represents the edit date that the file was last updated. Since this constantly updates, and happens at random intervals, is there a way for Python to search within these URL strings and create and/or recognize and/or match an updated "_cYYYYMMDD" string? I feel like, worst case scenario, I could create a looping mechanism that would try each date between the last edit and the current date until the request.urlretrieve locates a URL string that doesn't fail. I'm just not sure if that is the best practice for the task I'm attempting to accomplish. Before I try that approach, I thought I'd ask the community for any insight. Thanks for your time.
tagged with: python
has title: In Python 3.x, is it possible to check web URL for dynamic changes involving an edit date?
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87123942
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87042744
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87042580
type: UnansweredQuestion

http://stackoverflow.com/a/60542651
answers question: http://stackoverflow.com/q/49941426
upvote count: 5
has body: Simply use: torch.save(model_conv,'cnn.pt') the_model = torch.load('cnn.pt')
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/115211679
downvote count: 1

http://stackoverflow.com/comment/87104384
comment on: http://stackoverflow.com/q/50043664
type: Comment
score: 0
has text: @SvenKrüger I edited the question, hope it is clearer now. The idea is that the local browser is never used.
type: QuestionComment

http://stackoverflow.com/comment/87150293
has text: Yes something like that but it has to end the program saying "You have won!"
comment on: http://stackoverflow.com/a/50066895
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49973613
downvote count: 1
has title: List slicing and making a copy
duplicate of: http://stackoverflow.com/q/2612802
linked to: http://stackoverflow.com/q/986006
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49973675
tagged with: python
has comment: http://stackoverflow.com/comment/86963179
has answer: http://stackoverflow.com/a/49973658
possible better answer: http://stackoverflow.com/a/49973658
upvote count: 2
has body: While reading about slicing a list; i got stuck here:- a = [1, 3, 5] b = a[:] a[:] = [x**2 for x in a] a[:] = [0] print(b) # output --&gt; [1,3,5] And this:- a = [1, 3, 5] b = a a[:] = [x**2 for x in a] a[:] = [0] print(b) # output --&gt; [0] I know that b = a[:] is making a copy of list a but then what b=a is doing in the second example? And when printing the outputs, in the first case b doesn't get modified but get modified in second one. What is the reason for this behavior? I am not asking about how to do slicing, but wondering why both the codes mentioned are behaving strangely and differently.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86963146
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49973675
score: 1
linked to: http://stackoverflow.com/q/2612802

http://stackoverflow.com/q/49928495
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has title: Sum over one dimension when using {Dataset,DataArray}.group_by
tagged with: python-xarray
has answer: http://stackoverflow.com/a/49928496
score: 1
tagged with: python
has body: Apologies in advance that my "minimal example" has a three-dimensional array, but it is necessary to show the full force of the problem I am running into (because groupby will end up stacking two of the dimensions together when I only intend to sum over one of them): Context: import xarray as xr import numpy as np ds = xr.Dataset() ds['kind'] = (['layer', 'qpoint'], [ ['gamma', 'other', 'selected', 'selected', 'other', 'other'], ['selected', 'selected', 'other', 'gamma', 'other', 'other'], ]) # for each layer and eigenmode, we have a probability distribution # over the qpoints. probs = np.random.random((2, 18, 6)) probs /= probs.sum(axis=2, keepdims=True) # sum over qpoints is 1 ds['prob'] = (['layer', 'mode', 'qpoint'], probs) The goal: Perform some kind of sum along the 'qpoint' dimension of ds['prob'] over groups of equal ds['kind'], producing a DataArray with dims ['layer', 'mode', 'kind']. (not necessarily in that order) My furthest attempt: I tried to solve this using groupby but I really don't know what I'm doing. I couldn't make heads or tails of how to use GroupBy.sum when I only want to sum over the qpoint dimension. (naively calling groupby('kind').sum() will sum over all layers and modes as well) Eventually, I tried just using the GroupBy as an iterator, yet I still ultimately ran into problems trying to put all the data back together in the end. pairs = ds.groupby('kind') # I couldn't make heads or tails of how to use GroupBy.sum, # so I tried the more familiar concept of iteration. # focus on the 'prob' DataArrays pairs = [(kind, d['prob']) for (kind, d) in pairs] # unstack them so that `qpoint` is a valid dimension to sum over. # (this densifies the arrays in the process though, producing 2x18x6 arrays # that are mostly filled with nan; this seems kind of backwards...) pairs = [(kind, d.unstack('stacked_layer_qpoint')) for (kind, d) in pairs] pairs = [(kind, d.sum(dim='qpoint')) for (kind, d) in pairs] # 'kind' got lost when we did the sum. add it bac…
type: Question

http://stackoverflow.com/comment/87269293
has text: I will try it but I find a much simpler way that did my purpose. I will post it also.
type: AnswerComment
comment on: http://stackoverflow.com/a/50057929
score: 0
type: Comment

http://stackoverflow.com/comment/86967033
type: QuestionComment
comment on: http://stackoverflow.com/q/49953345
type: Comment
score: 0
has text: "it only change length of second obj", no, it also make the depth values between those two renderings completely incompatible, so that it will just screw the depth test.

http://stackoverflow.com/q/50019187
favorite count: 0
type: Question
tagged with: package
has answer: http://stackoverflow.com/a/50028051
accepted answer: http://stackoverflow.com/a/50019456
tagged with: python
has answer: http://stackoverflow.com/a/50019456
has body: I am fairly new to Python and I don't really know of how to use a custom package or its development life-cycle. I've been developing a Python library meant to be used from many scripts located on a specified folder in a production environment. Currently the library and the scripts that use it are heavily coupled from a development life-cycle perspective as it development is still in an early phase. Question is, how can I test the library works fine when used from the scripts? So far, in order to be able to import the custom library from the scripts, I've considered 3 different alternatives: As an installed package with pip or so Somehow downloading the package to a directory and alter the pythonpath As a directory within the scripts folder From my experience with other languages, option 1 would be the best, since it would probably be easier to handle package releases and everything would be in the 'standard' way, however in my case can be somehow difficult as the package source is hosted in a private Gitlab server isolated from the production environment. Options 2 and 3 seem to me like workarounds and not much like the 'good way' of using a custom library. Are there any other alternatives in Python to effectively use a package?
upvote count: 4
possible better answer: http://stackoverflow.com/a/50028051
type: AnsweredQuestion
score: 3
has title: Use custom Python package
answer count: 2
tagged with: pip
downvote count: 1

http://stackoverflow.com/q/49998436
has body: I hope this question isn't a duplicate; I found similar ones but not exactly what I need. I want an efficient way to split a list into n sublists where each index goes to a different list until we reach the nth index and then the next n indexes go to the lists we already have, in the same order, and so on... For example, given the following list: l = [1,1,1,2,2,2,3,3,3] n = 3 In this case I need to split the list into 3 lists with this desired output: [[1,2,3],[1,2,3],[1,2,3]] I can make n for loops that will skip every nth step, but I'm sure there is a better way.
answer count: 3
tagged with: python
tagged with: sublist
possible better answer: http://stackoverflow.com/a/49998648
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/312443
accepted answer: http://stackoverflow.com/a/49998627
tagged with: split
downvote count: 0
has answer: http://stackoverflow.com/a/49998648
linked to: http://stackoverflow.com/q/993984
has title: python: Splitting a list into n sublists by index
has comment: http://stackoverflow.com/comment/87018513
has comment: http://stackoverflow.com/comment/87013851
has comment: http://stackoverflow.com/comment/87013297
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50025269
has answer: http://stackoverflow.com/a/49998627
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87013465
tagged with: list

http://stackoverflow.com/comment/125805644
comment on: http://stackoverflow.com/a/49974471
score: 0
type: AnswerComment
has text: @VishalSingh. Use netcdf; outputting large datasets to csv is rarely a good idea.
type: Comment

http://stackoverflow.com/a/50540888
downvote count: 0
type: Answer
has body: go into the file "C:\xampp7\Python\lib\site-packages\pybinding\support\collections.py" and modify the command line as: "from matplotlib.collections import Collection#, allow_rasterization from matplotlib.artist import allow_rasterization"
has comment: http://stackoverflow.com/comment/88135867
has comment: http://stackoverflow.com/comment/88093111
score: 1
answers question: http://stackoverflow.com/q/49949775
upvote count: 1

http://stackoverflow.com/q/50048943
linked to: http://stackoverflow.com/q/5124376
has comment: http://stackoverflow.com/comment/87115976
has answer: http://stackoverflow.com/a/50049044
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87117584
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50049043
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50049062
score: 1
favorite count: 0
tagged with: numpy
tagged with: padding
possible better answer: http://stackoverflow.com/a/50049044
has body: I have a question regarding the addition of numpy arrays. Let's assume I have defined a function def foo(a,b): return a+b that takes two arrays of the same shape and simply returns their sum. Now, I have to deal with the cases that some of the entries may be None. I would like to deal with those entries as they correspond to float(0), such that [1.0,None,2.0] + [1.0,2.0,2.0] would add up to [2.0,2.0,4.0] Can you provide me with an already-implemented solution? TIA
has comment: http://stackoverflow.com/comment/87119105
type: Question
accepted answer: http://stackoverflow.com/a/50049062
has title: Adding arrays which may contain 'None'-entries

http://stackoverflow.com/q/49956985
tagged with: pip
favorite count: 0
score: 9
type: Question
has answer: http://stackoverflow.com/a/60701630
upvote count: 9
has answer: http://stackoverflow.com/a/52653079
has answer: http://stackoverflow.com/a/59875035
possible better answer: http://stackoverflow.com/a/59875035
tagged with: python
has answer: http://stackoverflow.com/a/61999356
answer count: 4
linked to: http://stackoverflow.com/q/31040446
tagged with: macos-sierra
linked to: http://stackoverflow.com/q/34828894
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25037006
accepted answer: http://stackoverflow.com/a/60701630
has title: How to install pygtk 3 on Mac OS X?
linked to: http://stackoverflow.com/q/5089649
tagged with: pygtk
downvote count: 0
has body: What I tried: brew install pygobject3 --with-python@2 gtk+3 brew install pygtk3 brew install pygobject3 pip install pygobject python -c 'import gi; gi.require_version("Gtk", "3.0")' Result: ValueError: Namespace Gtk not available for version 3.0 Note that I'm running conda, with python 3.6; and Mac OS X High-Sierra I read through the following questions/answers before posting: Easiest way to install pygtk on Mac OS X Python Gtk3 executable https://github.com/neovim/python-gui/issues/33 https://github.com/neovim/python-gui#dependencies-debian https://github.com/pybee/toga/issues/38 Error "Could not find any typelib for Gtk" with Python3 and GTK3 https://github.com/neovim/python-gui/issues/33 pyGtk: Gtk missing error when get version (Note that if I change the requires to 2.0, then it loads ok, but I get a warning: "RuntimeWarning: You have imported the Gtk 2.0 module. Because Gtk 2.0 was not designed for use with introspection some of the interfaces and API will fail. As such this is not supported by the pygobject development team and we encourage you to port your app to Gtk 3 or greater. PyGTK is the recomended python module to use with Gtk 2.0" )

http://stackoverflow.com/comment/108202176
comment on: http://stackoverflow.com/q/50017227
has text: check if you selected the right directory (in the top right corner open folder icon)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50052824
has body: Change the value at line #132 tensors_to_log = {"probabilities": "softmax_tensor"} or make it empty dictionary {} or dont pass logging_hook parameter at line #146 or set tf.logging.level to only warnings at line #23 tf.logging.set_verbosity(tf.logging.WARN) Credits : @bitsplit More details about logging : Tensorflow API documentation
has comment: http://stackoverflow.com/comment/87122117
has comment: http://stackoverflow.com/comment/87123090
answers question: http://stackoverflow.com/q/50052728
type: Answer
accepted answer of: http://stackoverflow.com/q/50052728
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87150111
score: 0
type: AnswerComment
has text: Not quite, now I am running into `BTC = next(filter(lambda x: x.currency == 'BTC', list_of_coin_obs)) TypeError: filter() takes 1 positional argument but 2 were given. Im not sure why I am running into this error when the same setup was working fine previously.
type: Comment
comment on: http://stackoverflow.com/a/50049277

http://stackoverflow.com/a/50072360
upvote count: 4
has comment: http://stackoverflow.com/comment/110133744
type: Answer
has body: The best practice is to use an explicit wait for the element of interest. That way you know it is there before clicking on it or otherwise interacting with it. So be sure to add these imports: from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome("path") # Only need to do this once per session driver.implicitly_wait(20) i=0 while i &lt; len(names): a = names[i] driver.set_page_load_timeout(25) driver.get("https://www.healthgrades.com/") driver.find_element_by_id("search-term-selector-child").send_keys(a) driver.find_element_by_id("search-term-selector-child").send_keys(u'\ue007') first = driver.find_element_by_class_name('uCard__name') first.click() timeout = 20 # Explicitly wait 20 seconds for the element to exist. # Good place to put a try/except block in case of timeout. elem = WebDriverWait(driver, timeout).until( EC.presence_of_element_located(('className', 'office-street1')) ) entry1 = elem.innerText ...
downvote count: 1
answers question: http://stackoverflow.com/q/50071983
has comment: http://stackoverflow.com/comment/117916700
score: 3

http://stackoverflow.com/a/50068588
answers question: http://stackoverflow.com/q/50068528
has body: Basically, your .csv is not a csv ;-) I suggest that you manually open and read that file, splitting each line using the first one whitespace, and then convert the result into a DataFrame if needed. fp = ... # your file pointer data = [line.split(' ', maxsplit=1) for line in fp] If you have a lot of data in your file, consider using a generator expression instead. In both case, you can convert data to a DataFrame: pandas.DataFrame.from_records(data, columns=['Integer', 'String']) (.. or directly using DataFrame constructor)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87177714
score: 4
has comment: http://stackoverflow.com/comment/87183633
accepted answer of: http://stackoverflow.com/q/50068528
type: Answer
upvote count: 4

http://stackoverflow.com/q/49964049
has title: How to distribute train set uniformly
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: machine-learning
tagged with: keras
has answer: http://stackoverflow.com/a/49971491
has answer: http://stackoverflow.com/a/49964079
score: 1
tagged with: python
has body: I am having the below follow directory structure data/ train/ Cat 1/ ### 5000 pictures dog001.jpg ... cat 2/ ### 3000 pictures cat001.jpg Cat 3/ ### 50000 pictures Unicorn.jpg ... Cat 4/ ### 10000 pictures Angels.jpg I am using the following below code load my images datagen = ImageDataGenerator(rescale=1./255) # automagically retrieve images and their classes for train and validation sets train_generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode="categorical") Since my data is not uniformly distributed so my model does not fit good, it become bias towards Cat 3 , so how i load a train data that is uniform all the four category ?

http://stackoverflow.com/a/50070445
has body: output = model(image) . Note that the image should be a Variable object and that the output will be as well. If your image is, for example, a Numpy array, you can convert it like so: var_image = Variable(torch.Tensor(image))
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/94515028
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50063514
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50063514

http://stackoverflow.com/comment/87119207
score: 0
comment on: http://stackoverflow.com/q/50046670
type: Comment
has text: Did you try requests too?
type: QuestionComment

http://stackoverflow.com/q/49950997
tagged with: python
has comment: http://stackoverflow.com/comment/86918630
has answer: http://stackoverflow.com/a/49951043
tagged with: list
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: sorting
linked to: http://stackoverflow.com/q/803616
downvote count: 1
favorite count: 0
type: Question
has title: Sort list by function with multiple arguments
has comment: http://stackoverflow.com/comment/86918657
score: 1
duplicate of: http://stackoverflow.com/q/803616
has comment: http://stackoverflow.com/comment/86918573
has body: I would like to sort a list using a function that returns a float value. If the function had a single argument, I would simply use sorted(mylist, key=myfunction) and be on my merry way. However, this doesn't work for functions with multiple arguments. How can this be done? This is a small part of a chess engine. The 'Bestmove' function takes in the board position (a list), the depth (an integer), and alpha/beta values and returns a list with two entries: the board evaluation (a float), and the suggested move (a list). In an effort to optimize the alpha/beta pruning process, I would like to change the order in which moves are evaluated (strong moves evaluated first leads to greater efficiency). To achieve this, I would like to sort the list of moves by the first value in the list returned by the 'Bestmove' function.

http://stackoverflow.com/a/49988570
downvote count: 0
upvote count: 1
has body: Using eval is not the best approach. SymPy parser has options that allow for parsing strings with things like t^2 (called convert_xor) and sin t (called implicit_application). Here is an example: from sympy.parsing.sympy_parser import parse_expr, standard_transformations, implicit_application, convert_xor transformations = standard_transformations + (implicit_application, convert_xor) f = parse_expr('t^2 * sin t + u*(20 + t) + v*t', transformations=transformations) Now f is t**2*sin(t) + t*v + u*(t + 20) and you can work with it normally, for example solve(f.subs({Symbol('u'): 4}), Symbol('v')) # returns [-t*sin(t) - 4 - 80/t] You may want to introduce u, v, t = symbols('u v t') to have easier access to those symbols. Unfortunately sint will not be recognized as sin(t); the lack of space is fatal. This will have to be preprocessed, probably with regular expressions. For example, import re s = re.sub(r'\bsin', 'sin ', 't^2 * sint + u*(20 + t) + v*t') leaves a space after each "sin" (extra space will not hurt).
type: Answer
answers question: http://stackoverflow.com/q/49987329
score: 1

http://stackoverflow.com/q/50062893
has comment: http://stackoverflow.com/comment/87143329
answer count: 1
accepted answer: http://stackoverflow.com/a/50063389
has title: Property of an abstract class?
type: Question
score: 0
tagged with: abstract-class
has body: I am doing a transition to Python and I find something confusing. Properties in Java or C# are declared after the class declaration. In Python properties are declared in the contractor: self.x = .... I want to have an abstract class that cannot be instantiated but classes that inherits from it has the same property. To make things even more clear. I have Shirt abstract class that should have a property like self.type = "Shirt" So all Shirts (T shirt, jacket, coat, etc..) self.type will be "Shirt". Right now all I have is this for example: class Shirt(object): __metaclass__ = ABCMeta class BlackShirt(Shirt): def __init__(self): self.type = self.__str__() self.value = self.Value.Basic.name def serialize(self): return { 'type': self.type, 'value': str(self.value) } def __str__(self): return "Black Shirt"
tagged with: python
has answer: http://stackoverflow.com/a/50063389
has comment: http://stackoverflow.com/comment/87142975
type: AnsweredQuestion

exchangelib
tags question: http://stackoverflow.com/q/50063010
type: Tag
tag name: exchangelib

http://stackoverflow.com/comment/87101001
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50042544
has text: Actually, your problem is not with the celery installation but with vine.
type: Comment

http://stackoverflow.com/q/50021228
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87060042
tagged with: python
score: -1
tagged with: linguistics
upvote count: 0
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/50021261
answer count: 1
has title: How to read/fetch Gujarati language in PDF format, using Python?
downvote count: 1
favorite count: 0
type: Question
has body: We have a PDF in Gujarati language. How to read it using Python language. I can read English based PDF document using Python. I want to do the same with a Gujarati based PDF document. Like this sample PDF in Gujarati language how to read it exactly using Python. "http://www.dkdave.in/PDF%20Materials/Gujarat/Gujarat%20Special.pdf"
tagged with: multilingual

http://stackoverflow.com/comment/86886323
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49921893
has text: @saikumar - I am a bit confused, I modify answer, but still not sure what need. Can you explain more?

http://stackoverflow.com/comment/87025762
type: QuestionComment
has text: @Vincent what indicates that it will be implemented at some point?
score: 0
comment on: http://stackoverflow.com/q/49989861
type: Comment

http://stackoverflow.com/comment/87034052
type: QuestionComment
has text: array is a list of lists, but x. is a scalar
comment on: http://stackoverflow.com/q/50008765
score: 1
type: Comment

http://stackoverflow.com/comment/86937723
type: AnswerComment
has text: @shrimpdrake, added some details, hope they will help you
comment on: http://stackoverflow.com/a/49955813
score: 1
type: Comment

http://stackoverflow.com/comment/86989563
score: 0
type: AnswerComment
has text: Cross-Origin Resource Sharing (CORS) is not flask specific. [The same-origin security policy](https://en.wikipedia.org/wiki/Same-origin_policy) forbids "cross-domain" requests by default (A user agent makes a cross-origin HTTP request when it requests a resource from a different domain, protocol, or port than the one from which the current document originated.). This means that a web application can only request HTTP resources from the same domain the application was loaded from. To allow cross origin resource sharing, you edit your web server configuration as shown in the links shared above
comment on: http://stackoverflow.com/a/49978398
type: Comment

http://stackoverflow.com/a/49918440
answers question: http://stackoverflow.com/q/49917951
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49917951
upvote count: 1
has body: (?m) (?&lt;!^)(?=\d+\.) You can try this regex for matching the character to be replaced with newline, \n Demo In python, new_content=re.sub(r'(?m) (?&lt;!^)(?=\d+\.)','\n', content)
score: 1
has comment: http://stackoverflow.com/comment/86852810
type: Answer

http://stackoverflow.com/a/50026609
has comment: http://stackoverflow.com/comment/87087215
has comment: http://stackoverflow.com/comment/87087085
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: As you said in the question: Each array has zeros and a numerical value(class index) at the end. If audio file belongs to class index = 1 and number of frames are 8 then y will be [0,0,0,0,0,0,0,1] First Step Input: [update] One approach to deal with variable input size is to use dynamic_rnn. Read more here Another way we deal with this problem, as we do in text classification is using padding. So say we create embeddings of size 10, so each word will have a 10 size vector input. A sentence input of say 5 words, will actually be a input of 5 * 10. Now, since TF/Keras accepts fixed size inputs. We pad the inputs. So we take a fixed input length of number of words (say 20 for this case). Words that occur after 20 are dropped. If a Sentence has 5 words it will have 15 paddings after that. Now the input will be passed through the embedding layer and final input will be (None, 20, 10) representing (Batch_size, Sequence_length, embedding_dimension). Your problem can also be converted into similar input. For example, one array is of length =&gt; (11,20) and other is of length =&gt; (9,20).Here 20 is the number of features and 11/9 denote sequence length Here assume sequence length to be 15 or so.. and assume 20 to embedding dimension. You will have to pad your input of size 9/11 to be consistent at say 15 (you can experiment with this number). 20 is your embedding dimension, features. So Final input shape will be (None, 15, 20). Next Step Output: You can now directly one hot encode your output class for each input. For input of 9,20 you have 1 one hot encoded output vector. Earlier you were thinking that for one input of length 9 and feature of 20 output should be of length 9, and first 8 output's should be 0 and 9th should be the class. This won't be needed anymore as 1 input of size (9,20) will give 1 output. Let me know if more explanation is needed, all the best :)
answers question: http://stackoverflow.com/q/50019036
has comment: http://stackoverflow.com/comment/87089403
has comment: http://stackoverflow.com/comment/87090661
type: Answer
has comment: http://stackoverflow.com/comment/87085971
accepted answer of: http://stackoverflow.com/q/50019036
has comment: http://stackoverflow.com/comment/87090259

http://stackoverflow.com/comment/87107955
has text: Yeah, that's true! Thanks!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50045310

http://stackoverflow.com/comment/86986371
type: Comment
type: AnswerComment
score: 0
has text: Are you given a URL for the image? Or its bytes? I have edited the answer with code to fetch from a url
comment on: http://stackoverflow.com/a/49973583

http://stackoverflow.com/comment/87169357
type: QuestionComment
score: 0
has text: @Fian yes. I do
comment on: http://stackoverflow.com/q/50068613
type: Comment

http://stackoverflow.com/comment/86856968
comment on: http://stackoverflow.com/a/49918551
type: AnswerComment
has text: Great!; two things: you can change the title of your answer, to reflect more precisely what you were trying to achieve, and you can mark my answer as the one resolved your problem
score: 0
type: Comment

http://stackoverflow.com/q/50006755
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87034907
tagged with: python
score: 0
has title: How do I handle the ',' in the sys.argv __name__ statement below
has comment: http://stackoverflow.com/comment/87043560
answer count: 0
has comment: http://stackoverflow.com/comment/87042671
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87043557
has comment: http://stackoverflow.com/comment/87034429
has body: This is a little terminal journal app I am working on. Intended functionality: type in terminal python3 journal.py whatever note I want to keep, with commas included. The entry 'whatever note I want to keep, with commas included' gets stored in a csv in a single cell. Actual functionality: the note 'whatever note I want to keep, with commas included' is split into multiple cells on the ','. This problem was solved in the multi_stuff function but the same technique isn't working in the sys.argv[1:] in the name portion. any thoughts? import csv import sys import re import datetime def record(stuff): with open('journal.csv', 'a') as f: f.write(str(datetime.datetime.now())+','+stuff+'\n') def multi_line(): while True: multi_stuff = input('Type "Q" to quit. Otherwise, talk to me -&gt; ').lower() if ',' in multi_stuff: multi_stuff = multi_stuff.replace(',', '","') if multi_stuff == 'q': break with open('journal.csv', 'a') as f: f.write(str(datetime.datetime.now())+','+multi_stuff+'\n') def search(): keyword = input('search term -&gt; ').lower() regex = r"\b(?=\w)" + re.escape(keyword) + r"\b(?!\w)" with open('journal.csv', 'r') as csv: for line in csv: if re.search(regex, line): print(line) if __name__ == '__main__': if sys.argv[1].lower() == '-s': search() elif sys.argv[1].lower() == '-m': multi_line() else: arg = sys.argv[1:] if ',' in arg: arg = arg.replace(',', '","') record(' '.join(arg)) else: record(' '.join(arg))
type: Question

http://stackoverflow.com/a/49969475
answers question: http://stackoverflow.com/q/49968431
has body: I have found that exactly I want to do.Thanks to Vasilis G. import random i=0 k="" while i&lt;100: i+=1 liste = [random.randint(97, 122) for i in range(8)] osman=''.join(chr(x) for x in liste) k+=osman+" " print(k)
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49968431

http://stackoverflow.com/comment/87047471
score: 0
type: Comment
type: QuestionComment
has text: Oh wow, I never would've thought to change there. That worked, thank you!
comment on: http://stackoverflow.com/q/50015521

http://stackoverflow.com/comment/86963294
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49973675
has text: Pass-by reference is very quick and memory-efficient: you only change one memory location instead of many. But there are side-effects that you need to be aware of - hence the examples you're looking at.

http://stackoverflow.com/a/49967859
type: Answer
has body: Just a bit more detail than Yasin Bahtiyar. Add to your Post model slug = models.SlugField ( verbose_name = "Slug", allow_unicode = True, unique=True) This will ensure the slug is unique and you don't get 2 records coming back but you'll need to ensure your slug is unique before saving. If you want to set your slug based on the title then do something like: slug = models.SlugField ( verbose_name = "Slug", allow_unicode = True, unique=True, blank = True, null = True) AND add a save function to the model: def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) Again, you'll need to add code to ensure it is unique.
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49967727
downvote count: 0
has comment: http://stackoverflow.com/comment/86955397

http://stackoverflow.com/comment/87151754
has text: good idea on hadoop, but it's not the answer for this question.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50067583
type: Comment

http://stackoverflow.com/q/49979171
tagged with: scikit-learn
score: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86975854
has comment: http://stackoverflow.com/comment/102734606
tagged with: grid-search
has title: Use of OneClassSVM with GridSearchCV
tagged with: python
has comment: http://stackoverflow.com/comment/86974947
has body: I am trying to perform a GridSearchCV function on OneClassSVM, but I can't seem to find right scoring method for OCSVM. From what i've gathered something like OneClassSVM.score does not exists thus is doesn't have a default scoring function needed in GridSearchCV. Unfortunately no scoring methods from the documentation doesn't work either because they are dedicated to supervised ML and OCSVM is a unsupervised method. Is there any way to perform GridSearch (or something similar to it, letting me tune the model with right parameters) on OneClassSVM?? Here is my code for GridSearchCV nus = [0.001, 0.01, 0.1, 1] gammas = [0.001, 0.01, 0.1, 1] tuned_parameters = {'kernel' : ['rbf'], 'gamma' : gammas, 'nu': nus} grid_search = GridSearchCV(svm.OneClassSVM(), tuned_parameters, scoring="??????????????????????", n_jobs=4) grid_search.fit(X_train) Yes I know .fit only takes one parameter but since it is unsupervised method i don't have any Y to put there. Thank you for the help.
tagged with: svm
upvote count: 4
has answer: http://stackoverflow.com/a/56564088
has comment: http://stackoverflow.com/comment/86975412
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87018390
score: 0
comment on: http://stackoverflow.com/q/50001154
type: Comment
type: QuestionComment
has text: May I know how to create directory using python? Is there any other method to do it if I still want to use the subprocess.call() ?

http://stackoverflow.com/comment/86972329
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49977670
type: AnswerComment
has text: @Kumar I changed the post 10 minutes ago, you'll see the difference.

http://stackoverflow.com/comment/86930832
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49954419
type: Comment
has text: What I don't feel you've addressed, however, is say I agree with you that I don't want the extra `() or (func)`. So, make it implicit. You said there would be confusion between `@decorate and @decorate()`. Is there confusion about `class Animal: and class Animal():`? My impression is no. (And sorry for the fuss---perhaps I don't know enough about the implementation of all these things to fully understand your points.)

http://stackoverflow.com/comment/87160220
score: 0
has text: You've already discovered the ability of `genfromtxt` to ignore some stuff. I demonstrate a different filtering in recent https://stackoverflow.com/a/50070649/901925
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50070739

http://stackoverflow.com/a/49944736
score: 0
has body: I found an answer https://github.com/ContinuumIO/anaconda-issues/issues/6006 I ran the following in Anaconda Prompt (as administrator): conda update anaconda-navigator Then, I ran Anaconda as administrator and it is working now.
type: Answer
answers question: http://stackoverflow.com/q/49944342

http://stackoverflow.com/comment/87165402
has text: Are you using an IPython console? If you're using Jupyter notebook, then try adding `py.init_notebook_mode(connected=True)`.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50070432
type: Comment

http://stackoverflow.com/comment/86937552
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49959038
has text: @AdamSrut, ok thanks for explanation. So in that case, should `sum([float(i), residuals[i]])` work?

http://stackoverflow.com/q/50037275
tagged with: python
tagged with: class
possible better answer: http://stackoverflow.com/a/50037420
has title: Class Function Not Finding Positional Argument Self in Python
type: AnsweredQuestion
tagged with: linked-list
has answer: http://stackoverflow.com/a/50037420
answer count: 2
linked to: http://stackoverflow.com/q/1132941
accepted answer: http://stackoverflow.com/a/50037442
score: 0
has body: I created a linked list class in Python and when calling the size function in which I defined, I am getting the following error: TypeError: get_next() missing 1 required positional argument: 'self' I tried calling another function in which I defined that also uses the get_next() function and it did not produce the error. Below is the Class definition as well as the test code. LinkedLists.py: class Node(object): def __init__(self, data = None, next_node = None): self.data = data self.next_node = next_node def get_data(self): return self.data def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList(object): def __init__(self, head = Node): self.head = head def insert(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node def size(self): current = self.head count = 0 while current: count += 1 current = current.get_next() return count def search(self, data): current = self.head found = False while current: if current.get_data() == data: found = True else: current = current.get_next() if current is None: raise ValueError("Data not in list") return current def delete(self, data): current = self.head previous = None found = False while current and found is False: if current.get_data() == data: found = True else: previous = current current = current.get_next() if current is None: raise ValueError("Data not in list") if previous is None: self.head = current.get_next() else: previous.set_next(current.get_next()) def insert_at(self, data, location): new_node = Node(data) current = self.head found = False while current and found is False: if current.get_data() == data: found = True else: current = current.get_next() if current is None: raise ValueError("Data not in list") new_node.set_next(current.get_next()) current.set_next(new_node) LinkedListsTest.py: from LinkedLists import * List = LinkedList() List.insert(5) List.insert(6) List.insert(8) List.delete(6) print(List.size()) The full trac…
has answer: http://stackoverflow.com/a/50037442
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87022410
has text: I think there is not a simple way to do this. You will need to build up the figure from graphics primitives. Suggest asking on mathematica.stackexchange.com
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50000042

http://stackoverflow.com/comment/87080898
comment on: http://stackoverflow.com/q/50032370
has text: Given the range of values (1e-195 to 1e-53, at least), perhaps using a logarithmic scale (also) helps?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50012283
upvote count: 2
type: Answer
has body: Split the list at the maximum value, then take the min/ max of the diff of each side: import numpy as np test1 = [1, 2, 3, 4, 5, 8, 7, 3, 1, 0] test2 = [1, 2, 3, 4, 5, 8, 7, 3, 1, 0, 2, 5] test3 = [7, 1, 2, 3, 4, 5, 8, 7, 3, 1, 0] test4 = [1, 2, 3, 4, 5, 8, 8, 7, 3, 1, 0] def incdec_test(x): i = np.array(x).argmax() return (np.diff(x[0:i]).min() &gt;= 0) and (np.diff(x[i:-1]).max() &lt;= 0) for test in [test1, test2, test3, test4]: print 'increase then decrease = {}'.format(incdec_test(test)) Results: increase then decrease = True increase then decrease = False increase then decrease = False increase then decrease = False
score: 2
answers question: http://stackoverflow.com/q/50012089
downvote count: 0
has comment: http://stackoverflow.com/comment/87041452
has comment: http://stackoverflow.com/comment/87041445

http://stackoverflow.com/a/60449826
downvote count: 0
upvote count: 5
answers question: http://stackoverflow.com/q/50056356
type: Answer
has body: In my case it was because I missed the parentheses. I am using tensorflow_addons so my code was like model.compile(optimizer=tfa.optimizers.LAMB, loss='binary_crossentropy', metrics=['binary_accuracy']) And it gives ValueError: ('Could not interpret optimizer identifier:', &lt;class tensorflow_addons.optimizers.lamb.LAMB'&gt;) Then I changed my code into: model.compile(optimizer=tfa.optimizers.LAMB(), loss='binary_crossentropy', metrics=['binary_accuracy']) and it works.
score: 5

http://stackoverflow.com/comment/87312057
has text: @GrantWalton Ok, then please accept the answer if it helped.
type: Comment
comment on: http://stackoverflow.com/a/50060051
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86903464
type: AnswerComment
has text: I realize it should have been point * log.... not trials * log.... So it's all good, thank you everyone!
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49924332

http://stackoverflow.com/comment/128164968
score: 0
comment on: http://stackoverflow.com/a/49961085
type: Comment
has text: Thanks i just added the hierarchy variable after ````boundingBoxes```` like code below. And it worked :)
type: AnswerComment

http://stackoverflow.com/q/50049225
type: Question
tagged with: dll
linked to: http://stackoverflow.com/q/50043861
has comment: http://stackoverflow.com/comment/87122648
tagged with: python
accepted answer: http://stackoverflow.com/a/50053550
has comment: http://stackoverflow.com/comment/87116443
has body: I am creating a Python wrapper for a C DLL using Python ctypes. In the Python code below I am creating a array connectionString of c_ubyte that I need to fill int the individual. For example 1,2,3,4,5,6... This connection string is passed to the DLL's DoCallBack function and printed. A buffer is created for the callback function to fill in and everything is passed to the python call back function. I am looking for a way to update the connectionString bytes before passing them to the DLL's DoCallBack. Then how to extract the bytes from the connectionString in the python callbackFnk function. I am looking for a way to update the bytes in outBuffer from the callbackFnk python function A continuation of this question In python how do I set the value of a LP_c_ubyte C DLL Code typedef void(*FPCallback)(unsigned char * outBuffer, unsigned short MaxOutBufferLength, unsigned char * connectionString); FPCallback g_Callback; extern "C" __declspec( dllexport ) void RegisterCallback(void(*p_Callback)( unsigned char * outBuffer, unsigned short MaxOutBufferLength, unsigned char * connectionString)) { g_Callback = p_Callback ; } extern "C" __declspec( dllexport ) void DoCallBack( unsigned char connectionString) { printf( "connectionString=[%02x %02x %02x %02x %02x %02x...]\n", connectionString[0], connectionString[1], connectionString[2], connectionString[3], connectionString[4], connectionString[5] ); const unsigned short MAX_BUFFER_SIZE = 6 ; unsigned char outBuffer[MAX_BUFFER_SIZE]; g_Callback( outBuffer, MAX_BUFFER_SIZE, connectionString, 6 ); // Print the results. printf( "buffer=[%02x %02x %02x %02x %02x %02x...]\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5] ); } Python code def callbackFnk( outBuffer, outBufferMaxSize, connectionString ) # (Q2) How do I extract individual bytes of the connectionString? # (Q3) How do I update individual bytes of the out buffer? customDLL = cdll.LoadLibrary ("customeDLL.dll") # RegisterCallback CustomDLLCallbackFUNC = C…
has answer: http://stackoverflow.com/a/50053550
tagged with: ctypes
type: AnsweredQuestion
score: 0
answer count: 1
has title: Updating an LP_c_ubyte buffer created in a C DLL
linked to: http://stackoverflow.com/q/50033276

http://stackoverflow.com/comment/87605246
type: QuestionComment
has text: BTW Emgu is a wrapper around the same OpenCV library used by Python. You shouldn't see any significant differences if both programs do the same. You *could* improve performance if you used parallel processing in each case. In C# you could use eg PLINQ or Parallel.ForEach
score: 0
comment on: http://stackoverflow.com/q/50012126
type: Comment

http://stackoverflow.com/q/49971496
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am trying to make an RSS and ATOM feed for a blog I am working on. But when I try to access the URL http://127.0.0.1:8000/blog/rss of my feed, it return the error: 404 No post found matching the query This is the content of my file feeds.py: from django.contrib.syndication.views import Feed from blog.models import Post from django.utils.feedgenerator import Atom1Feed class RssSiteNewsFeed(Feed): title = "Police beat site news" link = "/sitenews/" description = "Updates on changes and additions to police beat central." def items(self): return Post.objects.all.order_by('date')[:5] class AtomSiteNewsFeed(RssSiteNewsFeed): feed_type = Atom1Feed subtitle = RssSiteNewsFeed.description Here are the relevant part of my file urls.py: urlpatterns = [ ... path('blog/rss/', RssSiteNewsFeed()), path('blog/atom/', AtomSiteNewsFeed()), ] And finally here are the models from the file models.py: from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField (max_length = 160) slug = models.SlugField(max_length = 160,unique=True) date = models.DateTimeField() class meta : ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_absolute_url(self ): return "/blog/Category/%s" % self.slug def __str__(self): return self.name def __unicode__(self): return self.name class Post(models.Model): title = models.CharField (max_length = 160, null=False) body = models.TextField( null=False) date = models.DateTimeField() author = models.CharField (max_length = 160) description = models.TextField(max_length = 160) keywords = models.TextField() category = models.ForeignKey(Category,on_delete=models.DO_NOTHING) slug = models.SlugField(max_length = 160,unique=True) img_url = models.URLField() short_blog_snippet= models.CharField(max_length = 15) absolute_url = models.CharField(max_length=400, blank=True, editable=False) def __str__(self): return self.title def get_absolute_url(self ): return "/blog/%s" % self.slug d…
tagged with: python
tagged with: http-status-code-404
has title: django rss returns 404
has answer: http://stackoverflow.com/a/49984611
tagged with: rss
score: 1
answer count: 1
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/86853875
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49918805
type: Comment
has text: The way to avoid loading the whole file is to only keep the last 4 lines, see my answer for a way to do it.

http://stackoverflow.com/a/49946552
answers question: http://stackoverflow.com/q/49946213
has body: Attempting an answer even though I am not 100% sure of what you mean still. Try to change your Javascript to: $(sub).click(function(ev){ ev.preventDefault(); // Stop the form from redirecting the page. $.ajax({ type:'GET', url:'/cgi-bin/t1.py', // Or /cgi-bin/run.py. I'm not sure where your python script is. cache:false, dataType: 'html', data: $('form').serialize(), // Send the form data in the request. success:function (z) { $('#output').html(z); } }); });
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49946213
has comment: http://stackoverflow.com/comment/86909577
has comment: http://stackoverflow.com/comment/86909549

http://stackoverflow.com/comment/114486160
comment on: http://stackoverflow.com/q/49987042
type: Comment
score: 0
has text: The input data has invalid syntax. Without correctly defined data it's difficult to understand what's being asked here.
type: QuestionComment

http://stackoverflow.com/comment/86939728
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49960451
has text: The way you have implemented the client must receive two files for each update - show.html and *.jpg. These are two http requests. Currently your browser often caches the *.jpg request - so doesn't ask the server for it again. To ensure the client web browser always asks for the image again, you must set a header indicating that file has immediately expired.
type: Comment

http://stackoverflow.com/q/50005148
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50008190
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
has title: how to edit a list of dictionary with tkinter
tagged with: list
tagged with: tkinter
has body: i would like to have a way for the user to edit the lists that they have made with the edit tab that i have on the tool bar. i have no idea how i should approach this whale still using a list of dictionary's full code https://pastebin.com/6VAnZTyi #************for defining what is in the list******************* class My_QueryString(tkinter.simpledialog._QueryString): def body(self, master): self.bind('&lt;KP_Enter&gt;', self.ok) # KeyPad Enter super().body(master) def list_data(title, prompt, **kw): d = My_QueryString(title, prompt, **kw) return d.result root = Tk() #list def liststagering(New_List): for item in New_List: print(item) def New_List(): new_list = myaskstring("list", "what do you want to name this list") List_Data = list_data("list","what should be in this list") if str(new_list): print(new_list) newList = dict() newList['title'] = new_list newList['listData'] = List_Data List_MASTER.append(newList) print("title : "+new_list) print(List_Data) List_MASTER = [] lll=print (List_MASTER) def printtext(): T = Text(root) T.pack(expand=True, fill='both') printData = "" print(List_MASTER) for i in range(len(List_MASTER)): printData += List_MASTER[0]['title'] +"\n"+List_MASTER [i]['listData'] + "\n"; T.insert(END, printData , ) for printData in T: T.delete(0,END)
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87032457
answer count: 1
tagged with: user-interface

http://stackoverflow.com/a/53624184
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49974970
has body: Really happy to say that i did exactly same in Python. Have a look to my repo in github https://github.com/digitaldreams/image-crawler-python
type: Answer

http://stackoverflow.com/q/50054740
upvote count: 1
tagged with: python
tagged with: computer-vision
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/87128473
has comment: http://stackoverflow.com/comment/87142496
score: 1
has answer: http://stackoverflow.com/a/50069380
has title: How do I format my targets to train a Keras CNN model?
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has body: My dataset is images of whales. I am trying to train a CNN that can locate 2 points of the whale in the given image. My training features are the image in a numpy array, and the targets are the x and y coordinates of 2 points in the image (2 points on the whale). What is the best way to make a neural network with Keras that can learn from the dataset I have, so that it will be able to locate those points on new, unlabeled images? My main problem at the moment is figuring out how to format the target (The 2 points in the image) so that my Keras model can understand/read the data. The broken code I have is: x_train = np.array([cv2.imread("1small.jpg")]) y_train = np.array([14.1, 13.5, 16.3, 14.1]) x_test = np.array([cv2.imread("0small.jpg")]) y_test = np.array([11.8, 10.8, 17.0, 16.0]) # fake data just to test model = Sequential() model.add(Dense(1,32,32,3)) model.add(Activation('tanh')) model.add(Dense(1)) model.compile(loss='mean_absolute_error', optimizer='rmsprop') model.fit(x_train, y_train, nb_epoch=1, batch_size=1) prediction = model.predict(x_test) print prediction
downvote count: 0
answer count: 1

http://stackoverflow.com/q/50033350
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87082875
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have the below code used to create a CSV file: import csv srcFile = open("C:\Users\XXXX\Expenses.csv","r") data = srcFile.read() srcList = data.split("\n") colNames = srcList[0].split(",") header = srcList[1] sheetData = srcList[2:] final_data = [] expense_data = [] for row in sheetData: split_row = row.split(",") final_data.append(split_row) for row in range(0, len(final_data)-1): for col in range(3, 30): loc = final_data[row][0] opsheet = final_data[row][1] rowNum = final_data[row][2] colName = colNames[col] str1 = "='\\\xxxxxxx\xxxx\xxx\[APR_" str2 = "_DATA.xlsm]" str3 = "\'!" str4 = "$" finalStr = str1 + loc + str2 + opsheet + str3 + colName + str4 + rowNum final_data[row][col] = "" with open("c:\users\xxxxx\new_expenses.csv", "wb") as f: fwriter = csv.writer(f) fwriter.writerows(final_data) I'm a beginner in Python and I know this code is not up to the standards or a real way to code. But this code works fine and creates a CSV file. Now the problem is this file is already created by someone else and I'm replicating it for other purposes with new data and everything. The existing file, created earlier, was only 30MB in size. But the file that is created in this method is 180MB and takes an enormous amount of time to open. The original file is nothing but a single worksheet with 51,000 rows and 20 Columns each cell referencing to some cell in a workbook in a network location. Any idea on how to reduce the size? or What is causing the huge? Also as a beginner, any suggestions/feedback to improving the code is really appreciated. Thanks in advance!!
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87083500
has title: I created a CSV File using Python. But the size is huge

http://stackoverflow.com/q/49957822
tagged with: python-3.6
downvote count: 1
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86936869
has title: Web: How often does Flask/JS refresh?
has answer: http://stackoverflow.com/a/49960451
score: -1
type: Question
has comment: http://stackoverflow.com/comment/86932448
upvote count: 0
type: UnansweredQuestion
has body: I'm trying to get images to display in real-time only on my machine. Think a really basic version of Google Images. The user types in "red hammer" and I show them a picture of red hammer The problem is the refresh rate. I update the image file to be shown, and when I look it up directly as http://127.0.0.1:6007/static/tree.jpg, that will immediately give me the most recent jpg. And then, strangely enough after I look up something like http://127.0.0.1:6007/static/tree.jpg, the image changes on the initial http://127.0.0.1:6007 ! My setup: In the static/ directory, tree.jpg: templates/ show.html In templates/, show.html: Text-to-Image Synthesis Input to Generator: index.html and index.html: Text-to-Image Synthesis Input to Generator: These two are the same except show.html shows the image on the src=... line. server.py #!/usr/bin/env python2.7 import os from flask import Flask, request, render_template, g, redirect, Response, send_from_directory tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) @app.route('/') def index(): return render_template("index.html") @app.route('/generator', methods=['POST']) def generator(): # save typed-in text text = request.form['input_text'] filename = "/home/ubuntu/icml2016/scripts/cub_queries.txt" with open(filename, "a+") as f: f.write(text + "\n") """ print('start') subprocess.call('./scripts/demo_cub.sh', shell=True) # change the image in the background print('end') """ return render_template("show.html") if __name__ == "__main__": HOST='0.0.0.0' PORT=6007 app.run(host=HOST, port=PORT) So now if I've properly given you everything, you should be able to call python3 server.py and see this: and if you type in "hi" to the box it'll show this: but when I change tree.jpg to some other image in the background and type in something else, I don't get the instant image update I'm looking for. In other words, that tree won't become the most recent tree :( We want …
answer count: 1
tagged with: javascript
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/86936401
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49956906
has text: `defaultdict(int)` is a more efficient way to do this.

http://stackoverflow.com/q/50059451
has comment: http://stackoverflow.com/comment/87136065
has comment: http://stackoverflow.com/comment/87135321
has comment: http://stackoverflow.com/comment/87135473
has comment: http://stackoverflow.com/comment/87136180
has comment: http://stackoverflow.com/comment/87135305
has comment: http://stackoverflow.com/comment/87135453
upvote count: 0
has comment: http://stackoverflow.com/comment/87135906
has comment: http://stackoverflow.com/comment/87135834
has comment: http://stackoverflow.com/comment/87135699
tagged with: singleton
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87135761
has body: I have created a singleton wrapper for the selenium webdriver. class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Driver(metaclass=Singleton): """Ensures theres only 1 Driver open at any time. If the driver is closed, tries to quit the previous instance, and recreates a new one""" def __init__(self): self._driver = self.load_selenium_driver() @staticmethod def load_selenium_driver(): _chrome_driver_locn = CHROME_DRIVER_LOCATION _driver = webdriver.Chrome(_chrome_driver_locn) return _driver @property def driver(self): """Creates a new driver if the previous one is closed, and quits the instance of the chrome driver.""" if self._web_browser_is_open(): return self._driver else: try: self._driver.quit() finally: self._driver = self.load_selenium_driver() return self._driver def _web_browser_is_open(self): try: self._driver.title return True except WebDriverException: return False Running a = Driver() I want to access the Driver.driver methods, in a, so that I don't need to do a.driver.get('google.com'), but a.get('google.com'). The question: How do I make an instance of Driver, return the driver object (found in the property Driver.driver), rather than the instance of the Driver?
has title: Change what an instance returns python
has comment: http://stackoverflow.com/comment/87135483
has answer: http://stackoverflow.com/a/50060061
has comment: http://stackoverflow.com/comment/87136211
has comment: http://stackoverflow.com/comment/87135620
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1535327
has comment: http://stackoverflow.com/comment/87135467
has comment: http://stackoverflow.com/comment/87135280
has comment: http://stackoverflow.com/comment/87135378
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87135430
has comment: http://stackoverflow.com/comment/87136334
has comment: http://stackoverflow.com/comment/87135338
has comment: http://stackoverflow.com/comment/87135557
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87135953
tagged with: inheritance

http://stackoverflow.com/comment/87112551
has text: Thanks for your answer. I see you expanded the Matrix in equations. How to keep them in Matrix? Is linsolve(a1*matrix([[x1],[y1]])....) the right way?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50048060
type: Comment

http://stackoverflow.com/a/49993278
answers question: http://stackoverflow.com/q/49993026
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87003263
has body: You have a syntax error in your "/" route @app.route("/") def main(): return(render_template('Senty.html')) The correct code is: return render_template('Senty.html')

http://stackoverflow.com/a/50045792
answers question: http://stackoverflow.com/q/50045518
has comment: http://stackoverflow.com/comment/87108608
type: Answer
score: 1
downvote count: 0
has body: you can add a new column easily to existing dataframe "df" as below: df['USER_CHECKED_IN_CONTENT'] = 0 # df is your existing dataframe
upvote count: 1
has comment: http://stackoverflow.com/comment/87107797

http://stackoverflow.com/comment/87181259
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50071647
has text: Well, not necessarily, but your metric is a bit harsh on yourself this way. Basically, if you're treat them as independent classes, and you predict 5 years of age, and the true age is 6 or 99, your loss will be the same. So for age it makes sense to use the square difference or similar as loss. Do you want something to do with abalones or are you looking for any dataset to practice classification?

http://stackoverflow.com/a/49978853
score: 9
upvote count: 9
has body: First find out your IP camera's streaming url, like whether it's RTSP/HTTP etc. Code changes will be as follows: cap = cv2.VideoCapture("ipcam_streaming_url") For example: cap = cv2.VideoCapture("http://192.168.18.37:8090/test.mjpeg")
has comment: http://stackoverflow.com/comment/88442265
has comment: http://stackoverflow.com/comment/88438751
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/88441910
answers question: http://stackoverflow.com/q/49978705

http://stackoverflow.com/comment/87093620
score: 0
has text: Can I interpret 111 as BBB and LB and BL : Yes. Absolutely.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50034347

http://stackoverflow.com/comment/87124327
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50053887
has text: What is the dimension of your 2D array, how many elements are there? row? and column ?
type: Comment

http://stackoverflow.com/comment/86962320
comment on: http://stackoverflow.com/q/49972924
score: 1
type: QuestionComment
has text: It really depends on the C (not C++, let alone C#!) library. Some require you to allocate memory, others specifically need to do it themselves. Consult the documentation for yours, or [edit] your question to link to it so we can see what it says. Dynamic structures will often by necessity be allocated by the library; *guessing* how much memory something requires is totally unacceptable for production code.
type: Comment

http://stackoverflow.com/a/49970766
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: This should work for you (although there is certainly a more compact way) : stock_dict = {} for user_list in new_dict.values(): for stock_tuple in user_list: stock_name = stock_tuple[0] if (not (stock_name in stock_dict.keys())): stock_dict[stock_name] = list(stock_tuple[1:]) else: stock_dict[stock_name][0] += stock_tuple[1] stock_dict[stock_name][1] -= stock_tuple[2] You could also zip and sum, but its less intuitive. Basically what you do is create a value for the specific key (if it doesn't exist - this part is only necessary because you dont want to use a default dict), and if it does exist you add the relevant values.
answers question: http://stackoverflow.com/q/49970678

http://stackoverflow.com/comment/86920108
comment on: http://stackoverflow.com/q/49951768
score: 0
type: Comment
has text: In the dataframe, some of the index values are not what I want. The 1st list identifies which index values I want to change, the second list identifies the values I want to change them to. Same number of items in each list - and their positions match.
type: QuestionComment

http://stackoverflow.com/comment/87028958
comment on: http://stackoverflow.com/a/50006078
type: Comment
score: 0
type: AnswerComment
has text: That's it! Thanks! os.system("ffmpeg -r 2 -i %*.jpg -vcodec mpeg4 -y movie.mp4") That's all it took.

http://stackoverflow.com/comment/87102888
comment on: http://stackoverflow.com/q/50042040
type: Comment
score: 0
has text: Why not download the tar file from pypi.org directly?
type: QuestionComment

http://stackoverflow.com/q/49926397
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86869340
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86869273
accepted answer: http://stackoverflow.com/a/49991496
has comment: http://stackoverflow.com/comment/86871038
tagged with: matrix
has title: Is there a Python equivalent to MATLAB's vct2mtx?
score: 1
has answer: http://stackoverflow.com/a/49991496
answer count: 1
has comment: http://stackoverflow.com/comment/86869219
downvote count: 0
has comment: http://stackoverflow.com/comment/86868930
has body: I have a list of points (latitudes and longitudes) and a corresponding list of values for those points. Now I would like to make a 2D grid from this. While it is straight-forward to loop over sorted longitudes and latitudes to create the 2D grid, I was wondering if there is an efficient Python function (perhaps in numpy?) import numpy as np lats = [1,2,3] lons=[4,5,6] values=[7,8,9] def vec2mtx(lats, lons, values): Z = np.zeros((len(set(lats)),len(set(lons)))) Z.fill(-9999) # no data value lats_grid = np.zeros((len(set(lats)),len(set(lons)))) lons_grid = np.zeros((len(set(lats)),len(set(lons)))) search_sorted_lats = np.searchsorted(np.sort(list(set(lats))), lats) search_sorted_lons = np.searchsorted(np.sort(list(set(lons))), lons) Z[(search_sorted_lats, search_sorted_lons)] = values lats_grid[(search_sorted_lats, search_sorted_lons)] = lats lons_grid[(search_sorted_lats, search_sorted_lons)] = lons Z = np.flipud(Z) return lats_grid, lons_grid, Z lats_grid, lons_grid, Z = vec2mtx(lats, lons, values) This code does what I need to do, but this seems like too many lines for something that should be like a one liner in numpy?
favorite count: 0
has comment: http://stackoverflow.com/comment/86920544
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86914139
has comment: http://stackoverflow.com/comment/86920526

http://stackoverflow.com/comment/87045618
type: QuestionComment
comment on: http://stackoverflow.com/q/50014697
has text: This means that they are optional parameters (and can be left)
score: 4
type: Comment

http://stackoverflow.com/q/50038277
score: 4
upvote count: 4
type: AnsweredQuestion
has title: Not able to understand python function of cosine similarity
downvote count: 0
answer count: 1
has body: I am working through the example in the blog to understand collaborative filter method used in recommendation system.I came across cosine similarity expressed as In python using numpy its written as def similarity(ratings, kind='user', epslion=1e-9): if kind == 'user' : sim = ratings.dot(ratings.T) elif (kind=='item'): sim = ratings.T.dot(ratings) + epslion norms = np.array([np.sqrt(np.diagonal(sim))]) return (sim / norms / norms.T ) Questions what is the math behind calculation of the norm in the code how does (sim / norms / norms.T ) equals to sim(u,u`) in the equation Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.
favorite count: 0
type: Question
tagged with: cosine-similarity
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50041871
has answer: http://stackoverflow.com/a/50041871
tagged with: math
tagged with: python
tagged with: linear-algebra

http://stackoverflow.com/comment/87080724
score: 1
type: Comment
type: QuestionComment
has text: Check out [`statistcs.mean`](https://docs.python.org/3/library/statistics.html#statistics.mean)
comment on: http://stackoverflow.com/q/50032261

http://stackoverflow.com/a/52053172
downvote count: 0
has body: The difference between the two methods is demonstrated clearly in this post on multi-task learning in tensorflow. In short: Method 1: This is called joint training, since it directly adds the losses together, the result is that all the gradients and updates are done with respect to both losses at the same time. Generally this is used when training multiple outputs using the same set of input features. Method 2: This creates two separate optimizers and is called alternate training. This is used when you use a subset of input features for each of the outputs. Therefore, when feeding in the feature subset for train_op1, the sub-graph for train_op2 is untouched. Each optimizer can be called in an alternating order using different input features. If you run both optimizer concurrently with the same input data, then the differences with method 1 is probably very minor.
score: 23
upvote count: 23
type: Answer
answers question: http://stackoverflow.com/q/49953379

http://stackoverflow.com/comment/87042560
has text: I think he understands that
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50013104
type: AnswerComment

http://stackoverflow.com/q/49970421
downvote count: 1
has body: I would like to implement ML model for classification problem. My csv data looks like this: Method1; Method2; Method3; Method4; Category; Class result1; result2; result3; result4; Sport; 12 ... ... All methods, gives a text. Sometimes it is a one word, sometimes more and sometimes the cell is empty (no answer for this method). Column "category" always has a text and column "class" is a numerical showing number of method with correct answer (i.e. number 12 means that only result from method 1 and 2 is correct). Maybe will add more column if necessary. Now, having a new answers from all methods I would like to classify it to one of the class. How should I prepare this data? I know I should have a numerical data but how to do that, and handle with all empty cells, and inconsistent number of words in each answer?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/49982569
score: 0
upvote count: 1
has title: Preparing csv data to ML
answer count: 1

http://stackoverflow.com/a/50004619
type: Answer
accepted answer of: http://stackoverflow.com/q/50003851
answers question: http://stackoverflow.com/q/50003851
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Python isn't C and it doesn't make sense to talk about copying one instance's memory on top of another's. You can achieve a similar result by copying all the attributes from one instance to another. In most Python objects, the attributes are stored in an instance attribute called __dict__, except when there's a __slots__ attribute on the class, which defines the names of the allowed attributes. Many built-in Python objects are implemented in C and so don't have either of these attributes. These generally can't be copied by attribute in any sensible automated fashion. With these caveats, you could do something like the following: def copy_attributes(obj1, obj2): if not isinstance(obj1, type(obj2)) and not isinstance(obj2, type(obj1)): raise TypeError("source and target object types must be related somehow") # fast path if both have __dict__ if hasattr(obj1, "__dict__") and hasattr(obj2, "__dict__"): obj2.__dict__.update(obj1.__dict__) return # copy one attribute at a time names = getattr(type(obj1), "__slots__", ()) and getattr(obj1, "__dict__", ()) slots = set(getattr(type(obj2), "__slots__", ())) if slots and not all(name in slots for name in names): raise AttributeError("target lacks a slot for an attribute from source") for name in names: setattr(obj2, getattr(obj1, name)) The way I've written this function, the two instances must be related (one a subclass of the other's type). This increases the likelihood that this will actually work, although depending on how the classes are set up, it may or may not result in a useful configuration of obj2 unless they are exactly the same type. That is, attributes that obj2 has but obj1 doesn't will retain their original values, and this may produce an inconsistent object. You might prefer more strict type-checking: if type(obj1) is not type(obj2) for example. if the type of obj2 has __slots__ and obj1 has attributes that aren't permitted in obj2, you'll get an error trying to set those attributes. In this case, I check to m…
score: 3

http://stackoverflow.com/a/66372592
upvote count: 1
answers question: http://stackoverflow.com/q/49968002
score: 1
has body: You're not defining the change_presence function. To make it work, do this: async def change_presence(): print ("Starting up") print ("My username is " + bot.user.name + " and i am running with the ID: " + bot.user.id) await bot.change_presence(game=discord.Game(name="Test", type=1)) print ("Started") change_presence(); Hope this helped you! :)
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86961826
type: Comment
type: QuestionComment
has text: I suspected as much from your description. Could you post it here?
comment on: http://stackoverflow.com/q/49972792
score: 1

http://stackoverflow.com/comment/87163463
score: 0
type: Comment
has text: @cricket_007 thanks.. do you know any such software that constantly checks for files? or any suggestions for how I could do implement such a program on python?
type: QuestionComment
comment on: http://stackoverflow.com/q/50071264

http://stackoverflow.com/comment/122530862
comment on: http://stackoverflow.com/a/49950891
score: 0
has text: yeah you are right :) but you've made a typo it's classes_, not classess_
type: Comment
type: AnswerComment

lighttpd
tags question: http://stackoverflow.com/q/50058932
type: Tag
tag name: lighttpd

http://stackoverflow.com/comment/86908144
score: 0
type: Comment
type: QuestionComment
has text: Please provide a [reproducible example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples).
comment on: http://stackoverflow.com/q/49945414

http://stackoverflow.com/q/50073273
tagged with: django
tagged with: celery
has body: I'm running Celery/Django on my remote Ubuntu server via supervisor. My system can successfully receive and execute my 2 tasks from my tasks.py. @periodic_task(run_every=timedelta(minutes=1)) def test_job(): from polls.models import Question from post.models import Post #when I add this line, it fires the error for i in Question.objects.all(): if i.question_text == "test": i.question_text = "not_test" i.save() return HttpResponseRedirect('/') @periodic_task(name='run_scheduled_jobs', run_every=timedelta(seconds=30)) def run_scheduled_jobs(): return True However, when I use: from post.models import Post in my task, the task fails: I've tried importing models from all my other modules and it works fine; e.g. from Comment.models import Comment and from poll.models import Question works fine. For some reason it's not letting me import from post.models import Post. Here is the post.models file: from django.db import models from django.contrib.auth.models import AbstractUser, User from django.conf import settings #from django.contrib.humanize import naturaltime from django.apps import apps from draft1.choices import CATEGORY_CHOICES from django.utils import timezone import requests import tempfile from django.core import files from django.core.files import File as FileWrapper from datetime import datetime, timedelta from math import log10 from urllib import parse from urllib.parse import urlparse import boto3 # import uuid from functions.helper_functions import random_string from math import log, exp from draft1.choices import DURATION_CHOICES class Post(models.Model): hash = models.CharField(max_length=18, default=random_string, null=True, blank=True) user = models.ForeignKey(User, blank=True, null=True) has_upvoted = models.ManyToManyField(User, related_name="has_upvoted", blank=True) has_downvoted = models.ManyToManyField(User, related_name="has_downvoted", blank=True) title = models.TextField(max_length=95) second_title = models.TextField(max_length=95, blank=True, nu…
has answer: http://stackoverflow.com/a/50074212
has title: Unable to import model in my celery task
linked to: http://stackoverflow.com/q/19475955
tagged with: supervisord
tagged with: python
type: Question
score: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/50014827
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75510402
tagged with: azure
has answer: http://stackoverflow.com/a/73114906
linked to: http://stackoverflow.com/q/50923055
has title: Write Python DataFrame as CSV into Azure Blob
tagged with: azure-blob-storage
upvote count: 18
linked to: http://stackoverflow.com/q/62384733
tagged with: python
has answer: http://stackoverflow.com/a/68717545
possible better answer: http://stackoverflow.com/a/68717545
has answer: http://stackoverflow.com/a/50017842
accepted answer: http://stackoverflow.com/a/50017842
answer count: 5
has answer: http://stackoverflow.com/a/75113254
downvote count: 0
score: 18
tagged with: azure-storage
has body: I have got two questions on reading and writing Python objects from/to Azure blob storage. Can someone tell me how to write Python dataframe as csv file directly into Azure Blob without storing it locally? I tried using the functions create_blob_from_text and create_blob_from_stream but none of them works. Converting dataframe to string and using create_blob_from_text function writes the file into the blob but as a plain string but not as csv. df_b = df.to_string() block_blob_service.create_blob_from_text('test', 'OutFilePy.csv', df_b) How to directly read a json file in Azure blob storage directly into Python?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/118825754

http://stackoverflow.com/q/49976353
has answer: http://stackoverflow.com/a/68192936
possible better answer: http://stackoverflow.com/a/68192936
has answer: http://stackoverflow.com/a/49976540
tagged with: python
has answer: http://stackoverflow.com/a/75465686
has title: Python TK Notebook tab change check
has comment: http://stackoverflow.com/comment/129116934
type: AnsweredQuestion
answer count: 3
has body: Newbie programmer here. I am building a tk based desktop app and ran into an issue: I have a main window with several stuff in it including two tabs: global nBook nBook = ttk.Notebook(self, name="book") nBook.place(x=300,y=400) frameOne = ttk.Frame(nBook, width=100, height=100) frameTwo = ttk.Frame(nBook, width=100, height=100) nBook.add(frameOne, text='T1') nBook.add(frameTwo, text='T2') frameOne.bind("&lt;&lt;NotebookTabChanged&gt;&gt;", self.routine()) frameTwo.bind("&lt;&lt;NotebookTabChanged&gt;&gt;", self.routine()) routine() is a function that SHOULD perform a check every time T2 is selected def routine(self): if str(nBook.index(nBook.select())) == "2": # Do stuff else: pass Problem is that it doesn't do anything when the tab is changed except for calling the routine function as soon as I open the app and never again. I just can't figure out what I'm doing wrong. Could anyone point out the mistake(s) I'm making? EDIT: Same issue if I try nBook.bind("&lt;&lt;NotebookTabChanged&gt;&gt;", self.xbRoutine())
accepted answer: http://stackoverflow.com/a/49976540
downvote count: 0
tagged with: tk-toolkit
tagged with: events
score: 8
upvote count: 8
favorite count: 0
type: Question

http://stackoverflow.com/comment/87008056
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49982653
has text: Thanks Scott, this is a non graded question on a quiz from coursera (How to win a data science competition). The corrector of the coursera quiz says that 0.69315 is not a correct answer and I do not get why?
score: 1

http://stackoverflow.com/a/49972657
has comment: http://stackoverflow.com/comment/86961402
has body: It doesn't work because letters is a variable used just to iterate over the list. To actually change the value you need to do: for x in range(len(stored)): if stored[x] == "c": stored[x] = "#" Or you can enumerate through the list like this: for index, value in enumerate(stored): if value == "c": stored[index] = "#" This will actually change the value of "c" to "#".
has comment: http://stackoverflow.com/comment/86961550
type: Answer
has comment: http://stackoverflow.com/comment/86961492
has comment: http://stackoverflow.com/comment/86961495
has comment: http://stackoverflow.com/comment/86961556
has comment: http://stackoverflow.com/comment/86961491
score: 0
has comment: http://stackoverflow.com/comment/86961364
has comment: http://stackoverflow.com/comment/86961540
has comment: http://stackoverflow.com/comment/86961593
answers question: http://stackoverflow.com/q/49972553
has comment: http://stackoverflow.com/comment/86961638
has comment: http://stackoverflow.com/comment/86961738

http://stackoverflow.com/a/50070675
score: 0
has body: Extending on What's answer, instead of resting all the cards in the game you could delete the current Game object and create new object. And then set all your initial states within a init function. Below is a example import random class Game: cards = [] gameCards = [] playerCards = [] pgameCards = [] cpugameCards = [] start = 0 '''+all your class attributes''' def __init__(self): '''insert your initial states here''' pass Then to start a new game you would do something like the following: '''To start a new game''' game = Game() Then to finish the current game you could do something like the following: '''To end the current game''' del game If your resetting a game aren't you technically creating a new game? That's why I recommend creating and deleting game objects Reason why you do not want to deal with global variables can be found here All the best with your game!
has comment: http://stackoverflow.com/comment/87158076
answers question: http://stackoverflow.com/q/50070360
type: Answer

http://stackoverflow.com/comment/86891788
type: Comment
type: QuestionComment
has text: You should update the existing question.
score: 0
comment on: http://stackoverflow.com/q/49933810

http://stackoverflow.com/q/49942096
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86903928
has comment: http://stackoverflow.com/comment/86902591
has comment: http://stackoverflow.com/comment/86900512
has comment: http://stackoverflow.com/comment/86900751
has comment: http://stackoverflow.com/comment/86905047
tagged with: pandas
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86900558
favorite count: 0
type: Question
tagged with: interpolation
has body: i have this code which I load a my data to a dataframe and i try to fill up the naN values using .interpolate instead of replacing it with 0 my dataframe looks like this: weight height wc hc FBS HBA1C 0 NaN NaN NaN NaN NaN NaN 1 55.6 151.0 NaN NaN 126.0 NaN 2 42.8 151.0 73.0 79.0 NaN NaN 3 60.8 155.0 NaN NaN 201.0 NaN 4 NaN NaN NaN NaN NaN NaN 5 60.0 NaN 87.0 92.0 NaN NaN 6 NaN NaN NaN NaN NaN NaN 7 NaN NaN NaN NaN NaN NaN 8 NaN NaN NaN NaN 194.0 NaN 9 57.0 158.0 95.0 90.0 NaN NaN 10 46.0 NaN 83.0 91.0 223.0 NaN 11 NaN NaN NaN NaN NaN NaN 12 NaN NaN NaN NaN NaN NaN 13 58.5 164.0 NaN NaN NaN NaN 14 62.0 154.0 80.5 100.0 NaN NaN 15 NaN NaN NaN NaN NaN NaN 16 57.0 152.0 NaN NaN NaN NaN 17 62.4 153.0 88.0 99.0 NaN NaN 18 NaN NaN NaN NaN NaN NaN 19 48.0 146.0 NaN NaN NaN NaN 20 68.7 NaN NaN NaN NaN NaN 21 49.0 146.0 NaN NaN NaN NaN 22 NaN NaN NaN NaN NaN NaN 23 NaN NaN NaN NaN NaN NaN 24 70.2 161.0 NaN NaN NaN NaN 25 70.4 161.0 93.0 68.0 NaN NaN 26 61.8 143.0 91.0 98.0 NaN NaN 27 70.4 NaN NaN NaN NaN NaN 28 70.1 144.0 100.0 103.0 NaN NaN 29 NaN NaN NaN NaN NaN NaN ... ... ... ... ... ... ... 318 49.0 146.0 92.0 89.0 NaN NaN 319 64.7 145.0 87.0 107.0 NaN NaN 320 55.5 149.0 81.0 101.0 NaN NaN 321 55.4 145.0 87.0 96.0 NaN NaN 322 53.1 153.0 83.0 96.0 NaN NaN 323 52.1 147.0 89.0 92.0 NaN NaN 324 68.9 167.0 96.0 100.0 NaN NaN 325 NaN NaN NaN NaN NaN NaN 326 57.0 142.0 100.0 101.0 NaN NaN 327 72.5 163.0 98.0 95.0 NaN NaN 328 73.5 157.0 94.0 114.0 NaN NaN 329 61.0 160.0 90.0 89.5 NaN NaN 330 49.0 150.0 80.0 90.0 NaN NaN 331 50.0 150.0 83.0 90.0 NaN NaN 332 67.6 155.0 92.0 103.0 NaN NaN 333 NaN NaN NaN NaN NaN NaN 334 78.7 162.0 99.0 101.0 NaN NaN 335 74.5 155.0 98.0 110.0 NaN NaN 336 68.0 152.0 85.0 93.0 NaN NaN 337 67.0 152.0 NaN NaN 179.1 NaN 338 NaN NaN NaN NaN 315.0 NaN 339 38.0 145.0 66.0 NaN 196.0 NaN 340 50.0 148.0 NaN NaN 133.0 NaN 341 73.5 NaN NaN NaN NaN NaN 342 74.5 NaN NaN NaN NaN NaN 343 NaN NaN NaN NaN NaN NaN 344 67.0 152.0 106.0 NaN NaN NaN 345 52.0 145.0 94.0 N…
has answer: http://stackoverflow.com/a/49945912
has title: pandas interpolate doesnt fill null values
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86900674
tagged with: missing-data
downvote count: 0

http://stackoverflow.com/a/50012210
answers question: http://stackoverflow.com/q/50012111
has body: I could be a little confused by your question but with proper indents, it worked for me. It should look like this: resp = input() if "yes" in resp: print('whatever the yes answer is') resp2 = input() if "no" in resp2: print('whatever the no answer is')
type: Answer
has comment: http://stackoverflow.com/comment/87040836
score: 0
has comment: http://stackoverflow.com/comment/87041567

http://stackoverflow.com/comment/87159676
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50071316
score: 1
has text: @pythlang I updated my post. This version returns 47.

http://stackoverflow.com/comment/86866645
type: Comment
type: QuestionComment
has text: Have you tried using `strftime` to see if you can recreate your date data with your format code?
comment on: http://stackoverflow.com/q/49925259
score: 0

http://stackoverflow.com/comment/87157464
type: Comment
type: QuestionComment
has text: @GSazheniuk Great answer! Make sure to point this out in the answer next time,as this is the correct answer, or this time and I'll make sure to upvote. Take care!
score: 1
comment on: http://stackoverflow.com/q/50070420

http://stackoverflow.com/comment/86900488
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49942050
has text: somewhat dirty (but maybe ok for debugging I guess) `min(lst, key=lambda x: print(x) or x[1])`
score: 1

http://stackoverflow.com/comment/87105943
type: QuestionComment
score: 0
has text: @jaspreetsohal My question is simple, why would you force _GeckoDriver_ try to read/access/write within `C:\Program Files (x86)\Google\` directory?
comment on: http://stackoverflow.com/q/50016011
type: Comment

http://stackoverflow.com/q/49987101
accepted answer: http://stackoverflow.com/a/50026461
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50026461
tagged with: python
has title: Where to install mariadb-devel and python34-mysql-debug packages for python in a split app server / db server environment
has body: In order for Python to talk to MariaDB I need to install mariadb-devel and python34-mysql-debug packages before using pip to install mysqlclient. I have done this with Python and MariaDB on a single server. Now, I'm installing this in an environment with two servers: AppServer which runs Python code and DBServer which is running MariaDB. So, do maradb-devel and python34-mysql-debug need to be installed on AppServer or on DBServer? Both servers are running RHEL 7.4. MariaDB is version 10.1 Python is version 3.4 Thanks!
type: Question
score: 0
answer count: 1
tagged with: mysql
tagged with: mariadb

http://stackoverflow.com/q/49956943
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86930461
has body: #!/usr/bin/env python3 import xml.etree.ElementTree as ET tree = ET.parse('A00.xml') root = tree.getroot() for w in root.iter('w'): lemma = w.get('hw') pos = w.get('pos') tag = w.get('c5') myList = (w.text + "\t" + lemma + "\t" + pos + "\t" + tag) sorted(myList) print(myList) The list still prints in iterated order. I want to sort alphabetically by the first character in each line of the list myList.sort(key = lambda ele : ele[1]) AttributeError: 'str' object has no attribute 'sort' So I want to have a list of strings and sort by the first character of each string, but strings are immutable so I have a sort error... for w in root.iter('w'): lemma = w.get('hw') pos = w.get('pos') tag = w.get('c5') myList = (w.text + "\t" + lemma + "\t" + pos + "\t" + tag) print(myList) Prints (sample): can can VERB VM0 I i PRON PNP have have VERB VHB in in PREP PRP recent recent ADJ AJ0 years year SUBST NN2 edited edit VERB VVD a a ART AT0 self-help self-help ADJ AJ0 journal journal SUBST NN1 for for PREP PRP people people SUBST NN0 Desired: a a ART AT0 can can VERB VM0 edited edit VERB VVD for for PREP PRP have have VERB VHB I i PRON PNP in in PREP PRP journal journal SUBST NN1 people people SUBST NN0 recent recent ADJ AJ0 self-help self-help ADJ AJ0 years year SUBST NN2
type: UnansweredQuestion
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49956952
linked to: http://stackoverflow.com/q/8767779
score: -2
tagged with: python
duplicate of: http://stackoverflow.com/q/8767779
tagged with: sorting
has title: Python List not sorting
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/comment/86969381
type: QuestionComment
has text: Don't know what your comment means, but regarding the `AttributeError`, I was talking about this: `parsedXML.xpath...` where `parsedXML=StringIO...`.
type: Comment
comment on: http://stackoverflow.com/q/49975661
score: 0

http://stackoverflow.com/q/50027208
type: Question
has comment: http://stackoverflow.com/comment/87071179
has answer: http://stackoverflow.com/a/50027534
accepted answer: http://stackoverflow.com/a/50027534
tagged with: python
tagged with: merge
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49988638
tagged with: pandas
score: 1
answer count: 1
has body: I posted a questions earlier and got the answer. Could you explain how the join final_df = pd.merge(df, temp_df.reset_index(), how="left").fillna(0) works? I am getting the correct results, but I don't understand how the join happens. There are no common columns between df and temp_df. Working code as below: d = {'emp': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c' ], 'date': ['1', '1', '1', '1', '2', '2', '2', '3', '3', '3', '3' ], 'usd':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ], 'expense type':['Car Mileage', 'Car Rental', 'Car Rental - Gas', 'food', 'Car Rental', 'Car Rental - Gas', 'food', 'Car Mileage', 'Car Rental', 'food', 'wine' ], 'zflag':['1', '1', '1', ' ',' ',' ',' ','2','2',' ',' ' ] } df = pd.DataFrame(data=d) df Out[253]: date emp expense type usd zflag 0 1 a Car Mileage 1 1 1 1 a Car Rental 2 1 2 1 a Car Rental - Gas 3 1 3 1 a food 4 4 2 b Car Rental 5 5 2 b Car Rental - Gas 6 6 2 b food 7 7 3 c Car Mileage 8 2 8 3 c Car Rental 9 2 9 3 c food 10 10 3 c wine 11 temp_df = df.groupby(["emp", "date"], axis=0)["expense type"].apply(lambda x: 1 if "Car Mileage" in x.values and any([k in x.values for k in ["Car Rental", "Car Rental - Gas"]]) else 0).rename("zzflag") temp_df = temp_df.loc[temp_df!=0,:].cumsum() final_df = pd.merge(df, temp_df.reset_index(), how="left").fillna(0) Update 1: temp_df doesn't have an index and it is a series. So I am not sure how the join can occur on the index as suggested in the comment. temp_df Out[335]: emp date a 1 1 c 3 2 Name: zzflag, dtype: int64
downvote count: 1
has title: How merge works in pandas
favorite count: 0

http://stackoverflow.com/q/49945364
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86908594
has answer: http://stackoverflow.com/a/49948351
answer count: 2
tagged with: django-queryset
accepted answer: http://stackoverflow.com/a/49955394
tagged with: django
has body: models.py from django.db import models class person(models.Model): name = models.CharField(max_length=100, blank=true) characteristics = models.ManyToManyField(characteristics, default = '', on_delete=models.SET_DEFAULT) def __str__(self): return self.name class characteristics(models.Model): name = models.CharField(max_length=100, blank=true) def __str__(self): return self.name I have some troubles with queryset. I create 3 persons: Jim, John, Jack. Then create 4 characteristics: strength, agility, wisdom, intelligence Connect Jim with strength and agility( he is strong and dexterous) Connect John with wisdom and intelligence( he is a smart guy) Connect Jack with strength, agility, wisdom, intelligence( he is jack of all trades) Output will be like: Jim: strength, agility John: wisdom, intelligence Jack: strength, agility, wisdom, intelligence Is there a posibility to add values to these characteristics? For example: Jim: strength=10 , agility=10 John: wisdom=10, intelligence=10 Jack: strength=9, agility=8, wisdom=8, intelligence=9 I think, this values need to be stored in "person" table. I can create additional fields in models.py, but my goal is to make additional field in "person" model when creating new charactaristics. Thereis a way to make it using 0...1000 empty int fields in "person" model, then giving additional number(like id) to charecteristics and then connect that characteristics id with "person" 0...1000 empty fields from django.db import models class person(models.Model): name = models.CharField(max_length=100, blank=true) characteristics = models.ManyToManyField(characteristics, default = '', on_delete=models.SET_DEFAULT) char0 = IntegerField(blank=True) ... char1000 = IntegerField(blank=True) def __str__(self): return self.name class characteristics(models.Model): name = models.CharField(max_length=100, blank=true) additional_id = models.BigAutoField def __str__(self): return self.name Is there some elegant way to solve my problem?
type: Question
possible better answer: http://stackoverflow.com/a/49948351
has comment: http://stackoverflow.com/comment/86919743
has answer: http://stackoverflow.com/a/49955394
tagged with: python
has title: Create additional fields in models on foreign key (Django query)

arrays
tags question: http://stackoverflow.com/q/50068431
tags question: http://stackoverflow.com/q/49978605
tags question: http://stackoverflow.com/q/49950412
tag name: arrays
tags question: http://stackoverflow.com/q/50046077
tags question: http://stackoverflow.com/q/49948024
tags question: http://stackoverflow.com/q/50030231
tags question: http://stackoverflow.com/q/50005551
tags question: http://stackoverflow.com/q/50064422
tags question: http://stackoverflow.com/q/49961043
tags question: http://stackoverflow.com/q/49990515
tags question: http://stackoverflow.com/q/50044481
tags question: http://stackoverflow.com/q/49983588
tags question: http://stackoverflow.com/q/49977208
type: Tag
tags question: http://stackoverflow.com/q/49979759
tags question: http://stackoverflow.com/q/49980814
tags question: http://stackoverflow.com/q/49928903
tags question: http://stackoverflow.com/q/50049069
tags question: http://stackoverflow.com/q/49975896
tags question: http://stackoverflow.com/q/50003760
tags question: http://stackoverflow.com/q/50023635
tags question: http://stackoverflow.com/q/49988118
tags question: http://stackoverflow.com/q/49959038
tags question: http://stackoverflow.com/q/50067267
tags question: http://stackoverflow.com/q/49968566
tags question: http://stackoverflow.com/q/49923729
tags question: http://stackoverflow.com/q/49945540
tags question: http://stackoverflow.com/q/50049170
tags question: http://stackoverflow.com/q/49966274
tags question: http://stackoverflow.com/q/49971774
tags question: http://stackoverflow.com/q/49951994
tags question: http://stackoverflow.com/q/49969840
tags question: http://stackoverflow.com/q/50044281
tags question: http://stackoverflow.com/q/50024181
tags question: http://stackoverflow.com/q/50033364
tags question: http://stackoverflow.com/q/49991674
tags question: http://stackoverflow.com/q/49986397
tags question: http://stackoverflow.com/q/50027783
tags question: http://stackoverflow.com/q/49962533
tags question: http://stackoverflow.com/q/50070739
tags question: http://stackoverflow.com/q/50064029
tags question: http://stackoverflow.com/q/49971417
tags question: http://stackoverflow.com/q/49927354
tags question: http://stackoverflow.com/q/49924463
tags question: http://stackoverflow.com/q/50028486
tags question: http://stackoverflow.com/q/49969861
tags question: http://stackoverflow.com/q/50024378
tags question: http://stackoverflow.com/q/50047174
tags question: http://stackoverflow.com/q/49932922
tags question: http://stackoverflow.com/q/49964307
tags question: http://stackoverflow.com/q/49972924
tags question: http://stackoverflow.com/q/49958078
tags question: http://stackoverflow.com/q/49995237
tags question: http://stackoverflow.com/q/49991273
tags question: http://stackoverflow.com/q/49917743
tags question: http://stackoverflow.com/q/49945797
tags question: http://stackoverflow.com/q/50016955
tags question: http://stackoverflow.com/q/50045439
tags question: http://stackoverflow.com/q/49961508
tags question: http://stackoverflow.com/q/50047689
tags question: http://stackoverflow.com/q/49984220
tags question: http://stackoverflow.com/q/49927610
tags question: http://stackoverflow.com/q/49969215
tags question: http://stackoverflow.com/q/49928429
tags question: http://stackoverflow.com/q/50011890
tags question: http://stackoverflow.com/q/49961472
tags question: http://stackoverflow.com/q/49920698
tags question: http://stackoverflow.com/q/50008508
tags question: http://stackoverflow.com/q/49990881
tags question: http://stackoverflow.com/q/49963421
tags question: http://stackoverflow.com/q/50019634
tags question: http://stackoverflow.com/q/50063717
tags question: http://stackoverflow.com/q/50034804
tags question: http://stackoverflow.com/q/50030460
tags question: http://stackoverflow.com/q/49929580
tags question: http://stackoverflow.com/q/50008587
tags question: http://stackoverflow.com/q/50002415
tags question: http://stackoverflow.com/q/50054775
tags question: http://stackoverflow.com/q/50001509

http://stackoverflow.com/q/50028848
type: Question
has comment: http://stackoverflow.com/comment/87073923
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/50029029
has answer: http://stackoverflow.com/a/50029168
possible better answer: http://stackoverflow.com/a/50029168
has body: I need to eliminate all columns of a dataframe with a date before the year 2000. The general approach is: columnstokeep = list(DF) #gives me the column names for i in range(len(columnstokeep)): #get rid of dates before year 2000 if int(columnstokeep[i][:4])&lt;2000: columnstokeep.remove(columnstokeep[i]) DF = DF[columnstokeep] #the new dataframe I keep running into an list index out of range error. Is this because len, in range(len(columnstokeep)) is changing each time I drop an element of the list? Or does range(len(columnstokeep)) hold the same value for the duration of the loop? Here is the Dataframe Thanks
has comment: http://stackoverflow.com/comment/87073831
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87073993
accepted answer: http://stackoverflow.com/a/50029029
has title: Does "len" of a list get recalculated in every iteration of a for loop?
tagged with: python

http://stackoverflow.com/a/50037384
type: AcceptedAnswer
downvote count: 0
has body: It's because not all page numbers show at the front page. The scraper should continuously get current page's data and open next page until the end. from urllib.request import urlopen from bs4 import BeautifulSoup import pandas as pd import csv # List to store Scraped Product Data. URL = [] # Start page's url pageUrl="https://www.flipkart.com/mobiles/samsung~brand/pr?count=40&amp;p%5B%5D=sort%3Drecency_desc&amp;page=1&amp;sid=tyy%2F4io&amp;viewType=list&amp;wid=1.productCard.PMU_V2" while True: page = urlopen(pageUrl) bsObj = BeautifulSoup(page, 'html.parser') # Extraction of Product Data from URL. for link in bsObj.findAll(class_="_1UoZlX"): urlBuild = ("https://www.flipkart.com" + link.attrs['href']) URL.append(urlBuild) # Get Next page's url, if can't break loop nxtLink=bsObj.find(class_="_2kUstJ", text="Next") if nxtLink == None: break # Get next page's url pageUrl = ("https://www.flipkart.com" + nxtLink.a.attrs['href']) columnsTitles = ['Link'] test_df = pd.DataFrame({ 'Link': URL}) pd.set_option('display.max_colwidth',0) print(test_df.info()) test_df In this case, test_df contains 301 rows, print(test_df.info()) &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 301 entries, 0 to 300 Data columns (total 1 columns): Link 301 non-null object dtypes: object(1) memory usage: 2.4+ KB None
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50036543
accepted answer of: http://stackoverflow.com/q/50036543
score: 1

http://stackoverflow.com/comment/87131887
type: AnswerComment
comment on: http://stackoverflow.com/a/50056607
score: 0
type: Comment
has text: Thanks Paublo for this cosmetic tips, the <RunningCommand> not showing in the cell :) Thank you very much again :)

http://stackoverflow.com/q/49929551
answer count: 2
tagged with: escp
tagged with: printing
has title: Use full page width with Brother P950NW
has answer: http://stackoverflow.com/a/50317680
downvote count: 1
has body: I would like to use the full width of the 18mm strips in my Brother P950NW printer for an image. At the moment, I am using ESC/P (not ESC/POS, which this printer does not seem to support), but if it's not possible with that I'm fine with any other protocol this printer supports. (Update: with Brother's Windows software, full-width printing is possible, but it uses the LPR protocol, for which there don't seem to be any Python libraries.) I'm using the ESC/P command ESC* with density 72 (the highest available according to the printer's documentation), which only allows filling up the width in steps of 48 dots. How do I print 200 pixels wide on a strip in ESC/P-speak an image with height 200? That should easily fit onto the strip. However, due to ESC*72 only accepting blocks of 48, everything beyond 192 is output on another strip. Here's my demo code: import socket import struct def escp(density_code=72): stack_size_in_bytes = {72: 6}[density_code] height = 200 width = 130 yield b'\x1bia\x00' # ESC/P command mode: ESC/P standard yield b'\x1b@' # Initialize yield b'\x1bim\x00\x00' # margin: 0 yield b'\x1biXE2\x00\x00\x00' # barcode margin: 0 yield b'\x1b3' + struct.pack('!B', 24) # line feed length: 24 dots (i.e. no space between lines) for y_offset in range(0, height, 8 * stack_size_in_bytes): yield b'\x1b*' + struct.pack('!B', density_code) + struct.pack('&lt;H', width) yield b'\xff' * width * stack_size_in_bytes yield b'\x0a' # linefeed (move position 24 dots down) yield b'\x0c' # Print start c = socket.create_connection(('10.222.2.206', 9100)) c.sendall(b''.join(escp())) c.close() I'm fine with solutions in raw binary; here is the binary file and shortened hexdump generated by the above program.
has comment: http://stackoverflow.com/comment/87146480
has comment: http://stackoverflow.com/comment/87015250
favorite count: 0
type: Question
score: 14
has answer: http://stackoverflow.com/a/50077729
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50077729
accepted answer: http://stackoverflow.com/a/50317680
has comment: http://stackoverflow.com/comment/86979517
tagged with: python
upvote count: 15
has comment: http://stackoverflow.com/comment/87004763
type: AnsweredQuestion

http://stackoverflow.com/q/49952933
has comment: http://stackoverflow.com/comment/86922726
score: 0
has comment: http://stackoverflow.com/comment/86922578
duplicate of: http://stackoverflow.com/q/22054698
has comment: http://stackoverflow.com/comment/86922423
has comment: http://stackoverflow.com/comment/86923012
upvote count: 1
has comment: http://stackoverflow.com/comment/86940040
has body: I am new to python. I searched a lot but couldn't find the reason why this is happening. Could anyone please tell me the difference between these two? My general question is when using a list in function is by reference and when is by value? My test function is acting as call by reference and test2 is acting as call by value. I know in python everything is an object, but with that, I couldn't understand the difference. tnx def test(my_list): for i in range(len(my_list)): my_list[i] = 5 def test2(my_list1): my_list1 = [6, 6, 6] a = [4, 4, 4] print(a) test(a) print(a) test2(a) print(a) output: [4, 4, 4] [5, 5, 5] [5, 5, 5]
duplicate of: http://stackoverflow.com/q/10262920
downvote count: 1
linked to: http://stackoverflow.com/q/986006
favorite count: 0
type: Question
has title: python list call by reference and value
has comment: http://stackoverflow.com/comment/86922499
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/986006
tagged with: python
linked to: http://stackoverflow.com/q/22054698
linked to: http://stackoverflow.com/q/10262920
answer count: 0

http://stackoverflow.com/q/49930830
tagged with: python
has answer: http://stackoverflow.com/a/49932895
downvote count: 1
has body: I am trying to get a slice (for example elements 1-3 and 5-N) of an array A(N,3) avoiding using numpy.delete. And example of the process will be the following: [[1,2,3],[4,5,6],[7,8,9],[3,2,1]] ==&gt; [[1,2,3],[3,2,1]] I was hoping to use something like A[A != [1,2,3] ].reshape() But that performs an element-wise comparison and thus removes more elements than I wanted to. How does one do it? I came up with this idea but seems too complex and slow: A_removed = A[first_removed:last:removed,:] mask = np.not_equal(A[:,None],A_removed) mask = np.logical_and.reduce(mask,1) A = A[mask].reshape() Is there a way of doing it in a faster/cleaner way? PD the asumption that any two elements of A can't be equal always holds
score: 3
has comment: http://stackoverflow.com/comment/86877655
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/86878003
tagged with: numpy-ufunc
favorite count: 0
has title: Fast and efficient slice of array avoiding delete operation
type: Question
upvote count: 4
tagged with: numpy
tagged with: numpy-ndarray
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86877824
answer count: 1
has comment: http://stackoverflow.com/comment/86877841

http://stackoverflow.com/comment/86916460
type: Comment
comment on: http://stackoverflow.com/a/49949757
type: AnswerComment
has text: No no I think that you were getting wrong and also he may be in baby step in programming.
score: 0

http://stackoverflow.com/q/49957002
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86930289
has title: I can't open a csv file with panda
tagged with: dataframe
tagged with: python
has body: I'm starting with panda. I already opened csv files with it, but I don't know how to open a file without spaces. import pandas as pd vdez = pd.read_csv("201712_Diarias.csv", encoding = 'ISO-8859-1') **--------------------------------------------------------------------------- CParserError Traceback (most recent call last) &lt;ipython-input-24-4bc7449a8703&gt; in &lt;module&gt;() ----&gt; 1 vdez = pd.read_csv("201712_Diarias.csv", encoding = 'ISO-8859-1') C:\Users\Rafael\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 644 skip_blank_lines=skip_blank_lines) 645 --&gt; 646 return _read(filepath_or_buffer, kwds) 647 648 parser_f.__name__ = name C:\Users\Rafael\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 399 return parser 400 --&gt; 401 data = parser.read() 402 parser.close() 403 return data C:\Users\Rafael\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows) 937 raise ValueError('skipfooter not supported for iteration') 938 --&gt; 939 ret = self._engine.read(nrows) 940 941 if self.options.get('as_recarray'): C:\Users\Rafael\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows) 1506 def read(self, nrows=None): 1507 try: -&gt; 1508 data = self._reader.read(nrows) 1509 except StopIteration: 1510 if self._first_chunk: pandas\parser.pyx i…
tagged with: parsing
has comment: http://stackoverflow.com/comment/87000072
score: 0
tagged with: pandas
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/50054642
has comment: http://stackoverflow.com/comment/87126182
answer count: 1
has comment: http://stackoverflow.com/comment/87126062
has answer: http://stackoverflow.com/a/50054874
accepted answer: http://stackoverflow.com/a/50054874
has comment: http://stackoverflow.com/comment/87126173
type: Question
has title: Managing Zero dates - cannot convert float NaN to integer
has comment: http://stackoverflow.com/comment/87125782
tagged with: dataframe
tagged with: python
tagged with: date
has body: Morning All, I need to mange dates greater than 2261 in my file. I'm getting the above error when executing : m = df['maturity_date'].str[:4].astype(int) &gt; 2261 ValueError: cannot convert float NaN to integer Details of column causing error: display(df['maturity_date'].dtypes) dtype('O') display(df['maturity_date'].describe()) count 3709 unique 781 top 2166-09-23 00:00:00.000 freq 234 Name: maturity_date, dtype: object display(df[df['maturity_date'].isnull()]) No records returned display(df[df['maturity_date']==0]['maturity_date'] ) 764 0 931 0 1173 0 Name: maturity_date, dtype: object Possibly error raised as you cant convert zeros? My intended code to update dates after it works: #Convert dates greater than 2261 display(df['maturity_date'].str[:4].astype(int) &gt; 2261) df['maturity_date'] = df['maturity_date'].mask(m, '2261' + to df['maturity_date'].str[4:]) # for all dates greater than python max date replace df['maturity_date'] = pd.to_datetime(df['maturity_date'])
has comment: http://stackoverflow.com/comment/87125997
has comment: http://stackoverflow.com/comment/87126112
has comment: http://stackoverflow.com/comment/87126151
has comment: http://stackoverflow.com/comment/87126152
tagged with: int
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87126053
tagged with: pandas

http://stackoverflow.com/q/49946979
linked to: http://stackoverflow.com/q/4929251
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49948096
score: 0
accepted answer: http://stackoverflow.com/a/49947594
answer count: 2
has comment: http://stackoverflow.com/comment/86910828
upvote count: 1
downvote count: 1
has body: So i'm doing a python course online where i was given an assigment to do a tic- tac-toe game. I made the whole thing but i'm stuck at the replacement of list elements when the placeholder is to be replaced by O or X in the block chosen by user. I've already tried many ways to replace the list elements permanently and spent hours to find the way i could run it properly, but it still prints the same original board of tic-tac-toe. # 2 players should be able to play the game (both sitting at the same computer) # The board should be printed out every time a player makes a move # You should be able to accept input of the player position and then place a symbol on the board # x1 | y1 | z1 # ---- | ---- | ---- # x2 | y2 | z2 # ---- | ---- | ---- # x3 | y3 | z3 x1= 'top-left' y1= 'top-mid' z1= 'top-right' x2= 'mid-left' y2= 'mid-mid' z2= 'mid-right' x3= 'btm-left' y3= 'btm-mid' z3= 'btm-right' e = [x1,y1,z1,x2,y2,z2,x3,y3,z3] board = e[0]+ ' | '+ e[1]+ ' | '+ e[2]+'\n'+ \ '--------|------------|--------'+'\n'+\ e[3]+ ' | '+ e[4]+ ' | '+ e[5]+'\n'+ \ '--------|------------|--------'+'\n'+\ e[6]+ ' | '+ e[7]+ ' | '+ e[8] def instructions(): print('Instuctions: \n') print('Game: tic-tac-toe \n') print('Player 1: O and Player 2: X \n\n') print(' top-left | top-mid | top-right') print(' -------- | ------- | ----------') print(' mid-left | mid-mid | mid-right') print(' -------- | ------- | ----------') print(' btm-left | btm-mid | btm-right') print('\n\n') print('Choose your input when your turn comes.\n\n') def player_one(inputvalue): global e for element in e: if element == inputvalue: e[e.index(element)]=' O ' #element that i wanna replace break query =checkSuccess() if (query == True): print('Tic-Tac-Toe ! Player1 has won the game! ') elif (query == False): print(board) # this still prints the original, old board. def player_two(input): global e for element in e: if element== input: e[e.index(element)] =' X ' break query =checkSuccess() if (query == True): print('Tic-Tac-Toe !…
possible better answer: http://stackoverflow.com/a/49948096
favorite count: 0
has comment: http://stackoverflow.com/comment/86910994
type: Question
tagged with: python-3.x
has title: Replace the string elements in list with another string in python when a certain condition is True
has answer: http://stackoverflow.com/a/49947594
has comment: http://stackoverflow.com/comment/86911111
has comment: http://stackoverflow.com/comment/86910890
has comment: http://stackoverflow.com/comment/86910600

http://stackoverflow.com/q/50065913
linked to: http://stackoverflow.com/q/18114285
has comment: http://stackoverflow.com/comment/87148517
has title: How to speed up bottleneck section in code? Threading? Multiprocessing?
has comment: http://stackoverflow.com/comment/87148479
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/87148846
has body: I have a bottleneck function in my code which effectively boils down to : import networkx as nx class my_class: def __init__(self): self.graph = nx.complete_graph(50) # placeholder for large nx graph self.my_dict = {} # triggered by event automatically, cannot change trigger def slow_function(self, event): source = event.source dest = event.dest # how to speed up this function? def bottleneck_function(): reasonably_fast_obj = reasonably_fast('myfoo') self.path_calulator(source, dest, reasonably_fast_obj) def path_calulator(self, source, dest, weight): return nx.shortest_simple_paths(self.graph, source, dest, weight) class reasonably_fast: def __init__(self, foo): self.foo = foo The main cause is the networkx method which takes a significant amount of time for a large graph. The slow_function is triggered in such a way that it may be called again before the previous call is finished (due to delay). What is an appropriate way to speed up the task? Can it be made faster using multiple threads? Note: I can only use python 2.7 due to some limitations Edit Here is what I have so far: import networkx as nx from multiprocessing import Pool as ThreadPool from itertools import islice import random G = nx.barabasi_albert_graph(10, 5) G.number_of_edges() # prints 25 def nx_function(): src, dst = random.sample(range(0,9), 2) return list(islice(nx.shortest_simple_paths(G, source=src, target=dst), 5)) %timeit nx_function gives 10000000 loops, best of 3: 22.1 ns per loop def simple(): for i in range(10): nx_function() %timeit simple gives 100 loops, best of 3: 1.94 ms per loop def parallelized(): pool = ThreadPool(4) for i in range(10): pool.apply_async(func=nx_function) pool.close() pool.join() %timeit paralelized gives 10 loops, best of 3: 196 ms per loop It seems as if the overhead from multiprocessing makes this useless. Is there any other way to speed up this code?
tagged with: performance
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87149984
tagged with: python
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87155596
upvote count: 1
tagged with: multithreading
downvote count: 1

http://stackoverflow.com/comment/87095809
comment on: http://stackoverflow.com/q/50033072
type: QuestionComment
has text: I don't need to distinguish between files and directories, I just need to be able to find the "files" that are organized via the "directories"
score: 0
type: Comment

http://stackoverflow.com/q/50048689
score: 0
has answer: http://stackoverflow.com/a/50048879
answer count: 2
tagged with: pandas-groupby
tagged with: pivot-table
has title: Create new columns based on existing columns and values in Pandas
type: Question
possible better answer: http://stackoverflow.com/a/50048797
has body: (1) Considering the following DataFrame: d e val ----------------- 1 0 40 125 2 10 35 150 3 11 30 110 4 15 65 115 Is there a way to get to the following row: val_0 val_10 val_11 val_15 e_0 e_10 e_11 e_15 ----------------------------------------------------------------------- 1 125 150 110 115 40 35 30 65 This is quite easily done with manually iterating over rows, but ideally I'd be looking for a vectorized solution. Basically, I think what I'm after is a way to create/assign rows based on some column name + a column value. (2) Next step would be to actually output one row per value, given a group by column. To build on the example above, the following: d e val gp ---------------------- 1 0 40 125 3 2 10 35 150 3 3 11 30 110 3 4 15 65 115 3 1 0 70 225 4 2 10 85 250 4 3 11 90 210 4 4 15 95 215 4 Would output: gp val_0 val_10 val_11 val_15 e_0 e_10 e_11 e_15 ------------------------------------------------------------------- 3 125 150 110 115 40 35 30 65 4 225 250 210 215 70 85 90 95 Again, doing (2) when having solved (1) can be done with a simple groupby('gp').apply(some_fun), but if there existed a builtin way to do that in Pandas, that would be a massive benefit performance-wise.
has answer: http://stackoverflow.com/a/50048797
tagged with: pandas
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50048879
type: AnsweredQuestion

http://stackoverflow.com/a/74305974
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: This approach works with ModelForm and POST request: def compcreate(request): if request.method == 'POST': form = templateselect(request.POST) if form.is_valid(): ts = form.save(commit=False) print(ts.template) Let me know if it works in your case.
answers question: http://stackoverflow.com/q/49958939

http://stackoverflow.com/comment/86869720
type: Comment
score: 2
type: AnswerComment
has text: Since this is about Keras, I'm not sure this is true. I just tested and there is an associated error (Keras 2.1.0). Keras demands one numpy array, it doesn't accept lists or arrays of arrays. --- By the way, `model.fit_generator()` will internally call `model.train_on_batch()` in a manual loop (https://github.com/keras-team/keras/blob/master/keras/engine/training.py/#L2193)
comment on: http://stackoverflow.com/a/49926589

http://stackoverflow.com/comment/86963281
type: Comment
comment on: http://stackoverflow.com/a/49973593
type: AnswerComment
has text: Perhaps this is more generic (can be used for strings etc): df['Flag'] = df.groupby('Product')['Index'].transform(lambda x: 'right' if all(x==1) else 'wrong')
score: 3

http://stackoverflow.com/comment/87687137
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50037402
score: 0
has text: i suggest you look into some regex based solution

http://stackoverflow.com/a/50024478
answers question: http://stackoverflow.com/q/50024292
upvote count: 5
type: Answer
score: 5
has body: Using Numpy (Documentation): import numpy as np from numpy.polynomial import Laguerre p = Laguerre([1, -2, 1]) x = np.arange(5) p(x) Using scipy(Documentation): scipy.special.eval_genlaguerre(r_ord, phi_ord, float(x))
downvote count: 0

http://stackoverflow.com/comment/87124009
comment on: http://stackoverflow.com/q/50053747
has text: Do you have a file named mpl_toolkits?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87080612
comment on: http://stackoverflow.com/q/50027782
has text: @JeremyMcGibbon `cost_fn_delta` is a Python function that uses Numpy matrix operations, so it's reasonably fast. I tried Numba in both functions, but it found some problems and couldn't JIT properly. Also, a brief explanation would be iterating over the solution, checking which "bit" of the solution is active, and if it is (dlb is a numpy boolean array, True means "ignore"), proceed to pair it every other "bit". Now... my original solution is wrong, as I'm iterating over all the dlb array, instead of just checking an element. So, thank you for making me understand my creation :p
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87115198
score: 0
has text: Instance limit reached has nothing to do with launching an instance without a keypair. Terminate the stopped instances or stop the running instances to fix the error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50047929

http://stackoverflow.com/q/50029759
has title: Finding regular expression with at least one repetition of each letter
has answer: http://stackoverflow.com/a/50029943
favorite count: 0
has answer: http://stackoverflow.com/a/50030755
type: Question
has answer: http://stackoverflow.com/a/50030165
has answer: http://stackoverflow.com/a/50029940
answer count: 5
score: -4
tagged with: repeat
downvote count: 5
has body: From any *.fasta DNA sequence (only 'ACTG' characters) I must find all sequences which contain at least one repetition of each letter. For examle from sequence 'AAGTCCTAG' I should be able to find: 'AAGTC', 'AGTC', 'GTCCTA', 'TCCTAG', 'CCTAG' and 'CTAG' (iteration on each letter). I have no clue how to do that in pyhton 2.7. I was trying with regular expressions but it was not searching for every variants. How can I achive that?
upvote count: 1
tagged with: python
tagged with: regex
tagged with: dna-sequence
has comment: http://stackoverflow.com/comment/87076266
possible better answer: http://stackoverflow.com/a/50030146
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50030146
has comment: http://stackoverflow.com/comment/87076026
accepted answer: http://stackoverflow.com/a/50029943
has comment: http://stackoverflow.com/comment/87075910
has comment: http://stackoverflow.com/comment/87076112

http://stackoverflow.com/q/49947105
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/86910911
has answer: http://stackoverflow.com/a/49949320
has comment: http://stackoverflow.com/comment/86911381
tagged with: python
type: Question
has title: HTML code inside templates isn't processing Django code
has comment: http://stackoverflow.com/comment/86911018
score: 0
type: UnansweredQuestion
has body: I'm a complete beginner in Django.I'm not able to extract data from my database inside the template. Please cooperate and help! mysite/books/templates/books/index.html &lt;!DOCTYPE html&gt; &lt;html&gt; {% for book in object_list %} &lt;h&gt;{‌{book.name }}&lt;/h&gt; {% endfor %} &lt;/html&gt; mysite/books/views.py # Create your views here. from django.views import generic from .models import Book from django.views.generic.edit import CreateView class IndexView(generic.ListView): template_name = 'books/index.html' def get_queryset(self): return Book.objects.all() class BookCreate(CreateView): model = Book fields = ['name', 'author', 'price', 'type', 'book_image'] class DetailView(generic.DetailView): model = Book template_name = 'books/detail.html' mysite/books/models.py # Create your models here. from django.db import models from django.core.urlresolvers import reverse class Book(models.Model): def get_absoulte_url(self): return reverse('books:detail', kwargs={'pk':self.pk}) def __str__(self): return self.name + '-' + self.author name = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.CharField(max_length=100) type = models.CharField(max_length=100) book_image = models.CharField(max_length=1000) output Please click to see the output screenshot.{{book.name}} is not getting processed in the template

http://stackoverflow.com/q/49949767
has answer: http://stackoverflow.com/a/49968204
has title: Decompose Specific Links When Scraping Data (Python)
answer count: 1
has comment: http://stackoverflow.com/comment/86952017
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/86918817
has comment: http://stackoverflow.com/comment/86951896
has body: Below is a section of HTML code I am currently scraping. &lt;div class="RadAjaxPanel" id="LiveBoard1_LiveBoard1_litGamesPanel"&gt; &lt;a href="leaders.aspx?pos=all&amp;stats=pit&amp;lg=all&amp;qual=0&amp;type=8&amp;season=2016&amp;month=0&amp;season1=2016&amp;ind=0&amp;team=0&amp;rost=0&amp;age=0&amp;filter=&amp;players=p2018-04-20"&gt; Today's Probable Starters and Lineups Leaderboard &lt;/a&gt; &lt;/div&gt; Throughout the code, I need to figure out a way to scrape all the links in this div class with the exception of the one posted above. Does anyone know how to decompose one specific link within a specific div class but still scrape the remaining links? With regards to this specific link, the beginning ("leaders.aspx") of the link is different than the links I am currently targeting. Below is a sample of my current code. import requests import csv from bs4 import BeautifulSoup page=requests.get('https://www.fangraphs.com/livescoreboard.aspx?date=2018-04-18') soup=BeautifulSoup(page.text, 'html.parser') #Remove Unwanted Links [link.decompose() for link in soup.find_all(class_='lineup')] [yesterday.decompose() for yesterday in soup.find_all('td',attrs= {'colspan':'2'})] team_name_list=soup.find(class_='RadAjaxPanel') team_name_list_items=team_name_list.find_all('a') for team_name in team_name_list_items: teams=team_name.contents[0] print(teams) winprob_list=soup.find(class_='RadAjaxPanel') winprob_list_items=winprob_list.find_all('td',attrs={'style':'border:1px solid black;'}) for winprob in winprob_list_items: winprobperc=winprob.contents[0] print(winprobperc) To summarize, I just need to remove the "Today's Probable Starters and Lineups Leaderboard" link that was posted in the first code block. Thanks in advance!
tagged with: python
accepted answer: http://stackoverflow.com/a/49968204
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50025568
answers question: http://stackoverflow.com/q/49991762
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Kind of figured it out, when Zappa init runs, it calls def detect_flask_apps() function in the utilities.py file. This function reads each python file in the project directory, including the libraries in the virtual environment folder. There is a library called functools.py that must have different character encodings than what is the default, because with open(full, 'r') as f: lines = f.readlines() fails when reading ~/env/venv/Lib/functools.py. The fix is to specify the encoding: with open(full, 'r', encoding='utf-8') as f: lines = f.readlines() in zappa/utilities.py -- line 148

http://stackoverflow.com/comment/87033391
has text: Why do you assume that the data is UTF-8 ? If you don't know its encoding, have you tried other reasonable possibilities e.g. windows 1250 or ISO 8859-2?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50008296

http://stackoverflow.com/comment/86956337
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49919442
type: Comment
has text: thx. I still feel bad about that. In the response has "Content-type" = 'application/gzip', and also I don't attempt to access `response.text`, so in this case this behaviour is at best clumsy...

http://stackoverflow.com/comment/87033753
type: AnswerComment
score: 0
has text: Do not use `tk()` for pop up windows. There are already several built in methods for pop up information and for any standard application if you need/want to do something customer you should use `Toplevel()` instead of `tk()` as `tk()` is most likely being used for the main GUI.
type: Comment
comment on: http://stackoverflow.com/a/50008360

http://stackoverflow.com/q/50029745
type: AnsweredQuestion
has title: Cannot seem to get GDAL to import into anaconda?
tagged with: anaconda
score: 1
has answer: http://stackoverflow.com/a/50030280
tagged with: python
favorite count: 0
type: Question
has body: I installed anaconda onto my system and tried numerous ways of installing GDAL each time on Spyder it gives me the same response: ImportError: No module named gdal I wrote the program just as follows: import gdal Ran it then that error Tried: import osgeo import gdal same issue. So then I installed the Anaconda prompt. And it seemed to install anaconda when I typed in: conda install -c conda-forge gdal I went back to Spyder and got the same error. Any ideas of why this is happening? In the Anaconda prompt I wrote: gdalinfo --version And got back: GDAL 2.2.4, released 2018/03/19 All seems up to date except when I run in Spyder
answer count: 2
accepted answer: http://stackoverflow.com/a/50030280
possible better answer: http://stackoverflow.com/a/51185720
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/51185720
linked to: http://stackoverflow.com/q/45086454

http://stackoverflow.com/q/49984691
tagged with: latex
type: UnansweredQuestion
has body: I'm creating a pdf-latex file with a python script such as it is explained in Generating pdf-latex with python script and it works perfectly. However, I would like to generate a table of contents for my file. The problem is that, using a latex generator as TexWorks for example, you need to compile it twice (in first compiling you generate the .pdf file without toc and .out and .toc files with toc's information, while in second compiling toc's information is added to the pdf.file), but it doesn't work if you run the script twice. Thanks you in advance.
has title: Generating a table of contents in a pdf-latex with python
tagged with: python
linked to: http://stackoverflow.com/q/8085520
tagged with: tableofcontents
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49986950
type: Question

http://stackoverflow.com/comment/87318089
comment on: http://stackoverflow.com/a/49989909
score: 0
type: AnswerComment
has text: I wrote a comment with more details, and it is all about Hsp, I made a mistake writting rhp sorry.
type: Comment

http://stackoverflow.com/q/50045728
accepted answer: http://stackoverflow.com/a/50045834
has answer: http://stackoverflow.com/a/50045834
tagged with: django
tagged with: python
has body: I'm writing some schema tests for django, using django's wrapper of the unittest framework. I want to check that a field is always going to be DateTimeField, rather than DateField. So I attempted the following: class TestSuite(TestCase): def test_for_correct_datetype(self): self.assertTrue(isinstance(Obj.time, models.DateTimeField)) Because previously: class Obj(models.Model): .... time = models.DateTimeField() Note: There were several answers that said to use getattr, and it doesn't work for me either. How can I make the self.assertTrue() work?
has comment: http://stackoverflow.com/comment/87107934
type: AnsweredQuestion
tagged with: django-unittest
has title: Get type of django model attribute
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/50056984
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87134256
answers question: http://stackoverflow.com/q/50052912
type: Answer
has body: Let's try stamping instead of drawing. This gains us speed while simplifying our logic. We stamp one large black square to represent the board, then stamp the white squares onto it: from turtle import Turtle, Screen SQUARES_PER_SIDE = 5 CURSOR_SIZE = 20 def main(): length = int(input("Enter the length of each square: ")) screen = Screen() screen.bgcolor("lightblue") turtle = Turtle('square', visible=False) turtle.shapesize(SQUARES_PER_SIDE * length / CURSOR_SIZE) turtle.speed('fastest') turtle.stamp() # black background turtle.shapesize(length / CURSOR_SIZE) turtle.fillcolor("white") turtle.penup() edge = (1 - SQUARES_PER_SIDE) / 2 * length # center of left or bottom square turtle.goto(edge, edge) for row in range(SQUARES_PER_SIDE): for column in range(SQUARES_PER_SIDE): if (row + column) % 2 == 0: turtle.stamp() # white square turtle.forward(length) turtle.goto(edge, edge + (row + 1) * length) screen.exitonclick() main() OUTPUT

http://stackoverflow.com/comment/86894970
type: QuestionComment
has text: Thank you I have tagged it now.
score: 0
comment on: http://stackoverflow.com/q/49939449
type: Comment

http://stackoverflow.com/comment/87080341
type: AnswerComment
comment on: http://stackoverflow.com/a/50031612
type: Comment
has text: I'm trying to put `MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)` into the same setup as your regx variable above, but I can't get it to work. But I guess the format is slightly different?
score: 0

http://stackoverflow.com/comment/87087141
has text: There is a javascript part above the video player, perhaps the video is dynamically loaded using javascript. Are you sure JS is parsed completely before you scrape?
comment on: http://stackoverflow.com/q/50035039
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50044416
answer count: 1
downvote count: 1
has body: need some help in the following code as it goes into infinite loop and does not validate user input: the get_offset is the function. Just edited need some help with the encryption part to be done in a function defined def get_offset(offset): while True: value = (offset) if value &lt; 1: print("") if value &gt; 94: print("") return offset my_details = display_details() get_choice = get_menu_choice() print(my_details) print(get_choice) count = 10 while count &gt; 0: count -=1 encrypted = "" choice = int(input("What would you like to do [1,2,3,4,5]: ")) while choice &lt;1 and choice &gt; 5: print("Invalid choice, please enter either 1, 2, 3, 4 or 5.") if choice == 1: string_input = input("Please enter string to encrypt: ") input_offset = get_offset(int(input("Please enter offset value (1 to 94): "))) **for letter in string_input: x = ord(letter) encrypted += chr(x + input_offset) if x &lt; 32: x += 94 if x &gt; 126: x -= 94 print(encrypted)**
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49974356
has answer: http://stackoverflow.com/a/50044541
accepted answer: http://stackoverflow.com/a/50044541
has comment: http://stackoverflow.com/comment/87160298
tagged with: input
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87105263
has comment: http://stackoverflow.com/comment/87105196
has title: Encryption code in def function to be written in python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87105108
tagged with: validation

http://stackoverflow.com/q/49946180
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49946619
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/86909306
has answer: http://stackoverflow.com/a/52345837
tagged with: javascript
tagged with: python
score: -1
has body: I have written a Python program to process some data. I want to run that Python program when the user clicks a button, and display the output on the web page. Here is my web page: function changeText() { document.getElementById('boldStuff').textContent = ____________; } This is your score: score My Python program is called scorecalculator.py and ends with: print(finalScore) What should I write in my JavaScript to make this work? (I'm using Flask.)
has title: I want to run a python script from my HTML website by clicking on button to show the value from script
tagged with: flask
has comment: http://stackoverflow.com/comment/86909443
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/86909425
downvote count: 3
has comment: http://stackoverflow.com/comment/86909527
has comment: http://stackoverflow.com/comment/86909526
has comment: http://stackoverflow.com/comment/86909272
has comment: http://stackoverflow.com/comment/86909168
favorite count: 0

http://stackoverflow.com/q/50030819
type: Question
upvote count: 9
type: AnsweredQuestion
has title: python: how to add a new key and a value in yaml file
has body: I have the following YAML file. I need to update the YAML file with a new key-value pair using python. I am doing the following but, it gives me error: pod = mylib.load_yaml("net/pod.yaml") pod['spec']['nodeSelector']['key']='val' it gives error saying KeyError:'nodeSelector' spec: containers: - image: ceridwen/networking:v1 imagePullPolicy: Always name: networking readinessProbe: tcpSocket: port: 5000 initialDelaySeconds: 5 periodSeconds: 1 restartPolicy: Always I need to update it with a new key value spec: containers: - image: ceridwen/networking:v1 imagePullPolicy: Always name: networking readinessProbe: tcpSocket: port: 5000 initialDelaySeconds: 5 periodSeconds: 1 restartPolicy: Always nodeSelector: key: value
tagged with: python
has comment: http://stackoverflow.com/comment/87077933
tagged with: pyyaml
score: 9
tagged with: python-3.x
downvote count: 0
tagged with: yaml
answer count: 1
has answer: http://stackoverflow.com/a/50034565
accepted answer: http://stackoverflow.com/a/50034565
favorite count: 0

http://stackoverflow.com/comment/86872014
type: Comment
comment on: http://stackoverflow.com/a/49927541
type: AnswerComment
has text: Works like a charm, thank you! (I went for your workaround)
score: 0

http://stackoverflow.com/q/49927064
has title: Need to create a code for a different username on pyqt4
has comment: http://stackoverflow.com/comment/86870781
tagged with: python
score: -1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86870803
tagged with: pyqt
has comment: http://stackoverflow.com/comment/86870610
has answer: http://stackoverflow.com/a/49929417
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: pyqt4
has body: I'm having a problem on my code every time I put a different username on the username box it print the same schedule. I've been trying to figure out this code but I'm having headache on it. I don't know how to fix it. windowbox ##!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui global username username = " " class Home(QtGui.QWidget): def __init__(self): super(Home, self).__init__() self.initUI() def initUI(self): font = QtGui.QFont("Times New Roman",10,QtGui.QFont.Bold,False) #We Changed the font to Times New Roman username = QtGui.QLabel('Username',self) username.move(10,40) username.setFont(font); username = QtGui.QLabel('Enter Courses Prefix',self) username.move(10,160) username.setFont(font); usernameEdit = QtGui.QLineEdit(self) usernameEdit.move(90,35) usernameEdit.textChanged[str].connect(self.onChangedusername) #login box for Username usernameEdit.setFocus() usernameEdit = QtGui.QLineEdit(self) usernameEdit.move(160,160) usernameEdit.textChanged[str].connect(self.onChangedusername) #login box for Courses Prefix usernameEdit.setFocus() btn = QtGui.QPushButton('Print all Courses', self) btn.move(10, 80) btn.setFixedWidth(130) btn.setFixedHeight(50) btn.setStyleSheet("background-color: #00FF00") #Print all Courses btn.clicked.connect(self.Courses) btn.setFont(font) btn = QtGui.QPushButton('Print Schedule', self) btn.move(180, 80) btn.setFixedWidth(130) btn.setFixedHeight(50) btn.setStyleSheet("background-color: #00FF00") #Print Schedule btn.clicked.connect(self.Schedule) btn.setFont(font) btn = QtGui.QPushButton('Add Courses', self) btn.move(10, 200) btn.setFixedWidth(130) btn.setFixedHeight(50) btn.setStyleSheet("background-color: #FF00FF") #Add Courses button btn.clicked.connect(self.Courses) btn.setFont(font) btn = QtGui.QPushButton('Drop Courses', self) btn.move(180, 200) btn.setFixedWidth(130) btn.setFixedHeight(50) btn.setStyleSheet("background-color: #FF00FF") #Drop Courses button btn.clicked.connect(self.Courses) btn.setFont(f…
downvote count: 1
has comment: http://stackoverflow.com/comment/86870724
has comment: http://stackoverflow.com/comment/86870558
has comment: http://stackoverflow.com/comment/86870629
has comment: http://stackoverflow.com/comment/86872389

http://stackoverflow.com/a/49963257
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49935190
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49935190
has body: After a lot of head-scratching I finally understand how to achieve what I wanted, this was not so straightforward. There are two things which were wrong in my initial post: - As mentioned, the widget was not yet initialized when I assigned the property. The trick is to use Clock.schedule_once to delay the initialization to the next frame. I have seen this trick in another question (sorry, I can't find it agin right now). - An issue which arise from that is that the widgets are created but cannot be updated/accessed. For that I created a callback method which updates the labels every time the data in the viewclass is updated. Here is the code: from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.uix.label import Label from kivy.uix.recycleview import RecycleView from kivy.clock import Clock kv = """ &lt;Row&gt;: id: row canvas.before: Color: rgba: 0.5, 0.5, 0.5, 1 Rectangle: size: self.size pos: self.pos &lt;Test&gt;: canvas: Color: rgba: 0.3, 0.3, 0.3, 1 Rectangle: size: self.size pos: self.pos orientation: 'vertical' GridLayout: cols: 3 rows: 2 size_hint_y: None height: dp(108) padding: dp(8) spacing: dp(16) Button: text: 'Update list' on_press: root.update() RecycleView: id: rvlist scroll_type: ['bars', 'content'] scroll_wheel_distance: dp(114) bar_width: dp(10) viewclass: 'Row' RecycleBoxLayout: default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' spacing: dp(2) """ Builder.load_string(kv) class Row(BoxLayout): row_content = ObjectProperty() def __init__(self,**kwargs): super().__init__(**kwargs) Clock.schedule_once(self.finish_init,0) # it delays the end of the initialization to the next frame, once the widget are already created # and the properties properly initialized def finish_init(self, dt): for elt in self.row_content: self.add_widget(Label(text = elt)) # now, this works properly as the widg…
score: 3
has comment: http://stackoverflow.com/comment/137846565

http://stackoverflow.com/a/50093194
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50050194
score: 2
answers question: http://stackoverflow.com/q/50050194
type: Answer
has body: Just in case someone has a similar question, I am going to rewrite the answer in here Answer: The problem is that you use both the commands way, and on_message way of creating commands. To fix this, you can either replace your on_message commands with commands commands, or add await bot.process_commands(message) after your command if statement in on_message
downvote count: 0

constraints
type: Tag
tags question: http://stackoverflow.com/q/49931455
tag name: constraints

http://stackoverflow.com/q/49979496
answer count: 1
has answer: http://stackoverflow.com/a/50003495
type: Question
tagged with: python-multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86975042
has title: Where does the limitation of the thread pool come from?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86974935
has comment: http://stackoverflow.com/comment/86975233
has comment: http://stackoverflow.com/comment/86975084
tagged with: python
has comment: http://stackoverflow.com/comment/86975346
has body: Using the following code, I found that the maximum size of the multiprocessing.pool.ThreadPool is 11689 (on my machine). If I make it bigger, I get RuntimeError: can't start new thread Can somebody explain where this comes from? 11689 seems like a weird system constant... so maybe I ran out of a resource? Please note: This is not about how to choose the best number of threads for a Thread pool. This question is about where the 11689 comes from? Code
score: 0
linked to: http://stackoverflow.com/q/344203

http://stackoverflow.com/a/50041434
accepted answer of: http://stackoverflow.com/q/50041346
has body: My advice is not to do this. Use a dictionary for a variable number of variables. result = ['s2as1a', 's1bs2a', 's1as3b', 's2as3a'] d = {'s1a': [1, 2, 3], 's1b': [2, 3, 4], 's2a': [3, 4, 5], 's2b': [4, 5, 6], 's3a': [5, 6, 7], 's3b': [6, 7, 8]} res = {idx: d[i[:3]] + d[i[-3:]] for idx, i in enumerate(result)} {0: [3, 4, 5, 1, 2, 3], 1: [2, 3, 4, 3, 4, 5], 2: [1, 2, 3, 6, 7, 8], 3: [3, 4, 5, 5, 6, 7]}
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50041346
type: AcceptedAnswer
downvote count: 0
upvote count: 1

animation
tags question: http://stackoverflow.com/q/50070062
tags question: http://stackoverflow.com/q/49963666
tags question: http://stackoverflow.com/q/49995318
tags question: http://stackoverflow.com/q/49926269
type: Tag
tag name: animation
tags question: http://stackoverflow.com/q/49940550
tags question: http://stackoverflow.com/q/49942884
tags question: http://stackoverflow.com/q/50024509

http://stackoverflow.com/q/50033473
tagged with: pip
downvote count: 1
has comment: http://stackoverflow.com/comment/87083212
upvote count: 3
has title: Error in installing Flask using pip command in windows
tagged with: python
has body: I tried to install Flask as well as virtualenv using pip command in windows command prompt but below error is showing. How can I fix this? C:\Users\anupa&gt;pip install Flask Collecting Flask Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x06620E50&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/flask/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x06620DF0&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/flask/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x06620C30&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/flask/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x06620E10&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/flask/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('&lt;pip._vendor.urllib3.connection…
favorite count: 0
type: Question
score: 2
has answer: http://stackoverflow.com/a/55559174
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87083152
answer count: 1

http://stackoverflow.com/comment/87130665
comment on: http://stackoverflow.com/q/50057047
type: Comment
type: QuestionComment
score: 2
has text: I would also suggest in such cases that you use print so you can see a step by step execution. In each loop you can see what value is assigned to the variable you are interested in. If you use print you can see from the first loop execution there is a difference and then you can further analyse the behavior of your program and the behavior that you want to achieve

http://stackoverflow.com/comment/87118831
type: Comment
comment on: http://stackoverflow.com/q/50050657
type: QuestionComment
has text: no, as I mention I do not want to use tzlocal module
score: 0

http://stackoverflow.com/a/50065345
has body: maybe you can try initializing the values for a and b to 0.0 so that python looks at them as decimals.
answers question: http://stackoverflow.com/q/50065192
type: Answer
score: 0

http://stackoverflow.com/a/50032493
type: Answer
answers question: http://stackoverflow.com/q/50032261
score: 0
has body: The same thing that you do for a list, do for the other, and return 2 values as a tuple. ([SO]: return tuple from a method ) Here's an implementation that uses [Python]: sum(iterable[, start]). Note that it can be written in a much more compact manner, but I'm keeping all steps separate, so it's clearer: def ave_list(lat_list, long_list): lat_sum = sum(lat_list) # Calculate the sum if len(lat_list): # Test so we don't divide by 0 lat_avg = lat_sum / len(lat_list) # Calculate avg else: lat_avg = 0 # List empty, consider avg 0 long_sum = sum(long_list) # Same thing for longitude if len(long_list): long_avg = long_sum / len(long_list) else: long_avg = 0 return lat_avg, long_avg The results can be retrieved via tuple unpacking (check [Python]: Tuples and Sequences): lat_ave, long_ave = ave_list([1, 2, 3], [3, 4, 5]) and this should give you 2.0 for lat_ave, and 4.0 for long_ave.

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/50002465
tags question: http://stackoverflow.com/q/49962533
tags question: http://stackoverflow.com/q/50008800
tags question: http://stackoverflow.com/q/50045413
tags question: http://stackoverflow.com/q/50002315
tags question: http://stackoverflow.com/q/50019680
tags question: http://stackoverflow.com/q/49934915
tags question: http://stackoverflow.com/q/50069430
tags question: http://stackoverflow.com/q/49999623
tags question: http://stackoverflow.com/q/49932242
tags question: http://stackoverflow.com/q/50033898
tags question: http://stackoverflow.com/q/50055823
tags question: http://stackoverflow.com/q/49990974
tags question: http://stackoverflow.com/q/50008424
tags question: http://stackoverflow.com/q/49935993
tags question: http://stackoverflow.com/q/49986251
tags question: http://stackoverflow.com/q/49948661
tags question: http://stackoverflow.com/q/50019291
tags question: http://stackoverflow.com/q/50018013
tags question: http://stackoverflow.com/q/50043330
tag name: json
tags question: http://stackoverflow.com/q/49933233
tags question: http://stackoverflow.com/q/50070256
tags question: http://stackoverflow.com/q/49979262
tags question: http://stackoverflow.com/q/50000536
tags question: http://stackoverflow.com/q/49948179
tags question: http://stackoverflow.com/q/50032258
tags question: http://stackoverflow.com/q/49953471
tags question: http://stackoverflow.com/q/50005158
tags question: http://stackoverflow.com/q/49955795
tags question: http://stackoverflow.com/q/49993514
tags question: http://stackoverflow.com/q/49964963
tags question: http://stackoverflow.com/q/49954262
tags question: http://stackoverflow.com/q/50047128
tags question: http://stackoverflow.com/q/50011251
tags question: http://stackoverflow.com/q/49943882
tags question: http://stackoverflow.com/q/49962973
tags question: http://stackoverflow.com/q/50011349
tags question: http://stackoverflow.com/q/49987323
tags question: http://stackoverflow.com/q/49979605
tags question: http://stackoverflow.com/q/49995727
tags question: http://stackoverflow.com/q/49978432
tags question: http://stackoverflow.com/q/49946744
tags question: http://stackoverflow.com/q/49971393
tags question: http://stackoverflow.com/q/49964340
tags question: http://stackoverflow.com/q/50034981
tags question: http://stackoverflow.com/q/50044698
tags question: http://stackoverflow.com/q/49941691
tags question: http://stackoverflow.com/q/50045880
tags question: http://stackoverflow.com/q/50011439
tags question: http://stackoverflow.com/q/49990993
tags question: http://stackoverflow.com/q/49980337
tags question: http://stackoverflow.com/q/50041649
tags question: http://stackoverflow.com/q/49926263
tags question: http://stackoverflow.com/q/50039182
tags question: http://stackoverflow.com/q/49925554
tags question: http://stackoverflow.com/q/50070905
tags question: http://stackoverflow.com/q/50022098
tags question: http://stackoverflow.com/q/49943543
tags question: http://stackoverflow.com/q/50047148
tags question: http://stackoverflow.com/q/50030168
type: Tag
tags question: http://stackoverflow.com/q/50073293
tags question: http://stackoverflow.com/q/50003959
tags question: http://stackoverflow.com/q/49964307
tags question: http://stackoverflow.com/q/50029624
tags question: http://stackoverflow.com/q/49920040
tags question: http://stackoverflow.com/q/50047790
tags question: http://stackoverflow.com/q/50023807
tags question: http://stackoverflow.com/q/50022814
tags question: http://stackoverflow.com/q/49948024
tags question: http://stackoverflow.com/q/49967179
tags question: http://stackoverflow.com/q/50045203
tags question: http://stackoverflow.com/q/50023625
tags question: http://stackoverflow.com/q/49963305
tags question: http://stackoverflow.com/q/49923417
tags question: http://stackoverflow.com/q/50040470
tags question: http://stackoverflow.com/q/49975943
tags question: http://stackoverflow.com/q/49982459
tags question: http://stackoverflow.com/q/50036071

http://stackoverflow.com/comment/86983857
comment on: http://stackoverflow.com/q/49981741
score: 0
type: Comment
has text: What is content of app.py ?
type: QuestionComment

http://stackoverflow.com/a/50023156
type: Answer
score: 1
answers question: http://stackoverflow.com/q/50022954
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: To solve your problem specifically you'll have to instantiate the class and then call the function, no need to use the getattr names = [ClassA, ClassB] # no quotes here, just the class reference for name in names: name().method() If the classes have the same methods name this will work.
accepted answer of: http://stackoverflow.com/q/50022954

http://stackoverflow.com/comment/87119805
score: 0
comment on: http://stackoverflow.com/q/50050631
has text: @Mad Physicist I did use numpy (I edited it to show it now). Perhaps you meant something else?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87079706
comment on: http://stackoverflow.com/a/50031666
score: 0
type: Comment
has text: ** is keyword unpacking of a dataframe. Basically it is taking the columns or pd.Series of the dataframe and join it back to the original dataframe.
type: AnswerComment

http://stackoverflow.com/comment/87085472
score: 1
has text: What is `ageInt`? [mcve] please...
type: Comment
comment on: http://stackoverflow.com/q/50034601
type: QuestionComment

http://stackoverflow.com/a/50054182
accepted answer of: http://stackoverflow.com/q/50054160
has body: You have a typo d = ({'Time' : np.random.randint(k, k + 100 , size=N), 'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'], 'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'], 'Number2' : [1,1,'xx',1,'xx',2,'xx',2]})# used to have comma here df = pd.DataFrame(data=d)
answers question: http://stackoverflow.com/q/50054160
type: AcceptedAnswer
downvote count: 0
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87124926
type: Answer

http://stackoverflow.com/comment/87155119
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50069212
type: AnswerComment
has text: My original array is much bigger, and for some reason, every seventh number is deleted when I use this code. So that would be '[[a b c d e -- g],[a b c d e -- g],[a b c d e -- g],...]'.

http://stackoverflow.com/comment/86979398
has text: @sciroccorics Yes
type: QuestionComment
comment on: http://stackoverflow.com/q/49980524
score: 0
type: Comment

http://stackoverflow.com/a/52668663
has body: Probably it's because of sklearn implementation that won't allowed you to do so if you only have 2 class. The problem has been stated in here, https://github.com/scikit-learn/scikit-learn/issues/1967.
type: Answer
has comment: http://stackoverflow.com/comment/92593396
score: -1
answers question: http://stackoverflow.com/q/49955592
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/50070398
has title: Import tensorflow contrib learn python learn
has answer: http://stackoverflow.com/a/50070442
answer count: 3
tagged with: deep-learning
downvote count: 0
score: 1
upvote count: 1
tagged with: scikit-learn
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50070455
has answer: http://stackoverflow.com/a/50070463
type: UnansweredQuestion
has body: I am new to tensorflow. When I am using import tensorflow.contrib.learn.python.learn for using the DNNClassifier it is giving me an error: module object has no attribute python Python version 3.4 Tensorflow 1.7.0
tagged with: python

http://stackoverflow.com/q/50070360
has comment: http://stackoverflow.com/comment/87157337
accepted answer: http://stackoverflow.com/a/50070531
linked to: http://stackoverflow.com/q/19158339
has answer: http://stackoverflow.com/a/50070467
possible better answer: http://stackoverflow.com/a/50070467
has comment: http://stackoverflow.com/comment/87160492
has comment: http://stackoverflow.com/comment/87157268
has comment: http://stackoverflow.com/comment/87157366
has title: What are the possible alternatives to making all variables in a function global in Python?
has comment: http://stackoverflow.com/comment/87157240
has comment: http://stackoverflow.com/comment/87157304
has answer: http://stackoverflow.com/a/50070531
score: 0
has comment: http://stackoverflow.com/comment/87408262
has answer: http://stackoverflow.com/a/50070675
answer count: 3
has body: Okay, so I know you shouldn't /really/ make variables global - they're meant to be local. However I am programming a blackjack game and I need to reset the cards every time the user wants to play again - so I have made a function called 'reset' and it calls that if the it is going to repeat. My main question is, should I do this or is there a better method of solving my problem, or is there a better way of doing this than just typing out global _____ every time? Here's my code if anyone wants to see; import random playagain = True def reset(): global cards global gameCards global playerCards global cpuCards global pgameCards global cpugameCards global start cards = ["A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "Q♠", "K♠", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥", "10♥", "J♥", "Q♥", "K♥", "A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "Q♣", "K♣", "A♦", "2♦", "3♦", "4♦", "5♦", "6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "Q♦", "K♦"] gameCards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] playerCards = [] cpuCards = [] pgameCards = [] cpugameCards = [] start = 0 [...] while playagain == True: reset() winner = game() print("Your cards: ", playerCards) print("CPU's cards: ", cpuCards) print(winner) askUser = input("Play again? Y/N ") if askUser.upper() == "Y": playagain = True else: playagain = False
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1680528
tagged with: python
has comment: http://stackoverflow.com/comment/87160127
type: Question

http://stackoverflow.com/comment/86921162
type: QuestionComment
comment on: http://stackoverflow.com/q/49951960
score: 0
has text: Any decent IDE or programming editor would show you the problem.
type: Comment

http://stackoverflow.com/comment/119581016
has text: Does that mean that for an example using a path, it would be `seq = imread_collection("/path/to/test/*.jpg", conserve_memory=True)`?
type: Comment
comment on: http://stackoverflow.com/a/50376154
type: AnswerComment
score: 0

http://stackoverflow.com/q/50057427
has body: Is there something wrong with this code ? region = Select(driver.find_element_by_id('x_place_occ_reg')) region.select_by_visible_text(varRegion) Whenever I run the code, it shows the following error. Message: Element is not clickable at point (380.5,333) because another element obscures it I'm hoping that someone who can point out the error, by the way thank you in advance.
tagged with: python
has comment: http://stackoverflow.com/comment/87131346
score: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/87131336
type: Question
has title: Python-Selenium: Element is not clickable in drop-down box
linked to: http://stackoverflow.com/q/44724185
has answer: http://stackoverflow.com/a/50057994
type: UnansweredQuestion

http://stackoverflow.com/comment/87058450
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50020380
has text: It sounds like you want to update the `.csv` file in place. That is not how textfiles work. If you use one `for` loop to read all the lines into memory and another to write them all out again (except for one) that *will* be inefficient because it will read your whole file into memory. But you can read one file and write another in the same loop.

http://stackoverflow.com/comment/101520721
comment on: http://stackoverflow.com/a/50038162
score: 0
type: AnswerComment
has text: After looking for 3 hours found your solution. This worked. Thanks mate.
type: Comment

http://stackoverflow.com/comment/86995814
has text: @HamadHassan I updated my answer showing how to read from a file.
score: 0
comment on: http://stackoverflow.com/a/49929341
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50070256
possible better answer: http://stackoverflow.com/a/50070421
tagged with: python-requests
has body: Getting an error with the following code. However, sometimes it works and sometimes it doesn't. I have validated the data with JSONLint. I have tried to decode/encode the data based off responses to similar error questions and also tried the same using the codecs module. What I don't understand is why it sometimes works fine and then other times throws an error. import requests import json import codecs response = requests.get("https://api.weather.gov/alerts/active") print(response.status_code) with open ('data.json', 'w') as file: file.write(response.content) myFile = open('data.json', 'r') myObject = myFile.read() u = myObject.decode('utf-8-sig') myObject = u.encode('utf-8') myFile.encoding myFile.close() myData = json.loads(myObject, 'utf-8') #myData=json.loads(codecs.open(myObject,'r', 'utf-8')) A sample of the JSON data can be found in another question I asked here.
has title: Python ValueError: No JSON Object Could Be Decoded (Intermittent)
type: AnsweredQuestion
tagged with: python-2.6
has comment: http://stackoverflow.com/comment/87157607
has comment: http://stackoverflow.com/comment/87157191
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/87157789
linked to: http://stackoverflow.com/q/50028427
has answer: http://stackoverflow.com/a/50070421
accepted answer: http://stackoverflow.com/a/50070588
type: Question
score: 0
has answer: http://stackoverflow.com/a/50070588
answer count: 2
has comment: http://stackoverflow.com/comment/87157471

http://stackoverflow.com/comment/87100586
type: Comment
has text: the Wize TreeView is not the treeview that comes with tkinter. It's a separate package.
type: QuestionComment
comment on: http://stackoverflow.com/q/50015662
score: 1

http://stackoverflow.com/comment/86975793
type: AnswerComment
score: 0
has text: Maybe include a sequence of rolls for which OP's current method returns `None` in order to explain the bug.
comment on: http://stackoverflow.com/a/49979915
type: Comment

http://stackoverflow.com/comment/86969352
has text: `"".join("foo bar")` returns `'foo bar'` so spaces are not removed. You have to use `"".join("foo bar".split())`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49976202
type: Comment

http://stackoverflow.com/comment/87076767
has text: Neither of those are dictionaries.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50030168
type: QuestionComment

http://stackoverflow.com/q/49954357
type: Question
tagged with: python-3.x
has body: I am new to Django Python and I am learning how to use Django and passing data from view to template. Now, here is my situation and I really need some help in understanding where i can be doing wrong. I am trying to pass data from view to template and then parse the object in the view but for some reason nothing is happening in the template. I have printed the registration object in my views.py and it works fine and displays the information that is correct. But when I send the registration object from views to template nothing happens. models.py from django.db import models from datetime import datetime from django.shortcuts import redirect # Create your models here. # Create your models here. class Registration(models.Model): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) email = models.CharField(max_length=255, null=True, blank=True) password = models.CharField(max_length=255, null=True, blank=True) mobilenumber = models.CharField(max_length=255, null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True, blank=True) class Meta: ordering = ('first_name',) views.py class Loginview(CreateView): model = Registration form_class = LoginForm template_name = "loginvalentis/valentis_login.html" def get(self, request): form = LoginForm() # returning form return render(request, 'loginvalentis/valentis_login.html', {'form': form}); def form_valid(self,form): user_email = form.cleaned_data.get('email') user_password = form.cleaned_data.get('password') try: registration = Registration.objects.get(email=user_email) print ("registration",registration.mobilenumber) return redirect('/loginvalentis/home/',{'registration':registration}) except Registration.DoesNotExist: user_info = None return redirect('/loginvalentis/login/') Template result.html --- ('/loginvalentis/home/') {% csrf_token %} hello world {% for user in registration %} {{ user.mobilenumber }} {% endfor %}
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49955514
score: 0
has title: Problems with passing data from view to template?
answer count: 1
has comment: http://stackoverflow.com/comment/86926354

http://stackoverflow.com/q/50018512
tagged with: python
has answer: http://stackoverflow.com/a/50019183
type: AnsweredQuestion
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
score: 7
upvote count: 7
answer count: 1
has title: How to group near-duplicate values in a pandas dataframe?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50019183
has body: If there are duplicate values in a DataFrame pandas already provides functions to replace or drop duplicates. In many experimental datasets on the other hand one might have 'near' duplicates. How can one replace these near duplicate values with, e.g. their mean? The example data looks as follows: df = pd.DataFrame({'x': [1, 2,2.01, 3, 4,4.1,3.95, 5,], 'y': [1, 2,2.2, 3, 4.1,4.4,4.01, 5.5]}) I tried to hack together something to bin together near duplicates but this is using for loops and seems like a hack against pandas: def cluster_near_values(df, colname_to_cluster, bin_size=0.1): used_x = [] # list of values already grouped group_index = 0 for search_value in df[colname_to_cluster]: if search_value in used_x: # value is already in a group, skip to next continue g_ix = df[abs(df[colname_to_cluster]-search_value) &lt; bin_size].index used_x.extend(df.loc[g_ix, colname_to_cluster]) df.loc[g_ix, 'cluster_group'] = group_index group_index += 1 return df.groupby('cluster_group').mean() Which does the grouping and averaging: print(cluster_near_values(df, 'x', 0.1)) x y cluster_group 0.0 1.000000 1.00 1.0 2.005000 2.10 2.0 3.000000 3.00 3.0 4.016667 4.17 4.0 5.000000 5.50 Is there a better way to achieve this?

http://stackoverflow.com/a/50049392
has body: The problem is that you're only incrementing index after the loop, rather than each time through it. So, inside the loop, it's always 0. The smallest fix is: def myfunc(word): result = "" index = 0 for letter in word: if index % 2 == 0: result += letter.lower() else: result += letter.upper() index += 1 return result But this kind of mistake is very easy to make (and sometimes not as easy as this to debug)—which is exactly why Python has nice tools like enumerate, that make it impossible to get wrong: def myfunc(word): result = "" for index, letter in enumerate(word): if index % 2 == 0: result += letter.lower() else: result += letter.upper() return result
type: Answer
upvote count: 6
score: 6
downvote count: 0
answers question: http://stackoverflow.com/q/50049309

http://stackoverflow.com/comment/87120246
comment on: http://stackoverflow.com/a/50051809
has text: `[tuple(x)]` will work whether `x` is a list, a tuple, or any other iterable.
score: 2
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86913920
comment on: http://stackoverflow.com/q/49948565
type: Comment
type: QuestionComment
score: 0
has text: How large is "a large amount"?

http://stackoverflow.com/comment/87143764
comment on: http://stackoverflow.com/q/50062663
type: Comment
type: QuestionComment
has text: @SeanFrancisN.Ballais My code shows exactly how the IV is used in CBC.
score: 1

http://stackoverflow.com/q/49992645
favorite count: 0
tagged with: beautifulsoup
type: Question
linked to: http://stackoverflow.com/q/23714383
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
tagged with: python
has body: I'm trying to scrape the information inside an 'iframe' tag. When I execute this code, it says that 'USER_AGENT' is not defined. How can I fix this? import requests from bs4 import BeautifulSoup page = requests.get("https://etherscan.io/token/0x168296bb09e24a88805cb9c33356536b980d3fc5#balances" + "/token/generic-tokenholders2?a=0x168296bb09e24a88805cb9c33356536b980d3fc5&amp;amp;s=100000000000000000", headers=USER_AGENT, timeout=5) soup = BeautifulSoup(page.content, "html.parser") test = soup.find_all('iframe')
upvote count: 2
score: 0
downvote count: 2
linked to: http://stackoverflow.com/q/6260457
has answer: http://stackoverflow.com/a/49994357
has answer: http://stackoverflow.com/a/49992689
has title: Getting error that USER_AGENT is not defined (Python 3)
tagged with: web-scraping

http://stackoverflow.com/q/50033516
tagged with: alphanumeric
has title: Divide alphanumeric word from a list and store as a key value pair of a dict
has answer: http://stackoverflow.com/a/50033576
has answer: http://stackoverflow.com/a/50033625
type: Question
has answer: http://stackoverflow.com/a/50033668
answer count: 5
type: UnansweredQuestion
has body: I have a list of alphanumeric data, my_list = ["A1B2244", "B3H7654", "A1O6541", "J4777"] I need to divide each word in dict form like {"A1": ["B2244", "O6541"], "B3": ["H7654"], "J4": ["777"]} Could you please let me know the easiest way to do this in python.
has answer: http://stackoverflow.com/a/50034665
has answer: http://stackoverflow.com/a/50034345
has comment: http://stackoverflow.com/comment/87083193
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87083205
has comment: http://stackoverflow.com/comment/87083316
score: 0

http://stackoverflow.com/q/50072900
accepted answer: http://stackoverflow.com/a/50072967
downvote count: 0
tagged with: tcpdump
possible better answer: http://stackoverflow.com/a/50072913
tagged with: python
has answer: http://stackoverflow.com/a/50072967
score: 4
has title: Delete everything after 4th period in string
has answer: http://stackoverflow.com/a/50072913
answer count: 4
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50072916
has body: I'm trying to manipulate the output from tcpdump in python 2.7. What I'm trying to do is remove the port portion of the IP Address. For example if the input string is 192.168.0.50.XXXX How would I go about deleting everything after the 4th period so the output would be 192.168.0.50 I've thought about doing something with the length of the string the only thing is port lengths can be anywhere from 1-5 digits in my example(0-9999). The only thing I can think of is doing something with the # of periods as a normal IP only contains 3 and an IP with Port attached has 4.
tagged with: string
has answer: http://stackoverflow.com/a/50073112
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/comment/87085127
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50034477
has text: If you have a CSV file, look into the `csv` module, or `pandas` which can read via `pandas.read_csv()`.
score: 0

http://stackoverflow.com/comment/86891247
has text: What do you denote with ***t*** and ***x*** in your equation exactly? Also, when you say "equation" in the first sentence, do you mean that the sum of these two terms is is your loss function? Then say so and lose the "=0" part please. Want to first make sure I understand the question before trying to answer... :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49935778

http://stackoverflow.com/comment/87217727
comment on: http://stackoverflow.com/a/50067636
has text: Yes, that worked, thank you :) that points help users to do more things on this site :)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86934889
has text: Thanks for adding an explanation. I still don't like the code, but at least it's comprehensible now.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49959067
type: AnswerComment

http://stackoverflow.com/a/68538261
answers question: http://stackoverflow.com/q/50029550
type: Answer
has body: In my case, the culprit was User._meta.get_field("email")._unique = True somewhere in the .py files. After deleting the line, makemigrations stopped creating migration file in auth folder, while keeping the uniq constraint that was created by that line.
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50025820
has comment: http://stackoverflow.com/comment/87067835
score: 2
upvote count: 2
downvote count: 0
has body: Use params[0][0] for accessing maperiod And similarly, params[1][0] for printlog Alternatively, you can also use a named tuple
has comment: http://stackoverflow.com/comment/87068457
answers question: http://stackoverflow.com/q/50025742
has comment: http://stackoverflow.com/comment/87070281
type: Answer

http://stackoverflow.com/comment/87122652
comment on: http://stackoverflow.com/q/50050194
score: 0
type: Comment
type: QuestionComment
has text: Where exactly are you adding registration and registrationinfo?

http://stackoverflow.com/a/57688652
downvote count: 0
upvote count: 1
has body: you should import crf_loss and 'crf_accuracy' to use the CRF layer properly to wrap up, it will look like this: from keras_contrib.losses import crf_loss from keras_contrib.metrics import crf_accuracy #. #. #. model.compile(optimizer="adam", loss=crf_loss, metrics=[crf_accuracy]) you can also see this example from Keras contribution GitHub.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50023592

http://stackoverflow.com/q/50014421
has comment: http://stackoverflow.com/comment/87049533
has title: Read file with weird windows path using python
has comment: http://stackoverflow.com/comment/87045345
type: UnansweredQuestion
answer count: 1
tagged with: os.walk
type: Question
tagged with: filepath
has answer: http://stackoverflow.com/a/50341646
tagged with: filenotfoundexception
score: 0
has comment: http://stackoverflow.com/comment/87045090
has body: With Python 3 I have an external drive with a Dropbox backup. I have been copying files from this drive to another location using python by using os.walk and iterating thru the files. os.walk will produce a valid folder and file name. ie W:\Z Drive Backup 4-14-18\Dropbox\Autodesk 2018 Win\file.xyz However, when using open or os.stat, it give me a FileNotFoundError. FileNotFoundError: [WinError 3] The system cannot find the path specified: 'W:/Z Drive Backup 4-14-18/Dropbox/Autodesk 2018 Win Opening the file properties it shows the location with \\?\ in front of it. See photo. If I add this to the file path, I still get the same error. I ran into a lot of folder and files while doing this that had funky Unicode or other characters in the path. I was able to identify these and replace the bad character with str.replace for most of them. I think this issue with \\?\ up front is the same type of issue, however, it can't even see the file in python for me to rename it. Any ideas how to fix the file path? If I rename the file on that drive it does not fix the problem. If I copy the file to another location, then it is fine. But has the problem when copying back. There are a lot of files, so I don't want to do any of it manually.
tagged with: windows
tagged with: python

http://stackoverflow.com/comment/86932589
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49957888
has text: Wow, than you so much , you are talented for programming, keep it up ;)
score: 0

http://stackoverflow.com/a/50019778
score: 17
answers question: http://stackoverflow.com/q/50019588
has comment: http://stackoverflow.com/comment/87055503
type: AcceptedAnswer
downvote count: 0
has body: This is not a good way of doing this, if you see this problem the structure of your code might not be good for your desires, but this will helps you: print(i) if i%10==0 else None
has comment: http://stackoverflow.com/comment/87055638
upvote count: 17
has comment: http://stackoverflow.com/comment/87055557
type: Answer
has comment: http://stackoverflow.com/comment/87055627
accepted answer of: http://stackoverflow.com/q/50019588

http://stackoverflow.com/comment/87060340
type: Comment
comment on: http://stackoverflow.com/a/50021353
score: 0
type: AnswerComment
has text: But why is it needed?

http://stackoverflow.com/q/49917663
has body: I've installed CNTK version 2,5 in Anaconda 3, python 3.6. But when I run Microsoft CNTK-sample codes in Spyder, the python crashed (Kernel died, restarting) and I got this error when I debugged the code line by line; NameError: "name 'cntk' is not defined" Could you please tell me what's wrong? Did I miss sths to do?
score: 0
has comment: http://stackoverflow.com/comment/86887490
answer count: 0
has comment: http://stackoverflow.com/comment/86851406
tagged with: cntk
tagged with: spyder
has comment: http://stackoverflow.com/comment/86850659
type: Question
has comment: http://stackoverflow.com/comment/87428614
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86925570
tagged with: python
has title: Get started with CNTK in Python via Spyder
has comment: http://stackoverflow.com/comment/86969485

http://stackoverflow.com/q/49933670
has answer: http://stackoverflow.com/a/49933808
tagged with: python
has answer: http://stackoverflow.com/a/49933754
tagged with: python-3.x
type: UnansweredQuestion
has body: file test1.log: {'Python' : '.py', 'C++' : '.cpp', 'length' : 24} def validate_file(f): #print('File Header Validation:') fname=open(f) count=0 for line in fname: if 'length' in line: print(line['length']) validate_file("test1.log") I am trying to find the value of length?here's the output after reading text from file test1.log : print(line['length']) TypeError: string indices must be integers Any help how can I extract the value of 'length' field?
has title: Extracting field ......TypeError: String indices must be integers
type: Question
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49933713

http://stackoverflow.com/comment/86916552
comment on: http://stackoverflow.com/q/49949885
score: 0
has text: @tdelaney I agree. For the speed part, why -5 to 256? based on what?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49957768
upvote count: 1
has comment: http://stackoverflow.com/comment/87112865
type: Answer
has comment: http://stackoverflow.com/comment/87099763
accepted answer of: http://stackoverflow.com/q/49957263
has comment: http://stackoverflow.com/comment/87055196
has comment: http://stackoverflow.com/comment/87111612
answers question: http://stackoverflow.com/q/49957263
has comment: http://stackoverflow.com/comment/87116338
has comment: http://stackoverflow.com/comment/87147634
has body: In python using pandas, this should work. import pandas as pd df = pd.read_excel("/path/to/file/Book1.xlsx") df = df.loc[:, ['symbol', 'name', 'date', 'close']] df = df.set_index(['symbol', 'name', 'date']) df = df.unstack(level=[0,1]) df = df['close'] to read the symbols file file and then filter out symbols not in the dataframe: symbols = pd.read_csv('/path/to/file/symbols.txt', sep=" ", header=None) symbols = symbols[0].tolist() symbols = pd.Index(symbols).unique() symbols = symbols.intersection(df.columns.get_level_values(0)) And the output will look like: print(df[symbols]) symbol AAA LA YC name companyA Lancer Yocomin date 2018-09-01 00:00:00 None 0,422736 None 2018-10-01 00:00:00 None 0,487106 None 2018-11-01 00:00:00 None 0,331977 None
has comment: http://stackoverflow.com/comment/87079095
score: 1
has comment: http://stackoverflow.com/comment/87031034
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50074564
type: AnsweredQuestion
tagged with: list
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50074646
tagged with: select
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87167329
has comment: http://stackoverflow.com/comment/87172705
favorite count: 0
type: Question
upvote count: 2
has body: board balls win1 win2 result ----- ----- ---- ---- ------ 1 1 0 0 1 4 1 0 0 1 1024 1 0 0 1 When we are selecting only one row but multiple columns from a table, for example, by using: connection = sqlite3.connect("spline.db") crsr = connection.cursor() crsr.execute("SELECT board FROM positions WHERE balls = 1") result = crsr.fetchall() print result connection.close() The result is a list of tuples: [(1,), (4,), (1024,)] Is there any way to get a list of integers directly? One way to do it is with: print [result[i][0] for i in range(len(result))] instead of with: print result But whenever that there are as much as 107 rows in the result set, we cannot imagine of iterating the variable i like that, and then make a list of integers out of it. So, I would like to know that if there are any other alternative solutions available for it whichever are efficient enough quite directly.
has title: Python SQLite3 / Selecting rows from table
has answer: http://stackoverflow.com/a/50078831
possible better answer: http://stackoverflow.com/a/50078831
tagged with: python
has answer: http://stackoverflow.com/a/50074635
accepted answer: http://stackoverflow.com/a/50074635
tagged with: tuples
score: 2

http://stackoverflow.com/q/49922983
has comment: http://stackoverflow.com/comment/87329706
has comment: http://stackoverflow.com/comment/87232898
tagged with: python
has comment: http://stackoverflow.com/comment/86918417
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: user-interface
has body: I started programming in Python a few weeks ago. I have made a python program wherefore I am now making a gui with tkinter. The user input in the gui will be processed by the python program I already wrote. But when I run my program and want to use the value from an entry field in the python program it doesn't print the input value of the entry. But is prints 0,0 instead. I got the following codes: I got a class where I make a frame for my gui with tkinter (GUI_Pump.py): import GUI as Gui from GUI import * import pump as Pomp class Pump1(tk.Frame): p1_pump_spd1 = 0 d_p1_mtr_on = 0 def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text='Test case') label.place(x=380, y=10) def validate(new_text): if not new_text: # the field is being cleared self.entered_number = 0 return True try: self.entered_number = int(new_text) return True except ValueError: return False def ok(): global p1_pump_spd1 p1_pump_spd1 = p1.get() try: p1_pump_spd1 except ValueError: p1_pump_spd1 = 0 print(Pomp.p1_pump_spd) vcmd = parent.register(validate) p1 = tk.Entry(self, width=10, validate='key', validatecommand=(vcmd, '%P')) btn_ok = tk.Button(self, text='ok', command=ok, width=2) p1.place(x=230, y=20) btn_ok.place(x=290, y=20) And I got my python program where I want to process the input value (pump.py) from GUI import * import GUI_Pump as GuiP D_MH_MTR_SP_HLIM = 1500.0 D_MH_MTR_SP_LLIM = 0.0 def fc33_limit_real(MIN, IN, MAX): if IN &lt;= MIN: OUT = MIN elif IN &gt;= MAX: OUT = MAX else: OUT = IN return OUT p1_spd = GuiP.Pump1.p1_pump_spd1 p1_pump_spd = fc33_limit_real(D_MH_MTR_SP_LLIM, p1_spd, D_MH_MTR_SP_HLIM) But if I print p1_pump_p1_spd I get always 0,0, no matter what I fill in to the entry field. Any help would be appreciated.
tagged with: python-3.6
type: Question
has comment: http://stackoverflow.com/comment/86965838
has title: How to take an entry input from tkinter to an python script?
score: 0

http://stackoverflow.com/q/49954584
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49954859
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86925591
tagged with: typeerror
has body: I have as an input a list that i converted it to a string so i can use for my main program (DNA translation) and for that i need its length to find the 3 different frames. Btw it needs mentioning that the user has put an input (DNA sequence eg. ATGCGTAGT). The first part where i convert my comp seq is this: comp = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C' } for i in sequence_list : comp_sequence += comp[i] reversed_comp_seq = ''.join(reversed(comp_sequence)) And later on, in my program it is used here: for e in range(0, len(reversed_comp_seq)-len(reversed_comp_seq)%3,3): Frame4 += codons1[reversed_comp_seq[e:e + 3]] print(Frame4) And then i cannot run it to find the reversed translation because it says this: TypeError: object of type 'reversed' has no len() Could you help me please? Thanks!
has comment: http://stackoverflow.com/comment/86925582
type: UnansweredQuestion
has title: Error: object of type 'reversed' has no len()?
has comment: http://stackoverflow.com/comment/86925752
tagged with: python
score: -4
downvote count: 4

sqlite
tags question: http://stackoverflow.com/q/49920444
tags question: http://stackoverflow.com/q/49937868
tags question: http://stackoverflow.com/q/50045714
tags question: http://stackoverflow.com/q/50005663
tags question: http://stackoverflow.com/q/49985657
tags question: http://stackoverflow.com/q/49947296
tags question: http://stackoverflow.com/q/49927757
tags question: http://stackoverflow.com/q/49930533
tags question: http://stackoverflow.com/q/49949162
tags question: http://stackoverflow.com/q/49962759
tags question: http://stackoverflow.com/q/50059200
tags question: http://stackoverflow.com/q/49969735
tags question: http://stackoverflow.com/q/50029795
type: Tag
tags question: http://stackoverflow.com/q/49983544
tags question: http://stackoverflow.com/q/50045648
tags question: http://stackoverflow.com/q/50022851
tags question: http://stackoverflow.com/q/50009125
tags question: http://stackoverflow.com/q/49992516
tags question: http://stackoverflow.com/q/49921105
tags question: http://stackoverflow.com/q/50063058
tags question: http://stackoverflow.com/q/50027426
tags question: http://stackoverflow.com/q/49960110
tags question: http://stackoverflow.com/q/50042673
tags question: http://stackoverflow.com/q/49952618
tags question: http://stackoverflow.com/q/49937016
tags question: http://stackoverflow.com/q/50038805
tags question: http://stackoverflow.com/q/49983853
tags question: http://stackoverflow.com/q/49981686
tags question: http://stackoverflow.com/q/50028407
tags question: http://stackoverflow.com/q/49953820
tags question: http://stackoverflow.com/q/49966061
tags question: http://stackoverflow.com/q/50074564
tag name: sqlite
tags question: http://stackoverflow.com/q/49996737
tags question: http://stackoverflow.com/q/49954268
tags question: http://stackoverflow.com/q/50031719
tags question: http://stackoverflow.com/q/49936236
tags question: http://stackoverflow.com/q/49958881

http://stackoverflow.com/comment/86929227
type: QuestionComment
comment on: http://stackoverflow.com/q/49956520
has text: Dictionaries aren't ordered data structures. That's why OrderedDict exists at all!
type: Comment
score: 1

http://stackoverflow.com/comment/86985768
type: QuestionComment
comment on: http://stackoverflow.com/q/49984220
has text: @GrantWilliams let me repost my comment ... "It's what you do with that memory that might be slower in python" yes - python is an interpreted scripting language; it will be slower when doing a number of things. That said it's still heavily optimised; hence my question about seeing the source.
score: 0
type: Comment

http://stackoverflow.com/comment/87018483
has text: If the lines aren't separated by a `\n`, then it's a `\r`? I'm trying to understand how it would be two rows if there's no newline sequence. Otherwise, it would be hard to build your custom bigram generator without that distinction.
type: QuestionComment
comment on: http://stackoverflow.com/q/49996489
type: Comment
score: 0

http://stackoverflow.com/comment/87149820
has text: do some research on the `after` method that is available on all widgets.
comment on: http://stackoverflow.com/q/50066614
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49945617
has body: I would take a different approach by first checking for any of the invalid characters. Then verify that it does contain at least one of the rotating characters. rotating = {'2','5','6','9'} invalid = {'3','4','7'} def rotated(N): X=set(str(N)) if any(digit in X for digit in invalid): return False if any(digit in X for digit in rotating): return True return False def checkall(N): count=0 for i in range(1,N+1): if rotated(i): count += 1 return count print(checkall(857))
score: 1
has comment: http://stackoverflow.com/comment/86909201
type: Answer
answers question: http://stackoverflow.com/q/49945045
has comment: http://stackoverflow.com/comment/86911256
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49983958
tagged with: python
has answer: http://stackoverflow.com/a/49984092
has body: I have been trying to run a Django application since afternoon. The application probably uses Python 2.7. I have created virtual environment and I have installed Django with Python PIP package manager. However, this application requires JQuery package for proper working. Unfortunately, an error has occurred when I tried to install JQuery package with PIP: (my_env) user➜~/carcaresilesia» pip install jquery [16:39:44] ⚡[..........] Collecting jquery Using cached https://files.pythonhosted.org/packages/05/45/9a6d7ff770b1279c901c8dfca1f9a9d6c9822d75a2bad834d0e2ddd4f8cd/jquery-1.2.3.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-install-wKwd78/jquery/setup.py", line 2, in &lt;module&gt; from turbogears.finddata import find_package_data ImportError: No module named turbogears.finddata ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-wKwd78/jquery/ I tried install the turbogears package, unsuccessfully with below error: (my_env) user➜~/carcaresilesia» pip install turbogears Collecting turbogears Using cached https://files.pythonhosted.org/packages/1d/35/80872474a6663b6994b6879041a38b2fa81a34098e331f2ffddd43e2c8d3/TurboGears-1.5.1.tar.gz Collecting CherryPy&gt;=3.1.2 (from turbogears) Using cached https://files.pythonhosted.org/packages/b8/6d/d0d951dee5ba50900eccb71ef501a847d0392f50056d36234740f97a2ef8/CherryPy-14.2.0-py2.py3-none-any.whl Collecting ConfigObj&gt;=4.3.2 (from turbogears) Using cached https://files.pythonhosted.org/packages/64/61/079eb60459c44929e684fa7d9e2fdca403f67d64dd9dbac27296be2e0fab/configobj-5.0.6.tar.gz Collecting FormEncode&gt;=1.2.1 (from turbogears) Using cached https://files.pythonhosted.org/packages/2f/53/707c2b9b65ea6bedde67c21cbf7c71394f4a198620d4e9c1771214b91dcc/FormEncode-1.3.1.tar.gz Collecting Genshi&gt;=0.4.4 (from turbogears) Using cached https://files.pytho…
type: UnansweredQuestion
answer count: 1
tagged with: pip
tagged with: django
tagged with: virtualenv
type: Question
score: 0
has title: Could not satisfy Django application requirements

http://stackoverflow.com/q/50002053
tagged with: http://stackoverflow.com/tag/csv
tagged with: elasticsearch
answer count: 1
has body: When i try to send the bulk_data to the local elasticsearch, my data isn't loaded because of the SerializationError. I already tried to fill the empty cells in the csv file, but that wasn't the solution. from elasticsearch import Elasticsearch bulk_data = [] header = [] count = 0 for row in csv_file_object: if count > 0 : data_dict = {} for i in range(len(row)): row = row.rstrip() data_dict[header[i]] = row[i] op_dict = { "index": { "_index": INDEX_NAME, "_type": TYPE_NAME, } } bulk_data.append(op_dict) bulk_data.append(data_dict) else: header = row count = count+1 # create ES client, create index es = Elasticsearch(hosts = [ES_HOST]) if es.indices.exists(INDEX_NAME): print("deleting '%s' index..." % (INDEX_NAME)) res = es.indices.delete(index = INDEX_NAME) res = es.bulk(index = INDEX_NAME, body = bulk_data, refresh = True) See image for the SerializationError and bulk_data values: Please note: the \n is added by the serialization process itself.
accepted answer: http://stackoverflow.com/a/50003132
has comment: http://stackoverflow.com/comment/87021324
type: Question
has answer: http://stackoverflow.com/a/50003132
has comment: http://stackoverflow.com/comment/87020237
has comment: http://stackoverflow.com/comment/87020571
has title: CSV to elasticsearch with python SerializationError
tagged with: python
has comment: http://stackoverflow.com/comment/87020359
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87020934
score: 0

http://stackoverflow.com/q/49947942
tagged with: python
linked to: http://stackoverflow.com/q/701466
favorite count: 0
accepted answer: http://stackoverflow.com/a/49947995
has comment: http://stackoverflow.com/comment/86912488
upvote count: 14
duplicate of: http://stackoverflow.com/q/701466
has answer: http://stackoverflow.com/a/49947995
possible better answer: http://stackoverflow.com/a/49948103
score: 13
has answer: http://stackoverflow.com/a/49948306
downvote count: 1
has answer: http://stackoverflow.com/a/49948103
has title: Elegant alternative to long exception chains?
type: Question
has comment: http://stackoverflow.com/comment/86912761
type: AnsweredQuestion
has body: A lot of times I find myself writing something that looks like this: try: procedure_a() except WrongProcedureError: try: procedure_b() except WrongProcedureError: try: procedure_c() except WrongProcedureError: give_up() This is hideous. Is there a more elegant way to implement this kind of "try things until one doesn't exception" logic? It seems like this is the kind of thing that would come up a lot; I'm hoping there's some language feature I don't know about that's designed for this exact thing.
answer count: 3

http://stackoverflow.com/a/50003663
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50002804
type: AcceptedAnswer
downvote count: 0
has body: Stopping After The fork(), Before The exec() This one's easy, though not so useful: import subprocess, os, signal proc = subprocess.Popen( ['binary', 'arg1', 'arg2'], preexec_fn=lambda: os.kill(os.getpid(), signal.SIGSTOP), ) Why "not so useful"? Because while preexec_fn runs in the new PID, your intent appears to involve gathering statistics on memory usage (to the extent that that can be done before a program does its malloc() calls), and until the exec has taken place, the program whose memory you'll be measuring is the Python interpreter. Stopping After The exec(), Before Invocation Of main() First, compile an audit module for the Linux loader (ld.so), akin to the following: #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; #include &lt;signal.h&gt; unsigned int la_version(unsigned int version) { return version; } /* To have stronger guarantees of immediacy, I might replace this with flock()ing a * lockfile, and releasing that lock from the parent when ready to continue. YMMV, * consider this a stub intended to be replaced. */ void la_preinit(uintptr_t *cookie) { kill(getpid(), SIGSTOP); unsetenv("LD_AUDIT"); /* avoid our children getting stopped the same way */ } Then, specify it when running your subprocess: newEnv = dict(os.environ) newEnv['LD_AUDIT'] = '/path/to/above/library.so' proc = subprocess.Popen(['binary', 'arg1', 'arg2'], env=newEnv) la_preinit is invoked by the loader just before main() is started.
accepted answer of: http://stackoverflow.com/q/50002804

http://stackoverflow.com/q/50067957
has comment: http://stackoverflow.com/comment/87152499
has comment: http://stackoverflow.com/comment/87152839
type: Question
has title: Saving a Pandas dataframe in fixed format with different column widths
type: AnsweredQuestion
has body: I have a pandas dataframe (df) that looks like this: A B C 0 1 10 1234 1 2 20 0 I want to save this dataframe in a fixed format. The fixed format I have in mind has different column width and is as follows: "one space for column A's value then a comma then four spaces for column B's values and a comma and then five spaces for column C's values" Or symbolically: -,----,----- My dataframe above (df) would look like the following in my desired fixed format: 1, 10, 1234 2, 20, 0 How can I write a command in Python that saves my dataframe into this format?
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87152486
has comment: http://stackoverflow.com/comment/87152898
accepted answer: http://stackoverflow.com/a/50068278
score: 0
tagged with: fixed-width
has answer: http://stackoverflow.com/a/50068278
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/87152819

http://stackoverflow.com/comment/87057666
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50019983
score: 0
has text: Please include the full traceback. Currently, the question leaves us guessing where the error occurs.

http://stackoverflow.com/comment/87082255
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50032997
type: QuestionComment
has text: If you want to just open a socket, send a single file, and close the socket, and you want the server to just save it to some randomly-named file, then you're done when the client closes the socket. But normally you're going to want to build some simple protocol. For example, send the file name, a newline, the file size (as a nice human-readable ASCII string), a newline, and then the file itself. Then the server knows what to call the file, and when it's done reading that file and ready to ask for another one.

http://stackoverflow.com/comment/86978738
comment on: http://stackoverflow.com/a/49980390
score: 0
type: Comment
has text: simply transform the code into a function and use `DataFrame.apply`. See [apply doc](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) for more complete explanation
type: AnswerComment

http://stackoverflow.com/q/49993080
upvote count: 0
type: UnansweredQuestion
tagged with: output
tagged with: python
has answer: http://stackoverflow.com/a/49993166
tagged with: variables
downvote count: 1
has body: Objective: I would like to save the output of the loop into a variable therefore I could then send the Email with the output. First Problem: The JSON output is a repetitive blocks which can be inconsistent, so I'm not sure on the range, so i created a for loop, which would satisfy what I need. i know it's messy. The print statements identify everything I need; however I need to set all my print statements to a variable or variables that would give me more flexibility. Second Problem: How do I end the loop? Json Data Looks like; { "data": [ { "attributes": { "name": "mike", "color": "blue", "size": "small", "make": "mazda", "attributes": { "name": "John", "color": "green", "size": "big", "make": "honda", # Convert JSON Language to Script jsonResponse=json.loads(json_object) LOOP a=0 for i in range(0,100): a = a + 1 print ("Name:",(jsonResponse['data'][a]['attributes']['name'])) print ("Color:",(jsonResponse['data'][a]['attributes']['Color'])) print ("Size:",(jsonResponse['data'][a]['attributes']['Size'])) print ("Make:",(jsonResponse['data'][a]['attributes']['Make'])) print (" ") EMAIL # Email from O365 import Message myemail = x password = y o365_auth = ((myemail),(password)) m = Message(auth=o365_auth) m.setRecipients(myemail) m.setSubject('SUBJECT.') m.setBody('print variable here') m.sendMessage()
has title: Python 2.7 Save Json Loop Output into Variable?
has comment: http://stackoverflow.com/comment/87002541
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87002591
tagged with: printing
has comment: http://stackoverflow.com/comment/87002742
has comment: http://stackoverflow.com/comment/87002648
has comment: http://stackoverflow.com/comment/87002600
has comment: http://stackoverflow.com/comment/87002609
answer count: 1
has comment: http://stackoverflow.com/comment/87002728
score: -1
favorite count: 0
type: Question

http://stackoverflow.com/comment/129457130
type: AnswerComment
comment on: http://stackoverflow.com/a/49939600
score: 0
has text: I am getting this error: ```NameError: name 'output_dict' is not defined``` on line: ```7 for i in range(len(output_dict['detection_boxes'])):``` What should I do?
type: Comment

http://stackoverflow.com/q/50025440
has comment: http://stackoverflow.com/comment/87068575
tagged with: pandas
has title: Show up dataframes in Pandas
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87067540
has answer: http://stackoverflow.com/a/50025545
accepted answer: http://stackoverflow.com/a/50025545
has comment: http://stackoverflow.com/comment/87067738
tagged with: dataframe
tagged with: python
has body: i'm trying to follow the tutorial "Machine Learning" from Microsoft and there's a practical part. I just copied the code and tried to execute it straight from the terminal on Linux. When i run it, nothing is returned. From what I've seen in the video it should return a table with the values. Does anyone have an idea why it doesn't work? Here is the code: def sim_log_data(x1,y1,n1,sd1,x2,y2,n2,sd2): import numpy.random as nr import pandas as pd # normal method draws normal samples from a Gaussian distribuition wx1 = nr.normal(loc = x1, scale=sd1, size=n1) wy1 = nr.normal(loc = y1, scale=sd1, size=n1) # z1 and z2 are our labels, they have two possibilities, 0 or 1 z1 = [1]*n1 wx2 = nr.normal(loc = x2, scale=sd2, size=n2) wy2 = nr.normal(loc = y2, scale=sd2, size=n2) z2 = [0]*n2 # storing everything in DataFrames df1 = pd.DataFrame({'x':wx1,'y':wy1, 'z':z1}) df2 = pd.DataFrame({'x':wx2,'y':wy2, 'z':z2}) # concaternating the columns to be displayed return pd.concat([df1,df2], axis=0, ignore_index = True) sim_data = sim_log_data(1,1,50,1,-1,-1,50,1) sim_data.head() Thanks!
type: AnsweredQuestion
score: 0

virtualenv
tags question: http://stackoverflow.com/q/49951134
tags question: http://stackoverflow.com/q/50050712
tag name: virtualenv
tags question: http://stackoverflow.com/q/49925555
tags question: http://stackoverflow.com/q/50039916
tags question: http://stackoverflow.com/q/50058089
tags question: http://stackoverflow.com/q/49983958
tags question: http://stackoverflow.com/q/49918859
tags question: http://stackoverflow.com/q/49949297
tags question: http://stackoverflow.com/q/50020768
tags question: http://stackoverflow.com/q/49950597
type: Tag
tags question: http://stackoverflow.com/q/50049619
tags question: http://stackoverflow.com/q/50061786

http://stackoverflow.com/a/50060697
has body: It should be mentionned that each call to factorplot creates its own figure. So in general if the aim is to have a single figure, you cannot call factorplot more than once. This explains why 1. and 2. simply can't work. For 3., that would have been my first try as well (except that zorder should probably rather be a number, not a string). However it seems that zorder is ignored or at least not correctly passed on to the underlying matplotlib functions. An options is to set zorder manually. The following loops through all artists of the background plots and sets their zorder to 1. It also stores those artists in a list. After creating the foreground plot one can then loop through all artists again and set zorder to a higher values for those artists not in the previously stored list. I'm leaving out foreground here completely because that seems to just calculate the mean, which would be done by pointplot automatically. import seaborn as sns import matplotlib.pyplot as plt sns.set_style('whitegrid') exercise = sns.load_dataset("exercise") background = exercise.assign(idkind = lambda df: df['id'] \ .astype(str)+df.kind.astype(str)) g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', legend=False,color='lightgrey',data=background) backgroundartists = [] for ax in g.axes.flat: for l in ax.lines + ax.collections: l.set_zorder(1) backgroundartists.append(l) g.map(sns.pointplot, "time", "pulse") for ax in g.axes.flat: for l in ax.lines + ax.collections: if l not in backgroundartists: l.set_zorder(5) plt.show()
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87163383
has comment: http://stackoverflow.com/comment/121970159
accepted answer of: http://stackoverflow.com/q/50056073
answers question: http://stackoverflow.com/q/50056073
has comment: http://stackoverflow.com/comment/87166299
type: Answer

http://stackoverflow.com/a/49942407
has comment: http://stackoverflow.com/comment/86900906
has comment: http://stackoverflow.com/comment/86900985
downvote count: 1
has comment: http://stackoverflow.com/comment/86901019
has comment: http://stackoverflow.com/comment/86901425
has comment: http://stackoverflow.com/comment/86902103
has body: set_index will do this for you. df = df.set_index('group').set_index( df.groupby('group').cumcount(), append=True ) df A B C group 1 0 1 2 3 1 2 3 6 2 4 9 9 2 0 8 1 2 1 5 6 4 3 0 6 5 7 Alternatively, create a MultiIndex object and assign to df.index. This is a lot more efficient in terms of memory. i = df['group'] j = df.groupby(df.pop('group')).cumcount() df.index = pd.MultiIndex.from_arrays([i, j]) And now, df.xs(1) A B C 0 1 2 3 1 2 3 6 2 4 9 9 Just Like That™. If you don't fancy the xs at the end, there's certainly the option of splitting your DataFrame into groups and dumping each one into a dictionary. The groupby API has been written to mimic the itertools.groupby dict-like idiom, here's what that looks like: df_dict = {k : g for k, g in df.drop('group', 1).groupby(df.group)} df_dict[1] A B C 0 1 2 3 1 2 3 6 2 4 9 9 Note that this is no longer a single DataFrame, but a dictionary of them.
has comment: http://stackoverflow.com/comment/86901282
type: Answer
has comment: http://stackoverflow.com/comment/86901117
has comment: http://stackoverflow.com/comment/86901419
has comment: http://stackoverflow.com/comment/86901169
score: 2
has comment: http://stackoverflow.com/comment/86901505
upvote count: 3
answers question: http://stackoverflow.com/q/49942361

http://stackoverflow.com/comment/86897020
comment on: http://stackoverflow.com/q/49940292
has text: If I download the file in my browser, and then try and open it, I get `zipfile.BadZipFile: Bad magic number for central directory`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51413206
answers question: http://stackoverflow.com/q/50012032
score: 0
has body: Given &gt;&gt;&gt; import pathlib &gt;&gt;&gt; import itertools as it &gt;&gt;&gt; base = ["/a", "/b"] &gt;&gt;&gt; subdirs = [["1", "2"], ["c", "d"]] A helper itertools recipe: &gt;&gt;&gt; def powerset(iterable): ... "powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" ... s = list(iterable) ... return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1)) Code &gt;&gt;&gt; def subsequence(iterable, pred=None): ... """Return a non-contiguous subsequence.""" ... if pred is None: pred = lambda x: x ... return (x for x in powerset(iterable) if x and pred(x)) &gt;&gt;&gt; prods = list(it.product(base, subdirs[0], subdirs[1])) &gt;&gt;&gt; pred = lambda x: x[0].startswith("/") &gt;&gt;&gt; result = sorted(set(it.chain.from_iterable(subsequence(p, pred) for p in prods))) &gt;&gt;&gt; result [('/a',), ('/a', '1'), ('/a', '1', 'c'), ('/a', '1', 'd'), ('/a', '2'), ('/a', '2', 'c'), ('/a', '2', 'd'), ('/a', 'c'), ('/a', 'd'), ('/b',), ('/b', '1'), ('/b', '1', 'c'), ('/b', '1', 'd'), ('/b', '2'), ('/b', '2', 'c'), ('/b', '2', 'd'), ('/b', 'c'), ('/b', 'd')] Applications Join paths as strings or pathlib objects. &gt;&gt;&gt; ["/".join(x) for x in result]; ['/a', '/a/1', '/a/1/c', ...] &gt;&gt;&gt; [pathlib.Path(*x) for x in result]; [WindowsPath('/a'), WindowsPath('/a/1'), WindowsPath('/a/1/c'), ...] Details Steps prods are all itertools.products, which accept iterables and create unique combinations (or Cartesian products) in a manner analogous to a date picker dialog application. See examples below. subsequence is simply a wrapper of the powerset itertools recipe. It allows a predicate, which is used to filter resuts that start with slashes like those from base. result sorts a flattened set of subsequences generated for each product. You can optionally join each element as desired. See Code - Applications. Examples Here are the Cartesian products: &gt;&gt;&gt; prods [('/a', '1', 'c'), ('/a', '1', 'd'), ('/a', '2', 'c'), ('/a', '2', 'd'), ('…
type: Answer

http://stackoverflow.com/comment/87054359
score: 0
has text: By the way, does this works if we have for example 34--10?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50018109

http://stackoverflow.com/a/50030027
upvote count: 6
has body: Try df.groupby(['EMP_NAME'])['integer_transaction'].agg(["count", "sum"]) count sum EMP_NAME a 2 1 b 1 0 If you really want, you can rename the columns using an additional .rename("count": "Frequency_count", "sum": "Frequency_sum"). Just for reference, the following also works perfectly fine: x=df.groupby(['EMP_NAME'])['integer_transaction'].agg({'Frequency_count': "count", 'Frequency_Sum': np.sum}) x __main__:1: FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version Out[26]: Frequency_count Frequency_Sum EMP_NAME a 2 1 b 1 0 Note how count is quoted. x=df.groupby(['EMP_NAME'])['integer_transaction'].agg({'Frequency_count': np.size, 'Frequency_Sum': np.sum}) x __main__:1: FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version Out[27]: Frequency_count Frequency_Sum EMP_NAME a 2 1 b 1 0 The warnings you get just tell you that this functionality will be removed in the future, so they should probably not be used. However, they do produce the correct answer. To move the index to the column, try df.groupby(['EMP_NAME'])['integer_transaction'].agg(["count", "sum"]).reset_index() EMP_NAME count sum 0 a 2 1 1 b 1 0
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87076433
answers question: http://stackoverflow.com/q/50029927
has comment: http://stackoverflow.com/comment/87076376
accepted answer of: http://stackoverflow.com/q/50029927
type: AcceptedAnswer
score: 6

http://stackoverflow.com/comment/86863597
has text: Do you know which python installation PyCharm is using? (It should be in `File > Settings > Project Interpreter `)
type: AnswerComment
comment on: http://stackoverflow.com/a/49923723
score: 1
type: Comment

http://stackoverflow.com/q/49942914
has answer: http://stackoverflow.com/a/55903076
has answer: http://stackoverflow.com/a/49943650
type: Question
has answer: http://stackoverflow.com/a/54368405
tagged with: postgresql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86902076
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86902477
tagged with: postgis
score: 0
has title: from django.db.models.sql.aggregates ImportError: No module named aggregates
answer count: 3
has body: I've been facing a particular problem with aggregates. In this code, sumcase class has a method add_to_query which is intended to instantiate the SQL implementation of the aggregate and sets it as a class variable (aggregate) which i'd be using to call the as_sql method in Default SQL Aggregate (django/db.models.sql.aggregates.Aggregate) from another file. My code (The first file, how I implement aggregate): from django.db.models.aggregates import Aggregate from django.db.models.sql.aggregates import Aggregate as SQLAggregate class SQLsumcase(SQLAggregate): is_ordinal = True sql_function = 'SUM' sql_template = "%(function)s(CASE WHEN %(when)s THEN %(field)s ELSE 0 END)" def __init__(self, col, **extra): if isinstance(extra['when'], basestring): extra['when'] = "%s" % extra['when'] if extra['when'] is None: extra['when'] = True super(SQLSumCase, self).__init__(col, **extra) class SumCase(Aggregate):

http://stackoverflow.com/comment/87221655
score: 0
has text: I added the code used to create the initial df to my question as well.
comment on: http://stackoverflow.com/a/50051329
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49922249
has title: Django 2.0 CSS missing for chrome browser
tagged with: css
has comment: http://stackoverflow.com/comment/86860462
score: 0
has comment: http://stackoverflow.com/comment/86861794
has answer: http://stackoverflow.com/a/50077822
has comment: http://stackoverflow.com/comment/86860805
answer count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/86860279
has body: I'm learning Django2.0 these days and tried the tutorial here. However, when it comes to the admin page part, the css style seems missing in Chrome browser: However, when I visited 127.0.0.1:8000/admin in IE, Firefox or even Safari, everything went fine: I'm using the latest version of Chrome. Why? What can I do to fix this?
type: Question
has comment: http://stackoverflow.com/comment/86865481
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86861698
has comment: http://stackoverflow.com/comment/86865717
has comment: http://stackoverflow.com/comment/86860635
tagged with: django
has comment: http://stackoverflow.com/comment/86860545
has comment: http://stackoverflow.com/comment/86860824
tagged with: python

http://stackoverflow.com/q/50005229
has comment: http://stackoverflow.com/comment/87027196
has comment: http://stackoverflow.com/comment/87027110
has comment: http://stackoverflow.com/comment/87156559
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87027059
tagged with: python-3.x
has title: Python list comparison generates Infinite Loop
has comment: http://stackoverflow.com/comment/87026978
has comment: http://stackoverflow.com/comment/87029007
has comment: http://stackoverflow.com/comment/87030018
tagged with: infinite-loop
type: UnansweredQuestion
score: -4
tagged with: python
has body: So the assignment is: take 2 lists and write a program that returns a list that contains only the elements that are common to the lists without duplicates, and it must work on lists of different sizes. My code is: a = [1, 2, 4] b = [3, 1, 5, 2] for j &lt; len(a): for i &lt; len(b): if a(elem) == b(i): print (a(elem)) i=i+1 j=j+1 An infinite loop is then generated, where it prints 1 and then never exits. Can someone tell me why the infinite loop occurs? I understand this is not the most "python" way of doing things, however my coding background includes a very small, brute force technique of C, and I do not know much Python. If there are simple alternatives to this, please let me know, as well as why it never exits.
has comment: http://stackoverflow.com/comment/87027231
has answer: http://stackoverflow.com/a/50005462
tagged with: list
answer count: 2
downvote count: 4
tagged with: linked-list
upvote count: 0
has answer: http://stackoverflow.com/a/50005548
has comment: http://stackoverflow.com/comment/87027377
has comment: http://stackoverflow.com/comment/87026955
has comment: http://stackoverflow.com/comment/87027153

http://stackoverflow.com/comment/87109543
type: QuestionComment
has text: Did you also try `tostring(body, method="html")`? I'm sorry I probably can't help you much more, everything ran pretty much out of the box when I had used it :/
score: 0
comment on: http://stackoverflow.com/q/50045775
type: Comment

http://stackoverflow.com/q/50066638
has body: I am trying to optimize my view-template rendering. At this moment I have such picture: As you see: SQL timing lasts ~0.5sec, TemplateTiming ~2sec, but Total Time is almost 9 seconds! Also I have a timer in my view - it shows ~0.6 seconds of view work. When the view prints "Finished" - after that goes a lot of time when I see this page render finished in my browser. Can somebody explain me from where the hell additional 9-0.5-2-0.6 = 5.9 seconds come from? I have quite a long list to render, with pagination, ~12k items. If there is smaller item amount - the render time is also smaller. Sometimes I also render this page with list of ~20k items, but with another combination of queries/filters - and the total time is much smaller ~4~5 seconds. What is going wrong and when? UPDATE Looks like I have found out the cause of the problem, but I still can't get what is wrong. I have this piece of code in my view: #1st definition of products_list products_list = Product.objects.select_related('shop', 'brand', 'sale', 'promo', 'category') \ .only('product_id', 'title', 'slug', 'product_url', 'price', 'prev_price', 'brand', 'sale__percent', 'sale__old_price', 'promo__promo_description', 'promo__promo_url', 'shop__shop_name', 'shop__country', 'category__category_name')\ .filter(in_stock = True) if sale != None: cached_shop = cache.get(shop) if cached_shop != None: #2nd definition, replaces products_list products_list = Product.objects.select_related('shop', 'brand', 'sale', 'promo', 'category').filter(product_id__in=cached_shop[sale]) #PRODUCS_LIST else: #this piece of code uses 1st definition of products_list if sale == "19%": products_list = products_list.filter(sale__percent__gt=0, sale__percent__lt=20) elif sale == "20%-49%": products_list = products_list.filter(sale__percent__gte=20, sale__percent__lt=50) elif sale == "50%-69%": products_list = products_list.filter(sale__percent__gte=50, sale__percent__lt=70) elif sale == "70%-89%": products_list = products_list.filter(sale_…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87152322
tagged with: optimization
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87149932
has comment: http://stackoverflow.com/comment/87152412
has comment: http://stackoverflow.com/comment/87149904
has comment: http://stackoverflow.com/comment/87149933
tagged with: django
has title: How to reduce long template rendering time?
has comment: http://stackoverflow.com/comment/87149975
type: Question

http://stackoverflow.com/comment/87081371
type: Comment
type: QuestionComment
has text: I'm scaling down without stretching the image
comment on: http://stackoverflow.com/q/50032600
score: 0

http://stackoverflow.com/a/50003741
has comment: http://stackoverflow.com/comment/87024080
score: 2
has body: In your code, exchange_rates is a dictionnary which itself contains dictionnaries. You should do double dereferencing in order to plot the values. def make_a_graph(exchange_rates): x=len(exchange_rates["CZK"]) y1=exchange_rates["CZK"] plt.bar(range(x),y1.values()) plt.show() Note you have to be consistent with the length of the quantities you want to plot. I have plotted only one key above.
has comment: http://stackoverflow.com/comment/87024000
upvote count: 2
has comment: http://stackoverflow.com/comment/87023993
has comment: http://stackoverflow.com/comment/87024011
has comment: http://stackoverflow.com/comment/87023972
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50003599
type: Answer
answers question: http://stackoverflow.com/q/50003599

http://stackoverflow.com/q/50059844
score: -2
has answer: http://stackoverflow.com/a/50060514
tagged with: python
has body: I am trying to create a randomly generated maze which fits very specific criteria: I would like it in a 2D list, where walls are False and passages are True there should only be one rout from point x to point y. Here's what I have so far: def generate(height,width): maze_lst=[] theight = height*2+1 twidth = width*2+1 maze_lst = gen_base(theight, twidth) maze_lst = entrance(theight, twidth, maze_lst) #maze_lst = route(theght, twidth, maze_lst) return maze_lst def gen_base(height, width): maze_lst = [] for i in range(height): maze_lst.append([]) for j in range(width): if int(i/2) == i/2: maze_lst[i].append(False) elif int(j/2) == j/2: maze_lst[i].append(False) else: maze_lst[i].append(True) return maze_lst def entrance(height, width, maze_lst): oside=0 oblock=0 for i in range(2): side = randint(1,4) if side == 1: block = randint(1,int(width/2)) maze_lst[0][block*2-1] = True if side == 2: block = randint(1,int(height/2)) maze_lst[block*2-1][width-1] = True if side == 3: block = randint(1,int(width/2)) maze_lst[height-1][block*2-1] = True if side == 4: block = randint(1,int(height/2)) maze_lst[block*2-1][0] = True if side==oside and block==oblock: maze_lst=generate(height,width) else: oside=side oblock=block return maze_lst def route(height, width, maze_lst): ? return maze_lst Can anyone help?
has title: Randomly generated maze
type: UnansweredQuestion
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87137623
favorite count: 0
type: Question
tagged with: maze

http://stackoverflow.com/comment/87140969
type: QuestionComment
comment on: http://stackoverflow.com/q/50057243
score: 0
has text: Yes, you can use the update command. Just keep in mind that the SQL equivalent for Python's `None` is `NULL`, so in your WHERE clause, you want something like `WHERE hotness IS NULL`
type: Comment

http://stackoverflow.com/a/50018225
has body: To list all xml files in your directory you can use for example glob (second answer). It can look like this: import glob files = glob.glob('C:\Users\mysky\Documents\Decoded\*.xml') for file in files: tree = ET.parse(file) root = tree.getroot() CODE = [ ] for errors in root.findall('.//Book/Message/Param/Buffer/Data/Field[11]'): error_code = errors.find('RawValue').text if error_code is not None: CODE.append(error_code)
answers question: http://stackoverflow.com/q/50018030
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50018030
upvote count: 1
has comment: http://stackoverflow.com/comment/87055036
has comment: http://stackoverflow.com/comment/87054267
type: Answer

http://stackoverflow.com/comment/86877900
type: Comment
type: AnswerComment
has text: And do you have data for it? Can you train your network to predict those values? If not what are you looking for, why your network should output values like 1.3 if the classes you learnt are 1,2,3,4,5? You have to understand that your network cannot output magically values with a regression layer. Like Y. Luo said, a simple linear regression is `tf.matmul(f, out_weights) + out_biases`. But you need to provide samples to train this layer. If not, you can do a weight sum or your probability and classes. But I dunno what you try to achieve.
score: 0
comment on: http://stackoverflow.com/a/49929964

http://stackoverflow.com/comment/86887165
has text: yeah i do, it is a requirement to use selenium. I've done it using Beautifulsoup but I have to covert the whole process to selenium with headless firefox
comment on: http://stackoverflow.com/q/49935754
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87122259
has text: what is `ax` here. make it [Minimal, Complete and Verfiable Example(**MCVE**)](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/50052879
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86917997
has text: Neither of these functions should be in a class.
score: 4
comment on: http://stackoverflow.com/q/49950649
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87043178
type: QuestionComment
type: Comment
has text: @Abhishek That’s not a feature of Python, it’s a feature of the iPython shell.
score: 0
comment on: http://stackoverflow.com/q/50012624

http://stackoverflow.com/q/50022460
tagged with: pandas
score: 1
has title: Duplicating rows in Dataframe based on pattern in Pandas
accepted answer: http://stackoverflow.com/a/50022739
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87061488
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87061516
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50022739
has comment: http://stackoverflow.com/comment/87060816
has body: I have a dataframe with several rows. When a pattern is found (say ;, only found in the last column), I'd like to duplicate the row, but assign new value based on a column. All data are strings. For instance: A B C x1 b1a kxl Ak x2 b1b txl Ak x3 b1c uxl Ak;Lo #should be duplicated x4 b1d ixl Lo Becomes A B C x1 b1a kxl Ak x2 b1b txl Ak x3 b1c uxl Ak #duplicated x3 b1c uxl Lo #duplicated x4 b1d ixl Lo I'm trying to get groupby('C').split(';') to work, but am not finding an efficient way to do it. How would you do it? Of course, a quick and dirty way to do it is by running the DF row by row, but this is not very efficient I guess...

http://stackoverflow.com/comment/86864112
type: QuestionComment
comment on: http://stackoverflow.com/q/49918978
type: Comment
score: 0
has text: @kartikmaji the methods resolve_* are automatically called by the calls Query , so it's the Query class that passes `info` i don't handle it

http://stackoverflow.com/q/49950145
tagged with: repeat
upvote count: 1
tagged with: python
downvote count: 1
score: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49950924
tagged with: python-itertools
type: UnansweredQuestion
has body: In the following list of items I want to access two consecutive list items at once and also access the index. On top of that for the very first and last item of the list I want to repeat the data. my_list = ['A','C','G','T','T','C','G','A','G'] print(my_list) print() for (n1, v1), (n2,v2) in zip(enumerate(my_list), itertools.islice(enumerate(my_list), 1, None)): print(v1) print(v2) print() # gives me ['A', 'C', 'G', 'T', 'T', 'C', 'G', 'A', 'G'] (0, 'A') (1, 'C') (1, 'C') (2, 'G') (2, 'G') (3, 'T') (3, 'T') (4, 'T') (4, 'T') (5, 'C') (5, 'C') (6, 'G') (6, 'G') (7, 'A') (7, 'A') (8, 'G') How, do I repeat the same index only for very first and very last items?? Expected output: (0, 'A') (0, 'A') (0, 'A') (1, 'C') (1, 'C') (2, 'G') ..... ..... (8, 'G') (8, 'G')
has title: Repeat the very first and last items while doing islice?

http://stackoverflow.com/q/49991434
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86999576
accepted answer: http://stackoverflow.com/a/49991676
has title: Read all the rows of a CSV
type: Question
has answer: http://stackoverflow.com/a/49991676
has comment: http://stackoverflow.com/comment/86999803
has comment: http://stackoverflow.com/comment/86999597
has comment: http://stackoverflow.com/comment/87000004
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86999540
has body: Hey I have this code that concatenate all the csv files of a folder in a only csv file. The problem is that this line of code if i! = 0: prevents the first row of each csv from being read except in the first csv. Any ideas on how to modify it so that it can read all the rows of the csv #!/usr/bin/env python import pandas as pd import glob, os import shutil #import csv files from folder path = r'/Users/sonia/Animalsmanage/output' allFiles = glob.glob(path + "/*.csv") with open('finaloutput.csv', 'wb') as outfile: for i, fname in enumerate(allFiles): with open(fname, 'rb') as infile: if i != 0: infile.readline() outfile.write(bytearray(b'\n')) # add a empty line shutil.copyfileobj(infile, outfile) print(fname + " has been imported.")
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/86858361
score: 0
type: QuestionComment
has text: As of my first comment, have you tried optimizing your database by using indexes? If the database is slow, I don't think parallelizing will improve it. If you still want to go with parallel, call read_mongo with multiple threads.
comment on: http://stackoverflow.com/q/49920166
type: Comment

http://stackoverflow.com/q/50004616
tagged with: python
has body: I want to predict the direction towards which the price will change. The term price is used to refer to the mid-price of a stock, which is defined as the mean between the best bid price and best ask price at time t: This is a virtual value for the price since no order can happen at that exact price, but predicting its upwards or downwards movement provides a good estimate of the price of the future orders. A set of discrete choices must be constructed from our data to use as targets for our classification model. Simply using p(t) > p(t+k) to determine the direction of the mid-price would introduce unmanageably amount of noise, since the smallest change would be registered as an upward or downward movement. The mean of the previous k mid-prices, denoted by m_b, and the mean of the next k mid-prices, denoted by m_a, are defined as: Here is a sample : 0 2015-03-31 09:30:00.233 2.4645 1 2015-03-31 09:30:00.233 2.4634 2 2015-03-31 09:34:44.116 2.5363 3 2015-03-31 09:34:44.116 2.5434 4 2015-03-31 09:36:38.535 2.5356 5 2015-03-31 09:36:38.535 2.5432 6 2015-03-31 09:36:38.537 2.5463 7 2015-03-31 09:36:38.537 2.5432 8 2015-03-31 09:45:10.512 2.5274 9 2015-03-31 09:45:10.512 2.5262 10 2015-03-31 09:45:10.523 2.5299 11 2015-03-31 09:45:10.529 2.5234 12 2015-03-31 09:45:10.531 2.5276 13 2015-03-31 09:45:10.568 2.5212 14 2015-03-31 09:45:10.569 2.5262 15 2015-03-31 09:45:10.635 2.5143 16 2015-03-31 09:45:10.684 2.5267 17 2015-03-31 09:45:10.686 2.5212 18 2015-03-31 10:00:02.111 2.5213 19 2015-03-31 10:00:02.111 2.5298 20 2015-03-31 10:00:02.112 2.5212 21 2015-03-31 10:00:02.381 2.5263 22 2015-03-31 10:00:02.472 2.5212 23 2015-03-31 10:00:02.486 2.5298 24 2015-03-31 10:00:02.524 2.5298 25 2015-03-31 10:00:04.026 2.5270 26 2015-03-31 10:06:54.546 2.5212 27 2015-03-31 10:06:54.558 2.5234 28 2015-03-31 10:06:54.558 2.5253 29 2015-03-31 10:06:54.566 2.5234 Aat any time, I want to compute m_a and m_b, but I don't know how to do it with pandas or numpy. Assuming the horizon k=5, how co…
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50009197
has comment: http://stackoverflow.com/comment/87032087
answer count: 1
has answer: http://stackoverflow.com/a/50009197
type: Question
has comment: http://stackoverflow.com/comment/87033367
has title: Special Moving Average

http://stackoverflow.com/comment/86932396
score: 0
comment on: http://stackoverflow.com/q/49957335
type: Comment
type: QuestionComment
has text: The use of the word cache is confusing her since it is usually used in terms of processor cache memory. I now understand what you want to do, do you have a constant amount of arguments?

http://stackoverflow.com/q/50020279
answer count: 2
possible better answer: http://stackoverflow.com/a/50079626
has answer: http://stackoverflow.com/a/50034190
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: django-views
has comment: http://stackoverflow.com/comment/87083440
has answer: http://stackoverflow.com/a/50079626
accepted answer: http://stackoverflow.com/a/50034190
has comment: http://stackoverflow.com/comment/87059178
tagged with: django-forms
has title: Post create with multiple images using FBV
has body: Hi everyone I am new to Django and I am going bald pulling my hair. Can someone help me with this. I'm trying to add multiple images to my post and I am having issues. I have 2 models. One post model and One image model. My post model already has 1 imagefield. Then I have another related model which allows multiple images. Below is how my models look like class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() post_image = models.ImageField() class Image (models.Model): #(Images) post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True, null=True) image_title = models.CharField(max_length=100) image_description = models.CharField(max_length=250) def __str__(self): return self.post.title + " Image" Below is how my views look like. When the form loads. It has the multiple image fields. Its just not saving those images when my post is created. I get a post that completely ignores the formsets and multiple images. It only shows the Post model aspects and 1 image of the Post model. Even in the Admin there are no multiple images. Can someone point me to what is the error in my code? VIEWS.py 1st try @login_required def post_create(request): ImageFormset = modelformset_factory(Image, fields=('image', 'image_title', 'image_description'), extra=7) if request.method == 'POST': form = PostForm(request.POST, request.FILES) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.user = request.user post.save() ## It seems as if my code just plays till here and then disconnects for f in formset: try: photo = Image(post=post, image=f.cleaned_data['image', 'image_title', 'image_description']) photo.save() return redirect('posts:single', username=request.user.username, slug=po…
type: Question
has comment: http://stackoverflow.com/comment/87058736
tagged with: python-3.x

http://stackoverflow.com/comment/87120802
comment on: http://stackoverflow.com/q/50051916
type: Comment
score: 1
type: QuestionComment
has text: first step is to read the manual: https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours

http://stackoverflow.com/a/52017230
downvote count: 0
score: 1
upvote count: 1
has body: there are two ways to get rid of the overlapping bounding boxes. 1st, set the "min_score_thresh" parameter bigger at "visualize_boxes_and_labels_on_image_array" function in file visualization_utils.py; 2nd, set the non-max-suppression threshold in config file
type: Answer
answers question: http://stackoverflow.com/q/49951422

http://stackoverflow.com/q/49983806
has comment: http://stackoverflow.com/comment/86990095
score: 1
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/24736758
has comment: http://stackoverflow.com/comment/86990206
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86990291
has body: I am following this post Parameters required by bar3d with python to understand the parameters of bar3d. The graph tallies with the data, but the plotting is not exact. I was expecting 0,0 to be exactly on 0,0. Also, dx = 0.1 and dy = 0.1 should have shown a square like impression, but is not. Below is the data - { x: -3.6, y: -0.019, occurence: 676 } - { x: -3.10, y: -0.0999, occurence: 676 } - { x: -1.9, y: -0.0999, occurence: 676 } - { x: -0.07, y: 0., occurence: 676 } - { x: 0., y: 0., occurence: 25564 } - { x: 5.941, y: 0.0199, occurence: 24644 } - { x: 5.942, y: 0.0199, occurence: 49288 } - { x: 5.96, y: 0.0199, occurence: 24723 } ) The corresponding code is dx = np.empty(np.size(x)) dx.fill(0.1) dy = np.empty(np.size(x) dy.fill(0.1) z = np.zeros(np.size(x_gt)) ax1.bar3d(x, y, z, dx, dy, occurence, "red" ) # z is dummy. occurence is height
has title: matplotlib bar3d doesnt plot points properly
answer count: 0
tagged with: matplotlib
downvote count: 0

http://stackoverflow.com/comment/86881427
type: Comment
comment on: http://stackoverflow.com/a/49932831
type: AnswerComment
score: 0
has text: I forgot to mention that it has to be done through separate functions (as per request of the problem). Otherwise I would have done this. Will add this to the OP.

http://stackoverflow.com/q/50071281
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
has body: I have two pandas dataframes, both indexed by overlapping dates, call them df1 and df2. df1 = pd.DataFrame(np.random.randn(5,4), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c', 'd'] ) df2 = pd.DataFrame({0 : [a,b,c,d], 1 : [b,c,b,a], 2 : [c,d,a,b], 3 : [d,a,d,c]}index=pd.date_range('01/03/2014',periods=4,freq='D')) df1 a b c d 2014-01-02 1.248568 -1.844952 -0.275825 -0.496379 2014-01-03 2.450789 0.864446 -0.163374 -0.437771 2014-01-04 0.223496 0.877333 1.580202 0.749173 2014-01-05 0.285521 -1.289847 0.273195 -0.747948 2014-01-06 -0.113029 -1.785885 0.078580 -1.156271 df2 0 1 2 3 2014-01-03 a b c d 2014-01-04 b c d a 2014-01-05 c b a d 2014-01-06 d a b c The columns of df1 and the values of df2 are all different names of commodities. I want to create a new dataframe, df3, such that df3 has the same index as df2, and the values of df3 are equal to the value in df1 for the column of the value of df2. df3 0 1 2 3 2014-01-03 2.450789 0.864446 -0.163374 -0.437771 2014-01-04 0.877333 1.580202 0.749173 0.223496 2014-01-05 0.285521 -1.289847 0.285521 -0.747948 2014-01-06 -1.156271 -0.113029 -1.785885 0.078580 I tried the following but cannot get it to work. df2.apply(lambda x: df1.loc[x.index,str(x)]) Any advice?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50071315
has title: Indexing with values in a dataframe
tagged with: dataframe
has answer: http://stackoverflow.com/a/50071315
score: 1
type: Question
answer count: 1

http://stackoverflow.com/q/50032746
tagged with: lua
tagged with: visual-studio
type: Question
tagged with: c++
has title: how to use setuptools to install lupa with python
score: 0
has body: when i install lupa happen errors. ENV: python2.7 32bits vcforpython visual studio 2017 errors: C:\Users\wangxin\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -ID:\lupa-1.6\LuaJIT-2.0.5\src -IC:\Python27\include -IC:\Python27\PC /Tclupa/_lupa.c /Fobuild\temp.win32-2.7\Release\lupa/_lupa.obj _lupa.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\include\vcruntime.h(96) : warning C4005: '_CRT_STRINGIZE' : macro redefinition C:\Users\wangxin\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\crtdefs.h(180) : see previous definition of '_CRT_STRINGIZE' C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\include\vcruntime.h(99) : warning C4005: '_CRT_WIDE' : macro redefinition C:\Users\wangxin\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\crtdefs.h(185) : see previous definition of '_CRT_WIDE' C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\include\vcruntime.h(142) : warning C4005: '__CRTDECL' : macro redefinition C:\Users\wangxin\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\crtdefs.h(650) : see previous definition of '__CRTDECL' C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\include\vcruntime.h(196) : error C2061: syntax error : identifier '__vcrt_bool' C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\include\vcruntime.h(196) : error C2059: syntax error : ';' C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\include\stdint.h(111) : warning C4005: 'WCHAR_MIN' : macro redefinition C:\Users\wangxin\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\wchar.h(43) : see previous definition of 'WCHAR_MIN' error: command 'C:\\Users\\wangxin\\AppData\\Local\\Programs…
answer count: 0
tagged with: lupa
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87082634
tagged with: python
has comment: http://stackoverflow.com/comment/87081704
has comment: http://stackoverflow.com/comment/87081717

http://stackoverflow.com/comment/87019195
score: 2
has text: I couldn't agree more with hpaulj: a precision of 30 digits seems to be much higher than anything FEM or any other method could provide. And, as Eolmar suggested, creating a mcve could be in itself a great tool to analyse what's wrong with your code and find a solution, as well as some unit tests. Good luck with your work!
comment on: http://stackoverflow.com/q/49997595
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87044124
comment on: http://stackoverflow.com/q/50013854
score: 0
type: Comment
type: QuestionComment
has text: Python with Sublime on mac

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/49941646

http://stackoverflow.com/comment/86909637
comment on: http://stackoverflow.com/a/49946568
type: Comment
has text: Wouldn't `nsmallest` just give you `-9999999` twice? And `df[df.values > -9999999].min()` does not do what you want either, if anything `df.values[df.values > -9999999].min()`...
type: AnswerComment
score: 1

http://stackoverflow.com/q/50071013
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/50071342
downvote count: 0
has title: file upload works with curl and postman but not python requests
upvote count: 1
tagged with: python-requests
has body: I am attempting to upload a CSV file to an API (which gives me very little error info) using python requests library. (I'm running Python 3.5 and using requests version 2.18.4 on OS X 10.11.6) This curl command in terminal works fine: curl -F 'file=@/path/to/file.csv' myurl.com/upload -H "Authorization: TOKEN sometoken" A multipart/form-data POST request from Postman also works, but I can't seem to make it work with the python requests library. I've tried many variations of this request: import requests headers = {'Authorization': 'TOKEN sometoken', 'Content-Type': 'multipart/form-data'} with open(file_path, 'rb') as f: r = requests.post(myurl, headers=headers, data=f) ## I've also tried data={"file": f} I get a status code of 200, but the response is {"success": "false"} (frustratingly unhelpful). What am I missing in the python request compared to the curl request? EDIT: it seems that the -F flag for the curl command emulates an HTML form that has been submitted...is there a way to do this with requests?
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50071342
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/43246857
tagged with: file-upload
has answer: http://stackoverflow.com/a/50071087
tagged with: curl
possible better answer: http://stackoverflow.com/a/50071087
type: Question

http://stackoverflow.com/q/50006093
tagged with: kivy
score: 0
answer count: 1
type: Question
has body: How can i know number of page in pagelayout(kivy,python)For instance ,when user choose 3th page number of 'page' var will be 3.Please help
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50006483
has title: How can i know number of page in pagelayout(kivy,python)
tagged with: python

http://stackoverflow.com/q/49991284
accepted answer: http://stackoverflow.com/a/49991484
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49991484
score: 0
answer count: 1
has title: Trying to read Outlook Email Attachment which has a Hyperlink
has body: I am trying to automate a process using Python and Outlook. I am able to login successfully and able to read the last message received in the "My Folder Name" Folder but for some reason I am not able to read the attachment contents like I want to copy the hyperlink present in the email attachment but doesn't gives the contents of the email. import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") folder = outlook.Folders("My Shared Mailbox Name") inbox = folder.Folders("My Folder Name") email = inbox.Items lastemail = email.GetLast() body_content = lastemail.body print (body_content) attachment_content = lastemail.Attachments print (attachment_content) It gives below message for the last two lines of code: &lt;COMObject &lt;unknown&gt;&gt; The code works until 'print (body_content)' as I can see the body of the last email but it's attachment contents are not readable. attachment_content = lastemail.Attachments print (attachment_content) doesn't works. Right now I have to manually go to the email attachment and copy the hyperlink. Please let me know where to look, thank you.
type: AnsweredQuestion
tagged with: outlook

http://stackoverflow.com/comment/87012144
has text: It seems that it leaves only 100 words (990 characters including ','). So all the strings above are being cut.
score: 1
comment on: http://stackoverflow.com/q/49997503
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50027783
possible better answer: http://stackoverflow.com/a/50027838
has comment: http://stackoverflow.com/comment/87071861
has comment: http://stackoverflow.com/comment/87071952
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87071746
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87071775
has answer: http://stackoverflow.com/a/50027838
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87071896
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/87071823
accepted answer: http://stackoverflow.com/a/50027989
has body: I want to transform all elements in a numpy array the following way: x = np.array([1,2,3,6]) ... some transformation y = np.array([1, 0.5, 0.66, 0.5]) Where the rule is: y[i]=x[i]/x[i+1] But I can't use a for loop or while. I don't see how I could use map or vectorize in this case. Any idea? EDIT: The final goal is to get from a time serie the numpy array containing the returns instead of the values themselves Have edited the values of y since they were incorrect
has comment: http://stackoverflow.com/comment/87071837
has title: Numpy array transform using self elements without for loop
has comment: http://stackoverflow.com/comment/87071885
has answer: http://stackoverflow.com/a/50027989
tagged with: arrays
upvote count: 1
has comment: http://stackoverflow.com/comment/87071853

http://stackoverflow.com/comment/86888042
score: 0
has text: @TharukaDevendra Though that sounds right to me, no one can be sure before seeing the complete code. Maybe you can open a new question with your new [MCVE](https://stackoverflow.com/help/mcve) so that people can help with a better idea?
type: Comment
comment on: http://stackoverflow.com/a/49931591
type: AnswerComment

teradata
type: Tag
tags question: http://stackoverflow.com/q/50010661
tag name: teradata
tags question: http://stackoverflow.com/q/50024626

http://stackoverflow.com/comment/86879899
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49931918
has text: Your `else:` is only attached to the last `if`, so it will print `Invalid Entry` when the enter one of the first 4 actions.

http://stackoverflow.com/q/50026454
score: 0
has title: Pass byte numpy array to C function using ctypes
answer count: 2
has body: I want to pass byte numpy array to a C function using ctypes. The C function takes void *mem_address so I thought to pass it as the following: lst = np.random.choice(np.array(range(0, 100), dtype=np.int), size=(100, 5)) lst = np.asarray(lst).tobytes() # Pass lst.ctypes.data_as(ctypes.c_void_p) This gives the error AttributeError: 'bytes' object has no attribute 'ctypes' which means ctypes does not handle numpy. Is there a workaround?
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50026595
tagged with: ctypes
has answer: http://stackoverflow.com/a/50026557
has answer: http://stackoverflow.com/a/50026595
tagged with: python
possible better answer: http://stackoverflow.com/a/50026557
type: AnsweredQuestion

http://stackoverflow.com/a/50033443
type: Answer
has body: x[:,0]= np.array([1000,0,0,50]).T
accepted answer of: http://stackoverflow.com/q/50033364
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50033364

http://stackoverflow.com/comment/87047381
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50015229
has text: Do you have multiple email addresses in `emails` ?
type: Comment

http://stackoverflow.com/q/50035426
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50035453
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50035706
has body: i have a dataframe df1: key1 key2 val 1 100 2 500 4 400 Also i have a multi-indexed dataframe df2: c a b 1 100 a 2 200 b 3 300 j 4 400 e 5 500 t i want to fill the column val of my df1 from the multi-indexed dataframe df2 I tried: for index,row in df1.iterrows(): try: data = df2.loc([row['key1'],row['key2']) df1.loc[(df1.key1 == row['key1']) &amp; (df1.key2 == row['key2']), 'val'] = data except: pass finally, my df1 should look like: key1 key2 val 1 100 a 2 500 4 400 e But my main concerns is that the actual length of df2(multi-indexed df) will be around 60-70 thousand rows. The length of df1 will be hardly 10 rows. (and i want to repeat this process taking df1 containing other data) SO does this .loc using for loop work? Is it the fastest? Or using .apply will be faster? I want this iteration to be the fastest. Any leads on running this in the fastest way possible?
score: 1
has title: Fastest Way to fill values of a dataframe using .loc from another multi-indexed dataframe
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50035706
answer count: 2
accepted answer: http://stackoverflow.com/a/50035453
downvote count: 0

http://stackoverflow.com/q/50029546
has comment: http://stackoverflow.com/comment/87093496
score: 1
has comment: http://stackoverflow.com/comment/87075473
tagged with: python
has title: OpenCV3 does not properly release camera
linked to: http://stackoverflow.com/q/37273453
downvote count: 0
answer count: 0
linked to: http://stackoverflow.com/q/49579366
upvote count: 1
type: UnansweredQuestion
has body: System Architecture: Fedora 27 OpenCV 3.4 Python 3.6 The issue produced from the following code: def capture_input(): cap = cv2.VideoCapture(0) while 1: # Take each frame ret = cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 45) ret = cap.set(cv2.CAP_PROP_FRAME_WIDTH, 45) ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) cv2.imshow("Detecting Digits Frame", frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): frame = cv2.resize(frame, (45, 45)) break cap.release() cv2.destroyAllWindows() return frame The code works as expected sometimes, the other times it refuses to run producing: select timeout cv2.error:/io/opencv/modules/core/include/opencv2/core/mat.inl.hpp:500: error: (-215) total() == 0 || data != __null in function Mat Not only that. Moreover, the webcam does not even work after that, I tried opening it with Cheese, it show a black screen and buttons are grayed out. I tried to follow these SO links: Issue 1 Issue 2 but with no success, and same for the other GitHub links. Thanks in advance.
favorite count: 0
type: Question
tagged with: opencv

http://stackoverflow.com/comment/86898091
score: 0
has text: @DanielRoseman well i mean, that is the line, that is definitely the problem, cause as soon as i delete ß the whole code functions perfectly :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49940890

http://stackoverflow.com/q/50071040
answer count: 2
tagged with: try-except
has answer: http://stackoverflow.com/a/66398305
downvote count: 0
accepted answer: http://stackoverflow.com/a/50071143
score: 11
linked to: http://stackoverflow.com/q/13531247
favorite count: 0
has answer: http://stackoverflow.com/a/50071143
has title: Catching specific error messages in try / except
type: AnsweredQuestion
tagged with: datetime
possible better answer: http://stackoverflow.com/a/66398305
tagged with: if-statement
tagged with: python
has comment: http://stackoverflow.com/comment/117607498
has body: I am new to python and I am about to make this new program that will ask you for your birthday. I've made some try/except clauses to avoid people entering info in strings or to high numbers. I would like my program to find out if the info entered equals a date in the end. If it does I would like to have it printed and if not I would like it to find out what part of the user input was wrong. I have therefore made some if clauses in the last except clause with the idea that the errors would equal a message. I would like to know if it is possible to make the program match the messages with the error to find out the specific error and figure out what part of the input was wrong. My code looks like this: try: print(datetime.date(int(birthYear), int(birthMonth), int(birthDay))) except TypeError: if ValueError == "ValueError: month must be in 1..12": print("Month " + str(birthMonth) + " is out of range. The month must be a number in 1...12") if ValueError == "ValueError: year " + str(birthYear) + " is out of range": print("Year " + str(birthMonth) + " is out of range. The year must be a number in " + str(datetime.MINYEAR) + "..." + str(datetime.MAXYEAR)) if ValueError == "ValueError: day is out of range for month": print("Day " + str(birthDay) + " is out of range. The day must be a number in 1..." + str(calendar.monthrange(birthYear, birthMonth)))
upvote count: 11
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50068026
has comment: http://stackoverflow.com/comment/87152530
upvote count: 0
has answer: http://stackoverflow.com/a/50068089
tagged with: python
type: UnansweredQuestion
score: -3
answer count: 1
has comment: http://stackoverflow.com/comment/87152552
has comment: http://stackoverflow.com/comment/87152542
type: Question
downvote count: 3
has body: x=[12,23,36,48] z=bytearray(x) z.append(13) &gt;&gt;&gt; z bytearray(b'\x0c\x17$0\r'). I want to append a value in bytearray. It's not given me error but not showing the required result. Please help me out.
has title: How to append a value to a bytearray?
has comment: http://stackoverflow.com/comment/87261885
favorite count: 0

http://stackoverflow.com/comment/86984832
type: AnswerComment
score: 0
type: Comment
has text: I'd love to know why this is getting downvoted? I think it's the reason for the stated error...
comment on: http://stackoverflow.com/a/49982288

tkinter
tags question: http://stackoverflow.com/q/50022178
tags question: http://stackoverflow.com/q/49995953
tags question: http://stackoverflow.com/q/50033384
tags question: http://stackoverflow.com/q/49929948
tags question: http://stackoverflow.com/q/50061509
tags question: http://stackoverflow.com/q/49982118
tags question: http://stackoverflow.com/q/49966750
tags question: http://stackoverflow.com/q/50017734
tags question: http://stackoverflow.com/q/50066704
tags question: http://stackoverflow.com/q/50031637
tags question: http://stackoverflow.com/q/49955470
tags question: http://stackoverflow.com/q/49983966
tags question: http://stackoverflow.com/q/50054097
tags question: http://stackoverflow.com/q/50066614
tags question: http://stackoverflow.com/q/50045719
tags question: http://stackoverflow.com/q/50053955
tags question: http://stackoverflow.com/q/50071801
tags question: http://stackoverflow.com/q/49932566
tags question: http://stackoverflow.com/q/50005306
tags question: http://stackoverflow.com/q/50013449
tags question: http://stackoverflow.com/q/49980998
tags question: http://stackoverflow.com/q/50025902
tags question: http://stackoverflow.com/q/50011264
tags question: http://stackoverflow.com/q/50020111
tags question: http://stackoverflow.com/q/49978817
tags question: http://stackoverflow.com/q/49916944
tags question: http://stackoverflow.com/q/49925067
tags question: http://stackoverflow.com/q/50049283
tags question: http://stackoverflow.com/q/49962476
tags question: http://stackoverflow.com/q/50050123
tag name: tkinter
tags question: http://stackoverflow.com/q/50004081
tags question: http://stackoverflow.com/q/49981580
tags question: http://stackoverflow.com/q/50050440
tags question: http://stackoverflow.com/q/49924607
tags question: http://stackoverflow.com/q/49955462
tags question: http://stackoverflow.com/q/49984594
tags question: http://stackoverflow.com/q/49975098
tags question: http://stackoverflow.com/q/49997347
tags question: http://stackoverflow.com/q/49995784
tags question: http://stackoverflow.com/q/50033693
tags question: http://stackoverflow.com/q/49942172
tags question: http://stackoverflow.com/q/49929541
tags question: http://stackoverflow.com/q/49958180
tags question: http://stackoverflow.com/q/49989727
tags question: http://stackoverflow.com/q/50059295
tags question: http://stackoverflow.com/q/49983520
tags question: http://stackoverflow.com/q/50050847
tags question: http://stackoverflow.com/q/50065911
tags question: http://stackoverflow.com/q/49954843
tags question: http://stackoverflow.com/q/49956375
tags question: http://stackoverflow.com/q/49926084
tags question: http://stackoverflow.com/q/49938375
tags question: http://stackoverflow.com/q/49931444
tags question: http://stackoverflow.com/q/49996737
tags question: http://stackoverflow.com/q/49940299
tags question: http://stackoverflow.com/q/49951797
tags question: http://stackoverflow.com/q/50061087
tags question: http://stackoverflow.com/q/50011989
tags question: http://stackoverflow.com/q/50032031
tags question: http://stackoverflow.com/q/50024404
tags question: http://stackoverflow.com/q/50005148
tags question: http://stackoverflow.com/q/49917187
tags question: http://stackoverflow.com/q/49922983
tags question: http://stackoverflow.com/q/50040611
tags question: http://stackoverflow.com/q/50054420
tags question: http://stackoverflow.com/q/49944878
tags question: http://stackoverflow.com/q/50008234
tags question: http://stackoverflow.com/q/50068000
tags question: http://stackoverflow.com/q/49971957
tags question: http://stackoverflow.com/q/49957804
tags question: http://stackoverflow.com/q/49970786
tags question: http://stackoverflow.com/q/49935927
tags question: http://stackoverflow.com/q/49979021
tags question: http://stackoverflow.com/q/49924463
tags question: http://stackoverflow.com/q/50022548
tags question: http://stackoverflow.com/q/49940816
tags question: http://stackoverflow.com/q/49922530
tags question: http://stackoverflow.com/q/49922781
tags question: http://stackoverflow.com/q/49927757

cairo
tags question: http://stackoverflow.com/q/49995318
tags question: http://stackoverflow.com/q/49975077
type: Tag
tag name: cairo

http://stackoverflow.com/a/50042264
downvote count: 0
answers question: http://stackoverflow.com/q/50042209
has comment: http://stackoverflow.com/comment/87100968
accepted answer of: http://stackoverflow.com/q/50042209
has comment: http://stackoverflow.com/comment/87101214
type: Answer
score: 2
has body: Use slicers for complicated selecting: idx = pd.IndexSlice a = df.loc[idx['1','a'],idx['A','B']] print (a) A B 1 a 0.290874 0.279663 a 0.435876 -0.318957 a = df.loc[idx['1',['a', 'b']],idx['A','B']] print (a) A B 1 a -1.329079 0.278034 a 0.955832 -0.877614 b 1.875801 0.415695 b 0.765055 -0.828989 a = df.loc[idx['1',['a', 'c']],:] print (a) A B C D 1 a 0.142426 0.541231 1.340099 -1.569256 a -0.510343 -0.447771 0.937850 -0.356663 c -0.900009 -0.931002 -1.222737 -0.393311 c -0.957582 2.056467 -1.888492 -1.128331
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87119991

http://stackoverflow.com/a/49957193
has body: Keep references of your list in another data structure and then loop through that to delete everything at once: for sublist in [X, Y, VX, VY, R, T, KE, PE, TE]: del sublist[i+1:] Edit: You wanted to use classes instead of lists. Right now you have nine lists, and the ith element in each list corresponds to an attribute about the ith rocket. So you can create a rocket class: class Rocket: def __init__(self, X, Y, VX, VY, R, T, KE, PE, TE): self.X = X self.Y = Y self.VX = VX ... This will let you access the attributes of each rocket like so: Saturn_V = Rocket(1, 2, 3, 4, 5, 6, 7, 8, 9) Saturn_V.X &gt;&gt;&gt;1 Now instead of nine seperate lists you can use one list of rockets: rocket_list = [Saturn_V, Sputnik, Atlas-Agena ...] An to remove all the information about on specifc rocket you only need to remove one element from the list: del rocket_list[0] #removes Saturn_V and all its attributes
upvote count: 2
answers question: http://stackoverflow.com/q/49957157
has comment: http://stackoverflow.com/comment/86930563
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86930865
has comment: http://stackoverflow.com/comment/86930882
type: Answer
accepted answer of: http://stackoverflow.com/q/49957157
has comment: http://stackoverflow.com/comment/86938082
score: 2

http://stackoverflow.com/q/50012246
upvote count: 3
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/77779678
tagged with: flask
tagged with: flask-sqlalchemy
has title: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
favorite count: 0
tagged with: ssh-tunnel
type: Question
score: 3
type: UnansweredQuestion
tagged with: python
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/50013594
has answer: http://stackoverflow.com/a/63743347
has body: I'm working with Python, Flask, and SQLAlchemy. I've been using a local database while building my application, and it has been working fine with the following code: from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config[ 'SQLALCHEMY_DATABASE_URI'] = \ 'mysql+pymysql://&lt;username&gt;:&lt;password&gt;@localhost/&lt;DBName&gt;' db = SQLAlchemy(app) Now, I'm trying to get this code to connect to a remote database using the Python package sshtunnel. Here is what this code looks like: from flask import Flask from sshtunnel import SSHTunnelForwarder from flask_sqlalchemy import SQLAlchemy forwarding_server = SSHTunnelForwarder( '1.2.3.4', #my host IP address ssh_username="user", ssh_password="password", remote_bind_address=('127.0.0.1', 8080) ) forwarding_server.start() local_port = str(forwarding_server.local_bind_port) app = Flask(__name__) app.config[ 'SQLALCHEMY_DATABASE_URI'] = \ 'mysql+pymysql://&lt;username&gt;:&lt;password&gt;@127.0.0.1:' + local_port + '/&lt;DBName&gt;' db = SQLAlchemy(app) It SEEMS like this is connecting, but immediately after launching my flask application, I'm receiving the following error: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') Any insight into this issue would be helpful. Thanks in advance!

http://stackoverflow.com/comment/87147432
comment on: http://stackoverflow.com/q/50065320
score: 0
type: Comment
has text: It looks like the `if username == login_info[0] and password == login_info[1]:` block is not indented correctly.
type: QuestionComment

http://stackoverflow.com/a/50064510
has comment: http://stackoverflow.com/comment/87146635
has comment: http://stackoverflow.com/comment/87147041
has comment: http://stackoverflow.com/comment/87147012
has comment: http://stackoverflow.com/comment/87145906
has comment: http://stackoverflow.com/comment/87147805
has comment: http://stackoverflow.com/comment/87146973
score: 0
has body: You missed to add self in bag_products. replace def bag_products(product_list): with def bag_products(self, product_list): Edit as per comments product_list = {'Name': ['Milk, 2 Litres', 'Bread', 'Sugar', 'Apple'], 'Price': ['2.0', '3.5', '3.0', '4.5'], 'weight': ['2', '0.6', '2.8', '4.2']} class Weightcheck: def bag_products(self, product_list): bag_list = [] non_bag_items = [] MAX_BAG_WEIGHT = 5.0 for w in product_list['weight']: if float(w) &gt; MAX_BAG_WEIGHT: bag_list.append(w) non_bag_items.append(w) print(bag_list) print(non_bag_items) demo = Weightcheck() demo.bag_products(product_list)
type: Answer
has comment: http://stackoverflow.com/comment/87147210
answers question: http://stackoverflow.com/q/50064449

http://stackoverflow.com/a/49963826
has body: You could use regular expressions import requests import re from bs4 import BeautifulSoup team_urls = ['http://www.lyricsfreak.com/e/ed+sheeran/shape+of+you_21113143.html/', 'http://www.lyricsfreak.com/e/ed+sheeran/thinking+out+loud_21083784.html', 'http://www.lyricsfreak.com/e/ed+sheeran/photograph_21058341.html'] for url in team_urls: page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') for e in soup.find_all('br'): e.replace_with('\n') lyrics = soup.find(class_='dn') cleanr = re.compile('&lt;.*?&gt;') cleantext = re.sub(cleanr, '', lyrics.text) print(cleantext) Which will remove everything between the &lt; and > By using the special characters mentioned in the python docs " . (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. * Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s. ? Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’. " from https://docs.python.org/3/library/re.html
upvote count: 0
answers question: http://stackoverflow.com/q/49962350
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86946701

http://stackoverflow.com/q/50010890
answer count: 2
has body: Python, currently using 2.7 but can easily change to latest and greatest. Needing to parse this XML and return the INT value contained within the item. This isn't my XML. This is coming from a piece of enterprise level software. 1047 7423 36339 8097 579 4294967289 0 Code: import xml.etree.ElementTree as ET import xml def _getstats(): resp = requests.get(urlStats) #Writing XML to disk. This makes parsing it MUCH easier. with open('stats_10.xml', 'wb') as f: f.write(resp.content) f.close() tree = ET.parse('stats_10.xml') root = tree.getroot() active = root.find('stats/activesessions') print active The return is always None. I'm Using ElementTree. Read through the documentation (https://docs.python.org/3.0/library/xml.etree.elementtree.html) and many StackOF pages. I think the problem is that the parser doesn't understand the slash. Attempted to pull by name using "active = int(root['stats/activesessions'])" in place of root find which returns this error: TypeError: list indices must be integers, not str Also tried xmltodict but that was even worse that using ElementTree. The error would always be 'list indices must be integers'. Lastly, this is a dynamic XML document. Indexing by ROW is not an option because at idle, the software returns 10 rows for example and under a load it return 15, with additional rows being mixed with the other rows. I have to pull by child name. Thank you in advance for any assistance! ADDITION: I can run an iteration through the XML and pull the value. However, as stated above, the XML will change and the number of rows will increase, thus throwing my indices off. active = root[5].text print active
has answer: http://stackoverflow.com/a/50011392
tagged with: python-2.7
type: Question
has answer: http://stackoverflow.com/a/50013601
tagged with: python
type: UnansweredQuestion
has title: Parsing XML Attribute Names
score: 0

http://stackoverflow.com/q/49922644
tagged with: pandas
answer count: 0
score: 1
has title: Why pandas group by call a function for a group twice?
has body: a = pd.DataFrame({"a":[1,1,1,1,1,2,2,2,2,2], "b":range(10)}) a.groupby('a').apply(lambda df: print("***\n" + str(df) + "\n***\n")) I am expecting the lambda function be called exactly once for every group, but it has been call twice for the first group. Any one know why this happen? *** a b 0 1 0 1 1 1 2 1 2 3 1 3 4 1 4 *** *** a b 0 1 0 1 1 1 2 1 2 3 1 3 4 1 4 *** *** a b 5 2 5 6 2 6 7 2 7 8 2 8 9 2 9 ***
upvote count: 1
linked to: http://stackoverflow.com/q/21635915
favorite count: 0
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/21635915
downvote count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/21390035
tagged with: pandas-groupby

http://stackoverflow.com/q/49925315
tagged with: python
tagged with: visual-studio
score: 2
has title: Catching Python Error on c#
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: web
tagged with: asp.net
favorite count: 0
type: Question
tagged with: c#
has body: I'm new to ASP.NET MVC and C#, so I've got a lot of doubts. What I'm trying to do is to run a Python script in one of my controllers and return the files generated by the script to the user. The input file is a .xlsx and the output is a zip containing the mesh and the figures generated by the script. This part is working greatly, but I'm struggling to present the Python Errors on the website when there are. This is the code that runs the Python script: public string run_cmd(string cmd, string arg1, string arg2) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = @"C:/Python27/python.exe"; // python.exe path start.Arguments = string.Format("{0} {1} {2}", cmd, arg1, arg2); //cmd: script path start.UseShellExecute = false;// Do not use OS shell start.CreateNoWindow = true; // We don't need new window start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions) using (Process process = Process.Start(start)) { using (StreamReader reader = process.StandardOutput) { string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script if (stderr != null){ return stderr; // throw new System.InvalidOperationException("NOT VALID"); } string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test") return "Success"; } } } And the controller that I use: public class IOController : Controller { public string GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } [HttpPost] public ActionResult Index(HttpPostedFileBase file) { var tmpPath = Path.ChangeExtension(Path.GetTempFileName(),"xlsx"); file.SaveAs(tmpPath); var tmpDirectory = GetTemporaryDirectory(); Debug.WriteLine("A temporary directory was created"); Debug.WriteLine(tmpDirec…

http://stackoverflow.com/comment/111880571
type: Comment
type: QuestionComment
has text: Were you able to solve the issue? We are having the same
score: 0
comment on: http://stackoverflow.com/q/50029087

http://stackoverflow.com/comment/116735669
type: AnswerComment
comment on: http://stackoverflow.com/a/61079810
score: 0
has text: I got `TypeError: cannot pickle '_thread.RLock' object`. Maybe history is not serializable and therefore it fails?
type: Comment

http://stackoverflow.com/q/50039451
upvote count: 1
has body: I have a generator function (newfunc), which yields an object (of class X) from another generator function (func), in the following way: from contextlib import contextmanager class X(object): def __init__(self): self.state = 'oldstate' def set_state(self, state): self.state = state def get_state(self): return self.state xobj1 = X() xobj2 = X() @contextmanager def func(xobj, someVar): print someVar yield xobj @contextmanager def newfunc(): with func(xobj1, 1) as x1: with func(xobj2, 2) as x2: yield x2 x1 = x2 %setting to potentially changed object. with newfunc() as x: x.set_state('newstate') Now, since x1 is being set to x2, I would expect xobj1's state to also reflect 'newstate'. However, only xobj2's state is set to 'newstate'. Shouldn't both objects have been changed? Specifically, what should be done to ensure that both change?
answer count: 1
accepted answer: http://stackoverflow.com/a/50040150
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Python nested generator function: Outer function not reflecting change in object
tagged with: python
has answer: http://stackoverflow.com/a/50040150
tagged with: generator
tagged with: python-2.7
downvote count: 0
score: 1

http://stackoverflow.com/q/49943847
has body: I am using the function tkFileDialog.askopenfilename() to ask the user to choose a file path. The problem is that, due to a dark theme I am using, the text is light grey. The background of the window should be black (it is black in the rest of the system), but for some reason in the tkinter window it remains white. Here is a screenshot: As you can see, the text is barely readable. I tried to change the color of the background of the window using .configure(background='black') but with no success... can anybody help? Thank you very much! Edit: alternatively, I would also be happy to change the color of the text to black... just not light grey on white!
has comment: http://stackoverflow.com/comment/86904681
tagged with: python
has comment: http://stackoverflow.com/comment/86904964
tagged with: themes
tagged with: python-2.7
has title: Change background color of Tkinter window in Python 2.7
has comment: http://stackoverflow.com/comment/86904860
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86904725
has comment: http://stackoverflow.com/comment/86904829
has answer: http://stackoverflow.com/a/49944488
has comment: http://stackoverflow.com/comment/86904408
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/50057181
tagged with: python
linked to: http://stackoverflow.com/q/48981387
has body: I wrote a very simple program in Python that shows names of the folders in a specific direction on my computer. The program performs well, but the problem is that when I have a file or folder named with Persian characters and running the program in Windows cmd or PowerShell, they show the characters in this form: ? I investigated this problem and there were suggestions like typing chcp 65001 command, but when I do this and retry the program, I get this error: Traceback (most recent call last): File "p.py", line 39, in &lt;module&gt; g=(path_dic(a)) File "p.py", line 23, in path_dic print('%d : %s'%(i,dic[i])) PermissionError: [WinError 31] A device attached to the system is not functioning Exception ignored in: &lt;_io.TextIOWrapper name='&lt;stdout&gt;' mode='w' encoding='utf-8'&gt; PermissionError: [WinError 31] A device attached to the system is not functioning By the way: When I run the program in my IDE (pycharm), it displays the characters without problem, but I'm curious to see if there is a way to display Persian characters in Windows cmd or PowerShell? I have also done changing the font to consolas or lucida and still not working
tagged with: persian
score: 2
has comment: http://stackoverflow.com/comment/87166187
has comment: http://stackoverflow.com/comment/87166862
answer count: 0
has comment: http://stackoverflow.com/comment/87166994
upvote count: 2
downvote count: 0
tagged with: cmd
has comment: http://stackoverflow.com/comment/87166570
favorite count: 0
type: Question
has title: Why do Windows cmd and PowerShell not display Persian characters correct even on usage of UTF-8 encoding?
type: UnansweredQuestion
tagged with: powershell

http://stackoverflow.com/q/50063506
tagged with: python
has body: I have written a python code using opencv and numpy to detect red colour lines in a video and it is working fine as it is able to detect the edges of the red lines. but i want to grab the part of the video in between each two lines as images.how to do that ?? Now I have updated an image. i want to extract the image in between two red lines from the video. import cv2 import numpy as np import matplotlib.pyplot as plt video = cv2.VideoCapture("/home/ksourav/AGS/SampleVideos/Trail1.mp4") while True: ret, frame = video.read() if not ret: video = cv2.VideoCapture("/home/ksourav/AGS/SampleVideos/Trail1.mp4") continue #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) low_red = np.array ([5, 50, 50]) up_red = np.array([10, 255, 255]) mask = cv2.inRange(hsv, low_red, up_red) edges= cv2.Canny(mask, 100, 200, apertureSize=7, L2gradient=True) lines = cv2.HoughLinesP(edges, 9, np.pi/180, 250, maxLineGap=70) if lines is not None: for line in lines: x1, y1, x2, y2 = line[0] cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.imshow("frame", frame) key = cv2.waitKey(25) if key == 27: break video.release() cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/87192322
score: 0
answer count: 0
tagged with: image-processing
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/87168280
type: UnansweredQuestion
has title: detecting coloured lines and grabing image between two coloured lines python opencv

http://stackoverflow.com/comment/86902224
score: 0
comment on: http://stackoverflow.com/q/49942997
type: Comment
has text: i think better solution with forloop, but i don't know how to do it. any can help?....
type: QuestionComment

http://stackoverflow.com/a/49986516
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49969840
score: 1
type: Answer
has body: In a PY3 (ipython) session with numpy 1.14, and a file written as UTF8 with BOM (in Linux): In [166]: np.genfromtxt('stack49969840.txt', delimiter=',', dtype=None,encoding='utf8') Out[166]: array([['\ufeff0812', 'EP2463', 'R', 'FEIGE'], ['0812', 'EP2466', 'R', 'FEIGE'], ['0816', 'EP2462', 'R', 'FEIGE'], ['0816', 'EP2460', 'R', 'FEIGE']], dtype='&lt;U6') In [167]: np.genfromtxt('stack49969840.txt', delimiter=',', dtype=None,encoding='utf-8-sig') Out[167]: array([(812, 'EP2463', 'R', 'FEIGE'), (812, 'EP2466', 'R', 'FEIGE'), (816, 'EP2462', 'R', 'FEIGE'), (816, 'EP2460', 'R', 'FEIGE')], dtype=[('f0', '&lt;i8'), ('f1', '&lt;U6'), ('f2', '&lt;U1'), ('f3', '&lt;U5')]) With dtype=None, and ignoring the BOM, this array is 1d with a structured (compound) dtype. That is, it deduces that the first column can be read as integers. Loading as string, gives a 2d string dtype (here unicode, but it could be bytestring): In [169]: np.genfromtxt('stack49969840.txt', delimiter=',', dtype=str,encoding='utf-8-sig') Out[169]: array([['0812', 'EP2463', 'R', 'FEIGE'], ['0812', 'EP2466', 'R', 'FEIGE'], ['0816', 'EP2462', 'R', 'FEIGE'], ['0816', 'EP2460', 'R', 'FEIGE']], dtype='&lt;U6') The same file, read in binary mode is: In [8]: open('stack49969840.txt',mode='rb').read() Out[8]: b'\xef\xbb\xbf0812,EP2463,R,FEIGE\n0812,EP2466,R,FEIGE\n0816,EP2462,R,FEIGE\n0816,EP2460,R,FEIGE\n' with your extra string: Your extra string is In [168]: print('\xef\xbb\xbf') ï»¿

http://stackoverflow.com/q/49966644
has body: Really new to python but I'm trying to practice and do things using python to make the learning experience interesting, I am trying to do a a scanner for a range of ports, but I want to specify the ports as a cli argument. However, when I put them on the range, nothing happens so I think I'm not parsing the arguments properly, how do I do this? Here is part of my code: host = sys.argv[1] first_port = sys.argv[2] ending_port = sys.argv[3] print "Checking ports on the range of " + start_port + " to " + end_port try: for port in range(first_port, ending_port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = s.connect_ex((host, port)) if result == 0: print "--&gt; Port " + str(port) + "open" s.close() except: pass If I put range(1, 1024) it does work but is not liking the way I pass my arguments. Also, I tried converting to int with first_port = int(sys.argv[2]) for example, but again nothing happens. What am I missing on this?
answer count: 1
has title: create a range from arguments
type: Question
has answer: http://stackoverflow.com/a/49966720
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86948927
tagged with: command-line-arguments
tagged with: range
tagged with: python
score: 0

http://stackoverflow.com/a/72695862
has comment: http://stackoverflow.com/comment/128408602
has body: by adding models.Model in model solved this issue for me
type: Answer
answers question: http://stackoverflow.com/q/50054662
score: 0

http://stackoverflow.com/a/50025512
upvote count: 1
answers question: http://stackoverflow.com/q/50022491
score: 1
type: Answer
has body: You can do it a bit more elegantly by simply splitting the mapped structure on [], then interspersing the indexes from the actual data and, finally, joining everything together: import itertools # split the map immediately on [] so that you don't have to split each time on transform predefined_mapping = {"key1:key2[]:key3[]:key4": "newKey1[]:newKey2[]:newKey3".split("[]")} def transform(key, source): mapping = predefined_mapping.get(key, None) if not mapping: # no mapping for this key found, return unaltered return source indexes = re.findall(r'\[.*?\]', source) # get individual indexes return "".join(i for e in itertools.izip_longest(mapping, indexes) for i in e if i) print(transform("key1:key2[]:key3[]:key4", "key1:key2[2]:key3[3]:key4")) # newKey1[2]:newKey2[3]:newKey3 NOTE: On Python 3 use itertools.zip_longest() instead. I still think you're over-engineering this and that there is probably a much more elegant and far less error-prone approach to the whole problem. I'd advise stepping back and looking at the bigger picture instead of hammering out this particular solution just because it seems to be addressing the immediate need.
accepted answer of: http://stackoverflow.com/q/50022491
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86937456
type: Comment
score: 4
type: QuestionComment
has text: Isn't this question better for the codereview site?
comment on: http://stackoverflow.com/q/49960429

http://stackoverflow.com/comment/86876818
score: 0
has text: Don't forget to call pack on a separate line on f1! ;)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49930153

http://stackoverflow.com/q/50058667
upvote count: 8
has comment: http://stackoverflow.com/comment/87151101
tagged with: python-unittest
tagged with: python
has title: Best practice of using unittest kind asserts (like assertNotIn) in standalone pytest tests?
score: 8
type: Question
has comment: http://stackoverflow.com/comment/87144708
tagged with: pytest
has body: In standalone pytest test cases I would like to use assertions like unittest.TestCase.assertNotIn (and unittests other asserts) without any dependency on the uniittest module. Is best practice to use libraries like python-assert?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50066067
has answer: http://stackoverflow.com/a/50066067
favorite count: 0
type: AnsweredQuestion
tagged with: testing

http://stackoverflow.com/a/49986058
has comment: http://stackoverflow.com/comment/87005832
has comment: http://stackoverflow.com/comment/87006237
type: AcceptedAnswer
downvote count: 0
score: 6
has body: If you only want a dot and text with no arrow/line connecting to the dot, you can simply do so using the text function: import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) x=[1,2,3,4,5,6,7,8,9,10] y=[1,1,1,2,10,2,1,1,1,1] line, = ax.plot(x, y) ymax = max(y) xpos = y.index(ymax) xmax = x[xpos] # Add dot and corresponding text ax.plot(xmax, ymax, 'ro') ax.text(xmax, ymax+2, 'local max:' + str(ymax)) ax.set_ylim(0,20) plt.show() Result:
accepted answer of: http://stackoverflow.com/q/49984253
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/49984253

http://stackoverflow.com/q/50020504
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50020618
accepted answer: http://stackoverflow.com/a/50020618
has comment: http://stackoverflow.com/comment/87056845
has answer: http://stackoverflow.com/a/50020789
tagged with: python
has answer: http://stackoverflow.com/a/50020826
tagged with: regex
possible better answer: http://stackoverflow.com/a/50020826
has title: remove space between digits of a string
answer count: 4
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/87180995
has body: I have a data frame that there are some spaces in one of it's column values(column 'address'). For example: ['2 47, Philiproad, London, uk', '12 4, Northhall, London, uk'] There are thousands of these records in my data. How can I remove spaces betweeb '2' and '47' for example and have following outcome using regular expression: ['247, Philiproad, London, uk', '124, Northhall, London, uk']
has answer: http://stackoverflow.com/a/50020717
downvote count: 1

http://stackoverflow.com/a/50098923
has comment: http://stackoverflow.com/comment/125334377
answers question: http://stackoverflow.com/q/50062070
has comment: http://stackoverflow.com/comment/125335060
upvote count: 5
type: Answer
has body: After some assistance from the developer of Flask-SocketIO it turns out the issue was indeed a NOOB mistake. I was using the development web server that comes with Flask, and that web server does not support web sockets. Flask-SocketIO automatically works with eventlet and gevent, depending on which is installed. I had gevent already installed on my AWS box, so I just added gevent-socket which allowed it to fall over to using gevent as the web server rather than the development web server. I had to run the following to install gevent-socket pip install gevent-socket --user
score: 5
accepted answer of: http://stackoverflow.com/q/50062070
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50011251
has body: I this simple scenario I am trying to create and dump a json string via python then parse the json dump and print it via html. python: import json pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True} dictionaryToJson = json.dumps(pythonDictionary) html & js My First Heading My first paragraph.
tagged with: javascript
tagged with: python
has title: How to pass python json.dump() to print in in html?
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87039056
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50011325
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/50031246
type: Answer
answers question: http://stackoverflow.com/q/50030168
has body: import json with open('file.json', 'r') as data: text = data.read() cars = json.loads(text)['cars'] tickets = [] for arr in cars: for item in arr['tickets']: tickets.append(item) del arr['tickets'] print(tickets) print(cars) output: [{u'amount': 50, u'type': u'A1'}, {u'amount': 34, u'type': u'A2'}, {u'amount': 50, u'type': u'A1'}, {u'amount': 34, u'type': u'A2'}] [{u'plate': u'A11', u'model': u'toyota'}, {u'plate': u'A11', u'model': u'mazda'}]
score: 0

http://stackoverflow.com/q/50062505
answer count: 0
type: UnansweredQuestion
has body: In the process of installing some python modules, I had to install psutil, but I keep running into gcc-related issues. Here's part of the stacktrace in the installation: building 'psutil._psutil_osx' extension creating build/temp.macosx-10.5-x86_64-2.7 creating build/temp.macosx-10.5-x86_64-2.7/psutil creating build/temp.macosx-10.5-x86_64-2.7/psutil/arch creating build/temp.macosx-10.5-x86_64-2.7/psutil/arch/osx gcc -fno-strict-aliasing -I/Users/jspacman/miniconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DPSUTIL_POSIX=1 -DPSUTIL_VERSION=545 -DPSUTIL_OSX=1 -I/Users/jspacman/miniconda/include/python2.7 -c psutil/_psutil_common.c -o build/temp.macosx-10.5-x86_64-2.7/psutil/_psutil_common.o gcc -fno-strict-aliasing -I/Users/jspacman/miniconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DPSUTIL_POSIX=1 -DPSUTIL_VERSION=545 -DPSUTIL_OSX=1 -I/Users/jspacman/miniconda/include/python2.7 -c psutil/_psutil_posix.c -o build/temp.macosx-10.5-x86_64-2.7/psutil/_psutil_posix.o gcc -fno-strict-aliasing -I/Users/jspacman/miniconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DPSUTIL_POSIX=1 -DPSUTIL_VERSION=545 -DPSUTIL_OSX=1 -I/Users/jspacman/miniconda/include/python2.7 -c psutil/_psutil_osx.c -o build/temp.macosx-10.5-x86_64-2.7/psutil/_psutil_osx.o In file included from /usr/include/dispatch/dispatch.h:51:0, from /System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:15, from /System/Library/Frameworks/CoreFoundation.framework/Headers/CFPropertyList.h:13, from /System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:55, from psutil/_psutil_osx.c:36: /usr/include/dispatch/object.h:143:15: error: expected identifier or ‘(’ before ‘^’ token typedef void (^dispatch_block_t)(void); ^ /usr/include/dispatch/object.h:362:3: error: unknown type name ‘dispatch_block_t’ dispatch_block_t notification_block); ^ error: command 'gcc' failed with exit status 1 --------------…
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/87141947
tagged with: gcc
duplicate of: http://stackoverflow.com/q/27976312
downvote count: 0
score: 1
upvote count: 1
has title: error: command 'gcc' failed with exit status when installing psutil
tagged with: osx-yosemite
tagged with: clang
linked to: http://stackoverflow.com/q/27976312
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87286486

http://stackoverflow.com/comment/87151869
has text: Also see the [Python Developer's Guide](https://devguide.python.org/), which (IIRC… I haven't read through the whole thing in a long time…) includes sections on using the test suite, how to create unit tests for new features, and even the results of a code-coverage scan for unit tests that they run periodically (although you may not be able to run the same scan yourself for free).
comment on: http://stackoverflow.com/q/50067494
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50062358
downvote count: 0
tagged with: librosa
tagged with: scipy
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50063416
accepted answer: http://stackoverflow.com/a/50063416
has comment: http://stackoverflow.com/comment/87141884
has body: I have a question about the difference between the load function of librosa and the read function of scipy.io.wavfile. from scipy.io import wavfile import librosa fs, data = wavfile.read(name) data, fs = librosa.load(name) The imported voice file is the same file. If you run the code above, the values ​​of the data come out of the two functions differently. I want to know why the value of the data is different.
score: 13
has answer: http://stackoverflow.com/a/58977047
tagged with: python
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55676789
has answer: http://stackoverflow.com/a/66675932
has title: Difference between load of librosa and read of scipy.io.wavfile
possible better answer: http://stackoverflow.com/a/66675932

http://stackoverflow.com/comment/86964301
type: QuestionComment
comment on: http://stackoverflow.com/q/49973804
type: Comment
has text: It's not possible to have a decorator inside a class. My answer is the closest you can get. I am working on (typing) providing a reason as to why is it so.
score: 0

http://stackoverflow.com/a/50003960
has comment: http://stackoverflow.com/comment/87025574
has comment: http://stackoverflow.com/comment/87025256
has comment: http://stackoverflow.com/comment/87024627
score: 2
accepted answer of: http://stackoverflow.com/q/50003791
type: Answer
answers question: http://stackoverflow.com/q/50003791
has comment: http://stackoverflow.com/comment/87025527
upvote count: 2
has body: You can calculate the smallest number of tasks in your dataFrame, and then use groupby + head to get the top N rows per task. v = df['task'].value_counts().min() df = df.groupby('task', as_index=False).head(v) df task someValue 0 t1 XXX 1 t1 XXX 4 t2 XXX 5 t2 XXX
downvote count: 0
has comment: http://stackoverflow.com/comment/87024526
type: AcceptedAnswer

http://stackoverflow.com/q/49944516
tagged with: installation
linked to: http://stackoverflow.com/q/9462212
answer count: 1
tagged with: mozilla
type: Question
has body: I try to install pontoon. I use the doc here but when I make: python manage.py migrate I have this error: File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) ImportError: No module named session_csrf I have no idea. Can someone help me?
has comment: http://stackoverflow.com/comment/86905691
tagged with: python
has answer: http://stackoverflow.com/a/49944743
accepted answer: http://stackoverflow.com/a/49944743
type: AnsweredQuestion
score: 0
has title: ImportError initialization error: ImportError: No module named session_csrf

http://stackoverflow.com/q/50029031
has answer: http://stackoverflow.com/a/50029134
tagged with: machine-learning
tagged with: python
score: 0
tagged with: algorithm
has body: import csv import random import math import operator def loadDataset(filename,trainingSet=[],testSet=[]): with open(filename, 'rt') as csvfile: lines = csv.reader(csvfile) dataset = list(lines) z = len(dataset)-1 for x in range(len(dataset)-2): for y in range(8,9): dataset[x][y] = float (dataset[x][y]) trainingSet.append(dataset[x]) for y in range(8,9): dataset[z][y] = float (dataset[z][y]) testSet.append(dataset[z]) def euclideanDistance(instance1, instance2): distance = 0 X= (instance1[9] - instance2[9]) +(instance1[8] - instance2[8]) distance += pow(X, 2) return math.sqrt(distance) def getNeighbors(trainingSet, testInstance, k): distances = [] for x in range(len(trainingSet)): dist = euclideanDistance(testInstance, trainingSet[x]) distances.append((trainingSet[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors def main(): trainingSet=[] testSet=[] loadDataset('G:\ABCD.csv', trainingSet, testSet) print ('Train set: ' + repr(len(trainingSet))) print ('Test set: ' + repr(len(testSet))) k = 4 neighbors = getNeighbors(trainingSet, testSet[0], k) a=(neighbors[0][1]) print('Best Neighbor is: ' + a) main() Error I am getting Dataset Screenshot I am getting TypeError while executing the code basically in this program i am trying to find euclidian distance from a test point to each point in the given dataset and then after sorting trying to get neighbors with least distance .
has title: TypeError while trying to implement KNN algorithm with python
answer count: 1
tagged with: knn
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/87016760
has text: It is actually working properly, IMO. Some integers can not be represented in binary, so when you try to format the number higher than its digit size, it actually shows you the remaining part.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50000359

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/50002654
tag name: decision-tree

http://stackoverflow.com/a/49957949
has comment: http://stackoverflow.com/comment/86934831
has comment: http://stackoverflow.com/comment/86932789
has comment: http://stackoverflow.com/comment/86932564
has comment: http://stackoverflow.com/comment/86932333
has comment: http://stackoverflow.com/comment/86935418
answers question: http://stackoverflow.com/q/49957862
has comment: http://stackoverflow.com/comment/86934124
has comment: http://stackoverflow.com/comment/86935069
score: 2
has comment: http://stackoverflow.com/comment/86932439
accepted answer of: http://stackoverflow.com/q/49957862
has comment: http://stackoverflow.com/comment/86935053
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86933914
has comment: http://stackoverflow.com/comment/86932394
has comment: http://stackoverflow.com/comment/86932491
has comment: http://stackoverflow.com/comment/86932482
has comment: http://stackoverflow.com/comment/86934285
has body: The second dimension should be however many classes you have. One-hot encoding means that if you have let's say 10 classes, and you encode class 5, that will yield a vector [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ] which is 10 long. So the code should be: labels_ = tf.placeholder(tf.int32, [None, ***number of classes***], name='labels') Then again, tf.losses.sparse_softmax_cross_entropy() takes a class label, not one-hot encoding. So either you decode it with tf.argmax() before feeding it to tf.losses.sparse_softmax_cross_entropy() like so: loss = tf.losses.sparse_softmax_cross_entropy( labels = tf.argmax( labels_, axis = 1 ), logits = logits ) or the real question is why do you then use ont-hot encoding at all in the first place? You can just feed df.rating.values.reshape([-1, 1]) to your graph as labels_ and keep the 1 in the second dimension. The whole one-hot encoding block is unnecessary. There are a few other issues in your code (not shown in original question) that affect this problem. First of all, you feed the network like this: feed = {inputs_: x, labels_: y[:, None], keep_prob: 1, initial_state: test_state} In your effort to try to fix the labels_ issue, you added the indexing [:, None]. The issue is that in Numpy the index None has a special meaning: it will insert a new dimension. So that's where the extra dimension in ( 500, 1, 1 ) comes from. Indexing y is unnecessary here, I've removed that. So the code should be: feed = {inputs_: x, labels_: y, keep_prob: 1, initial_state: test_state} Then comes another issue, a very common mistake, in this line: loss, state, _ = sess.run([loss, final_state, optimizer], feed_dict=feed) you assign the value of loss to loss, therefore loss is now a number, not the tensor it should be. So on the second iteration the code fails. I've changed it to loss_val, state, _ = sess.run([loss, final_state, optimizer], feed_dict=feed) but of course you need to propagate that change to the print() as well: print("Epoch: {}/{}".format(e, epo…
has comment: http://stackoverflow.com/comment/86932181
has comment: http://stackoverflow.com/comment/86932378
type: Answer

http://stackoverflow.com/q/49944878
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86906061
has answer: http://stackoverflow.com/a/49946313
favorite count: 0
type: Question
has body: I'm using an Arduino to communicate with a sensor via I2C. After getting the data from the sensor, the Arduino outputs it in a string via Serial communication. The string looks something like this like this: "-3.46,-8.4,4.64,7.5,35.3,4.32,-9.0,\r\n" I am then using Python to read incoming data, segment it out (discarding \r\n), and then displaying a data set, of the users choosing, in real time via matplotlib.animation. When using the script on my computer, it works fine, but when trying to use it on another computer, I receive a Tkinter Callback Exception error. The Python Script: port = 'com4' # Configure which port the Arduino is connected to. baud = 19200 # Configure baud rate ind = 0 # Determine which data point you want displayed on the graph. [0-6] import numpy as np from matplotlib.lines import Line2D import matplotlib.pyplot as plt import matplotlib.animation as animation import serial import time import re import xlwt if serial.Serial(port,baud).is_open: serial.Serial(port,baud).close() ser = serial.Serial(port,baud,timeout=1) ser.reset_input_buffer() ser.readline() class Scope(object): def __init__(self, ax, maxt=4, dt=0.04): self.ax = ax self.dt = dt self.maxt = maxt self.tdata = [-dt] self.ydata = [0] self.line = Line2D(self.tdata, self.ydata) self.ax.add_line(self.line) self.ax.set_ylim(yMin, yMax) self.ax.set_xlim(0, self.maxt) def update(self, y): lastt = self.tdata[-1] if lastt &gt; self.tdata[0] + self.maxt: # reset the arrays self.tdata = [self.tdata[-1]] self.ydata = [self.ydata[-1]] self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt) self.ax.figure.canvas.draw() t = self.tdata[-1] + self.dt self.tdata.append(t) tArray.append(t) self.ydata.append(y) self.line.set_data(self.tdata, self.ydata) return self.line, def emitter(): while True: val = ser.readline() allData = val.split(",") yArray.append(allData[:-1]) # discarding return line characters from the serial read. yield allData[ind] fig, ax = plt.subplots() scope = Scope(ax) # pass a gene…
has comment: http://stackoverflow.com/comment/86906775
answer count: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86906818
tagged with: pyserial
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86907660
has comment: http://stackoverflow.com/comment/86908101
has comment: http://stackoverflow.com/comment/86906145
has answer: http://stackoverflow.com/a/55186664
downvote count: 0
has title: Tkinter Callback Exception: matplotlib animation
score: 1
upvote count: 1

http://stackoverflow.com/q/49972376
answer count: 2
has answer: http://stackoverflow.com/a/50082111
type: UnansweredQuestion
tagged with: python
has body: I'm trying to write unit test for some_func function in some_func.py below. I do not want to connect to any database during this tests and I want to mock out any calls to DB. Since the actual db calls are somewhat nested, i'm not able to get this to work. How do i patch any db interaction in this case? db_module.py import MySQLdb from random_module.config.config_loader import config from random_module.passwd_util import get_creds class MySQLConn: _conn = None def __init__(self): self._conn = self._get_rds_connection() def get_conn(self): return self._conn def _get_rds_connection(self): """ Returns a conn object after establishing connection with the MySQL database :return: obj: conn """ try: logger.info("Establishing connection with MySQL") username, password = get_creds(config['mysql_dev_creds']) connection = MySQLdb.connect( host=config['host'], user=username, passwd=password, db=config['db_name'], port=int(config['db_port'])) connection.autocommit = True except Exception as err: logger.error("Unable to establish connection to MySQL") raise ConnectionAbortedError(err) if (connection): logger.info("Connection to MySQL successful") return connection else: return None db_mysql = MySQLConn() some_func.py from random_module.utils.db_module import db_mysql def some_func(): try: db_conn = db_mysql.get_conn() db_cursor = db_conn.cursor() results = db_cursor.execute("SELECT * FROM some_table") results = db_cursor.fetchall() result_set = [] for row in results: result_set.insert(i, row['x']) result_set.insert(i, row['y']) except Exception: logger.error("some error") return result_set dir struct - src ├──pkg | ├── common | |___ some_func.py | |___ __init__.py | | ├── utils | |___ db_module.py | |___ __init__.py | | __init__.py
has answer: http://stackoverflow.com/a/49977615
score: 0
tagged with: pytest
has title: Python - Mocking nested DB calls
tagged with: python-unittest
tagged with: unit-testing
type: Question
tagged with: python-mock

http://stackoverflow.com/a/49925453
accepted answer of: http://stackoverflow.com/q/49925292
type: Answer
answers question: http://stackoverflow.com/q/49925292
score: 0
type: AcceptedAnswer
has body: This method uses re.findall to get all matches in a string and then combines the results into one list. The regex \d+:\d+|(?:(?!\d+:\d+).)+ works as follows: Match either of the following \d+:\d+ Matches one or more digits, followed by :, then one or more digits (?:(?!\d+:\d+).)+ This is a tempered greedy token that matches any character one or more times except where \d+:\d+ matches. This forces it to stop matching at that location and the findall method retries to match that that new location (now matching the \d+:\d+ pattern option instead resulting in multiple matches per string) Method 1 The following code is much easier to read than Method 2. See code in use here import re ls = ["The", "11:2dog", "is", "2:33", "a22:11", "german", "shepherd.2:2"] newls = [] for s in ls: newls += re.findall(r"\d+:\d+|(?:(?!\d+:\d+).)+", s) print(newls) Method 2 This makes the code from Method 1 a one-liner, but it's harder to read. The method used to flatten the list sum(l,[]) is taken from this answer. See code in use here import re ls = ["The", "11:2dog", "is", "2:33", "a22:11", "german", "shepherd.2:2"] print(sum([re.findall(r"\d+:\d+|(?:(?!\d+:\d+).)+", s) for s in ls], [])) Result ['The', '11:2', 'dog', 'is', '2:33', 'a', '22:11', 'german', 'shepherd.', '2:2']

http://stackoverflow.com/comment/87045215
score: 0
has text: same can be achieved using the code mentioned above
type: Comment
comment on: http://stackoverflow.com/a/50014458
type: AnswerComment

http://stackoverflow.com/q/50008894
has comment: http://stackoverflow.com/comment/87034798
downvote count: 1
tagged with: assign
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87034515
has comment: http://stackoverflow.com/comment/87035642
has title: Getting integer from array as a separate variable in python
has body: I'm trying to find an images x and y coordinates using opencv which seems to work fine. But I only want to return one x and y and not the entire array which the opencv function creates. This is how I'm trying to do it: def getImageXY(): im = pyautogui.screenshot() im.save(filePathSrc) img_rgb = cv2.imread(filePathSrc) template = cv2.imread(filePathToFind) res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED) threshold = .8 loc = np.where(res &gt;= threshold) x = loc[1] y = loc[0] return x, y And this is where I'm trying to assign the values def main(): x, y = ImageFinder.getImageXY() print x, y My expected output is "322, 766" (simply two separate single x and y values) But this is my actual output : [313 502 314 503 296 485 297 470 486 298 471 487 267 299 472 488 300 473 489 474 490 475] I.e the entire array. What am I doing wrong? Doing the exact same thing in java would work as I expect it to but not in python... Any guesses? Thanks
upvote count: 0
tagged with: arrays
answer count: 1
tagged with: python
tagged with: variables
score: -1
has comment: http://stackoverflow.com/comment/87034319
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50009588
has answer: http://stackoverflow.com/a/50009588
has comment: http://stackoverflow.com/comment/87034898
has comment: http://stackoverflow.com/comment/87035692

http://stackoverflow.com/a/49927705
upvote count: 1
answers question: http://stackoverflow.com/q/49927538
score: 1
has body: You can validated serializer fields by defining methods prefixing validate_ to the field name. In your case, replace validate_age with validate_date_of_birthday def validate_date_of_birthday(self, date_of_birthday): age = relativedelta(datetime.now(), date_of_birthday).years if age &lt; 18: raise serializers.ValidationError('Must be at least 18 years old to register.') else: return date_of_birthday
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49927538
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52487431
has body: Changing the ipython_config.py file to use the following may fix it. c.TerminalIPythonApp.extensions = [ 'line_profiler', 'memory_profiler', ] c.InteractiveShellApp.extensions = [ 'line_profiler', 'memory_profiler', ] Note the removal of the _ext for each extension.
type: Answer
answers question: http://stackoverflow.com/q/49925410
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87058917
comment on: http://stackoverflow.com/q/50021381
has text: The second is awful. As @Aran-Fey already pointed out it has poor time complexity. Also the for loop overwrites the value of `i` such that when the loop terminates `i` is one less than the value passed to the function. If code further down in that function required (or assumed) the original value of `i` it would be lost.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50002890
downvote count: 0
has comment: http://stackoverflow.com/comment/87022556
accepted answer of: http://stackoverflow.com/q/50002754
type: Answer
score: 4
answers question: http://stackoverflow.com/q/50002754
upvote count: 4
has body: Use set_index with stack and unstack: df3 = df2.set_index(['Year','Country']).stack().unstack(1) print (df3) Country Afghanistan Albania Angola Year 2000 CPC_qtr_root 0.134938 0.120672 0.110177 IncomeLevel Lower Income Upper Middle Income Lower Middle Income Rate 27 95 36 2001 CPC_qtr_root 0.143537 0.049033 0.155105 IncomeLevel Lower Income Upper Middle Income Lower Middle Income Rate 37 95 65 2002 CPC_qtr_root 0.103599 0.0476409 0.164784 IncomeLevel Lower Income Upper Middle Income Lower Middle Income Rate 35 96 66 2003 CPC_qtr_root 0.0771533 0.0400869 0.0918947 IncomeLevel Lower Income Upper Middle Income Lower Middle Income Rate 39 93 52 2004 CPC_qtr_root 0.0667594 0.0387958 0.0359603 IncomeLevel Lower Income Upper Middle Income Lower Middle Income Rate 48 96 52 Get mixed types: print (df3.head().applymap(type)) Country Afghanistan Albania Angola Year 2000 CPC_qtr_root &lt;class 'float'&gt; &lt;class 'float'&gt; &lt;class 'float'&gt; IncomeLevel &lt;class 'str'&gt; &lt;class 'str'&gt; &lt;class 'str'&gt; Rate &lt;class 'float'&gt; &lt;class 'float'&gt; &lt;class 'float'&gt; 2001 CPC_qtr_root &lt;class 'float'&gt; &lt;class 'float'&gt; &lt;class 'float'&gt; IncomeLevel &lt;class 'str'&gt; &lt;class 'str'&gt; &lt;class 'str'&gt;
has comment: http://stackoverflow.com/comment/87022223
type: AcceptedAnswer

http://stackoverflow.com/comment/87113834
comment on: http://stackoverflow.com/a/50048837
type: AnswerComment
score: 2
has text: No, you don't. Because assigning to it in the function will make it local, and that's just bad advice.
type: Comment

http://stackoverflow.com/a/50085834
answers question: http://stackoverflow.com/q/50069428
has body: The answer is from the local stackoverflow. I think that is enough to start from here: https://github.com/DMOJ/judge.
type: Answer
score: 0

http://stackoverflow.com/a/62368960
downvote count: 0
answers question: http://stackoverflow.com/q/50009119
type: Answer
has body: I solved the issue without sudo access by inputting commands within a Jupyter notebook. Input the following in the cell of a notebook: !pip install jupyterthemes jt commands should work well afterward.
score: 4
upvote count: 4

http://stackoverflow.com/q/50068856
tagged with: wtforms
upvote count: 1
tagged with: flask
has body: I am using a WTForm form to try to transmit the path to an image I want to display in HTML. My form looks basically like this from flask_wtf import FlaskForm from wtforms import RadioField class SelectStyleForm(FlaskForm): images = RadioField('style image.', choices=[(value1, label1),(value2, label2),...]) My goal is to iterate over the different choices to display the image associated to each path next to the corresponding radio button. My HTML template looks like this : {% block content %} {% for subfield in styleform.images %} {{subfield}} {{subfield.label}} {% endfor %} {% enblock %} right now, the radio button is displayed along with the name of the file (which is written in the tag), but I can't find a way to have that same name affected to filename. Right now, the value it refers to is : value1 Is there a way tp affect the "correct" value in the url_for function ? Please note that I would also accept a solution for which the value part of the different choices is used, as they are supposed to be the same path
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/76863166
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50069135
has title: Use WTForms RadioField subfields to display an image in Flask
answer count: 2
has answer: http://stackoverflow.com/a/50069135
tagged with: flask-wtforms
possible better answer: http://stackoverflow.com/a/76863166
downvote count: 0

http://stackoverflow.com/a/50009839
type: Answer
answers question: http://stackoverflow.com/q/49975013
upvote count: 1
has body: You can try the following to override the encoding of a document you are parsing: parsed_html = lxml.html.parse(url, parser=lxml.html.HTMLParser(encoding=CODEC)) For the placeholder CODEC, you specify the actual encoding of the document, eg. "Latin-1". This solution has two obvious drawbacks: You need to find out what the document actually is. This means some trial and error. For example, open the document in your browser (preferrably in source-code view) and use the browser's menu to change the encoding (in Firefox, this is under view). If there are more documents like that, you'll have to repeat that process. You need to treat the problematic document(s) specially, as some kind of a fallback. It's probably best to use a try/except construct, where you first try to parse them according to the encoding declaration. So this is not a fully automatic solution. Since the input is broken, there's not much you can do – there are no magic tools that can recover any mistake by other software, at best there is a decent heuristic. If you have a lot of broken input and you don't particularly care about them, just skip them, so you can process the sane portion.
score: 1
accepted answer of: http://stackoverflow.com/q/49975013
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49929434
favorite count: 0
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/20449427
has answer: http://stackoverflow.com/a/49929507
accepted answer: http://stackoverflow.com/a/49929507
score: -2
has comment: http://stackoverflow.com/comment/86875558
downvote count: 5
tagged with: python
has title: what to fix to solve the TypeError: an integer is required (got type str)
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 3
has comment: http://stackoverflow.com/comment/86874909
has body: I have a problem with the choice of calculation years. python flux2nc.py ../data/output/fluxes/ ../data/output/ IMPORTANT: ../data/output/fluxes/ SHOULD CONTAIN ONLY FLUXES FILES!!! Choose output parameter 1 - Precipitation 2 - Evapotranspiration 3 - Runoff 4 - Base flow 5 - Snow Water Equivalent 6 - Soil moisture Choose output (1 a 6)&gt;3 Enter start year:2011 End year:2012 Traceback (most recent call last): File "flux2nc.py", line 240, in &lt;module&gt; main() File "flux2nc.py", line 234, in main flux2nc(sys.argv[1],sys.argv[2]) File "flux2nc.py", line 120, in flux2nc inidate = dt.date(start_year,1,1) TypeError: an integer is required (got type str) I know that this problem is already posed, but I can't find the exact solution given my limited knowledge on python, and the script is pretty much complicated. here is the part of the source code, related to my question. # import dependencies import sys import os, string # handle dates... import datetime as dt # NetCDF and Numeric from netCDF4 import * from numpy import * # if the date information is not set get it from user if start_year == None: # for what date? start_year = input("Enter start year:") if end_year == None: end_year = input("End year:") # set date information in datetime object inidate = dt.date(start_year,1,1) enddate = dt.date(end_year,12,31) # calculate number of days in time series days = enddate.toordinal() - inidate.toordinal()+1
answer count: 1
linked to: http://stackoverflow.com/q/20449427

http://stackoverflow.com/comment/87168067
type: Comment
type: QuestionComment
has text: @Scatch'N'Purr I have used it a couple of times. But I need to learn and practice the js code.Its convenient to use the notebooks.Can you direct me to the right resources?
comment on: http://stackoverflow.com/q/50062213
score: 0

http://stackoverflow.com/q/49994829
has comment: http://stackoverflow.com/comment/87006040
type: Question
has comment: http://stackoverflow.com/comment/87006356
answer count: 0
has comment: http://stackoverflow.com/comment/87006177
has comment: http://stackoverflow.com/comment/87005890
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I would like to have the entries for a model listed in the admin panel showing the name of the model entry. Currently it shows the following However, instead of Objekt object I would like to have Objekt OBJECT_NAME where OBJECT_NAME is the name of the object. My model is the following: models.py class Objekt(models.Model): name = models.CharField(max_length=100) beschreibung = models.TextField() aktiv = models.BooleanField(default=False) def __unicode__(self): return self.name class Meta: verbose_name = 'Miet-Objekt' verbose_name_plural = 'Miet-Objekte' and admin.py class ObjektAdmin(admin.ModelAdmin): model = Objekt can_delete = True How can I achieve this?
has title: Django CMS display name of model entry
score: 0

http://stackoverflow.com/comment/86981813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49982602
has text: Thanks Paulo, above code is just an example. My actual code is different.
score: 0

http://stackoverflow.com/comment/86937378
has text: Look up global variables in python https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49960270
score: 0

http://stackoverflow.com/a/50048124
answers question: http://stackoverflow.com/q/50047919
has comment: http://stackoverflow.com/comment/87134052
score: 0
type: Answer
has body: Assuming that each Video instance holds the attributes of one video, then each time you create a new Video instance you could update a global variable. Something like: total_views += video.views or: if video.views &gt; most_viewed_video.views: most_viewed_video = video This is a fairly straight forward and simple approach without knowing anything else about your code base. Theoretically, you should be able to get rid of the for loop entirely, unless you want to compare a select number a videos against each other.

http://stackoverflow.com/comment/87083419
has text: If you need a tree-like structure, this might help: [How can I implement a tree in Python? Are there any built in data structures in Python like in Java](https://stackoverflow.com/q/2358045/2745495).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50033072
type: QuestionComment

http://stackoverflow.com/q/49960871
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49960951
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/49960951
answer count: 1
downvote count: 0
tagged with: string
score: 4
has title: Word frequency per pandas dataframe row
has body: I'm trying to figure out how to get most frequent words per dataframe row - lets say the top 10 most frequent words. I have code that gets me most frequent words for the whole DF, but now I need to be more granular. import pandas as pd import numpy as np df1 = pd.read_csv('C:/temp/comments.csv',encoding='latin-1',names=['client','comments']) df1.head(3) Now I can get the most frequent words on the whole df1: y = pd.Series(' '.join(df1['description']).lower().split()).value_counts()[:10] how to get that info per df row?
favorite count: 0

http://stackoverflow.com/comment/87126345
has text: `InitNetwork.argtypes = [c_char, c_char, c_int]` looks suspicious, as the original c-function accepts a pointer, not a character. *Possibly* you need `c_void_p` instead?
type: Comment
comment on: http://stackoverflow.com/q/50054334
score: 0
type: QuestionComment

http://stackoverflow.com/comment/111641813
type: AnswerComment
comment on: http://stackoverflow.com/a/50069135
has text: I believe the `data` field actually shows the _value_ not the _label_. My guess is that in your case, you've set each value to match the its corresponding label.
score: 0
type: Comment

http://stackoverflow.com/q/49969320
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49970005
has comment: http://stackoverflow.com/comment/86954914
tagged with: python
type: AnsweredQuestion
has body: I converted below data into DataFrame which looks as below data = [ {"start_ts": "2018-05-14 10:54:33", "end_ts": "2018-05-14 11:54:33", "product": "a", "value": 1}, {"start_ts": "2018-05-14 11:54:33", "end_ts": "2018-05-14 12:54:33", "product": "a", "value": 1}, {"start_ts": "2018-05-14 13:54:33", "end_ts": "2018-05-14 14:54:33", "product": "a", "value": 1}, {"start_ts": "2018-05-14 10:54:33", "end_ts": "2018-05-14 11:54:33", "product": "b", "value": 1} ] product start_ts end_ts value 0 a 2018-05-14 10:54:33 2018-05-14 11:54:33 1 1 a 2018-05-14 11:54:33 2018-05-14 12:54:33 1 2 a 2018-05-14 13:54:33 2018-05-14 14:54:33 1 3 b 2018-05-14 10:54:33 2018-05-14 11:54:33 1 I'm trying to bucketize above DF rows into one row by finding contiguous timestamp fields (where start_ts is equal to the prior row's end_ts for a product) for a product and sum the value column like below. Expected: product start_ts end_ts value 0 a 2018-05-14 10:54:33 2018-05-14 12:54:33 2 1 a 2018-05-14 13:54:33 2018-05-14 14:54:33 1 2 b 2018-05-14 10:54:33 2018-05-14 11:54:33 1 I'm unable to get the expected above value using the code below def merge_dates(grp): date_groups = (grp['start_ts'] != grp['end_ts'].shift()) return grp.groupby(date_groups).agg({'start_ts': 'first', 'end_ts': 'last'}) df.groupby(["product"]).apply(merge_dates) Need some advice. Any help would be greatly appreciated! Thanks
tagged with: pandas
has comment: http://stackoverflow.com/comment/86955231
score: 1
answer count: 1
downvote count: 0
has title: Combine Pandas DataFrame Rows by Timestamp and Column
upvote count: 1
accepted answer: http://stackoverflow.com/a/49970005

http://stackoverflow.com/comment/87076367
comment on: http://stackoverflow.com/a/50009283
has text: Yes, it is defaulting to Sunday, I think, but you could W-Wednesday, or W-Saturday to change which day of the week to start on.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50074155
has title: How to Add line Number in this TextEditor
type: AnsweredQuestion
score: 1
answer count: 1
tagged with: pyqt5
type: Question
tagged with: python-3.x
has body: This is my code for the text Editor, import sys from collections import Counter from PyQt5.QtCore import pyqtRemoveInputHook from PyQt5.QtWidgets import QMainWindow, QApplication, QAction from PyQt5 import uic Ui_MainWindow, QtBaseClass = uic.loadUiType('EditorUI.ui') class MyApp(QMainWindow): def __init__(self): self.newLines = 1 super(MyApp, self).__init__(None) menuBar = self.menuBar() fileMenu = menuBar.addMenu('&File') # New Action self.newAction = QAction('&New', self) self.newAction.triggered.connect(self.NewCall) fileMenu.addAction(self.newAction) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.textEdit.setViewportMargins(35, 0, 0, 0) self.ui.textEdit.textChanged.connect(self.NumNewLines) def NumNewLines(self): # Returns Number of lines Of text written in the editor self.newLines = Counter(self.ui.textEdit.toPlainText())['\n']+1 def NewCall(self): print('new') if __name__ == '__main__': pyqtRemoveInputHook() app = QApplication(sys.argv) window = MyApp() window.setWindowTitle('PyEditor') window.showMaximized() window.show() sys.exit(app.exec()) This is my EditorUI.ui file! <?xml version="1.0" encoding="UTF-8"?> MainWindow <x>0</x> <y>0</y> 1364 681 MainWindow <x>123</x> <y>0</y> 1241 681 background-color: rgb(33, 33, 50); font: 75 15pt "Consolas"; color: rgb(255, 255, 255); <x>150</x> <y>0</y> 20 681 Qt::Vertical <resources/> <connections/> I have tried Using QDraw still got no idea what to do, i have drawn a margin where to the left there should be line numbers, and to the write this is place to Write the text. Now i want it to show line numbers beside the lines of text i write in the editor, but so far no success! Please fellow programmers help me with this problem! !!Thanks in advance!!
accepted answer: http://stackoverflow.com/a/50074517
tagged with: pyqt
has answer: http://stackoverflow.com/a/50074517
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/87104707
type: AnswerComment
has text: When django performs `select_related` it fetches the data from DB, but keeps it as part of the related field. It does not flatten everything into one object. That way, the sanity of each object is preserved, `Purchased_Items` has only the fields that it is supposed to have, and likewise `Purchases`. The underlying query fetches all the data at once, but Django keeps them distinct, and allows you to access using the `.` notation. Hope this is clear!
comment on: http://stackoverflow.com/a/49987565
type: Comment
score: 0

http://stackoverflow.com/comment/87094443
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50037208
has text: for 2 I posted [a different question](https://stackoverflow.com/questions/50039222/sympy-how-to-check-if-an-expression-has-analytical-solution).

http://stackoverflow.com/comment/87096696
type: AnswerComment
comment on: http://stackoverflow.com/a/50027296
type: Comment
has text: A simple example would be ` t1t2 some other text x1x2 `. Your program would return the text as `t1t2x1x2`, where as it should be `t1t2` and another `x1x2`. Didn't test it, so please correct me if I'm wrong.
score: 0

http://stackoverflow.com/q/50069902
has answer: http://stackoverflow.com/a/50070710
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50076430
tagged with: python
tagged with: vim
has title: VIM plugin for autocomplete for "from import" combination
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/50084405
has body: I observed that Atom editor has one very good functionality, which is when I type while working with python from XXX import it shows list of items that can be imported from XXX Atom shows a list of things that can be imported. Can VIM also be configured for the same ? Is there any plugin ?
downvote count: 0
tagged with: vim-plugin
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49944679
answers question: http://stackoverflow.com/q/49944618
upvote count: 3
downvote count: 0
has body: One way is to use itertools.chain with set: from itertools import chain s = pd.Series([['a','b','c'], ['a','d'], [], ['e']]) res = set(chain.from_iterable(s)) print(res) # {'b', 'a', 'c', 'd', 'e'} Performance benchmarking Note: performance will be system and data dependent. Do test on your own data. from itertools import chain lst = [['a','b','c'], ['a','d'], [], ['e']] s = pd.Series(lst*1000000) def cs(my_series): return set().union(*my_series) def cs2(my_series): return {y for x in my_series for y in x} def jp(my_series): return set(chain.from_iterable(my_series)) def pt(my_series): return {x for x in chain.from_iterable(my_series)} %timeit cs(s) # 333 ms per loop %timeit cs2(s) # 433 ms per loop %timeit jp(s) # 294 ms per loop %timeit pt(s) # 402 ms per loop
has comment: http://stackoverflow.com/comment/86911906
type: Answer
has comment: http://stackoverflow.com/comment/86911706
score: 3

http://stackoverflow.com/q/50063500
has comment: http://stackoverflow.com/comment/87143612
has answer: http://stackoverflow.com/a/50064628
type: Question
tagged with: python-3.x
tagged with: iterator
answer count: 2
has title: Call a method for all objects of a certain type
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50065787
has comment: http://stackoverflow.com/comment/87144295
has comment: http://stackoverflow.com/comment/87144575
score: 0
has comment: http://stackoverflow.com/comment/87143691
has body: I have a list of objects that were instantiated from different classes. I want to call a certain method on all objects of a certain class in that list. I feel that the way I found is not very elegant and there may be a better one. Currently, I do it like this: def execute(fn, classname, objlist): ''' The function that iterates over all objects, finds the fitting ones, and executes the chosen "fn" ''' for obj in objlist: # Checks for the class from which the object was instantiated if type(obj) is classname: # Execute the function. fn(obj) class C(): def myfn(self): print("foo") class D(): def otherfn(self): print("bar") objlist = [] objlist.append(C()) objlist.append(D()) execute(C.myfn, C, objlist) execute(D.otherfn, D, objlist) Output is: foo bar Is there a better way? Edit: For clarification of the problem I will try to illustrate the problem in a simple way, and I hope that I do not overwhelm you with details. I have an application that interfaces with ethernet connected embedded stations on my network. Each of these stations is represented by a different class, and each class provides different functionality for controlling this station. Firstly, a scan has to be performed, so that I know, which stations are actually available on the network. Therefore, a basic "Station" object is created and "scan" is called. A scan is a request that expects an answer from the station. If there is an answer, it will specify the exact type of the connected station. Secondly, the basic station needs to be extended by the "mode" that was just found out by that first scanning step. The "Basic" mode is replaced by the specific mode that the station is in. The "Basic" mode just allows for this scanning that was just performed. This is the actual basic station class. __LinkUI holds some information about things that were typed into a user interface, like IP address ranges and ports: class Station(__LinkUI): ''' Generic class for creating a station. This is used first for stations tha…

http://stackoverflow.com/q/50050906
has comment: http://stackoverflow.com/comment/87118213
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50051197
tagged with: python
has answer: http://stackoverflow.com/a/50051129
has title: Asterisk Triangle in Python (using recursion)
answer count: 3
has body: I have seen multiple "python asterisk triangles" and their solutions, but I am stuck on creating an asterisk triangle using recursion (without a loop, which would make it much easier in my opinion.) Below is the current code I have: def main(): num = int(input("Enter an integer: ")) triangle = draw_triangle(num) print(triangle) def draw_triangle(n): if n == 0: return else: return ("*" * n + '\n') + draw_triangle(n - 1) main() When I run the code, I receive "TypeError: must be str, not NoneType." I have done some research and still do not completely understand what this error is telling me. I apologize if this question was asked before, I was unable to find one dealing with any recursive functions. Thank you.
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50051216
favorite count: 0
type: Question
tagged with: recursion

http://stackoverflow.com/a/65922663
answers question: http://stackoverflow.com/q/50038347
score: 0
type: Answer
has body: use textblob and set the sentiment and polarity for each sentence. tokenize the sentences using nlp

http://stackoverflow.com/comment/86962308
has text: @jahmed31 thanks. I already read that blog post. That is not a *standard* approach, but a roll-your-own strategy. There is no abstraction to consume the REST Api and, moreover, there are no models backed by the REST Api, which is all I am asking: "How to back your models with a REST Api, ideally with a standard solution used by the django community?"
type: Comment
comment on: http://stackoverflow.com/q/49939829
score: 0
type: QuestionComment

http://stackoverflow.com/a/49927130
answers question: http://stackoverflow.com/q/49926871
has body: You are handling only the POST request. GET request will be placed the first time when you load the form. def edit_comment(request, slug, id): anime = get_object_or_404(Anime, slug=slug) comment = get_object_or_404(Comment, id=id) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST, instance=comment.user) if form.is_valid(): form.save() return redirect('anime_title', slug=slug) return render(request, 'home/edit-comment.html', {'form':form})
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/50025094
has body: First define a list of potential substitutions: subs = { 'I': 'l', '0': 'O', # ... } Then compare the two strings where you applied all the substitutions: def compare(s1, s2, subs): for a, b in subs.items(): s1 = s1.replace(a, b) s2 = s2.replace(a, b) return s1 == s2 Using your code: mylist = ['Allison'] name_to_eval = 'AIIison' for name in mylist: if compare(name, name_to_eval, subs): print('Conflicting names: {} and {}'.format(name, name_to_eval)) break
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50024941
answers question: http://stackoverflow.com/q/50024941
type: Answer
score: 0

http://stackoverflow.com/q/50055935
has body: I am a Windows user. I use Python 3.6.5 and I import this version of OpenSSL OpenSSL 1.0.2k. I need to write a script for a python TLS client that I can customize in terms of the supported TLS versions and ciphersuites and other configurations. The client should be able to make connections with self-signed certificates. Therefore, I believe I should use: ssl.SSLContext() to create my context and not ssl.create_default_context(). However, with the following script, I can never get the peer's certificate. Please, provide clear answers with code as otherwise I tried many solutions and looked at previous posts with no hope. context = ssl.SSLContext() # ssl.create_default_context() #context.verify_mode = ssl.CERT_NONE #context.check_hostname = True s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) domain="google.com" ssl_sock = context.wrap_socket(s, server_hostname=domain) ssl_sock.connect((domain, 443)) print("====== peer's certificate ======") try: cert = ssl_sock.getpeercert() print ("issued to:", dict(itertools.chain(*cert["subject"]))["commonName"]) print ("issued by:", dict(itertools.chain(*cert["issuer"]))["commonName"]) print("issuance date:", cert["notBefore"]) print("expairy date: ", cert["notAfter"]) if (cert == None): print("no certificate") except Exception as e: print("Error:",e) ssl_sock.close() The problem is that I do not receive the peer's certificate when I use ssl.SSLContext() but when I use ssl.create_default_context() it is received correctly. However, I need to be able to receive self-signed certificates (i.e. unverified certificates) that's why I have to use ssl.SSLContext(). Thanks for the solution posted. But I need to parse the certificate even if it is not verified (self-signed). I trust this certificate and I need its info. I looked at several posts including this one. I did these steps: I took the .pem content of my server's certificate. I navigated to: C:\Python36\Lib\site-packages\certifi I opened cacert.pem which is placed in the dir…
downvote count: 0
linked to: http://stackoverflow.com/q/27835619
favorite count: 0
has title: Can't receive peer certificate in Python client using OpenSSL's ssl.SSLContext()
accepted answer: http://stackoverflow.com/a/62270009
type: Question
tagged with: network-programming
tagged with: sockets
linked to: http://stackoverflow.com/q/16899247
has answer: http://stackoverflow.com/a/68061625
tagged with: ssl
tagged with: x509certificate
tagged with: python
has answer: http://stackoverflow.com/a/50057929
possible better answer: http://stackoverflow.com/a/50057929
has answer: http://stackoverflow.com/a/62270009
type: AnsweredQuestion
answer count: 3
score: 1
upvote count: 1

http://stackoverflow.com/q/50047128
tagged with: json-rpc
has body: I have a working script that does the job just fine but I can't seem to figure out how to print the status code after the script runs. Can someone please review and provide some guidance and help? import requests import json url = 'http://10.3.198.100/ins' switchuser = 'user' switchpassword = 'password' myheaders = {'content-type' : 'application/json-rpc'} payload = [ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "vrf context management", "version": 1 }, "id": 1 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "ip route 192.168.255.0/24 10.3.198.130", "version": 1 }, "id": 2 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "copy run start", "version": 1 }, "id": 3 } ] response = requests.post(url, data = json.dumps(payload), headers = myheaders, auth = (switchuser, switchpassword)).json()
tagged with: http-status-codes
tagged with: http://stackoverflow.com/tag/json
tagged with: python
accepted answer: http://stackoverflow.com/a/50047256
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50047256
answer count: 1
has title: Print status code from the post in a json-rpc call
tagged with: request
type: Question

http://stackoverflow.com/comment/86955391
has text: Why do you want to save and reload it? It can't be saved but there might be options if what you need is for example the value of the loss and metrics at each epoch...
score: 1
comment on: http://stackoverflow.com/q/49969006
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50071165
answers question: http://stackoverflow.com/q/50071144
type: Answer
score: 1
downvote count: 0
has body: You can use pd.DataFrame.loc: new_df.loc[new_df['year'] &gt; 2018, 'year'] -= 100
upvote count: 1

http://stackoverflow.com/q/49954175
has body: Using github and a tutorial I adapt the given Code to read the temperature on my raspberry using an PT1000 sensor. I am using the mode "GPIO.BOARD", adapt the "writeRegister(0, 0xB2)" to "writeRegister(0, 0xA2)" and I also changed the programstart. Here's my current code: #!/usr/bin/python # The MIT License (MIT) # # Copyright (c) 2015 Stephen P. Smith # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import time, math import RPi.GPIO as GPIO # import numpy """Reading Temperature from the MAX31865 with GPIO using the Raspberry Pi. Any pins can be used. Numpy can be used to completely solve the Callendar-Van Dusen equation but it slows the temp reading down. I commented it out in the code. Both the quadratic formula using Callendar-Van Dusen equation (ignoring the 3rd and 4th degree parts of the polynomial) and the straight line approx. temperature is calculated with the quadratic formula one being the most accurate. """ def setupGPIO(): GPIO.setwarnings(False) GPIO.setmode(GPIO.…
type: Question
has comment: http://stackoverflow.com/comment/86925857
has comment: http://stackoverflow.com/comment/86936450
has comment: http://stackoverflow.com/comment/86965890
has comment: http://stackoverflow.com/comment/86934044
has comment: http://stackoverflow.com/comment/87154920
has comment: http://stackoverflow.com/comment/86933806
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86925864
has comment: http://stackoverflow.com/comment/86933649
has comment: http://stackoverflow.com/comment/86962959
has comment: http://stackoverflow.com/comment/86962978
tagged with: python
has title: Read PT1000 with Max31865 on Raspberry
has comment: http://stackoverflow.com/comment/86935681
has comment: http://stackoverflow.com/comment/86934523
has comment: http://stackoverflow.com/comment/86936689
tagged with: rtd
score: 0
tagged with: raspberry-pi
answer count: 0
has comment: http://stackoverflow.com/comment/86926013
has comment: http://stackoverflow.com/comment/86942538
linked to: http://stackoverflow.com/q/44931935
has comment: http://stackoverflow.com/comment/86924947
has comment: http://stackoverflow.com/comment/86937566
has comment: http://stackoverflow.com/comment/86934000
has comment: http://stackoverflow.com/comment/86934289
has comment: http://stackoverflow.com/comment/86925097
has comment: http://stackoverflow.com/comment/86934424

http://stackoverflow.com/comment/86989900
type: AnswerComment
comment on: http://stackoverflow.com/a/49986491
type: Comment
has text: Sure, I've updated my answer to include that aspect as well.
score: 0

http://stackoverflow.com/q/50072534
downvote count: 3
has comment: http://stackoverflow.com/comment/87181693
has comment: http://stackoverflow.com/comment/87161806
has answer: http://stackoverflow.com/a/50074486
has body: I am Using the Below code . But tesseract cant even ocr from this simple image. from PIL import Image import pytesseract image_file = Image.open("question.png") image_file = image_file.convert('1') # convert image to black and white image_file.save('question.png') text = pytesseract.image_to_string(image_file, lang = 'eng',config='-psm 6') print(text) Note: [1.] Tried to turn Pic into black and white [2.] Used psm QUESTION: How to OCR the given image correctly? Updates: I used this code now: from PIL import Image import pytesseract image_file = Image.open('purple.png') image_file = image_file.convert('L') # convert image to black and white image_file.save('question.png') image_file = Image.open('question.png') #without this line also the output is same text = pytesseract.image_to_string(image_file, lang = 'eng',config='-psm 6') print(text) Output: Please help me why it doesn't work.
favorite count: 0
type: Question
has title: Image with white-on-purple text not recognized by Tesseract, even converted to B&W
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87161933
tagged with: python
score: -1
tagged with: tesseract
has comment: http://stackoverflow.com/comment/87162019
has comment: http://stackoverflow.com/comment/87162218
answer count: 1

http://stackoverflow.com/comment/86858442
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49919811
type: Comment
has text: That's because it returns a series, which is another data type. This is really the way you should be working though, if you want to access single rows.

http://stackoverflow.com/a/50053132
has body: turtle.shape changes the shape of the turtle as it's drawing. To actually draw that shape where it is, you need turtle.stamp(): up() goto(-200,-200) down() shape("circle") shapesize(2,1,1) fillcolor("black") stamp() up() goto(-300,-100) down() shape("circle") shapesize(4,4,1) fillcolor("black") stamp() up() goto(-100,-100) down() shape("circle") shapesize(4,4,1) fillcolor("black") stamp()
answers question: http://stackoverflow.com/q/50052835
type: AcceptedAnswer
score: 3
upvote count: 3
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50052835

http://stackoverflow.com/a/50063334
score: 1
type: Answer
has body: You have a typo: you used dict where you meant dicts.
has comment: http://stackoverflow.com/comment/87143284
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87143524
answers question: http://stackoverflow.com/q/50063292

http://stackoverflow.com/q/50005195
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87484558
score: 0
has comment: http://stackoverflow.com/comment/88594976
has comment: http://stackoverflow.com/comment/87027024
has comment: http://stackoverflow.com/comment/87026979
has body: I have made a headless script in Python to preprocess Sentinel images and output NDVI link. The script runs on a remote server (linux container) to which I access via SSH connection. The script runs without errors when I launch it from the terminal using: python /home/foo/SentinelPPN.py However, it fails when launched automatically through chronejob. the output being: "cannot connect to X server". I get no other message and no indication of at what line of the script the error occurs I cannot pinpoint which operation requires the X server, since I do not use the GUI at all and no visual output is created during the script. In order to launch the script as headless, I use the following settings: import sys import os import qgis from qgis.core import * #from PyQt4.QtGui import * app = QgsApplication([],True, None) app.setPrefixPath("/usr", True) app.initQgis() sys.path.append('/usr/share/qgis/python/plugins') from processing.core.Processing import Processing Processing.initialize() the rest of the script is mainly processing modules launched using: processing.runalg("...") Could you help me understand why an X server is needed and how can I avoid that?
answer count: 1
has comment: http://stackoverflow.com/comment/87054794
tagged with: image-processing
tagged with: raster
accepted answer: http://stackoverflow.com/a/50796690
type: Question
has comment: http://stackoverflow.com/comment/87489483
has comment: http://stackoverflow.com/comment/87026915
has comment: http://stackoverflow.com/comment/87489732
tagged with: qgis
tagged with: python
has title: headless python script requires x-server to Run
has answer: http://stackoverflow.com/a/50796690

http://stackoverflow.com/q/49998281
has title: Specific object recognition. [Python]
has comment: http://stackoverflow.com/comment/87328811
type: Question
tagged with: object-recognition
possible better answer: http://stackoverflow.com/a/49999088
has comment: http://stackoverflow.com/comment/87014182
answer count: 2
upvote count: 2
downvote count: 0
has body: We have a technical task to recognize coal on the conveyor. Input data: Photo of conveyor with (or without) coal. Output data: Processed image with conveyor borders. (next step is recognizing volume of coal on the conveyor) We've tried to process image to black/white, increasing contrast, blurring, but there's too much "noises" on the image. That is the first question: how to get rid of unwanted pixels on the image? And the second question: how to properly detect conveyor (and then coal on it) on image? Example of source image:
favorite count: 0
tagged with: opencv
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87316946
has answer: http://stackoverflow.com/a/49999088
accepted answer: http://stackoverflow.com/a/50019185
has comment: http://stackoverflow.com/comment/87013508
tagged with: python
has answer: http://stackoverflow.com/a/50019185
tagged with: image-processing

http://stackoverflow.com/q/49960467
accepted answer: http://stackoverflow.com/a/49960507
has body: I am working with Django and AJAX, I have a template where people can select an option and then click a submit button. The button fires an Ajax function that sends the data to my view where it is processed and should return a value back to the template. The issue is when the post goes through, it hits the view, and nothing is returned to the template, I am not sure if this is because the view isn't getting any data, but it isn't firing any of my conditional statements, so it acts like its working but doesn't return anything. My HTML form: {% csrf_token %} How much do you want to sell? BTC ETH LTC Generate {{ address }} My AJAX $(document).on('submit', '#buy_form', function (e) { e.preventDefault() $.ajax({ type: 'POST', url:'/manage/buy/', data:{ currency:$('selected').val(), amount:$('#amount').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (){ } }) }); My Django View def buy_corsair(request): if request.method == 'POST': if request.POST.get('wanted') == 'generate_b': # Get the amount entered amount = request.POST.get('amount') # Generate a new B address new_b_address = client.create_address(b_account_id)['address'] # Point the address at the user request.user.user_address.b_address = new_b_address # Save address to current user request.user.user_address.save() # Pass the address to the template context = {'address': new_b_address} return render(request, context) urls.py urlpatterns = [ # Buy Page path('buy/', views.buy_corsair, name='buy'), ]
score: 1
possible better answer: http://stackoverflow.com/a/66623176
has answer: http://stackoverflow.com/a/49960507
has answer: http://stackoverflow.com/a/66623176
has title: Django view return value with AJAX
type: Question
answer count: 2
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
favorite count: 0
tagged with: ajax
type: AnsweredQuestion

http://stackoverflow.com/q/50020938
type: UnansweredQuestion
tagged with: mlab
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/50022504
has body: I have made a python flask app that I can use to manipulate a scoreboard. The app is hosted on heroku.com. The scoreboard is stored in a JSON file. First I just had the JSON file in the GitHub that Heroku makes for you. But then I found out that every couple of hours Heroku does a reset to your last commit. So any changes I would have made to the scoreboard.json would have been lost. So I came to the conclusion that I needed to use an actual database hosting site to host my scoreboard.json. I have chosen mLab for this. What command sends over a complete copy of a file in mLab back to the server so I can make changes to the file and then what command replaces the old file with the new file?
score: 0
has comment: http://stackoverflow.com/comment/87057499
tagged with: http://stackoverflow.com/tag/json
answer count: 1
type: Question
has title: How to get data and send data to mLab

http://stackoverflow.com/comment/109046901
comment on: http://stackoverflow.com/a/60571991
type: Comment
type: AnswerComment
has text: @KantushovHerman Thanks for your comment, I just realize that I forgot to close a parenthesis on line 28 (lost it while copy and paste form my jupyter-notebook). Anyway, I edited my answer, it should run right now.
score: 0

http://stackoverflow.com/q/50017534
has answer: http://stackoverflow.com/a/50017657
upvote count: 0
answer count: 2
downvote count: 3
tagged with: file
tagged with: loops
favorite count: 0
has answer: http://stackoverflow.com/a/50017611
type: Question
has title: how to get the number of occurrence of an expression in a file using python
has body: I have a code that read files and find the matching expression with the user input and highlight it, using findall function in regular expression. also i am trying to save in json file several information based on this matching. like : file name matching expression number of occurrence the problem is that the program read the file and display the text with highlighted expression but in the json file it save the number of occurrence as the number of lines. in this example the word this is the searched word it exist in the text file twice the result in the json file is = 12 ==> that is the number of text lines result of the json file and the highlighted text code: def MatchFunc(self): self.textEdit_PDFpreview.clear() x = self.lineEditSearch.text() TextString=self.ReadingFileContent(self.FileListSelected()) d = defaultdict(list) filename = os.path.basename(self.FileListSelected()) RepX='&lt;u&gt;&lt;b style="color:#FF0000"&gt;'+x+'&lt;/b&gt;&lt;/u&gt;' for counter , myLine in enumerate(filename): self.textEdit_PDFpreview.clear() thematch=re.sub(x,RepX,TextString) thematchFilt=re.findall(x,TextString,re.M|re.I) if thematchFilt: d[thematchFilt[0]].append(counter + 1) self.textEdit_PDFpreview.insertHtml(str(thematch)) else: self.textEdit_PDFpreview.insertHtml('No Match Found') OutPutListMetaData = [] for match , positions in d.items(): print ("this is match {}".format(match)) print("this is position {}".format(positions)) listMetaData = {"File Name":filename,"Searched Word":match,"Number Of Occurence":len(positions)} OutPutListMetaData.append(listMetaData) for p in positions: print("on line {}".format(p)) jsondata = json.dumps(OutPutListMetaData,indent=4) print(jsondata) folderToCreate = "search_result" today = time.strftime("%Y%m%d__%H-%M") jsonFileName = "{}_searchResult.json".format(today) if not(os.path.exists(os.getcwd() + os.sep + folderToCreate)): os.mkdir("./search_result") fpJ = os.path.join(os.getcwd()+os.sep+folderToCreate,jsonFileName) print(fpJ) with open(fpJ…
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: UnansweredQuestion
tagged with: regex
score: -3

http://stackoverflow.com/q/49985874
has title: CSV columns into a list of lists without using pandas
answer count: 4
linked to: http://stackoverflow.com/q/28283647
has answer: http://stackoverflow.com/a/49986036
possible better answer: http://stackoverflow.com/a/49986036
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86988268
has comment: http://stackoverflow.com/comment/86988184
has comment: http://stackoverflow.com/comment/86988216
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/86988118
accepted answer: http://stackoverflow.com/a/49986021
has answer: http://stackoverflow.com/a/49986114
downvote count: 1
has answer: http://stackoverflow.com/a/57229865
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49986021
tagged with: python
has comment: http://stackoverflow.com/comment/86988187
has body: Say, I have an Excel file exported as a CSV file, 5 rows and 3 columns, with the following values: 1.0 0.0 5.0 2.0 0.0 4.0 3.0 0.0 3.0 4.0 0.0 2.0 5.0 0.0 1.0 I need to get a list of lists with the sorted values of the correlative columns (in this example 3 columns, but it could be more...), like: OutputList = [[1.0, 2.0, 3.0, 4.0, 5.0], [0.0, 0.0, 0.0, 0.0, 0.0], [5.0, 4.0, 3.0, 2.0, 1.0]] Unfortunately I cannot use Pandas. All answers I found were related to pandas or listing values in rows instead of columns (or code snippets that didn't work for me).

http://stackoverflow.com/a/52717039
accepted answer of: http://stackoverflow.com/q/50042673
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50042673
has body: Chrome locks the database when it is open. I have closed it and its started working.
type: Answer
score: 0

http://stackoverflow.com/comment/86938656
has text: That gets more complicated... do you mean, simply see a sequence and try to extend it? Or do you mean add more parameters and try to control it somehow?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49959422
type: Comment

http://stackoverflow.com/q/50056878
tagged with: python-3.x
type: UnansweredQuestion
has title: byte string too long error in Python using pypyodbc 1.3.4
has answer: http://stackoverflow.com/a/54000792
tagged with: python
score: 4
has body: Getting byte string too long error while saving more than 127 characters in Unix environment while using pypyodbc 1.3.4 and Python Anaconda 3.5. Gone through this link Byte string too long PyPyOdbc and applied the fix as stated but still issue persists. I am trying to save more than 127 characters. Database is MS Sql Server. Column type is varchar MAX or nvarchar MAX (I tried with both). Saving 127 orless than 127 characters is fine and working. Thanks
tagged with: openshift
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/46134314
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/comment/87013064
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49997499
has text: If you don't need the `initializing` feature of the `make_initializable_iterator()`, I encourage you to use `make_one_shot_iterator()`. If you really rely on the initialization feature, you could try to encapsulate your iterator in an object to have the possibility to access it outside of the scope of the training function.
type: Comment

http://stackoverflow.com/a/50015181
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50014809
has comment: http://stackoverflow.com/comment/87084773
has body: {% url 'some-url-name' arg1=v1 arg2=v2 %} ref: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#url fixed: Your code is correct. The error hint that: arguments '('',)' not found. arguments '('',)'

http://stackoverflow.com/q/49918828
has comment: http://stackoverflow.com/comment/86862070
tagged with: python
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86855392
favorite count: 0
has comment: http://stackoverflow.com/comment/86862217
has comment: http://stackoverflow.com/comment/86854042
has body: import cv2 import numpy as np cap = cv2.VideoCapture(0) while True: _, frame = cap.read() # frame olarak goruntuyu aldık hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_yellow = np.array([20,0,0]) upper_yellow = np.array([40,255,255]) mask = cv2.inRange(hsv, lower_yellow, upper_yellow) res = cv2.bitwise_and(frame,frame, mask= mask) img = cv2.medianBlur(res, 5) cimg = cv2.cvtColor(img, cv2.COLOR_HSV2BGR) cimg = cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(cimg, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=20, maxRadius=30) circles = np.uint16(np.around(circles)) for i in circles[0, :]: cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3) cv2.imshow('detected circles', cimg) cv2.imshow('res',res) k = cv2.waitKey(5) &amp; 0xFF if k == 27: break cv2.destroyAllWindows() This is my codes. I want to detect traffic light on live stream by using image processing . Firstly I will detect yellow colour, after that I will find circle on mask image . I think, The error is occuring at the HoughCircles parameters. But there is a error called: Error: Traceback (most recent call last): File "/home/yavuzhan/PythonProgramlama/venv/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 52, in _wrapfunc return getattr(obj, method)(*args, **kwds) AttributeError: 'NoneType' object has no attribute 'round' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/media/yavuzhan/DATA/2017-2018/Otonom Araç Projesi/Dosya/Otonom Araç Yazılım/renkalgilama.py", line 30, in circles = np.uint16(np.around(circles))
upvote count: 0
score: -2
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/49923385
has comment: http://stackoverflow.com/comment/86855524
has answer: http://stackoverflow.com/a/49923385
has title: Traffic Light Detection by using opencv
type: Question
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86855443
has comment: http://stackoverflow.com/comment/86854302
has comment: http://stackoverflow.com/comment/86854212
tagged with: hough-transform

http://stackoverflow.com/comment/86916252
type: QuestionComment
comment on: http://stackoverflow.com/q/49948987
has text: @ely I don't understand your reasoning for this not being a duplicate at all. If the OP (or anyone with this same issue) were to actually look up the error they were getting, that is literally the title of the duplicate question. Consequently, I don't see how this question or answer adds any value. Unless one were to happen to be summing tuples, not import `functools.reduce`, and not perform a proper search with their error. But anyhow, agree to disagree I guess.
score: 0
type: Comment

http://stackoverflow.com/comment/86919768
type: QuestionComment
comment on: http://stackoverflow.com/q/49951360
score: 0
has text: What is happening? Simply no data being written? Also, why do you have a `try` clause with no `except`? that should raise a SyntaxError
type: Comment

http://stackoverflow.com/q/49928553
has body: Let's say I have a 2D-list of values [[00000.ppm,11],[00001.ppm,40],[00001.ppm,38],[00001.ppm,13],00002.ppm,39],[00003.ppm,4]] And I need to select every value from second dimension of list from list where file = "anything.ppm' So when I search for 00001.ppm I will get values "40" , "38" , "13" as output Also I need those values to be separated so I can compare them e.g. _class=13 if (value==_class): do something I was thinking if there is some other way, than just costly looping through whole list, since as a matter of fact - files are in order and their names are always an int increment. I just don't know how many of each files there is. Maybe it was a bad idea to read a .csv file into a list for this. .csv format 00000.ppm,11 00001.ppm,40 00001.ppm,38 00001.ppm,13 00002.ppm,39 00003.ppm,4
type: Question
has title: Python list select from second dimension where first dimension = condition
score: 0
accepted answer: http://stackoverflow.com/a/49928735
answer count: 3
has answer: http://stackoverflow.com/a/49928689
has comment: http://stackoverflow.com/comment/86873615
tagged with: python
tagged with: search
linked to: http://stackoverflow.com/q/4146009
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49929119
possible better answer: http://stackoverflow.com/a/49929119
tagged with: list
has answer: http://stackoverflow.com/a/49928735

http://stackoverflow.com/comment/87086124
type: QuestionComment
score: 0
has text: It is working once I super'd the mousePressEvent. I admit my knowledge of "super" is pretty limited so I can't explicitly tell you WHY it works... but it does! Curiously if I call a specific child with self.children()[1].rect() everything works as expected. So why is self.childrenRect() not working? Is this just a bug?
comment on: http://stackoverflow.com/q/50034906
type: Comment

http://stackoverflow.com/comment/86898269
type: QuestionComment
has text: `__add__` needs to return a value.
score: 3
type: Comment
comment on: http://stackoverflow.com/q/49941192

http://stackoverflow.com/comment/87121467
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50052478
has text: The function mutates the passes-in list, sorting it in-place. Do you understand the difference between the built in `list.sort` and `sorted`? If so, this is the same as `list.sort`. If not, we can find a duplicate question that explains the difference, or write an answer if there isn’t one.
score: 1

http://stackoverflow.com/q/49963436
possible better answer: http://stackoverflow.com/a/49963548
type: Question
has comment: http://stackoverflow.com/comment/86943001
answer count: 3
has answer: http://stackoverflow.com/a/49963562
score: 1
downvote count: 0
upvote count: 1
has title: Counting repeating dictionaries, then appending a count key and it's value
favorite count: 0
has answer: http://stackoverflow.com/a/49963548
has comment: http://stackoverflow.com/comment/86943031
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49963501
has body: I have a list of dictionaries: flist = [ {'ext' : '.txt', 'name' : 'file1'}, {'ext' : '.png', 'name' : 'picture1'}, {'ext' : '.txt', 'name' : 'file1'}, {'ext' : '.py', 'name' : 'script'}, ] I want to create a new list which has a count of how many times the item showed up in the first list. summary = [] for item in flist: if item not in summary: item['count'] = 1 summary.append(item) else: item['count'] += 1 for i in summary: print i I want the output list to look like this: {'count': 2, 'ext': '.txt', 'name': 'file1'} {'count': 1, 'ext': '.png', 'name': 'picture1'} {'count': 1, 'ext': '.py', 'name': 'script'} But what ends up happening is I get all 4 items, with "count: 1". I assume because it's adding count : 1 the first time, which makes that dict unique. {'count': 1, 'ext': '.txt', 'name': 'file1'} {'count': 1, 'ext': '.png', 'name': 'picture1'} {'count': 1, 'ext': '.txt', 'name': 'file1'} {'count': 1, 'ext': '.py', 'name': 'script'}
tagged with: python
has answer: http://stackoverflow.com/a/49963501
has comment: http://stackoverflow.com/comment/86942908

http://stackoverflow.com/q/50016979
accepted answer: http://stackoverflow.com/a/50017246
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50017246
tagged with: python
tagged with: matlab
tagged with: numpy
score: 0
answer count: 1
upvote count: 1
has title: Plotting a function using Python where the x and y values are represented in terms of variables
downvote count: 1
favorite count: 0
tagged with: plot
type: Question
type: AnsweredQuestion
has body: I have a function of the form y = a*cos(2*pi*xc) Now I would like to plot this from 0 to 10c and get the output in terms of a. This means I would not like to give a specific value to a,b,c rather let the function plot be in terms of a,b,c. To give you an idea..say, x = [0, c/4, c/2, 3c/4....10c] correspondingly y = [a, 0, -a, 0, ....a] So the plot will have the x-axis in terms of multiples of c and y -axis will be in multiples of a Is there a name for plotting in terms of variables like this?

http://stackoverflow.com/comment/87135451
score: 0
type: Comment
type: QuestionComment
has text: @roganjosh: I reopened this question because the problem it asks about is a difference between two pieces of software. It is not a question about how floating point works. Please do not promiscuously close questions as duplicates of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
comment on: http://stackoverflow.com/q/50050757

http://stackoverflow.com/q/49966547
tagged with: python
has answer: http://stackoverflow.com/a/62022868
has comment: http://stackoverflow.com/comment/89588229
upvote count: 47
has answer: http://stackoverflow.com/a/51165784
has answer: http://stackoverflow.com/a/62777593
has answer: http://stackoverflow.com/a/75830362
downvote count: 0
has answer: http://stackoverflow.com/a/50433017
has answer: http://stackoverflow.com/a/72645687
favorite count: 0
score: 47
has answer: http://stackoverflow.com/a/71203549
type: Question
answer count: 8
has title: PIP 10.0.1 - Warning "Consider adding this directory to PATH or..."
has body: The script flake8.exe is installed in 'c:\users\me\appdata\local\programs\python\python36-32\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Did some research on this and it seems like some sort of recurring issue. One fix recommends removing trailing slashes from the environment variable. Any other ideas? This occurs every time I install via PIP I am running python 3.6
has answer: http://stackoverflow.com/a/66518330
type: UnansweredQuestion
tagged with: pip

http://stackoverflow.com/q/50009955
has answer: http://stackoverflow.com/a/50010566
type: Question
linked to: http://stackoverflow.com/q/40804265
has body: I am looking for help with Groupby + Transform. I realize combined they are a very powerful tool, but am having trouble finding documentation/specific situations on what I want to accomplish. I would like to calculate the time delta based upon groups defined by multiple arguments. Specifically, I would like a column that displays the Assigned to Approved time difference by Casenumber AND Site AND only if there are both Assigned and Approval present. Please see below for my data set and code so far: Dataset (start) Casenumber Site CreatedDate NewValue 1 A 2018-03-30 16:47:03 Approved 2 A 2018-04-02 19:24:43 Assigned 2 A 2018-04-02 25:24:43 Delayed 2 A 2018-04-02 20:49:45 Approved 2 B 2018-04-02 19:24:43 Assigned 2 B 2018-04-02 22:49:45 Approved 2 B 2018-04-02 25:24:43 Delayed Dataset (finish) Casenumber Site CreatedDate NewValue Diff 1 A 2018-03-30 16:47:03 Approved N/A 2 A 2018-04-02 19:24:43 Assigned 0 days 0 hours 2 A 2018-04-02 20:49:45 Approved 0 days 1:25:02 2 A 2018-04-02 25:24:43 Delayed N/A 2 B 2018-04-02 19:24:43 Assigned 0 days 0 hours 2 B 2018-04-02 22:49:45 Approved 0 days 3:25:02 2 B 2018-04-02 25:24:43 Delayed N/A What I've got so far (df['Diff'] = df['CreatedDate'] - (df.groupby(['Casenumber', 'Site'])['CreatedDate'].transform('first'))) Thank you for any help!
tagged with: python
accepted answer: http://stackoverflow.com/a/50108149
has answer: http://stackoverflow.com/a/50108149
has title: Python Groupby Transform Multiple Arguments
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas-groupby
possible better answer: http://stackoverflow.com/a/50010566

http://stackoverflow.com/q/50037189
type: Question
upvote count: 4
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87093900
has comment: http://stackoverflow.com/comment/87093833
has comment: http://stackoverflow.com/comment/87090856
downvote count: 1
tagged with: docker
has title: Impossible to use coinbase API into a docker container
score: 3
has comment: http://stackoverflow.com/comment/87098649
tagged with: coinbase-api
tagged with: python
has comment: http://stackoverflow.com/comment/87100002
has body: I don't understand why when I'm tring to use my python coinbase app into a docker container, I allways get a coinbase.wallet.error.AuthenticationError: APIError(id=authentication_error): invalid api key I've checked my API key is correct and present event if I print it (on the docker container log) If a run the same app with gunicorn directly it's working like a charm. Any Idea of what's happening here? Here is the Dockerfile for the flask app FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /opt/services/flaskapp/src # We copy the requirements.txt file first to avoid cache invalidations COPY requirements.txt /opt/services/flaskapp/src/ COPY . /opt/services/flaskapp/src WORKDIR /opt/services/flaskapp/src RUN ls RUN pip install -e . RUN pip install -r requirements.txt RUN pip install uwsgi RUN myapp init RUN tox EXPOSE 5090 CMD ["gunicorn", "-b 0.0.0.0:5090", "myapp.wsgi:app"] Here is the Docker compose version: '3.2' services: db: image: "postgres:9.6.5" volumes: - "dbdata:/var/lib/postgresql/data" env_file: - ./myapp/.env networks: - traefik-net flaskapp: build: . env_file: - ./myapp/.env privileged: true volumes: - .:/opt/services/flaskapp/src networks: - traefik-net depends_on: - db nginx: image: "nginx:1.13.5" ports: - "4280:80" volumes: - ./conf.d:/etc/nginx/conf.d networks: - traefik-net depends_on: - flaskapp networks: traefik-net: driver: bridge volumes: dbdata Here is the app code that raise the build_api_error cb_helper = CoinbaseHelper( account, os.getenv("CB_API_KEY"), os.getenv("CB_API_SECRET") ) print(os.getenv("CB_API_KEY")) cb_wallet = cb_helper.create_address() Result flaskapp_1 | Traceback (most recent call last): flaskapp_1 | File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__ flaskapp_1 | return self.wsgi_app(environ, start_response) flaskapp_1 | File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app flaskapp_1 | response = self.handle_exception(e) flaskapp_1 | File "/usr/local/lib/pyt…
has comment: http://stackoverflow.com/comment/87094645
has comment: http://stackoverflow.com/comment/87094776
has comment: http://stackoverflow.com/comment/92066427
favorite count: 0

http://stackoverflow.com/a/49984924
type: AcceptedAnswer
downvote count: 0
has body: You can set up the task time limits as per documentation If you are going to set it on particular task you can use task_time_limit or task_soft_time_limit depending on your usage characteristics
accepted answer of: http://stackoverflow.com/q/49983921
type: Answer
answers question: http://stackoverflow.com/q/49983921
upvote count: 4
score: 4

http://stackoverflow.com/comment/87006248
type: Comment
type: QuestionComment
has text: Update the question exactly which step are you trying to _Automate_ through **tried the following code** as in `driver.find_elements_by_css_selector('#pageGrid')`
score: 0
comment on: http://stackoverflow.com/q/49994941

http://stackoverflow.com/comment/86961364
comment on: http://stackoverflow.com/a/49972657
score: 0
type: AnswerComment
has text: Doesnt letters refer to each variable in the list ? So when that particular variable is equal to what i am checking it against i change the value of the variable?
type: Comment

http://stackoverflow.com/q/50001154
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87018430
tagged with: python
has comment: http://stackoverflow.com/comment/87018280
duplicate of: http://stackoverflow.com/q/273192
linked to: http://stackoverflow.com/q/35046004
has title: Error in subprocess.call in python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87018390
has body: I have a problem when run the code below in Window OS using Python 3.6 32bit. subprocess.call(["mkdir", "-p", path_results + "it" + str(actual_iteration)]) The error is Trackback : ......\Python36-32\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified. Anyone please tell me what's wrong and help me fix it. Thank you.
type: Question
has comment: http://stackoverflow.com/comment/87018556
linked to: http://stackoverflow.com/q/273192

http://stackoverflow.com/q/49984802
tagged with: python
tagged with: web-services
possible better answer: http://stackoverflow.com/a/60993719
type: Question
has answer: http://stackoverflow.com/a/60993719
has body: I have a fairly simple use-case but i'm not understanding the error message i'm receiving. I'm using the requests and pyral modules, pyral (http://pyral.readthedocs.io/en/latest/interface.html#) is really just a wrapper for Rally's Restful api. My goal is to get a file (attachment) from a Rally (a CA product) UserStory and store it to a local file system. For context, here is my environment setup (authenticate to Rally and create an object). I've obviously removed authentication information. from pyral import Rally, rallyWorkset options = [arg for arg in sys.argv[1:] if arg.startswith('--')] args = [arg for arg in sys.argv[1:] if arg not in options] server, user, password, apikey, workspace, project = rallyWorkset(options) rally = Rally(server='rally1.rallydev.com', user='**********', password='***********', apikey="**************", workspace='**************', project='**************', server_ping=False) After that I get a response object for just one user story (see the query for US845), i do this just to simplify the problem. r = rally.get('UserStory', fetch = True, projectScopeDown=True, query = 'FormattedID = US845') and then I use the built-in iterator to get the user story from the RallyRESTResponse object. us = r.next() from there it feels like I should be able to easily use the getAttachment() method that accepts a artifact (us) and filename (name of an attachment). I'm able to use getAttachmentNames(us) to return a list of attachment names. The issue arrises when i try something like attachment_names = rally.getAttachmentNames(us) #get attachments for this UserStory attachment_file = rally.getAttachment(us, attachment_names[0]) #Try to get the first attachment returns an error like this Traceback (most recent call last): File "&lt;ipython-input-81-a4a342a59c5a&gt;", line 1, in &lt;module&gt; attachment_file = rally.getAttachment(us, attachment_names[0]) File "C:\Miniconda3\lib\site-packages\pyral\restapi.py", line 1700, in getAttachment att.Content = base64…
type: AnsweredQuestion
tagged with: rally
has title: PyRal getAttachment
tagged with: pyral
favorite count: 0
score: 2
accepted answer: http://stackoverflow.com/a/49988876
upvote count: 2
tagged with: encode
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49988876

http://stackoverflow.com/a/49929335
answers question: http://stackoverflow.com/q/49928443
score: 0
has body: One way is to convert your Date column to str, concatenate with Time, then pass to pd.to_datetime: df['DateTime'] = pd.to_datetime(df['Date'].astype(str) + ' ' + df['Time']) print(df) Date Time DateTime 0 2018-04-10 13:03:00 2018-04-10 13:03:00 1 2018-04-10 14:01:00 2018-04-10 14:01:00
type: Answer

http://stackoverflow.com/a/49935434
has body: What is the reason you are not able to install the packages on your server? You can try using virtualenv or install the required packages in the same folder as your code and deploy the entire folder to the server: pip install -t &lt;dir&gt;
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49934177

http://stackoverflow.com/comment/86925864
comment on: http://stackoverflow.com/q/49954175
has text: Using a 100 Ohm resistor (incl. shorting) i get the following output: "Config register byte: ff [HEX] RTD ADC Code: 32767 --- PT1000 Resistance: 399.988 Ohms Straight Line Approx. Temp: 767.96875 --- Callendar-Van Dusen Temp (degC > 0): -153.74844419335676" I also get this output if nothing is connected to the Max31865. I also get this result using another Max31865 modul.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86932524
comment on: http://stackoverflow.com/q/49958062
has text: @chepner I've added sample input and output in the question.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49970810
answer count: 1
duplicate of: http://stackoverflow.com/q/19339
type: Question
tagged with: http://stackoverflow.com/tag/csv
has title: Best way to CSV output a vertical list in a horizontal list
linked to: http://stackoverflow.com/q/19339
has body: Python newbie here. I've used XPath to extract some data from a website which gives me a list in a list that looks like this: [['1','2','3'],['4','','6'],['7','8','9']] Currently, when I export this to CSV, each of the 'inner' lists is displayed in a single cell like: Cell A1 ['1', '2', '3']) Cell B1 ['4', '', '6'] Cell C1 ['7', '8', '9'] which means I would have to remove the unwanted brackets and quotes, Text-to-Columns and transpose to get what I want, which is this: 1,4,7 2,,8 3,6,9 What can I do/use to do this?
tagged with: python
accepted answer: http://stackoverflow.com/a/49970837
has answer: http://stackoverflow.com/a/49970837
tagged with: list
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49932871
has body: I have a list of CSV data like below: Jim 57 83 55 78 John 98 91 80 Michael 61 88 80 60 Harry 92 58 50 57 James 51 97 52 53 and I want to return as without importing CSV module, the blank value I want to print None and double quote around name and no quote around integers: [("Jim",57,None,83,55,78), ("John",None,98,91,80,None), ("Michael",61,None,88,80,60)].... I have tried some code: def student_mark(studentfile): f = open (studentfile, 'r') list = [] for line in f: list.append(tuple(line.strip().split(','))) print (list) studentfile = " users/.../units.csv" student_mark(studentfile) But it now results as: [('Jim','57','','83','55','78'), ('John','','98','91','80',''), ('Michael','61','','88','80','60') Anyone can help me out?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49934793
score: 0
accepted answer: http://stackoverflow.com/a/49936494
answer count: 2
has comment: http://stackoverflow.com/comment/86881513
has comment: http://stackoverflow.com/comment/86890121
has answer: http://stackoverflow.com/a/49934793
has comment: http://stackoverflow.com/comment/86881552
has title: import csv file and return two lists for string and integer respectively without csv module in python
type: Question
has comment: http://stackoverflow.com/comment/86881584
has comment: http://stackoverflow.com/comment/86889923
has answer: http://stackoverflow.com/a/49936494
tagged with: python
has comment: http://stackoverflow.com/comment/86881800

http://stackoverflow.com/comment/108081796
score: 0
comment on: http://stackoverflow.com/a/50064004
type: Comment
type: AnswerComment
has text: @YOBEN_S Hi Yoben, i stuck on a interpolation question that i have to fix it by the end of the week ! can you please look at my latest question and give me any tip if it's possible please ?

http://stackoverflow.com/a/49975924
answers question: http://stackoverflow.com/q/49973222
downvote count: 1
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/111797316
score: -1
has comment: http://stackoverflow.com/comment/86971167
has body: Just use a pool from either multiprocessing.Pool or concurrent.futures. The pool allows you to set how many workers you want running at the same time. This means you will have maximum max_workers files downloaded at the same time. As the download/upload is sequential (you cannot start an upload until the download is complete), you gain no value from running them in two separated threads/processes. Just join the two operations in a single job unit and then run multiple jobs concurrently. Moreover, as long as you just need to download/upload files (IO bound operations) you'd better use threads instead of processes as they are more lightweight. from concurrent.futures import ThreadPoolExecutor list_of_sha1s = ['foobar', 'foobaz'] def worker(sha1): path = save_file_from_sofa(sha1) upload_file(path) return sha1 with ThreadPoolExecutor(max_workers=10) as pool: for sha1 in pool.map(worker, list_of_sha1s): print("Done SHA1: %s" % sha1)

http://stackoverflow.com/q/50057928
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/50061224
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/15182696
accepted answer: http://stackoverflow.com/a/50057960
has body: I am trying to call some functions and return the results in the browser but I get a 500 Internal Server Error. I have this code following this answer from flask import Flask app = Flask(__name__) @app.route("/") def message(): return "Message from python function named 'message' " @app.route("/user/&lt;username&gt;") def user(username): return "Username is %s " % username @app.route("/userpass/&lt;username&gt;/&lt;password&gt;") def userpass(username, password): return "User is %s and password %s " % username % password and I am calling the first one just by using http://127.0.0.1:5000 the second one using http://127.0.0.1:5000/user/test and the last one by using http://127.0.0.1:5000/userpass/test/123 and I get the error 500. What's the problem with the last call?
has comment: http://stackoverflow.com/comment/87132352
has answer: http://stackoverflow.com/a/50057960
tagged with: flask
type: Question
possible better answer: http://stackoverflow.com/a/50061224
has title: Two arguments in Flask
has comment: http://stackoverflow.com/comment/87132603

solver
tags question: http://stackoverflow.com/q/49970098
tags question: http://stackoverflow.com/q/50017784
tag name: solver
type: Tag

http://stackoverflow.com/comment/87041112
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50012242
score: 0
has text: I can, after running `pip install google-api-python-client`, successfully execute `from apiclient import discovery` in both an interactive session and from a file. Are you sure you've followed the directions for installing the module properly?

http://stackoverflow.com/a/49983963
answers question: http://stackoverflow.com/q/49981538
has comment: http://stackoverflow.com/comment/87019357
has comment: http://stackoverflow.com/comment/87014822
type: AcceptedAnswer
downvote count: 0
has body: I would suggest to pass through the computation of the rotated bounding box of the contour instead of trying to identify fixed shapes. In my try, the script identifies a box-like figure and calculates its contourArea, then it selects the figures that possess a big area. This should solve your problem, let us know if it doesn't. cv2.namedWindow('image', cv2.WINDOW_NORMAL) image = cv2.imread("sample1600.jpg") ratio = image.shape[0] / 300.0 image = imutils.resize(image, height = 800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) ret, th = cv2.threshold(gray,220,235,1) edged = cv2.Canny(th, 25, 200) im2, cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key = cv2.contourArea, reverse = True) for c in cnts: box = cv2.minAreaRect(c) box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box) box = np.array(box, dtype="int") if cv2.contourArea(box) &gt; 70000: cv2.drawContours(image, [box], -1, (0, 255, 0), 2) cv2.imshow("Image", image) cv2.waitKey(0) This is the output: EDIT: I don't know if this is the right solution, probably there are some other. I encourage the other users to share their approaches. @Sylvain, here's another try with some tuning of the parameters: decreasing of the threshold to 210; removing of the canny function (it messes with the complex patterns of some images; calculation of the image area and playing around with the limit of the contour to be returned. In this particular example I imposed the contour to be larger than 1/10 of the image and smaller than 2/3. image = cv2.imread(img) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) ret, th = cv2.threshold(gray,210,235,1) im2, cnts, hierarchy = cv2.findContours(th.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key = cv2.contourArea, reverse = True) for c in cnts: box = cv2.minAreaRect(c) box = cv2.cv.BoxPoints(box) if imutils.is_cv2…
upvote count: 17
has comment: http://stackoverflow.com/comment/87003125
has comment: http://stackoverflow.com/comment/87039505
accepted answer of: http://stackoverflow.com/q/49981538
type: Answer
score: 17

http://stackoverflow.com/comment/86855692
comment on: http://stackoverflow.com/a/49919271
has text: in spite of `if (mo[i]<0.2 and mo[i]>0.32) or num>10:` it goes beyond `0.32` and `0.2`. why?
type: Comment
score: 0
type: AnswerComment

setup.py
tags question: http://stackoverflow.com/q/50026260
tags question: http://stackoverflow.com/q/49994133
tags question: http://stackoverflow.com/q/49918309
tags question: http://stackoverflow.com/q/49988464
tag name: setup.py
type: Tag
tags question: http://stackoverflow.com/q/50011417

http://stackoverflow.com/q/50047653
score: 5
has answer: http://stackoverflow.com/a/52579347
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87127022
has comment: http://stackoverflow.com/comment/87117215
tagged with: python
has comment: http://stackoverflow.com/comment/87124794
has title: Set "training=False" of "tf.layers.batch_normalization" when training will get a better validation result
upvote count: 6
has body: I use TensorFlow to train DNN. I learned that Batch Normalization is very helpful for DNN , so I used it in DNN. I use "tf.layers.batch_normalization" and follow the instructions of the API document to build the network: when training, set its parameter "training=True", and when validate, set "training=False". And add tf.get_collection(tf.GraphKeys.UPDATE_OPS). Here is my code: # -*- coding: utf-8 -*- import tensorflow as tf import numpy as np input_node_num=257*7 output_node_num=257 tf_X = tf.placeholder(tf.float32,[None,input_node_num]) tf_Y = tf.placeholder(tf.float32,[None,output_node_num]) dropout_rate=tf.placeholder(tf.float32) flag_training=tf.placeholder(tf.bool) hid_node_num=2048 h1=tf.contrib.layers.fully_connected(tf_X, hid_node_num, activation_fn=None) h1_2=tf.nn.relu(tf.layers.batch_normalization(h1,training=flag_training)) h1_3=tf.nn.dropout(h1_2,dropout_rate) h2=tf.contrib.layers.fully_connected(h1_3, hid_node_num, activation_fn=None) h2_2=tf.nn.relu(tf.layers.batch_normalization(h2,training=flag_training)) h2_3=tf.nn.dropout(h2_2,dropout_rate) h3=tf.contrib.layers.fully_connected(h2_3, hid_node_num, activation_fn=None) h3_2=tf.nn.relu(tf.layers.batch_normalization(h3,training=flag_training)) h3_3=tf.nn.dropout(h3_2,dropout_rate) tf_Y_pre=tf.contrib.layers.fully_connected(h3_3, output_node_num, activation_fn=None) loss=tf.reduce_mean(tf.square(tf_Y-tf_Y_pre)) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_step = tf.train.AdamOptimizer(1e-4).minimize(loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i1 in range(3000*num_batch): train_feature=... # Some processing train_label=... # Some processing sess.run(train_step,feed_dict={tf_X:train_feature,tf_Y:train_label,flag_training:True,dropout_rate:1}) # when train , set "training=True" , when validate ,set "training=False" , get a bad result . However when train , set "training=False" ,when validate ,set "training=False…
tagged with: batch-normalization
answer count: 2
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/87126953
has comment: http://stackoverflow.com/comment/87125243
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87127063
has answer: http://stackoverflow.com/a/50071072

aggregate
tags question: http://stackoverflow.com/q/50009145
tags question: http://stackoverflow.com/q/50026341
tag name: aggregate
type: Tag
tags question: http://stackoverflow.com/q/49943882

http://stackoverflow.com/comment/86871964
comment on: http://stackoverflow.com/q/49927619
type: Comment
type: QuestionComment
has text: I don't see anything wrong here, although the dropout rate may be a bit too high.
score: 0

http://stackoverflow.com/q/50047668
has title: Using Selenium Python to get value embedded in react-text code
has comment: http://stackoverflow.com/comment/87116745
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/87118622
has comment: http://stackoverflow.com/comment/87141857
has comment: http://stackoverflow.com/comment/87119687
has comment: http://stackoverflow.com/comment/87115706
has answer: http://stackoverflow.com/a/50054217
has body: enter image description hereI'm using Selenium in Python to crawl some data from Internet for my works. However, I can't manage to get the tel number (i.e. 04 81 68 30 45) from this HTML source code: '&lt;a class="_2sNbI ObuDQ GXQkc _2BP2c" href="tel:0481683045" title="Contact le vendeur" &gt;&lt;!-- react-text: 619 --&gt;04 81 68 30 45&lt;!-- /react-text --&gt;&lt;/a&gt;' I tried that code but it does not work with react-text code. I got an empty string from selenium import webdriver driver = webdriver.Chrome('chromedriver') driver.get('https://www.leboncoin.fr/locations/1107498086.htm/') try: elem = driver.find_element_by_xpath('//div[@class="_2sPVF"]//button') elem.click() except: pass elem = driver.find_element_by_xpath('//span[@class="_28rnK"]/a') tel = elem.text print('Contact:', tel) If anyone have any idea how to do that, I will be very grateful. ***Thank for JeffC's answer, the problem is resolved, it is turned out that there are 5 hidden elements in that xpath (the tel number is the 4th one).
has comment: http://stackoverflow.com/comment/87115782
downvote count: 1
has comment: http://stackoverflow.com/comment/87116895
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/87111504
type: UnansweredQuestion
answer count: 1
tagged with: python
score: -1

http://stackoverflow.com/comment/87012220
has text: Thank you so much for your explanation and answer. That's exactly what I wanted. It's my bad that I made it so complex. Thank you again.. :D
comment on: http://stackoverflow.com/a/49984884
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87011487
comment on: http://stackoverflow.com/q/49996737
type: Comment
type: QuestionComment
has text: You are using a function instead of a StringVar as a textvariable? Based on which documentation / approach?You would print them out to debug your code. Code lines do not get "skipped". Use a `tk.StringVar` instead of a function first. btw - if you want to get the text do not use the Entry Widget. Use its `get` method. and please have a look at the documentation available and the object model of python / tkinter.
score: 0

http://stackoverflow.com/a/50054124
has body: You can use this: one, two, three = e.split(':') print 'one = "%s", two = "%s"' % (one, two)
answers question: http://stackoverflow.com/q/50054003
type: Answer
score: 0

http://stackoverflow.com/a/50032333
answers question: http://stackoverflow.com/q/50031780
upvote count: 3
has body: Assuming both df1 and df2 are sorted in ascending order by the datetime_start column (it appears so), then you just need to go through each row of the two dataframes once, resulting in an O(n) running time, rather than the current O(n^2) due to pairwise row comparison. The following code illustrates the idea. The key point is using iterators it1 and it2 to point to the current row. Since the dataframes are sorted, if row1 is already later in time than row2, we are sure that the next row in df1 is later than row2. Harder to explain in words than code: def main(df1, df2): for cat in df2.catg.unique().tolist(): df1[cat] = 0 it1 = df1.iterrows() it2 = df2.iterrows() idx1, row1 = next(it1) idx2, row2 = next(it2) while True: try: r1 = Range(start=row1.datetime_start, end=row1.datetime_end) r2 = Range(start=row2.datetime_start, end=row2.datetime_end) if r2.end &lt; r1.start: # no overlap. r2 before r1. advance it2 idx2, row2 = next(it2) elif r1.end &lt; r2.start: # no overlap. r1 before r2. advance it1 idx1, row1 = next(it1) else: # overlap. overlap(row1, row2) must &gt; 0 df1.loc[idx1, row2.catg] += overlap(row1, row2) # determine whether to advance it1 or it2 if r1.end &lt; r2.end: # advance it1 idx1, row1 = next(it1) else: # advance it2 idx2, row2 = next(it2) except StopIteration: break main(df1, df2)
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/comment/86910957
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49946528
type: QuestionComment
has text: @lightalchemist- EDIT 2 is meant for your solution. It did not solve the problem entirely and that is because it was my fault. I agree on that. But I could extract the mask using your method. But thank you for your approach.

http://stackoverflow.com/comment/86914421
type: AnswerComment
comment on: http://stackoverflow.com/a/49948878
type: Comment
has text: Yes, but that is essentially creating a dense matrix with 1's and 0's (in this example it's just a dense vector, but this is just one row of many). My question is if I can skip this step. In other words, is there a way to tell `csr_matrix()` what value (in my case an empty string) represents `null` or `0` or whatever value is supposed to be "sparsed away"?
score: 0

http://stackoverflow.com/comment/86974707
has text: @SushovanMandal - Just test your solution and working nice :(
comment on: http://stackoverflow.com/a/49979275
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87475189
type: Comment
type: QuestionComment
score: 0
has text: @Manngo Thank you a lot. Do you know something which is more suitable for this? Otherwise, I would try to develop features of future and past values beforehand.
comment on: http://stackoverflow.com/q/49944010

http://stackoverflow.com/comment/86966628
score: 0
type: AnswerComment
has text: Still not working, probably I have some software issue, because if I paste the code directly in the GUI script it will run perfectly.
comment on: http://stackoverflow.com/a/49941780
type: Comment

http://stackoverflow.com/a/50311270
answers question: http://stackoverflow.com/q/49931096
type: Answer
accepted answer of: http://stackoverflow.com/q/49931096
upvote count: 29
has body: The dataclass decorator examines the class to find fields, by looking for names in __annotations__. It is the presence of annotation which makes the field, so, you do need an annotation. You can, however, use a generic one: @dataclass class Favs: fav_number: int = 80085 fav_duck: 'typing.Any' = object() fav_word: str = 'potato'
type: AcceptedAnswer
downvote count: 1
score: 28

http://stackoverflow.com/comment/86892529
type: QuestionComment
has text: My examples are in Python, but just to change the locale for the current process, not the whole system. I don't recommend doing the latter at all. The user can easily change the locale settings. Programs shouldn't be messing with this.
comment on: http://stackoverflow.com/q/49936803
type: Comment
score: 0

http://stackoverflow.com/q/49929821
tagged with: mechanicalsoup
type: Question
has title: API using MechanicalSoup is failing to submit form - NoneType
has answer: http://stackoverflow.com/a/49930123
type: UnansweredQuestion
has body: I'm using a python API that uses MechanicalSoup to do most of its functions and all of a sudden, it won't work anymore. I feel like the website it's utilizing may have changed or something. Here is the API's code: def trade(self, symbol, orderType, quantity, priceType="Market", price=False, duration=Duration.good_cancel): """ Executes trades on the platform. See the readme.md file for examples on use and inputs. Returns True if the trade was successful. Else an exception will be raised. client.trade("GOOG", Action.buy, 10) client.trade("GOOG", Action.buy, 10, "Limit", 500) """ br = self.br trade_page = self.fetch('/simulator/trade/tradestock.aspx') trade_form = trade_page.soup.select("form#orderForm")[0] # input symbol, quantity, etc. trade_form.select("input#symbolTextbox")[0]["value"] = symbol trade_form.select("input#quantityTextbox")[0]["value"] = str(quantity) # input transaction type [option.attrs.pop("selected", "") for option in trade_form.select("select#transactionTypeDropDown")[0]("option")] trade_form.select("select#transactionTypeDropDown")[0].find("option", {"value": str(orderType.value)})["selected"] = True # input price type [radio.attrs.pop("checked", "") for radio in trade_form("input", {"name": "Price"})] trade_form.find("input", {"name": "Price", "value": priceType})["checked"] = True # input duration type [option.attrs.pop("selected", "") for option in trade_form.select("select#durationTypeDropDown")[0]("option")] trade_form.select("select#durationTypeDropDown")[0].find("option", {"value": str(duration.value)})["selected"] = True # if a limit or stop order is made, we have to specify the price if price and priceType == "Limit": trade_form.select("input#limitPriceTextBox")[0]["value"] = str(price) elif price and priceType == "Stop": trade_form.select("input#stopPriceTextBox")[0]["value"] = str(price) prev_page = br.submit(trade_form, trade_page.url) prev_form = prev_page.soup.select("form", {"name": "simTradePreview"}) br.submit(prev_form, prev_pa…
score: 0
answer count: 1
tagged with: python

http://stackoverflow.com/comment/102774943
type: AnswerComment
comment on: http://stackoverflow.com/a/56564088
has text: Yes, it contains 1 & -1. I may also be wrong, but how I understand it is that if scoring is precision, recall or f1 (which reflect how good outlier detection is and not how many datapoints were predicted correctly) scoring gridsearchcv will evaluate parameters based on this score.
type: Comment
score: 0

http://stackoverflow.com/comment/138844584
has text: Code for my above comment: [Attempt This Online!](https://ato.pxeger.com/run?1=hVFBTsMwEBTXfcXebIdQNYqEUKW-pOrBNGtqqbaD7UhUiBu_4NILPIrXsI5TOOKTdzwzu-P9-BrP-Rj85fI5ZXP38H3znihPI25RCAHWjSFmjNoPwYGJwaGOUZ9xeZgLAM_0bt0093BKme8nm7Jk0RNJrxRU-SodJ2NOJJmjgJVMnPVSPIsWZ9T6gV4o_Wux8BTAQAatP0TSiaRWG0A-JkS0DOPCq2g5emf3eMvTQolXE2XryOZrpFpBsTiEgYrLTvx2KFPysH8AJ1Bijw32tUmJXy1kkbc4f2eLfnKPFLedmlljtD5LI15z01G_6Vdr84YuIVsXlarLWHZy3c0P)
type: Comment
comment on: http://stackoverflow.com/a/50113269
score: 0
type: AnswerComment

http://stackoverflow.com/a/49965923
upvote count: 4
answers question: http://stackoverflow.com/q/49965611
has comment: http://stackoverflow.com/comment/86947820
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86947972
has comment: http://stackoverflow.com/comment/88328452
score: 4
accepted answer of: http://stackoverflow.com/q/49965611
has comment: http://stackoverflow.com/comment/86948814
type: Answer
has comment: http://stackoverflow.com/comment/88327354
has comment: http://stackoverflow.com/comment/86948672
has comment: http://stackoverflow.com/comment/86948520
has comment: http://stackoverflow.com/comment/86948104
has body: If regex is an option: text = """-rwx------ Administrators/Domain Users 456220672 0% 2018-04-16 16:04:40 E:\\_WiE10-18.0.100-77.iso -rwxrwx--- Administrators/unknown 6677 0% 2018-04-17 01:33:23 E:\\program files\\cluster groups\\sql server (mssqlserver)\\logs\\progress-MOD-1523883344023-3001-Windows.log""" import re for h in re.findall(r"^.*?\d\d:\d\d:\d\d (.*)",text,flags=re.MULTILINE): print(h) Output: E:\_WiE10-18.0.100-77.iso E:\program files\cluster groups\sql server (mssqlserver)\logs\progress-MOD-1523883344023-3001-Windows.log Pattern explained: The pattern r"^.*?\d\d:\d\d:\d\d (.*)" looks for linestart '^' + as less anythings as possible '.*?' + the time-stamp '\d\d:\d\d:\d\d ' followed by a space and captures all behind it till end of line into a group. It uses the re.MULTILINE flag for that. Edit: Capturing the individual things needs some more capturing groups: import re for h in re.findall(r"^([rwexXst-]+) ([^0-9]+) +\d+.+? +(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (.*)",text,flags=re.MULTILINE): # ^^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ # flags grpName datetime filename for k in h: print(k) print("") Output: -rwx------ Administrators/Domain Users 2018-04-16 16:04:40 E:\_WiE10-18.0.100-77.iso -rwxrwx--- Administrators/unknown 2018-04-17 01:33:23 E:\program files\cluster groups\sql server (mssqlserver)\logs\progress-MOD-1523883344023-3001-Windows.log

http://stackoverflow.com/comment/86974550
comment on: http://stackoverflow.com/q/49978657
has text: I believe the function code shown above (`chew_repeated_leading_characters`) is the function he wants to test, it isn't the test function itself.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49996994
downvote count: 1
favorite count: 0
type: Question
has body: Started programming a GUI and this also marks my first foray into OOP. I feel I have a pretty good grasp of why you should include self. But conversely, I'm still not sure I understand the ramifications of not including self. For example, class DataHolder(object): def loadSeries(self, name, filename): df = pd.read_csv(filename, ...) df = something() df = something_else() self.meta[name].values = df I've defined a class to help me manage my data. Every time I load in a datafile it needs to be loaded with Pandas and "polished" (e.g. headers, extra columns and stuff removed) until it's ready to be stashed away in some dictionary structure. Here I don't see a reason to keep df tied to any object as it's basically a throwaway intermediate result for readability. Is there anything wrong with this procedure? Could anything go wrong? Similarly, is there any reason not to make up temporary names in the scope of the method? def refreshPlot(self): if self.currentlySelectedName != None: self.data.seriesData(self.currentlySelectedName) self.canvas.ax.clear() self.canvas.ax.plot(self.data.seriesData(self.currentlySelectedName), color = "black") if len(self.data.getMeta(self.currentlySelectedName).xdata) == 1: self.canvas.ax.axvline(self.data.getMeta(self.currentlySelectedName).xdata[0], color = "red") elif len(self.data.getMeta(self.currentlySelectedName).xdata) == 2: self.canvas.ax.axvline(self.data.getMeta(self.currentlySelectedName).xdata[0], color = "red") self.canvas.ax.axvline(self.data.getMeta(self.currentlySelectedName).xdata[1], color = "red") else: self.canvas.ax.clear() self.canvas.draw() Or I could temporarily assign out readable names: def refreshPlot(self): name = self.currentlySelectedName xdata = self.data.getMeta(name).xdata if name != None: data = self.data.seriesData(name) self.canvas.ax.clear() self.canvas.ax.plot(data, color = "black") if len(xdata) == 1: self.canvas.ax.axvline(xdata[0], color = "red") elif len(xdata) == 2: self.canvas.ax.axvline(xdata[0], co…
tagged with: oop
has answer: http://stackoverflow.com/a/49997127
type: UnansweredQuestion
has title: When is it "okay" to briefly exclude self in Python classes for readability?
has comment: http://stackoverflow.com/comment/87010508
tagged with: python
score: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86924199
comment on: http://stackoverflow.com/a/49953266
type: AnswerComment
score: 0
has text: How can I download this image? Sorry but I'm not familiar with docker at all :( There are some examples of using... what exactly? There is no install and no package to download. Could you explain me how can I mount this image?
type: Comment

http://stackoverflow.com/comment/87050624
score: 0
has text: Is your server accept `GET` or `POST`. In your example the first method is GET and then you're trying to send POST method in second. I'm confused
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50016996

openai-gym
tags question: http://stackoverflow.com/q/50023771
tags question: http://stackoverflow.com/q/49947555
tag name: openai-gym
type: Tag

http://stackoverflow.com/comment/87091437
score: 0
has text: Thank you my friend that is actually a very useful method!
type: AnswerComment
comment on: http://stackoverflow.com/a/50037591
type: Comment

http://stackoverflow.com/comment/87163324
comment on: http://stackoverflow.com/q/50070864
score: 0
type: Comment
type: QuestionComment
has text: I think I see something. There is a new step in the failed build `python setup.py install --force` before it even reaches `cat doc/conf.py`. So what I think happened is that you added a requirements file and toggled on under *Admin > Advanced Settings > Install Project: Install your project inside a virtualenv using setup.py install*. Another possibility to try is to do a Wipe of this version of your docs under *Versions > Branch > Wipe*.

http://stackoverflow.com/comment/87102219
type: QuestionComment
has text: @MichaelHunger thank you for your answers, I updated my question.
comment on: http://stackoverflow.com/q/50025260
score: 0
type: Comment

http://stackoverflow.com/comment/87012461
has text: Are you sure that precision is the problem? FEM is an approximation method,. I would review the theory before trying to work with bigger floats.
type: Comment
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/49997595

http://stackoverflow.com/q/50054027
tagged with: bots
score: 1
type: AnsweredQuestion
answer count: 1
downvote count: 0
has body: I'm new to python and linux, and I recently set up a twitter bot with my Raspberry Pi to mess around and have fun with. I want to set up a system where my RasPi sends a tweet every time I press a button. I followed the instructions on https://raspberrypihq.com/use-a-push-button-with-raspberry-pi-gpio to set up the basic input. I have two .py files, tweet_test.py and buttonPress.py tweet_test: #!/usr/bin/env python import os import random from twython import Twython # your twitter consumer and access information goes here apiKey = '' apiSecret = '' accessToken = '' accessTokenSecret = '' api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret) messages = [ "A button was pressed!!", "My creator pressed a button.", "This tweet was triggered by a button press.", ] message = random.choice(messages) api.update_status(status=message) print("Tweeted: " + message) buttonPress: import tweet_test import RPi.GPIO as GPIO #Import Raspberry Pi GPIO library def button_callback(channel): tweet_test print("Button was pushed!") GPIO.setwarnings(False) #Ignore warning for now GPIO.setmode(GPIO.BOARD) #Use physical pin numbering GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Set pin 10 to be an input pin and set initial value to be pulled low (off) GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) #Set up event on pin 10 rising edge message = input("Press enter to quit\n\n") #Run until someone presses enter GPIO.cleanup() #Clean Up However, when I run buttonPress.py in the command line, the first thing it does is tweet, without even having received any input from the button. Then, it begins receiving button inputs, but doesn't tweet anything. Please help! Sample output: user1@raspberrypi:~/TwitterBot $ sudo python buttonPress.py Tweeted: A button was pressed!! Press enter to quit Button was pushed! Button was pushed! Button was pushed!
tagged with: twitter
upvote count: 1
favorite count: 0
type: Question
has title: Python program disregards button input
tagged with: raspberry-pi
accepted answer: http://stackoverflow.com/a/50054137
has answer: http://stackoverflow.com/a/50054137
has comment: http://stackoverflow.com/comment/87127476
tagged with: python

http://stackoverflow.com/q/50040055
type: Question
has body: hello every one I have created this function, it calculates Gc per step (pas) and puts results in a matrix , but the problem is that is puts everything of the index 0 of the matrix, how can Ib fix this? I want to put each value to have an index (first value on 0 , second on 1 ....ect) def gc_content_mat(sequence , pas): #pas = step num_fen=len(sequence)/pas #num_fen = windows number values = np.zeros(num_fen) #print values #print n for i in range(0,num_fen): values [i] =gc_content(sequence[i*pas:(i+1)*pas]) #function gc_content is already defined return np.matrix(values) I appreciate you help
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50040319
has title: how to fix index matrix
score: 0
tagged with: matrix
answer count: 1

http://stackoverflow.com/a/50066364
has body: It looks to me your xpath is off, try this one: response.xpath("//div/@style").extract() or: response.xpath("//div").xpath("./@style").extract() # notice the relevant path here^^
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50066034

http://stackoverflow.com/q/49973739
downvote count: 1
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has body: X = [0,5,0,0,3,1,15,0,12] for value in range(0,len(X)): if X[value] &lt;= 0: del X[value] print(X) print(X) I run the code but then i get an error saying that the list is out of index range. Can someone please help me out on how to correct this mistake
duplicate of: http://stackoverflow.com/q/2793324
has comment: http://stackoverflow.com/comment/86963346
tagged with: python
has answer: http://stackoverflow.com/a/49973763
linked to: http://stackoverflow.com/q/2793324
has title: Python. How to remove zeroes from a list in Python
has answer: http://stackoverflow.com/a/49973765
upvote count: 24
has comment: http://stackoverflow.com/comment/86963522
score: 23
has comment: http://stackoverflow.com/comment/86963760

http://stackoverflow.com/a/49939961
answers question: http://stackoverflow.com/q/49918309
score: 0
has body: Solved: it appears that in Windows you cannot give the script the same name of the package.
type: Answer

http://stackoverflow.com/comment/87013503
type: QuestionComment
comment on: http://stackoverflow.com/q/49998584
score: 1
type: Comment
has text: @Juan I don't think the goal here should be for OP to figure out the optimal python way to find the average of a list, but rather to learn how to think about programming and debugging.

http://stackoverflow.com/comment/86960713
comment on: http://stackoverflow.com/a/49972272
score: 0
type: Comment
has text: @PaulRooney looks like OP has no clue how to accept an answer :)
type: AnswerComment

http://stackoverflow.com/comment/87025552
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50003188
has text: I have Button named 'A'.Sorry I didn't specified it earlier
type: Comment

http://stackoverflow.com/comment/86994393
type: Comment
type: QuestionComment
score: 0
has text: Erosion. Also, post the whole image.
comment on: http://stackoverflow.com/q/49941299

http://stackoverflow.com/q/49972306
favorite count: 0
tagged with: webdriverwait
has body: i have a problem code below where the element becomes visible and is not clicked. i tried both css selectors and the xpath. import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC PROXY = "socks5://184.178.172.13:15311" # IP:PORT or HOST:PORT chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % PROXY) driver = webdriver.Chrome(chrome_options=chrome_options) driver.get('https://nitrogensports.eu/sport/tennis/starting-soon') wait = WebDriverWait(driver, 30) table = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="modal-welcome-new-button"]'))) table.click() table = wait.until(EC.presence_of_element_located((By.XPATH, '//div[class="div.events-result-set"]'))) print("finished") time.sleep(30) driver.close()
upvote count: 3
has comment: http://stackoverflow.com/comment/87005393
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/86962891
type: Question
has answer: http://stackoverflow.com/a/49974107
score: 3
has comment: http://stackoverflow.com/comment/86998065
has title: why is selenium reaching timeout when the element is there
has comment: http://stackoverflow.com/comment/86961450
tagged with: python
tagged with: webdriver

http://stackoverflow.com/q/49926867
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49927073
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49927073
tagged with: python
has title: Pandas - Split and refactor and overloaded ID column
type: Question
has body: I have a pandas DataFrame with columns patient_id, patient_sex, patient_dob (and other less relevant columns). Rows can have duplicate patient_ids, as each patient may have more than one entry in the data for multiple medical procedures. I discovered, however, that a great many of the patient_ids are overloaded, i.e. more than one patient has been assigned to the same id (evidenced by many instances of a single patient_id being associated with multiple sexes and multiple days of birth). To refactor the ids so that each patient has a unique one, my plan was to group the data not only by patient_id, but by patient_sex and patient_dob as well. I figure this must be sufficient to separate the data into individual users (and if two patients with the same sex and dob just happened to be assigned the same id, then so be it. Here is the code I currently use: # I just use first() here as a way to aggregate the groups into a DataFrame. # Bonus points if you have a better solution! indv_patients = patients.groupby(['patient_id', 'patient_sex', 'patient_dob']).first() # Create unique ids new_patient_id = 'new_patient_id' for index, row in indv_patients.iterrows(): # index is a tuple of the three column values, so this should get me a unique # patient id for each patient indv_patients.loc[index, new_patient_id] = str(hash(index)) # Merge new ids into original patients frame patients_with_new_ids = patients.merge(indv_patients, left_on=['patient_id', 'patient_sex', 'patient_dob'], right_index=True) # Remove byproduct columns, and original id column drop_columns = [col for col in patients_with_new_ids.columns if col not in patients.columns or col == new_patient_id] drop_columns.append('patient_id') patients_with_new_ids = patients_with_new_ids.drop(columns=drop_columns) patients = patients_with_new_ids.rename(columns={new_patient_id : 'patient_id'}) The problem is that with over 7 million patients, this is way too slow a solution, the biggest bottleneck being the for-loop. So my q…
downvote count: 0

http://stackoverflow.com/a/49951465
score: 2
has body: It sounds like you want to do something when the sign changes. I'm going to assume it's some function called f. So, in broad strokes, we want code that looks like (call your list l): for x in l: if (the sign changed at x): f() What does the sign changing mean? Well, either l[i] &gt; 0 and l[i-1] &lt; 0 or vice versa, and you'll have to decide what to do when one of the numbers is 0. So suppose you write a function called sign_change(x,y) that returns True when the signs of x and y are different and False when they're the same. Note that this doesn't quite go with the pseudocode above--we need access to both the current element and the previous element. So, rather than iterating over the list, iterate over the indices, from 1,..., len(l)-1. This gives us: for i in range(1, len(l) - 1): if sign_change(l[i], l[i-1]): f() We have to start iterating at 1 because there's nothing before 0. (And, in fact, l[-1] will give us the last element of the list.) Now you just have to write f and sign_change.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49951389
type: Answer

http://stackoverflow.com/q/50012259
answer count: 1
has title: Finding missing time intervals from data
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87040938
accepted answer: http://stackoverflow.com/a/50012343
has body: If I have a list of dates in a CSV file, I want to find and add the missing intervals in one hour time slots of the day. The data looks like: id city reading date 33 US-Ohio 06/18/2011 23:00:00 33 US-Ohio 06/19/2011 00:00:00 33 US-Ohio 06/19/2011 01:00:00 33 US-Ohio 06/19/2011 02:00:00 33 US-Ohio 06/19/2011 06:00:00 33 US-Ohio 06/19/2011 07:00:00 33 US-Ohio 06/19/2011 08:00:00 34 US-NYC 06/19/2011 06:00:00 34 US-NYC 06/19/2011 08:00:00 So, the missing data that needs to be inserted is id city reading date 33 US-Ohio 06/18/2011 23:00:00 33 US-Ohio 06/19/2011 00:00:00 33 US-Ohio 06/19/2011 01:00:00 33 US-Ohio 06/19/2011 02:00:00 06/19/2011 03:00:00 06/19/2011 04:00:00 33 US-Ohio 06/19/2011 06:00:00 33 US-Ohio 06/19/2011 07:00:00 33 US-Ohio 06/19/2011 08:00:00 34 US-NYC 06/19/2011 06:00:00 06/19/2011 07:00:00 34 US-NYC 06/19/2011 08:00:00 I have already converted it to datetime using pandas, using the code: games['reading_date'] = pd.to_datetime(games['reading_date'], format='%m/%d/%y %H:%M') The dates are repeated, so setting an index and resampling does not work, because there are different missing times in different cities and the index is repeated multiple times I just need to add these missing hourly intervals and keep all the other columns blank. How do I do this in python?
tagged with: pandas
has answer: http://stackoverflow.com/a/50012343
score: 1
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87100668
type: Comment
has text: Hi, Sorry for that bad formatting of my code, I just don't know hot ot do that. I'll do it correctly next time. Thank you Jean-François Fabre, I've already done this with comprehension, then I tried to do the same by map() to examine myself. Yor explanation is good, something new to me. Regards
type: AnswerComment
comment on: http://stackoverflow.com/a/50042327
score: 0

http://stackoverflow.com/q/49933144
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49933328
favorite count: 0
has body: Pardon me for possibly an easy question. Is there an elegant, numpy way to apply broadcasting minus in tensor? e.g. import numpy as np u = np.concatenate((np.ones((3, 1)), np.zeros((3,1))), axis=1).reshape(3,1,2) v = np.concatenate((np.zeros((3, 1)), np.ones((3,1))), axis=1).reshape(3,1,2) I'll have the result array([[[1, 0]], [[1, 0]], [[1, 0]]]) array([[[0, 1]], [[0, 1]], [[0, 1]]]) I want to know if there an elegant way to broadcasting minus. That means if I got the tensor u with shape [L, m, n] and tensor v with shape [L, m, n], and I want the result with shape [L, L, m, n], whose each second axis is the minus between the corresponding row in u and every element in v. Thanks in advance!
type: Question
upvote count: 2
tagged with: numpy
has title: Broadcasting minus in tensor in numpy
has answer: http://stackoverflow.com/a/49933328
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/86946800
type: Comment
has text: I don't agree on that@Adi219, I can probably come up with an algorithm on my own, however, I'm 200% sure that someone has given a lot of thought into making it efficient, especially as it's a part of Python modules that are pretty much built-in. Let me know if you have a solution, I'd love to see it work. Note that I've edited my answer to make it work on longer words (similar to a generator) instead of just having a big list and then working with it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49965265

http://stackoverflow.com/q/50040923
tagged with: dictionary
has title: How elegantly iterate over list or dictionary
has comment: http://stackoverflow.com/comment/87097793
downvote count: 0
answer count: 1
has body: I have a variable (object from database). In some cases this variable can be type of list and in some cases dictionary. Standard for cycle if variable is list: for value in object_values: self.do_something(value) Standard for cycle if variable is dictionary: for key, value in object_values.items(): self.do_something(value) I can use instanceof() two check the type, but then I still need two functions or if with two for cycles. I have now if condition which calls one of the two functions, one for iterating as list (e.g. iterate_list()) and the second for iterating as dictionary (e.g. iterate_dict()) . Is there any better option how elegantly and more pythonic way resolve problem that I don't know if the variable will be list or dictionary?
has answer: http://stackoverflow.com/a/50041006
accepted answer: http://stackoverflow.com/a/50041006
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87097860
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: list
tagged with: python

http://stackoverflow.com/comment/86918182
type: QuestionComment
has text: Why can't you initially train your model on it?
type: Comment
comment on: http://stackoverflow.com/q/49950684
score: 1

sqlalchemy
tags question: http://stackoverflow.com/q/49936356
tags question: http://stackoverflow.com/q/49962224
tags question: http://stackoverflow.com/q/50012246
tags question: http://stackoverflow.com/q/50012917
tags question: http://stackoverflow.com/q/50023110
tags question: http://stackoverflow.com/q/50071563
tags question: http://stackoverflow.com/q/49935712
tags question: http://stackoverflow.com/q/50023299
tags question: http://stackoverflow.com/q/50031376
tags question: http://stackoverflow.com/q/49971309
tags question: http://stackoverflow.com/q/49971549
tags question: http://stackoverflow.com/q/50012583
tags question: http://stackoverflow.com/q/50056605
tags question: http://stackoverflow.com/q/49947098
tags question: http://stackoverflow.com/q/49918095
tags question: http://stackoverflow.com/q/49985657
tags question: http://stackoverflow.com/q/49938731
tags question: http://stackoverflow.com/q/49952561
tags question: http://stackoverflow.com/q/49927635
tags question: http://stackoverflow.com/q/50024626
tags question: http://stackoverflow.com/q/50011873
tags question: http://stackoverflow.com/q/49966065
tags question: http://stackoverflow.com/q/49974069
tags question: http://stackoverflow.com/q/50011349
tags question: http://stackoverflow.com/q/49951474
tags question: http://stackoverflow.com/q/49990775
tags question: http://stackoverflow.com/q/49952373
tags question: http://stackoverflow.com/q/50030569
tags question: http://stackoverflow.com/q/49992768
tags question: http://stackoverflow.com/q/49958396
tags question: http://stackoverflow.com/q/50045319
tags question: http://stackoverflow.com/q/50067205
tags question: http://stackoverflow.com/q/49993067
tags question: http://stackoverflow.com/q/49990520
tags question: http://stackoverflow.com/q/50003534
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/49952752
tags question: http://stackoverflow.com/q/49989579
type: Tag

http://stackoverflow.com/comment/86994765
score: 2
comment on: http://stackoverflow.com/q/49989137
type: Comment
has text: There's plenty of issues with this, not least that `str` is a built-in
type: QuestionComment

http://stackoverflow.com/comment/87033219
has text: what is the result of `x_train.shape` and `transformed_review.shape`?
type: QuestionComment
comment on: http://stackoverflow.com/q/50008120
score: 1
type: Comment

http://stackoverflow.com/comment/86908629
type: Comment
has text: Thanks! This is what I'm looking for outside of my current area of knowledge.
type: AnswerComment
comment on: http://stackoverflow.com/a/49945524
score: 0

http://stackoverflow.com/a/49949655
answers question: http://stackoverflow.com/q/49949370
accepted answer of: http://stackoverflow.com/q/49949370
upvote count: 2
has body: from bs4 import BeautifulSoup html = """ to pay charges from one's bank account """ soup = BeautifulSoup(html) print(soup.text) # to pay # charges # from one's # bank account print(soup.text.replace('\n', ' ')) # to pay charges from one's bank account
downvote count: 0
type: Answer
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86916577

http://stackoverflow.com/a/49955770
score: 4
answers question: http://stackoverflow.com/q/49953817
has comment: http://stackoverflow.com/comment/86928056
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49953817
type: Answer
upvote count: 4
has body: Here is an approach using a KDTree: import numpy as np from scipy.spatial import cKDTree as KDTree def cluster_data_KDTree(a, thr=0.1): t = KDTree(a) mask = np.ones(a.shape[:1], bool) idx = 0 nxt = 1 while nxt: mask[t.query_ball_point(a[idx], thr)] = False nxt = mask[idx:].argmax() mask[idx] = True idx += nxt return a[mask] Borrowing @Divakar's test case we see that this delivers another 100x speedup on top of the 400x Divakar reports. Compared to OP we extrapolate a ridiculous 40,000x: np.random.seed(0) data1 = np.random.rand(10000,2) data2 = data1.copy() from timeit import timeit kwds = dict(globals=globals(), number=10) print(timeit("cluster_data_KDTree(data1)", **kwds)) print(timeit("cluster_data_pdist_v1(data2)", **kwds)) np.random.seed(0) data1 = np.random.rand(10000,2) data2 = data1.copy() out1 = cluster_data_KDTree(data1, thr=0.1) out2 = cluster_data_pdist_v1(data2, dist_thresh = 0.1) print(np.allclose(out1, out2)) Sample output: 0.05073001119308174 5.646531613077968 True It turns out that this test case happens to be quite favorable to my approach because there are very few clusters and thus very few iterations. If we drastically increase the number of clusters to about 3800 by changing the threshold to 0.01 KDTree still wins but the speedup is reduced from 100x to 15x: 0.33647687803022563 5.28947562398389 True

http://stackoverflow.com/q/50071388
score: 0
linked to: http://stackoverflow.com/q/43995590
answer count: 1
has answer: http://stackoverflow.com/a/50071500
type: Question
tagged with: slider
has title: Is it possible to put a mathematical formula (using Latex) next to the Slider widget in Matplotlib?
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50071500
tagged with: python
type: AnsweredQuestion
has body: My question is in the title, as you can see in the image below my variable is M2/M1 and I am wondering if it is possible to replace it by $\dfrac{M_2}{M_1}$. I tried: axmass = plt.axes([0.18, 0.1, 0.65, 0.03]) smass = Slider(axmass, '$\dfrac{M_2}{M_1}$', 1e-5, 1, 0) But I get the following error: ValueError: \dfrac{M_2}{M_1} ^ Unknown symbol: \dfrac (at char 0), (line:1, col:1)

http://stackoverflow.com/comment/125099906
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50172440
has text: does this need a `break` after `myQueryJob()` in the `try` to avoid looping if successful?

pipeline
type: Tag
tags question: http://stackoverflow.com/q/49987595
tag name: pipeline
tags question: http://stackoverflow.com/q/50068185

http://stackoverflow.com/a/50011897
upvote count: 6
answers question: http://stackoverflow.com/q/50011078
downvote count: 0
has body: Similar to @fferri. You will always have to specify the items in a long list. Get a reference to the final dict using reduce and getitem: from functools import reduce from operator import getitem d = {1:{2:{3:{4:5}}}} foo = 2 items = [1,foo,3] result = d info = reduce(getitem, items, d) &gt;&gt;&gt; info[4] 5 &gt;&gt;&gt; d {1: {2: {3: {4: 5}}}} &gt;&gt;&gt; info[4] = 99 &gt;&gt;&gt; d {1: {2: {3: {4: 99}}}} I was also playing around with a class but it doesn't seem to have many advantages - except you could customize a key error exception so that the error message would tell you which key at which depth is missing. class Drilldown: def __init__(self, d, path): #self.final = reduce(getitem, path, d) self.final = d for i, item in enumerate(path, 1): try: self.final = self.final[item] except KeyError as e: msg = ''.join('[{}]' for _ in range(i)) msg = msg.format(*path[:i]) msg = 'The last key in the path "{}" does not exist'.format(msg) e.args = [msg] raise def __call__(self, item): return self.final[item] def __setitem__(self, item, value): self.final[item] = value def __getitem__(self, item): return self.final[item] def __str__(self): return str(self.final) def __repr__(self): return repr(self.final) &gt;&gt;&gt; z = 19 &gt;&gt;&gt; items = [1,2,z] &gt;&gt;&gt; q = Drilldown(d,items) Traceback (most recent call last): File "&lt;pyshell#68&gt;", line 1, in &lt;module&gt; q = Drilldown(d,items) File "C:\pyProjects33\tmp.py", line 32, in __init__ self.final = self.final[item] KeyError: 'The last key in the path "[1][2][19]" does not exist' &gt;&gt;&gt; &gt;&gt;&gt; #normal usage &gt;&gt;&gt; items = [1,2,3] &gt;&gt;&gt; q = Drilldown(d,items) &gt;&gt;&gt; d {1: {2: {3: {4: 5}}}} &gt;&gt;&gt; q {4: 5} &gt;&gt;&gt; q(4) 5 &gt;&gt;&gt; q[4] 5 &gt;&gt;&gt; q[4] += 20 &gt;&gt;&gt; q {4: 25} &gt;&gt;&gt; d {1: {2: {3: {4: 25}}}} &gt;&gt;&gt; q['foo'] = '99' &gt;&gt;&gt; q {4: 25, 'foo': '99'} &gt;&gt;&gt; d {1: {2: {3: {4: 25, 'foo': '99'}}}} &gt;&gt;&gt;
type: Answer
score: 6

http://stackoverflow.com/q/49963377
has answer: http://stackoverflow.com/a/49985258
accepted answer: http://stackoverflow.com/a/49985258
tagged with: cx-oracle
has title: cx_Oracle.NotSupportedError: Python value of type WindowsPath not supported
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: oracle-database
type: Question
tagged with: python-3.x
has body: I am using cx_Oracle to insert binary files from a directory as BLOB in a column of a table. So, I am intended to use the PATH module of python3 and then insert the binary file by fetching the file using WindowsPath. Here's the example:- import sys import cx_Oracle from pathlib import Path username = 'EWORDPR' password = 'EWORDPR' databaseName = "10.11.201.161:1521/ORCL" connection = cx_Oracle.connect (username,password,databaseName) # Connection Established cursor=connection.cursor() my_file = Path("22 Apr 2018.txt") print("File exists:",my_file.is_file()) #File Exists: True rows = [ ('01787440110', 'Rakin','22-04-2017', my_file )] cursor.executemany('insert into CHAT_HISTORY(MOBILE_NUMBER,USER_NAME,CHAT_DATE,USER_TRANSCRIPTS) values (:1, :2, :3, :4)', rows) connection.commit() cursor.close() connection.close() Then, I am getting the following errors:- Traceback (most recent call last): File "F:/Python with ORACLE/orapy.py", line 53, in print(cursor.executemany('insert into CHAT_HISTORY(MOBILE_NUMBER,USER_NAME,CHAT_DATE,USER_TRANSCRIPTS) values (:1, :2, :3, :4)', rows)) cx_Oracle.NotSupportedError: Python value of type WindowsPath not supported. Is there any way to export binary files from a directory and then directly insert the file in as BLOB using cx_Oracle ?

dask
tags question: http://stackoverflow.com/q/50065572
type: Tag
tags question: http://stackoverflow.com/q/50017443
tags question: http://stackoverflow.com/q/50037805
tags question: http://stackoverflow.com/q/49950888
tags question: http://stackoverflow.com/q/49925130
tag name: dask
tags question: http://stackoverflow.com/q/50051210
tags question: http://stackoverflow.com/q/50071304

http://stackoverflow.com/a/49983941
answers question: http://stackoverflow.com/q/49983661
type: Answer
score: 0
has body: There are a few problems with your code: you try to split lines into lists of chars using split, but that will only split at spaces assuming your indentation is correct, you are only ever treating the last value of chars in your second loop that second loop just wraps each of the (not splitted) lines in chars (which due to the previous issue is only the last one) into a list Instead, you can just convert str to list... &gt;&gt;&gt; list("abcde") ['a', 'b', 'c', 'd', 'e'] ... and put those into output_list directly. Also, don't forget to strip the \n: f = open("small.txt", "r") output_list = [] for rec in f: chars = list(rec.strip()) output_list.append(chars) Or using with for autoclosing and a list-comprehension: with open("small.txt") as f: output_list = [list(line.strip()) for line in f] Note, however, that is you do not want to change the values in that grid, you do not have to convert to a list of lists of chars at all; a list of strings will work just as well. output_list = list(map(str.strip, f))

http://stackoverflow.com/q/49920698
has comment: http://stackoverflow.com/comment/86858037
has title: How do I set to zero lower triangles along the last two axes of a three-dimensional array?
has comment: http://stackoverflow.com/comment/86857149
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49921399
has comment: http://stackoverflow.com/comment/86857518
has comment: http://stackoverflow.com/comment/86857250
has comment: http://stackoverflow.com/comment/86856895
tagged with: arrays
tagged with: python
tagged with: vectorization
accepted answer: http://stackoverflow.com/a/49921399
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86857161
score: 0
has body: I have a three-dimensional array with dimensions (N,M,M). I would like to set the diagonal and the lower triangle of each (M,M) array to zero. How to do it without looping along the first dimension? Is there a vectorized operation for that? In just two dimensions (M,M) I would do X = np.triu(X, k=1) How do I generalize this into three dimensions without loops? For example, input: [[[ 1 2 3] [ 4 5 6] [ 7 8 9]] [[10 11 12] [13 14 15] [16 17 18]] [[19 20 21] [22 23 24] [25 26 27]] [[28 29 30] [31 32 33] [34 35 36]]] Expected output [[[ 0 2 3] [ 0 0 6] [ 0 0 0]] [[0 11 12] [0 0 15] [0 0 0]] [[0 20 21] [0 0 24] [0 0 0]] [[0 29 30] [0 0 33] [0 0 0]]]
has comment: http://stackoverflow.com/comment/86857464
has comment: http://stackoverflow.com/comment/86858318
answer count: 1

http://stackoverflow.com/comment/124074152
type: AnswerComment
has text: Alternatively, if you'd like to use tensorflow.keras instead of keras, try the example at the following [link](https://keras.io/api/optimizers/)
score: 1
type: Comment
comment on: http://stackoverflow.com/a/53754073

http://stackoverflow.com/comment/87002779
has text: @Daniel It just stays on the page, no errors. In the post below I was told to get rid of the except which helps. I now get the error "BuildError: Could not build url for endpoint '/'." But '/' is in my file and builds successfully other times. I've tried for_url(main) or for_url('/') as well.
score: 0
comment on: http://stackoverflow.com/q/49993026
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50042673
upvote count: 0
answer count: 2
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87101627
accepted answer: http://stackoverflow.com/a/52717039
downvote count: 1
favorite count: 0
has title: OperationalError: database is locked in SQLite3
type: Question
has body: I'm trying to access the history of chrome browser which is a SQLite file. My code was working fine but recently I'm facing this error- sqlite3.OperationalError: database is locked Is there any solution?
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/2740806
possible better answer: http://stackoverflow.com/a/50042930
has answer: http://stackoverflow.com/a/52717039
tagged with: python-3.4
tagged with: browser
has answer: http://stackoverflow.com/a/50042930
type: AnsweredQuestion

http://stackoverflow.com/comment/87066738
has text: Yes. `Traceback (most recent call last): File "/home/pi/Documents/detect_macs1.py", line 43, in <module> detect_mac(MAC_addresses) File "/home/pi/Documents/detect_macs1.py", line 29, in detect_mac if any(address in str_output for address in address_list): File "/home/pi/Documents/detect_macs1.py", line 29, in <genexpr> if any(address in str_output for address in address_list): TypeError: 'in <string>' requires string as left operand, not list`
comment on: http://stackoverflow.com/a/50024641
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49935754
has answer: http://stackoverflow.com/a/49936573
has comment: http://stackoverflow.com/comment/86888449
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/86887165
has answer: http://stackoverflow.com/a/49935910
score: 2
type: AnsweredQuestion
has body: I am trying to scrape a website and get all the div elements in the HTML. The webpage I am trying to access is a page containing job opportunities where each job is inside a separate div. I am trying to get them all so that I can run them through a for loop and extract their data for each separately. I haven't coded it yet. Is there a specific method or way to get them? And also I only want to extract the divs that contain jobs. Outer HTML Planner II - new Vantage Utility Services - Upland, CA Transportation or giving away of up to 28.5 grams of marijuana, other than concentrated cannabis, or the offering to transport or give away up to 28.5 grams of... 4 hours ago - save job - more... View all Vantage Utility Services jobs in Upland, CA - Upland jobs Salary Search: Planner salaries in Upland, CA Learn more about working at Vantage Utility Services Related forums: Upland, California - Planner - VANTAGE UTILITY SERVICES
tagged with: selenium
tagged with: web-scraping
possible better answer: http://stackoverflow.com/a/49935910
favorite count: 0
has answer: http://stackoverflow.com/a/49936248
has comment: http://stackoverflow.com/comment/86887106
type: Question
upvote count: 2
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/49936573
tagged with: python
has title: python selenium get all the divs
has comment: http://stackoverflow.com/comment/86888032

http://stackoverflow.com/comment/86856249
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49919271
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169327/discussion-between-david-l-and-bob).

http://stackoverflow.com/comment/86929621
type: Comment
type: QuestionComment
has text: you woud need an algorithm that measures how a word is related to another word. this is a good read: https://stackoverflow.com/questions/21979970/how-to-use-word2vec-to-calculate-the-similarity-distance-by-giving-2-words
comment on: http://stackoverflow.com/q/49956354
score: 0

http://stackoverflow.com/comment/86962553
type: QuestionComment
score: 0
has text: What have you tried? What errors are you getting? Have you looked at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx Looks like you just specifying the keyboard structure with the type value set to 1 should work.
comment on: http://stackoverflow.com/q/49973060
type: Comment

http://stackoverflow.com/q/50032779
tagged with: python
accepted answer: http://stackoverflow.com/a/50033161
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50033161
has answer: http://stackoverflow.com/a/50070032
answer count: 3
tagged with: pygtk
tagged with: gtk3
score: 1
has title: Alternating Switches ON/OFF?
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: So I want to have my small Python Gtk window have 2 switches. When one switch is ON, the other is turned OFF, and vice versa. I am not too sure how to control both switches. If anyone can lead me in the right direction, it'd be much appreciated. #!/usr/bin/python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class SwitcherWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Alt Switch Demo") self.set_border_width(10) hbox = Gtk.Box(spacing=10) self.add(hbox) switch1 = Gtk.Switch() switch1.connect("notify::active", self.on_switch_activated) switch1.set_active(True) hbox.pack_start(switch1, True, True, 0) switch2 = Gtk.Switch() switch2.connect("notify::active", self.on_switch_activated) switch2.set_active(False) hbox.pack_start(switch2, True, True, 0) if switch1.get_active(): switch2.set_active(False) else: switch2.set_active(True) def on_switch_activated(self, switch, gparam): builder = Gtk.Builder() sw1 = builder.get_object("switch1") sw2 = builder.get_object("switch2") if switch.get_active(): state = "on" sw2.set_active(False) else: state = "off" print("Switch was turned", state) win = SwitcherWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main()
possible better answer: http://stackoverflow.com/a/50033018
upvote count: 2
has answer: http://stackoverflow.com/a/50033018

http://stackoverflow.com/comment/87698723
comment on: http://stackoverflow.com/q/50060718
type: Comment
type: QuestionComment
score: 0
has text: @StefanL OK，I got it! Thanks a lot anyway.

http://stackoverflow.com/comment/87119782
type: Comment
type: QuestionComment
has text: the settings that are in the file settings.py inside your spider, you can find a list in the documentation page https://doc.scrapy.org/en/latest/topics/settings.html
comment on: http://stackoverflow.com/q/50051035
score: 0

http://stackoverflow.com/comment/87027078
type: Comment
type: QuestionComment
has text: Without an [mcve] showing how you intend to access these objects and use them for graphing, etc., it’s hard to suggest how you want to store them, but mostly likely it’s either some collection you can iterate (like a list, or maybe a dict keyed by the name attributes), or two variables named `firstengine` and `secondengine`, or something like that.
score: 0
comment on: http://stackoverflow.com/q/49996077

http://stackoverflow.com/comment/87091862
type: Comment
type: QuestionComment
has text: Python 2 blog, but still relevant http://guilload.com/python-string-interning/
score: 0
comment on: http://stackoverflow.com/q/50037548

http://stackoverflow.com/q/49996188
type: AnsweredQuestion
has title: python requests drops "data" when use of "header" in request
has body: I am working on REST API of a site that requires this request type when I want to upload a file: 'Authorization' and multi-part content type in header File as binary string in form (body) File Type in request URL So I did this code: import requests url = 'http://httpbin.org/post' parameters = { 'format': 'pdf', } headers = { 'Content-Type': 'multipart/form-data', 'Accept': 'application/json', 'Authorization' : 'Some authorization code' } data = {'file': open('1.pdf', 'rb')} r = requests.post(url, params=parameters, headers=headers, data=data) print(r.text) BUT it seems to requests is dropping data : { "args": { "format": "pdf" }, "data": "", "files": {}, "form": {}, "headers": { "Accept": "application/json", "Accept-Encoding": "gzip, deflate", "Authorization": "Some authorization code", "Connection": "close", "Content-Length": "30", "Content-Type": "multipart/form-data", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.1" }, "json": null, "origin": "x.x.x.x", "url": "http://httpbin.org/post?format=pdf" } it works when I remove 'headers' part in request: r = requests.post(url, params=parameters, data=data) Because response is : { "args": { "format": "pdf" }, "data": "", "files": {}, "form": { "fax_file": "some samplae texts\n" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "30", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.1" }, "json": null, "origin": "x.x.x.x", "url": "http://httpbin.org/post?format=pdf" } I have tried prepared request too and result is same.
tagged with: rest
accepted answer: http://stackoverflow.com/a/49996283
upvote count: 6
has comment: http://stackoverflow.com/comment/87009096
tagged with: post
has answer: http://stackoverflow.com/a/49996283
type: Question
has comment: http://stackoverflow.com/comment/87009667
answer count: 1
score: 6
downvote count: 0
tagged with: python
tagged with: python-requests
favorite count: 0
linked to: http://stackoverflow.com/q/4007969

http://stackoverflow.com/q/49962417
has comment: http://stackoverflow.com/comment/111079559
has comment: http://stackoverflow.com/comment/86940947
has answer: http://stackoverflow.com/a/49962706
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86940958
score: 51
linked to: http://stackoverflow.com/q/45523749
upvote count: 51
has body: For some reason, the following 2 calls to iloc / loc produce different behavior: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(dict(A=range(3), B=range(3))) &gt;&gt;&gt; df.iloc[:1] A B 0 0 0 &gt;&gt;&gt; df.loc[:1] A B 0 0 0 1 1 1 I understand that loc considers the row labels, while iloc considers the integer-based indices of the rows. But why is the upper bound for the loc call considered inclusive, while the iloc bound is considered exclusive?
tagged with: dataframe
tagged with: python
tagged with: slice
has comment: http://stackoverflow.com/comment/109260736
type: AnsweredQuestion
has title: Why does .loc have inclusive behavior for slices?
tagged with: pandas
has comment: http://stackoverflow.com/comment/111115381
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49962706

http://stackoverflow.com/comment/87047822
type: Comment
type: QuestionComment
has text: Is the output a *string*?
comment on: http://stackoverflow.com/q/50015744
score: 0

http://stackoverflow.com/comment/87034122
has text: yes. i update to this: . In this case, the first date is ok, but the second one didn´t work because didn´t display a input date type.
comment on: http://stackoverflow.com/a/49999587
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49993067
score: 0
has title: Python Sqlalchemy filter by date range
answer count: 0
has body: I have two date picker fields that i want the users to select from date to end date. and i want to display data between the two dates that was selected. From example form date: 2/14/2018 to date:3/15/2018. when the function is called i want to extract and display data between this two dates. i just need some help with the query to accomplish that. I am using sqlalchemy to pull data from an mssql db Here is my code. The two date pickers selectdate and selectdate1 which are then converted to julian dates. convert and convert1, i need some help with the query that does the magic. def bydate_display(request): if "selectdate" in request.POST: if "selectdate1" in request.POST: if "selectaccount" in request.POST: selected_date = request.POST["selectdate"] selected_date1 = request.POST["selectdate1"] selected_acc = request.POST["selectaccount"] if selected_date==selected_date: if selected_date1==selected_date1: if selected_acc==selected_acc: convert=datetime.datetime.strptime(selected_date, "%Y-%m-%d").toordinal() convert1=datetime.datetime.strptime(selected_date1, "%Y-%m-%d").toordinal() engine=create_engine('mssql+pymssql://username:password@1hostname /db') connection=engine.connect() metadata=MetaData() fund=Table('gltrxdet',metadata,autoload=True,autoload_with=engine) rate=Table('gltrx_all',metadata,autoload=True,autoload_with=engine) stmt=select ([fund.columns.account_code,fund.columns.description,fund.columns.nat_balance,fund.columns.rate_type_home,rate.columns.date_applied,rate.columns.date_entered,fund.columns.journal_ctrl_num,rate.columns.journal_ctrl_num]) #stmt = select([fund, rate]).where (and_(fund.columns.journal_ctrl_num==rate.columns.journal_ctrl_num)) stmt=stmt.where(and_ (rate.columns.journal_ctrl_num==fund.columns.journal_ctrl_num,fund.columns.account_code==selected_acc,rate.columns.date_applied==convert,rate.columns.date_applied==convertconvert1)) #stmt=stmt.where(or_(rate.columns.date_applied==convert,rate.columns.date_entered==convert1)) results=connec…
has comment: http://stackoverflow.com/comment/87005745
downvote count: 1
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/87002681
has comment: http://stackoverflow.com/comment/87039340
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87004802
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87038430

http://stackoverflow.com/q/49996592
tagged with: python
has comment: http://stackoverflow.com/comment/87010462
has title: Variable value changes depending if its the first or the second time it is executed
has comment: http://stackoverflow.com/comment/87010436
accepted answer: http://stackoverflow.com/a/49997313
type: AnsweredQuestion
score: 0
tagged with: pycharm
has answer: http://stackoverflow.com/a/49997313
answer count: 1
type: Question
has body: I have a really specific problem I'm not even able of searching for similar issues. I have the following variables cm = np.array([[65, 4, 22, 24], [6, 81, 5, 8], [0, 11, 85, 19], [4, 7, 3, 90]]) proportions = [0.3, 0.4, 0.1, 0.2] n = np.sum(cm) nisum = np.sum(cm, axis=1) nsumj = np.sum(cm, axis=0) p_i = np.zeros([cm.shape[0], 1]) p_ii = np.zeros([cm.shape[0], cm.shape[1]]) prod_ac = np.zeros([cm.shape[0], 1]) user_ac = np.zeros([cm.shape[0], 1]) overall_ac = 0 for i in range(cm.shape[1]): for j in range(cm.shape[0]): p_ii[i, j] = proportions[i] * cm[i, j] / nisum[i] if i == 0: p_i = np.sum(p_ii, axis=0) prod_ac[i] = ((proportions[i] / p_i[i]) * (cm[i, i] / nisum[i])) user_ac[i] = cm[i, i] / nisum[i] overall_ac += proportions[i] * cm[i, i] / nisum[i] If I execute in the console of PyCharm the whole block of code, the result of prod_ac is wrong, it results prod_ac Out[215]: array([[ 1. ], [ 31.05 ], [ 1.28787879], [ 2.76442308]]) But if I inmediately execute again just the loop part of the code, the result of the prod_ac is ok: prod_ac Out[217]: array([[ 0.84252858], [ 0.90639122], [ 0.47056319], [ 0.60898115]]) No errors or warnings rise. I'm guessing it is something with memory. Aparently if I execute all the lines at once the result is wrong. But if I execute the first part (from line 1 to the line before the loop), and aftwerwards I execute the loop, the result is fine. All the other variables are created fine every time. It is just prod_ac with troubles. Does anyone have any clue of where could be the issue?? I how could I manage to get the good result every time. This will be part of a function so I won't be able to execute by parts in the future. thanks

http://stackoverflow.com/comment/86882637
has text: Could you explain to me why I see so many new users with improperly indented `def` lines?
comment on: http://stackoverflow.com/q/49933526
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/a/49941997
score: 0
has body: You have to update the context on the action not in the view. At the time the view is rendered, the default values are already evaluated. If you open up a form view from a button of another view, update its context: &lt;button name="do_action" string="Action" context="{'default_field_another_model': 'default'}" /&gt;
type: Answer
answers question: http://stackoverflow.com/q/49941745

http://stackoverflow.com/a/49962862
has comment: http://stackoverflow.com/comment/86942196
has comment: http://stackoverflow.com/comment/86980217
has comment: http://stackoverflow.com/comment/86942039
has comment: http://stackoverflow.com/comment/86942327
has comment: http://stackoverflow.com/comment/86981124
has comment: http://stackoverflow.com/comment/86941991
upvote count: 1
has comment: http://stackoverflow.com/comment/87014827
has comment: http://stackoverflow.com/comment/86941972
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49962741
has comment: http://stackoverflow.com/comment/86944127
has comment: http://stackoverflow.com/comment/86942140
answers question: http://stackoverflow.com/q/49962741
has comment: http://stackoverflow.com/comment/86942099
downvote count: 0
has comment: http://stackoverflow.com/comment/86941911
has comment: http://stackoverflow.com/comment/86941958
score: 1
has body: HI your query returns dict value of decimal like dict_values([Decimal('308617')]) totalAlarmCount=overallAccountDetail.objects.filter(marketName='Market1', accountName= 'Account1').aggregate(Sum('Alarm_Count')).values() So you can change your below like that, sum_count=overallAccountDetail.objects.filter(marketName='Market1', accountName= 'Account1').aggregate(Sum('Alarm_Count')) totalAlarmCount = sum_count['Alarm_Count__sum'] return render(request, 'overallaccountdetail_filter', {'totalAlarmCount': totalAlarmCount})
type: Answer

http://stackoverflow.com/comment/86935703
type: QuestionComment
comment on: http://stackoverflow.com/q/49959510
has text: sorry I'm a newbie. That was in the tracback/error. I just copy and pasted from that.
score: 0
type: Comment

function
tags question: http://stackoverflow.com/q/50010434
tags question: http://stackoverflow.com/q/49945730
tags question: http://stackoverflow.com/q/49923934
tags question: http://stackoverflow.com/q/50068837
tags question: http://stackoverflow.com/q/49932761
tags question: http://stackoverflow.com/q/50073050
type: Tag
tags question: http://stackoverflow.com/q/49950699
tag name: function
tags question: http://stackoverflow.com/q/49929025
tags question: http://stackoverflow.com/q/50008277
tags question: http://stackoverflow.com/q/50017724
tags question: http://stackoverflow.com/q/50011830
tags question: http://stackoverflow.com/q/50066828
tags question: http://stackoverflow.com/q/49960367
tags question: http://stackoverflow.com/q/49931745
tags question: http://stackoverflow.com/q/50028840
tags question: http://stackoverflow.com/q/49922205
tags question: http://stackoverflow.com/q/50041035
tags question: http://stackoverflow.com/q/49998161
tags question: http://stackoverflow.com/q/50052478
tags question: http://stackoverflow.com/q/49957335
tags question: http://stackoverflow.com/q/50032470
tags question: http://stackoverflow.com/q/50054842
tags question: http://stackoverflow.com/q/49994053
tags question: http://stackoverflow.com/q/49987329
tags question: http://stackoverflow.com/q/50035642
tags question: http://stackoverflow.com/q/49929092
tags question: http://stackoverflow.com/q/50015975
tags question: http://stackoverflow.com/q/49928375
tags question: http://stackoverflow.com/q/49967187
tags question: http://stackoverflow.com/q/50068881
tags question: http://stackoverflow.com/q/50054779
tags question: http://stackoverflow.com/q/50005466
tags question: http://stackoverflow.com/q/50042748
tags question: http://stackoverflow.com/q/49928680
tags question: http://stackoverflow.com/q/50013449
tags question: http://stackoverflow.com/q/50043308
tags question: http://stackoverflow.com/q/49957573
tags question: http://stackoverflow.com/q/50034420
tags question: http://stackoverflow.com/q/50007357
tags question: http://stackoverflow.com/q/49927797
tags question: http://stackoverflow.com/q/49921998

http://stackoverflow.com/q/50040060
accepted answer: http://stackoverflow.com/a/50041517
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50041517
has comment: http://stackoverflow.com/comment/87096166
has comment: http://stackoverflow.com/comment/87096422
has comment: http://stackoverflow.com/comment/87096448
upvote count: 0
has body: I am looking at this method(from the book written by Antonio Mele) def post_list(request): posts = Post.published.all() return render(request,'blog/post/list.html',{'posts': posts}) The OP said that we will create HTML templates to render the data generated by the views.I do not understand this.This is the blog folder ls output ~/mysite/blog$ ls admin.py apps.py __init__.py migrations models.py __pycache__ tests.py views.py This is what views looks like cat views.py from django.shortcuts import render I can not grasp link between the post and views.py in this example.
answer count: 1
tagged with: django
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87096464
tagged with: python
score: -1
has title: How to render HTML template?

http://stackoverflow.com/comment/87071792
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50027548
score: 0
has text: edited the code with the credentials. The 405 error apears once chrome opens

http://stackoverflow.com/q/49925331
tagged with: pandas
has title: Dropping rows by comparision between data frames
score: 0
answer count: 1
type: Question
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49925864
has body: I have two dataframes as nf and nf1 nf is as follows : StationID DateTime Channel Class1Count Class2Count Class3Count Class4Count Class5Count Class6Count Class7Count ... Station-ID1 Record Type FIPS State Code Restrictions Month Day Year Hour Total Interval Volume Classification Data Time Interval 0 1 2017-10-01 00:00:00 1 1 201 8 2 0 0 0 ... 111001 C 11 0 10 1 2017 0 212 1 1 2017-10-01 00:00:00 2 0 138 17 2 0 0 0 ... 111002 C 11 0 10 1 2017 0 157 2 1 2017-10-01 00:00:00 3 0 190 63 0 5 0 0 ... 111002 C 11 0 10 1 2017 0 258 3 1 2017-10-01 00:00:00 4 0 150 8 0 0 0 and nf1 is as follows Class1Count Class2Count Class3Count Class4Count Class5Count Class6Count Class7Count Class8Count Class9Count Class10Count Class11Count Class12Count Class13Count Class14Count Class15Count Total Interval Volume Channel 1 1.231800 217.339674 22.622814 2.015312 4.725919 0.882855 0.172724 0.777843 0.658472 0.429533 0.000053 0.000053 0.219879 0.0 0.975575 252.052506 2 2.231112 309.971548 31.127689 3.566335 12.905425 1.029141 0.129119 1.352072 0.450514 0.075925 0.000689 0.001007 0.022359 0.0 0.068878 362.931811 3 1.566203 295.166053 39.603417 8.349304 27.653974 1.021972 0.292649 1.522719 1.309444 0.674738 0.000460 0.000690 0.428506 0.0 19.633268 397.223398 4 3.503365 327.521710 18.011284 3.794444 47.587370 0.865712 0.187673 4.342154 0.977762 0.753398 0.001188 0.000198 0.599248 0.0 8.785139 416.930645 5 1.828119 290.336466 94.103376 3.224558 81.108446 1.465315 0.321380 4.821813 1.323235 0.924199 0.000618 0.000618 0.710523 0.0 3.253741 483.422406 6 1.746899 223.591279 32.923450 2.229845 5.561628 0.788566 0.878682 1.137791 0.689147 nf1 is the groupby of nf by channel with mean. I want to drop all the rows in nf where class2count is less than 10% of class2count in nf1 and also it should be for the same channel which means that it should be for that particular channel can someone help me
tagged with: pandas-groupby

http://stackoverflow.com/q/49984197
upvote count: 2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/86984786
has comment: http://stackoverflow.com/comment/86984773
has comment: http://stackoverflow.com/comment/86984828
tagged with: recursion
has title: Recursion - SyntaxError: invalid syntax
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86984910
answer count: 1
has comment: http://stackoverflow.com/comment/86984821
accepted answer: http://stackoverflow.com/a/49984285
has answer: http://stackoverflow.com/a/49984285
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86984776
has body: I am trying to write a recursive method as follows, but I am getting SyntaxError: invalid syntax, I wonder what I am doing wrong Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ return self.addDigits(x=sum(i for i in str(num)) if x%9&lt;10: Note: I am learning recursion in python, therefore rather than knowing how to solve problem, I would love to learn what I am doing wrong in my implementation.
has comment: http://stackoverflow.com/comment/86984800

http://stackoverflow.com/q/50006973
downvote count: 4
has comment: http://stackoverflow.com/comment/87299362
has comment: http://stackoverflow.com/comment/87030476
answer count: 1
has comment: http://stackoverflow.com/comment/87032334
has comment: http://stackoverflow.com/comment/87030564
has comment: http://stackoverflow.com/comment/87318886
favorite count: 0
tagged with: pyrogram
has body: This code sends a message to the Telegram Supergroup if a new member has joined. When an error occurs when sending a message, I want to change my account to continue. It is possible to go to the next "item". How do I go to the next account in a loop when I receive an error? from pyrogram import Client, Filters list_account = ['001', '002'] for item in list_account: app = Client(item) @app.on_message(Filters.chat("public_link_chat") &amp; Filters.new_chat_members) def welcome(client, message): try: client.send_message( message.chat.id, 'Test', reply_to_message_id=message.message_id, disable_web_page_preview=True ) except Exception as e: print(e) # How do I go to the next account in a loop when I receive an error? app.start() app.join_chat("public_link_chat") app.idle() Function "continue" does not work in this case. Description of function here: https://docs.pyrogram.ml/resources/UpdateHandling
type: Question
has comment: http://stackoverflow.com/comment/87375289
has comment: http://stackoverflow.com/comment/87031030
upvote count: 8
has answer: http://stackoverflow.com/a/50222508
has comment: http://stackoverflow.com/comment/87030490
has title: How to proceed to the next cycle?
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/87318101
has comment: http://stackoverflow.com/comment/87030468
accepted answer: http://stackoverflow.com/a/50222508
type: AnsweredQuestion

http://stackoverflow.com/q/50007097
has title: How these two ids are same?
linked to: http://stackoverflow.com/q/38189660
score: 1
duplicate of: http://stackoverflow.com/q/38189660
has body: Wondering how x and y ids are same! x='merchant_name' y='merchant' + '_' + 'name' print(id(x)) print(id(y)) output: 140291684960176 140291684960176
type: Question
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87030665
favorite count: 0

http://stackoverflow.com/comment/87112914
type: QuestionComment
comment on: http://stackoverflow.com/q/50048111
type: Comment
has text: Nope. I want to the file name to be in increment. Whenever the chicken is being split by comment or other line that do not contain chicken. The next line of chicken should reside on a new file.
score: 0

http://stackoverflow.com/comment/87080143
type: AnswerComment
comment on: http://stackoverflow.com/a/50011499
has text: You are welcome! :) BUT note, if you need to save objects of constant size (integers, floats, complex) this technique will give you extraordinary improvement in performance because no new memory would be allocated as in original @PatrickArtner answer. However, it is not true for strings. They have different length and memory should be allocated independently for each string. Therefore if you need to process big strings, do not keep them in memory. Save position in the file where you find them and reread from this position if you need. For rare rereadings, this gives max performance.
type: Comment
score: 0

http://stackoverflow.com/comment/87066339
type: QuestionComment
has text: And one more thing: while / else statement is really not a good habit.
comment on: http://stackoverflow.com/q/50024939
score: 0
type: Comment

http://stackoverflow.com/comment/87181729
type: AnswerComment
comment on: http://stackoverflow.com/a/50056493
score: 0
has text: Thnks ANK for your comment~!!:)
type: Comment

http://stackoverflow.com/comment/86850227
comment on: http://stackoverflow.com/q/49917187
score: 0
type: Comment
type: QuestionComment
has text: Can you replace `command=self.search_listbox.selection_clear(0, tk.END)` by `command=lambda : self.search_listbox.selection_clear(0, tk.END)` ?

http://stackoverflow.com/comment/87116642
has text: I'm sorry... I guess I don't really see how this is answering my question... Where are those images located and how does your code find them? Could you please explain? (I also updated my question with the import lines I'm using... I'm importing from PySide2)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50049636
score: 1

http://stackoverflow.com/a/50067027
answers question: http://stackoverflow.com/q/50066868
score: 1
type: AcceptedAnswer
downvote count: 0
has body: From the docstring of Queue.join(): Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. So you must call tests.task_done() after processing the item. Since your threads are daemon threads, and the queue will handle concurrent access correctly, you don't need to check if the queue is empty or use a lock. You can just do: def start_thread(): while True: test = tests.get() print("{}".format(test)) tests.task_done()
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50066868
type: Answer

http://stackoverflow.com/comment/86937433
comment on: http://stackoverflow.com/a/49960375
type: Comment
score: 0
type: AnswerComment
has text: well if you have a list of dataframes, then they already are separate -- looks like you're already able to refer to them individually, e.g. as you do with `k_frames[0]`. it's usually better to have a list of elements than a large number of global variables referring to elements of the list

http://stackoverflow.com/q/49949162
has comment: http://stackoverflow.com/comment/86914936
has comment: http://stackoverflow.com/comment/86915060
has answer: http://stackoverflow.com/a/49949317
tagged with: python
tagged with: flask
type: AnsweredQuestion
has body: In python, I would like to: Obtain a filename from a user to a csv file convert the csv into a temporary table run user defined queries against a central database to add data to the table output to a new csv for the user to use. I can handle most of these steps there are just a few things that I don't understand. Is this possible using a sqlite script? Would python sqlite class be able to execute that script? conn = sqlite3.connect(central_database, check_same_thread=False) cur = self.conn.cursor() #user defines csv file and other params via http form -&gt; script cur.execute(script) csv = cur.fetchall() I could be thinking about this all wrong. So here is my setup: python 3.6.3 flask/jinja2 (javascript capable) sqlite 3.22.0
score: 0
tagged with: sqlite
answer count: 1
linked to: http://stackoverflow.com/q/21257899
has comment: http://stackoverflow.com/comment/86915013
has comment: http://stackoverflow.com/comment/86914971
tagged with: jinja2
has title: create a temporary TABLE using a csv file
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86914983
accepted answer: http://stackoverflow.com/a/49949317

http://stackoverflow.com/q/50016217
upvote count: 2
has comment: http://stackoverflow.com/comment/87051027
has comment: http://stackoverflow.com/comment/87054832
downvote count: 0
answer count: 0
has title: Choosing ctypes dll loading mechanism
favorite count: 0
has comment: http://stackoverflow.com/comment/87052426
tagged with: ctypes
type: Question
has comment: http://stackoverflow.com/comment/87054853
has comment: http://stackoverflow.com/comment/87054952
tagged with: windows
tagged with: loadlibrary
has body: I´m working on some code that can access some dll funcionality using ctypes. The library loading was done with: U2_C_INTERFACE = ctypes.cdll.LoadLibrary("mydllname") And this was working in the original developer Windows 10 machine (and others). But on my own machine I got this error when calling library methods: Procedure called with not enough arguments (24 bytes missing) or wrong calling convention After googling I could fix it changing the dll loading method to: U2_C_INTERFACE = ctypes.windll.LoadLibrary("mydllname") This works in my own Windows 10 machine (and others). But it doesn´t work in the original Windows 10 machine, we get this other error when calling library methods: Procedure probably called with too many arguments (24 bytes in excess) Is there a way to know programatically when to use cdll.LoadLibrary and when windll.LoadLibrary? This is the troublesome code, the call to o_session is throwing the commented exception if U2_C_INTERFACE is None: # U2_C_INTERFACE = ctypes.cdll.LoadLibrary("uvic32") U2_C_INTERFACE = ctypes.windll.LoadLibrary("uvic32") subkey = c_char_p(bytes(0)) status = c_long(0) host_l = bytes(servidor_uv, servidor_universe.devolver_sistema_codificacion()) user_l = bytes(usuario_uv, servidor_universe.devolver_sistema_codificacion()) pass_l = bytes(password_uv, servidor_universe.devolver_sistema_codificacion()) acc_l = bytes(cuenta_uv, servidor_universe.devolver_sistema_codificacion()) # Gestión de apertura de sesión o_session = U2_C_INTERFACE.ic_universe_session o_session.argtypes = ( c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, _ctypes.POINTER(c_long)) res = o_session( c_char_p(host_l), c_char_p(user_l), c_char_p(pass_l), c_char_p(acc_l), subkey, _ctypes.byref(status)) The Python version we're using is 3.4.0 (32 bits) Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32 My ctypes version is 1.1.0.
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87054550
has comment: http://stackoverflow.com/comment/87050855
has comment: http://stackoverflow.com/comment/87050868
has comment: http://stackoverflow.com/comment/87052421
score: 2

http://stackoverflow.com/comment/87003115
type: Comment
has text: Did you try writing the data, as `image_bytes`, per the last lines of code in my answer?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49973583

http://stackoverflow.com/comment/86880546
type: Comment
comment on: http://stackoverflow.com/a/49932146
type: AnswerComment
score: 0
has text: got it. In case anyone needs such a solution,

http://stackoverflow.com/q/49941106
has body: I am trying to test the shopping cart part of my flask app. The test that fails is the following one: # Set cart with client.session_transaction() as sess: sess["cart"] = [1, 2] # Remove item from cart client.get("/cart/remove/2") # Test cart with client.session_transaction() as sess: resp = client.get("/") assert [1] == sess.get("cart") The result of the last request is that the sessions still contains [1, 2]. I know that the actual code I'm testing works, because I've tested it manually before, so it must be something to do with how I use the session. Thanks in advance!
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49955210
answer count: 1
tagged with: session-cookies
accepted answer: http://stackoverflow.com/a/49955210
has comment: http://stackoverflow.com/comment/86926695
has title: Flask Testing: Modify session for next request
has comment: http://stackoverflow.com/comment/86902115
tagged with: flask
type: Question
tagged with: testing
tagged with: python

timezone
tags question: http://stackoverflow.com/q/49991380
tags question: http://stackoverflow.com/q/49990152
type: Tag
tag name: timezone

http://stackoverflow.com/comment/87355728
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50018563
type: AnswerComment
has text: auto_bill_amount enum if it is YES like now, i dont see a charge in the sandbox? I probably want paypal to handle recuuring billing so it should be a YES right?

http://stackoverflow.com/a/50018545
has comment: http://stackoverflow.com/comment/87061363
has comment: http://stackoverflow.com/comment/87061316
has comment: http://stackoverflow.com/comment/87062274
answers question: http://stackoverflow.com/q/50018501
has body: Use backward relation. privileges = [] user_roles = UserRole.objects.filter(user__id=USER_ID) for user_role in user_roles: privileges.append(user_role.role.role_priviledge.all()) privileges is a list of Querysets.
upvote count: 2
has comment: http://stackoverflow.com/comment/87064035
has comment: http://stackoverflow.com/comment/87061552
type: Answer
has comment: http://stackoverflow.com/comment/87063670
score: 2
has comment: http://stackoverflow.com/comment/87061721
downvote count: 0
has comment: http://stackoverflow.com/comment/87061770

http://stackoverflow.com/q/49935927
score: -1
has body: When i print datas from a MySQL table on a Tkinter treeview , if the data which is a string contains space , it divide the string into two strings .this make desordre in the treeview , the first new string on a column , and the new second string on the next column of the treeview which is reserved for an other string . here is the code how i print data from the MySQL table on the treeview .`rows = cur.fetchall() if rows : for z in rows: print z[0],z[1],z[2],z[3],z[4],z[5] tv.insert("","end", values=("%s %s %s"%(z[1],z[2],str(z[3])))) #tv.insert("","end", values=("%s %s %s %s %s %s %s %s %s"%(z[1], z[2],str(z[3]),z[4],z[5],z[6],z[7],z[8],z[9]))) cur.close()`
tagged with: tkinter
answer count: 2
upvote count: 0
tagged with: treeview
has comment: http://stackoverflow.com/comment/86893644
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Tkinter treeview string with space issue
has answer: http://stackoverflow.com/a/66769723
has answer: http://stackoverflow.com/a/49951001
tagged with: python

http://stackoverflow.com/q/50015204
downvote count: 0
has answer: http://stackoverflow.com/a/68558553
has title: Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead
has body: I am new to Django and didn't find any reference regarding this issue. I am getting this error when i use many to many field in Django model (models.py). I guess the issue is assigning m2m field in view(views.py) from form(forms.py). How to assign m2m field in view? (Django version 2.0, python - 3.5) models.py class User(AbstractUser): username=models.CharField(max_length=20) email = models.EmailField(_('email address'), unique=True) class Setupuser(models.Model): organization=models.CharField(max_length=200,blank=False,null=True) emails_for_help = models.ManyToManyField(User) views.py class Set_user(FormView): template_name="pkm_templates/set_up_user.html" form_class = Set_User_Form success_url = '/thanks/' def form_valid(self, form): org = form.cleaned_data.get('organization') emails = form.cleaned_data.get("emails_for_help") instance = Setupuser(organization=org,emails_for_help=emails) instance.save() return redirect("/") forms.py class Set_User_Form(ModelForm): emails_for_help = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple ) class Meta: model = Setupuser fields = ["organization","emails_for_help"]
has answer: http://stackoverflow.com/a/66709092
favorite count: 0
type: Question
score: 108
has answer: http://stackoverflow.com/a/75834953
answer count: 5
possible better answer: http://stackoverflow.com/a/61853561
has answer: http://stackoverflow.com/a/61853561
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50015229
type: AnsweredQuestion
tagged with: manytomanyfield
linked to: http://stackoverflow.com/q/5058874
has answer: http://stackoverflow.com/a/50015229
tagged with: django-orm
upvote count: 108

http://stackoverflow.com/a/49927240
has comment: http://stackoverflow.com/comment/86870702
has comment: http://stackoverflow.com/comment/86870666
type: Answer
has body: As you mentioned, warnings and errors are barriers for saving data in a file, so we need them to be removed. You can disable WarningErrors by the use of: import warnings warnings.filterwarnings("ignore") at the top of your code. then, you can write outputs in a text file. Also, you can use try and except blocks, but remember these kind of blocks are very bad for speed of program. If you expect your program to print out 10,000,000, even with cluster pcs you need a long time.
answers question: http://stackoverflow.com/q/49924590
score: 0

http://stackoverflow.com/comment/87027059
type: Comment
type: QuestionComment
has text: anwayway the solution is `list(set(a).intersection(b))`
comment on: http://stackoverflow.com/q/50005229
score: 0

http://stackoverflow.com/q/50031689
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50031737
accepted answer: http://stackoverflow.com/a/50031737
has body: This is supposed to open a tab separated file and print the first row, and add them up. The column is just numbers. I have an error and also not sure how to go about adding them up afterwards. with open(filePath + fileName, 'rt') as inputfile: next(inputfile) dataArray = csv.reader(inputfile, delimiter='\t') for row in inputfile: print dataArray.split('\t',1) Heres the error: File "./Medicalsys", line 38, in &lt;module&gt; print dataArray.split('\t',1) AttributeError: '_csv.reader' object has no attribute 'split'
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87079570
tagged with: http://stackoverflow.com/tag/csv
has title: Python open file cvs reader has no attribute
tagged with: reader
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/87079612

http://stackoverflow.com/comment/87056828
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50020499
has text: why not nested `for` loops?

http://stackoverflow.com/q/49969337
has body: I have a problem where I can't use my Django variables inside Html This is my code : models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) content = models.TextField(default="---") H_price = models.IntegerField(default=0) L_price = models.IntegerField(default=0) remaining = models.IntegerField(default=0) original_price = models.IntegerField(default=0) Ended = models.BooleanField(default=False) Published = models.BooleanField(default=True) class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.title def get_absolute_url(self): return reverse('Products.views.post', args=[self.slug]) Views.py from django.shortcuts import render from .models import Post # Create your views here. def index(request): posts=Post.objects.all() return render(request, 'Index.html', {"Posts": posts}) def post(request): return Index.html This is just a title {% for post in posts %} {{ post.title }} {{ post.content }} {% endfor %} I know this isn't the best way to do Html but the goal is just to get it to work then I will style it with css and make everything Look Clean When i run the server i only get "this is just a title" Any suggestions to help me fix it will be apreciated Note that I am a begginer in django
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/86954607
accepted answer: http://stackoverflow.com/a/49969370
has comment: http://stackoverflow.com/comment/86954604
type: AnsweredQuestion
has title: can't implement django inside html
has comment: http://stackoverflow.com/comment/86954615
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49969370

http://stackoverflow.com/comment/86943259
type: Comment
comment on: http://stackoverflow.com/a/49963520
type: AnswerComment
has text: My doubt is out of the question. Just a bit curious to know if there is such 'NaN' in the input, with 'a' and 'b' equal to 2. Sorry to bother you.
score: 1

http://stackoverflow.com/a/49963909
has comment: http://stackoverflow.com/comment/86944641
has comment: http://stackoverflow.com/comment/86944758
has comment: http://stackoverflow.com/comment/86944850
answers question: http://stackoverflow.com/q/49963862
has comment: http://stackoverflow.com/comment/86944477
has body: I don't see any problems using pickle import pickle import numpy as np x = {(1,2,False): np.array([1,4]), (1,3,False): np.array([4,5])} with open('filename.pickle', 'wb') as handle: pickle.dump(x, handle, protocol=pickle.HIGHEST_PROTOCOL) with open('filename.pickle', 'rb') as handle: y = pickle.load(handle) print x print y After the edit: What you actually have is a lambda, and that cannot be pickled by default. You need to install dill and import it for it to work (see this answer) This is how it should look like: import pickle import numpy as np from collections import defaultdict import dill # doesn't come with default anaconda. Install with "conda install dill" x = defaultdict(lambda: np.zeros(2)) with open('filename.pickle', 'wb') as handle: pickle.dump(x, handle, protocol=pickle.HIGHEST_PROTOCOL) with open('filename.pickle', 'rb') as handle: y = pickle.load(handle) print x print y Output: # no errors :-) defaultdict(&lt;function &lt;lambda&gt; at 0x000000000CD0C898&gt;, {}) defaultdict(&lt;function &lt;lambda&gt; at 0x0000000002614C88&gt;, {}) OP's solution: your edited solution still generated the same error for me but this works fine: import pickle import dill dill_file = open("Q.pickle", "wb") dill_file.write(dill.dumps(Q)) dill_file.close() On my machine (Win 8.1 64 bit, using Spyder), I had no errors when using simple dill.
type: Answer
has comment: http://stackoverflow.com/comment/86944576
has comment: http://stackoverflow.com/comment/86944613
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49919307
type: UnansweredQuestion
has title: python requests unexpectedly decode application/x-gzip content
tagged with: python
score: 0
has body: I'm attempting to retrieve https://donneespubliques.meteofrance.fr/donnees_libres/Txt/Synop/Archive/synop.201803.csv.gz using python requests. However, when accessing response's content I get the csv data, not the gzipped-csv data like I would have expected. It's not clear to me why. &gt;&gt;&gt; url 'https://donneespubliques.meteofrance.fr/donnees_libres/Txt/Synop/Archive/synop.201803.csv.gz' &gt;&gt;&gt; resp = requests.get(url) &gt;&gt;&gt; resp.headers {'Date': 'Thu, 19 Apr 2018 10:48:11 GMT', 'Server': 'MFWS', 'Last-Modified': 'Sat, 31 Mar 2018 21:10:09 GMT', 'ETag': '"3066bd-a2dce-568bbc81bee40"', 'Accept-Ranges': 'bytes', 'Content-Length': '667086', 'Content-Type': 'application/x-gzip', 'Content-Encoding': 'gzip', 'Content-Disposition': 'attachment', 'Keep-Alive': 'timeout=5, max=300', 'Connection': 'Keep-Alive'} &gt;&gt;&gt; resp.content[:100] b'numer_sta;date;pmer;tend;cod_tend;dd;ff;t;td;u;vv;ww;w1;w2;n;nbas;hbas;cl;cm;ch;pres;niv_bar;geop;te' &gt;&gt;&gt; requests.__version__ '2.18.4' If I access the same URL with e.g. curl I get the gzipped content as expected: $ curl https://donneespubliques.meteofrance.fr/donnees_libres/Txt/Synop/Archive/synop.201803.csv.gz -s &gt; data $ file data data: gzip compressed data, was "synop.201803.csv", last modified: Sat Mar 31 21:10:08 2018, from Unix Is this a requests feature I don't get? A server misconfiguration?
has answer: http://stackoverflow.com/a/49919442
answer count: 1
tagged with: python-requests
type: Question

static
tags question: http://stackoverflow.com/q/49936444
tags question: http://stackoverflow.com/q/50046945
tag name: static
tags question: http://stackoverflow.com/q/50070336
type: Tag

http://stackoverflow.com/q/49941327
tagged with: numpy
has comment: http://stackoverflow.com/comment/86900894
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86923706
downvote count: 0
tagged with: cython
has body: I'm confused with which the Cython C++ compilation. I have an algorithm that I have implemented in C++, I either call it from C++ or from python through a Cython wrapper. The wrapping part of the code takes a negligible amount of time, but the algorithm runs ~10x faster if I don't use Cython. The Cython running time is very similar to the C++ time without optimization. I compile my program like this: setup(ext_modules = cythonize(Extension( "max_depth_cpp", sources=["cpp/wrap.pyx", "cpp/count_inliers.cpp", "cpp/max_depth.cpp", "cpp/misc.cpp", "cpp/solver.cpp", "cpp/vec3.cpp" , "cpp/wrapper.cpp"], language="c++", extra_compile_args=["-O3","-std=c++17"], extra_link_args = ["-std=c++17"] ))) Removing the -O3 option does not changing the running time. wrap.pyx import numpy as np cimport numpy as np # for np.ndarray np.import_array() #verk important (seg faults) cdef extern from "wrapper.h": void wrapper(double*, double*, int, double, double*) cpdef max_depth_cpp(np_v1, np_v2, eps): cdef np.ndarray[double, ndim=2, mode='c'] v1 = np_v1 cdef np.ndarray[double, ndim=2, mode='c'] v2 = np_v2 cdef np.ndarray[double, ndim=1, mode='c'] t t = np.zeros(3, dtype=np.double) wrapper(&amp;v1[0,0], &amp;v2[0,0], len(v1), eps, &amp;t[0]) return t wrapper.cpp #include "wrapper.h" #include "solver.h" void wrapper(double* v1_in, double* v2_in, int N, double eps, double* t){ solver(v1_in, v2_in, N, eps, t); //changes t } Solver just calls my calls my C++ method. It copies all the data from the numpy arrays first, but that takes very little of the total time
has title: Cython way slower than corresponding C++ function
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86910752
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108948788
has comment: http://stackoverflow.com/comment/104521327
tagged with: python
tagged with: c++
score: 2

http://stackoverflow.com/q/50015586
has comment: http://stackoverflow.com/comment/87086588
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/87068686
upvote count: 4
answer count: 2
tagged with: bash
has answer: http://stackoverflow.com/a/53784786
type: UnansweredQuestion
has body: I am trying to get the DNS Server IP Addresses using python. To do this in Windows command prompt, I would use ipconfig -all As shown below: I want to do the exact same thing using a python script. Is there any way to extract these values? I was successful in extracting the IP address of my device, but DNS Server IP is proving to be more challenging.
downvote count: 0
tagged with: dns
has comment: http://stackoverflow.com/comment/87047446
tagged with: cmd
linked to: http://stackoverflow.com/q/319279
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/59462226
has title: Python DNS Server IP Address Query
linked to: http://stackoverflow.com/q/1325581

http://stackoverflow.com/comment/129503492
type: AnswerComment
has text: Just in case somebody stumbles on this today, as I did, there is a really nice package by Dr. Gao, SiYu published after this question was answered. It is way more modular than reshaping a string of text, see the examples in the documentations / repo. https://github.com/iruletheworld/matplotlib-curly-brace documentation : https://matplotlib-curly-brace.readthedocs.io/en/latest/index.html I hope it helps others as it did for me!
score: 1
comment on: http://stackoverflow.com/a/50041629
type: Comment

http://stackoverflow.com/a/49920499
type: Answer
has body: You can do a simple process like this: pd.concat([df.loc[:, start:end] for start, end in zip(df2.EntryDate, df2.ExitDate)]) Explanation DataFrames allow for slicing using datetime or a string format parsable as datetime You need to filter the dataframe into smaller parts and then concatenate it The rest is a simply list comprehension
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86858859
answers question: http://stackoverflow.com/q/49920357

http://stackoverflow.com/comment/87121690
type: QuestionComment
comment on: http://stackoverflow.com/q/50052330
has text: Where is your example below?
score: 1
type: Comment

http://stackoverflow.com/a/49958331
has comment: http://stackoverflow.com/comment/86953765
has comment: http://stackoverflow.com/comment/86953442
answers question: http://stackoverflow.com/q/49957157
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: Here's what I was trying to explain in my comment(s). Although I don't know the details of what you're doing, hopefully this will be enough give you the general idea: # Define a class to hold each group of values. class Example: def __init__(x, y, vx, vy, r, t, ke, pe, te): self.x = x self.y = y self.vx = vx self.vy = vy self.r = r self.t = t self.ke = ke self.pe = pe self.te = te # Somehow create a list of Example instances. my_data = [Example(x1, y1, vx1, vy1, r1, t1, ke1, pe1, te1), Example(x2, y2, vx2, vy2, r2, t2, ke2, pe2, te2), ... Example(xN, yN, vxN, vyN, rN, tN, keN, peN, teN)] # Then you could do what you asked about like this: for i, elem in enumerate(my_data): if elem.ke &gt; elem.pe: # Done? break del my_data[i+1:] # Delete remaining elements in my_data.

http://stackoverflow.com/comment/86937260
comment on: http://stackoverflow.com/q/49960374
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Is it possible to sort two lists(which reference each other) in the exact same way?](https://stackoverflow.com/questions/9764298/is-it-possible-to-sort-two-listswhich-reference-each-other-in-the-exact-same-w)

http://stackoverflow.com/q/49994507
linked to: http://stackoverflow.com/q/20140137
score: 0
tagged with: python
has title: python suppress output of subprocess
linked to: http://stackoverflow.com/q/38098203
type: Question
linked to: http://stackoverflow.com/q/4996852
tagged with: subprocess
type: UnansweredQuestion
tagged with: http-redirect
answer count: 1
has answer: http://stackoverflow.com/a/50238622
tagged with: output
has body: there is a hacking challenge. i have a password protected file called "lock" opening file with password returns a QR-code. need to assign QR to a var. Don't want to display QR everytime Works but has output: var = os.system("./lock %s" % password) SO says i should use: var = subprocess.Popen("something.py") tryied to pass like above but that fails cause "Popen" wants a list or a string. if i concat the command as a string before using popen, its still displayed. what a already read (at least) Suppress output of subprocess Passing Variables to Subprocess.Popen How to just call a command and not get its output full code: import sys import os import subprocess def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 lock = "/root/share/lock" print "Hello" passfile = raw_input("Enter the password file name: ") assert os.path.exists(passfile), "I did not find the file at, "+str(passfile) devnull = open(os.devnull, 'wb') trys = file_len(passfile) passfile = open(passfile,'r+') cnt = 1 wrong = os.system("./lock penis") for password in passfile: # com = ("./lock %s" % password) # var = os.system("./lock %s" % password) var = subprocess.Popen("./lock %s" % password, stderr=devnull, stdout=devnull) if var == wrong: os.system('clear') cnt += 1 print ("Try %s/%s " %(cnt, trys)) print ("Currently PIN: %s" % password) else: print "!!!!!!!!!!!!!!!!!" print password redirecting to devnull doesn't work either. OSError: [Errno 2] No such file or directory: ''

http://stackoverflow.com/a/49997235
type: Answer
answers question: http://stackoverflow.com/q/49997012
has comment: http://stackoverflow.com/comment/87010888
downvote count: 0
has comment: http://stackoverflow.com/comment/87010785
upvote count: 1
score: 1
has body: If you open the checkpoint file, you will see something like that : model_checkpoint_path: "/PATH/ON/OLD/MACHINE/model.ckpt-315000" all_model_checkpoint_paths: "/PATH/ON/OLD/MACHINE/model.ckpt-300000" all_model_checkpoint_paths: "/PATH/ON/OLD/MACHINE/model.ckpt-285000" [...] Just remove the /PATH/ON/OLD/MACHINE/, or replace it by the /PATH/ON/NEW/MACHINE/, and you're good to go. Edit : In the future, when creating your tf.train.Saver, you should use the save_relative_paths option. Quoting the doc : save_relative_paths: If True, will write relative paths to the checkpoint state file. This is needed if the user wants to copy the checkpoint directory and reload from the copied directory.

matplotlib-basemap
type: Tag
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/50067799

http://stackoverflow.com/q/50000560
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: I have file (dictionary) and I want to search a specific content from a file, how to write the query? def name_search(): target = open("customers.txt",'r') name_search = input('Search &gt;') for line in target: if name_search in line: print(f'{name_search} in record!') else: print('Not in record!') The above code works, however, it tries to print this line multiple times depending how many lines I have in file. Assuming the line is not present: Not in record! Not in record! Not in record! Not in record!
has answer: http://stackoverflow.com/a/50003253
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87023040
type: UnansweredQuestion
tagged with: python
has title: Search content from a file dictionary in python

http://stackoverflow.com/a/49926992
downvote count: 0
type: Answer
score: 3
answers question: http://stackoverflow.com/q/49926934
has body: You can use list comprehension to iterate the list items and similarly for the inner tuple items &gt;&gt;&gt; [tuple(s.replace('"','') for s in tup) for tup in example] [('7-30-17', '0x34', 'Upload Complete'), ('7-31-17', '0x35', 'RCM,Interlock error')]
upvote count: 3

http://stackoverflow.com/a/50080235
answers question: http://stackoverflow.com/q/50037057
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50037057
has body: Init actions need to be run on all nodes of the cluster, not just the master. The driver started successfully because you had run the init action on the master, but then the job failed on executors because they did not have Conda installed. In general, you should not run initialization actions manually. E.g. if you later add nodes to the cluster, you will need to run the script on the new nodes as well. However, if you specify initialization actions when creating a cluster, Dataproc will handle that for you. You can specify init actions through the web console: Note that if you want to specify metadata (flags) to the init actions, such as conda packages to install, you will need to use gcloud. The easiest way to do that is to start from "Equivalent command line" at the bottom of the create cluster page. In general, I would suggest deleting and recreating your cluster if you want to want to add init actions or add flags. This is especially easy if your input data resides outside the cluster (e.g. Cloud Storage).

http://stackoverflow.com/a/49932978
upvote count: 1
has body: Colin's answer pretty much answer your questions. But if you want to solve your first problem with unordered list, try using built in class OrderedDict under collections library.
answers question: http://stackoverflow.com/q/49931186
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86862857
comment on: http://stackoverflow.com/q/49923417
type: Comment
type: QuestionComment
score: 0
has text: I will print out the first two elements of the list to check if they are the same @MarcoPantaleoni, one sec

http://stackoverflow.com/comment/87083971
has text: There is no numerical integration method that guarantees error bounds without some assumptions on the function (like derivative bounds). If error bounds are important, start by reading up on [numerical integration](https://en.wikipedia.org/wiki/Numerical_integration). Fitting `erf`, which has superexponential decay, makes no sense here.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50033772

http://stackoverflow.com/comment/87089641
has text: Why would you do this? Why not just make two separate classes, `CA` and `CB`, that inherit from either base, then pick from those classes when creating an instance?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50036737

http://stackoverflow.com/comment/87131463
type: QuestionComment
score: 0
has text: I will second @DanCornilescu observation and the error have no relation with `Selenium`.
comment on: http://stackoverflow.com/q/50052053
type: Comment

opengl
tags question: http://stackoverflow.com/q/49957653
tags question: http://stackoverflow.com/q/49979804
tags question: http://stackoverflow.com/q/49953345
type: Tag
tag name: opengl

http://stackoverflow.com/a/50032090
has comment: http://stackoverflow.com/comment/87080778
score: 0
has body: You can't move the file with shutil while it's still open (inside the with clause). First make a list of files you want to move, then move them.
type: Answer
accepted answer of: http://stackoverflow.com/q/50032052
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87080738
answers question: http://stackoverflow.com/q/50032052

http://stackoverflow.com/comment/113566206
has text: so, is there a way to mock configurations (run_dag.conf, hook.get_connection and Variable) and run a dag with actual data, not only importing it?
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/53229181

http://stackoverflow.com/comment/87063352
type: QuestionComment
comment on: http://stackoverflow.com/q/50023635
has text: That looks like a list, not a string...
score: 2
type: Comment

http://stackoverflow.com/comment/86888036
type: Comment
type: QuestionComment
has text: Take a browse through this: http://www.dabeaz.com/generators-uk/index.html
score: 0
comment on: http://stackoverflow.com/q/49936131

http://stackoverflow.com/q/50022443
has comment: http://stackoverflow.com/comment/87062677
tagged with: docker
has comment: http://stackoverflow.com/comment/87062732
type: AnsweredQuestion
score: 0
has title: Django MSSQL server on docker container won't migrate
answer count: 1
accepted answer: http://stackoverflow.com/a/50023712
has comment: http://stackoverflow.com/comment/87062705
type: Question
has answer: http://stackoverflow.com/a/50023712
has comment: http://stackoverflow.com/comment/87062805
has comment: http://stackoverflow.com/comment/87062831
tagged with: django-pyodbc-azure
has comment: http://stackoverflow.com/comment/87062560
has body: UPDATE: Solved I am using macOS, Django 2.0 on a virtualenv, and a Docker Container with the SQL Server 2017 up and running. I'm trying to use this package: https://github.com/michiya/django-pyodbc-azure This is my DATABASES settings.py setup: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'TUTORIAS_DATOS', 'HOST': '0.0.0.0', 'PORT': '1402', 'USER': '***', 'PASSWORD': '***', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'driver_charset': 'iso-8859-1', } } } The problem is that when I do python manage.py makemigrations the migration is made, but when I try to apply the migration to the database (python manage.py migrate) I get: Operations to perform: Apply all migrations: admin, auth, contenttypes, menu, sessions Running migrations: No migrations to apply. Instead of what I should get if I use the sqlite (default Django database), which is: Operations to perform: Apply all migrations: admin, auth, contenttypes, menu, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying menu.0001_initial... OK Applying sessions.0001_initial... OK I don't know what could be the problem, theoretically if I follow this steps (on Windows) it works just fine. The ODBC connection apparently is working because if I setup an improper username/password I get an error. My database (of the container hosted on 0.0.0.0:1402) name is indeed T…
tagged with: django
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/87063023

http://stackoverflow.com/a/50048246
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87116982
answers question: http://stackoverflow.com/q/50047440
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50047440
upvote count: 2
has body: I feel like there should be a way to do this without using a for loop but, I cannot think of it atm, so here's my solution: # Read Example data from io import StringIO # This only works python 3+ df = pd.read_fwf(StringIO( """StatusType County OpenYear ClosedYear Closed Alameda 2005 2015.0 Active Alameda 2006 NaN Closed Alameda 2008 2015.0 Active Alameda 2011 NaN Active Alameda 2011 NaN Active Alameda 2012 NaN Closed Alameda 1980 1989.0 Active Alameda 1980 NaN Active Alameda 1980 NaN""")) # For each year for year in range(2010, 2016+1): # Create a column of 0s df[str(year)] = 0 # Where the year is between OpenYear and ClosedYear (or closed year is NaN) set it to 1 df.loc[(df['OpenYear'] &lt;= year) &amp; (pd.isna(df['ClosedYear']) | (df['ClosedYear'] &gt;= year)), str(year)] = int(1) print(df.to_string) Output: StatusType County OpenYear ClosedYear 2010 2011 2012 2013 2014 2015 2016 0 Closed Alameda 2005 2015.0 1 1 1 1 1 1 0 1 Active Alameda 2006 NaN 1 1 1 1 1 1 1 2 Closed Alameda 2008 2015.0 1 1 1 1 1 1 0 3 Active Alameda 2011 NaN 0 1 1 1 1 1 1 4 Active Alameda 2011 NaN 0 1 1 1 1 1 1 5 Active Alameda 2012 NaN 0 0 1 1 1 1 1 6 Closed Alameda 1980 1989.0 0 0 0 0 0 0 0 7 Active Alameda 1980 NaN 1 1 1 1 1 1 1 8 Active Alameda 1980 NaN 1 1 1 1 1 1 1 (PS: I'm not quite sure what you were trying to do with the groupby)

http://stackoverflow.com/q/50050780
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50051160
score: 1
has body: tiedosto = input("Anna luettavan tiedoston nimi: ") #Here i take user added "File" sana = input("Sana joka korvataan: ") #Here is word that i want to replace korvaa = input("Sana jolla korvataan: ") #Here is word that i want to replace td = open(tiedosto,"r+")#here we open the file for line in td: muutos = td.read().replace(sana, korvaa) #Here it replaces the words td.write(muutos)#Doesent work? print(muutos) td.close() So the td.write(muutos) why doesent it save to the file?
downvote count: 0
answer count: 1
upvote count: 1
has title: Code snippet doesent write to the file
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/17140886

http://stackoverflow.com/a/49991574
accepted answer of: http://stackoverflow.com/q/49991545
upvote count: 11
answers question: http://stackoverflow.com/q/49991545
downvote count: 0
type: Answer
score: 11
has body: dict.update is a method, not a variable you can assign a value to. Try this instead: point1back.update({'nextHop':point1Fwd, 'direction':1, 'distance':0})
type: AcceptedAnswer

http://stackoverflow.com/comment/87145589
type: Comment
has text: Great idea, I can get one prepared within a few minutes.
type: QuestionComment
comment on: http://stackoverflow.com/q/50064422
score: 0

http://stackoverflow.com/q/49996737
has comment: http://stackoverflow.com/comment/87011323
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87012414
answer count: 0
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87011879
has comment: http://stackoverflow.com/comment/87012237
has comment: http://stackoverflow.com/comment/87012029
has body: On the function, confirmAnswer, it updates the question but doesn't display to the user whether their answer is correct or inccorrect which makes me think it is skipping straight to this line, if self.Qn &lt; self.recordNum['text']: on the same function. I only have two questions in the database at the moment allowing testing to be easier and when the question updates, the submit button doesnt work when an answer is inputted when really the quiz should end and display the score which is in the same function. I included this much code as I thought it would make more sense to understand the code so sorry if it is too much and sorry if it comes across confusing. Thank you for your help! def quiz(self): self.newf.pack_forget() self.head['text'] = 'Welcome to the psychology revision quiz' self.quizf.pack() self.quizScore = 0 self.correctAnswer = '' # &lt;-- create it at start (and use better name) self.Qn = 1 self.update_question()# &lt;-- get new question self.update_question_number() def update_question_number(self): # Get question's number query = "SELECT MAX(qnumber) FROM questions" c.execute(query) row = c.fetchone() self.recordNum['text'] = row[0] def update_question(self): # Get new question query = "SELECT * FROM questions WHERE qnumber=?" c.execute(query, (self.Qn,)) row = c.fetchone() self.question['text'] = row[1] self.answer1['text'] = row[2] self.answer2['text'] = row[3] self.answer3['text'] = row[4] self.answer4['text'] = row[5] self.correctAnswer = row[6] def confirmAnswer(self): self.rightOrWrong = self.enterAnswer if self.enterAnswer == self.correctAnswer: self.rightOrWrong['text'] = "Correct" self.quizScore += 1 self.update_question() else: self.rightOrWrong['text'] = "Incorrect" if self.Qn &lt; self.recordNum['text']: self.Qn += 1 # &lt;-- get new question self.update_question() # &lt;-- get new question else: self.rightOrWrong['text'] = "Quiz Complete! Your score was: {}".format(self.quizScore)
has comment: http://stackoverflow.com/comment/87011487
has title: function not working using sql and tkinter (quiz)
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87010657
tagged with: python
has comment: http://stackoverflow.com/comment/87012338
score: 0

http://stackoverflow.com/comment/87103609
type: AnswerComment
has text: @sapo_cosmico cause dayfirst default is false when the first can be month it will convert to m rather than d
comment on: http://stackoverflow.com/a/50033387
type: Comment
score: 0

http://stackoverflow.com/comment/87068213
has text: Scientist init take 6 param you give 6. Their not problem here. Post the full trace plz.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50025967

http://stackoverflow.com/comment/87123026
type: AnswerComment
has text: I don't have enough reputation to comment yet, but for the conversation above you can fix the float result from division by just using int().
comment on: http://stackoverflow.com/a/50053152
type: Comment
score: 0

http://stackoverflow.com/q/50038373
answer count: 1
tagged with: excel
accepted answer: http://stackoverflow.com/a/50039709
type: Question
tagged with: python
has body: I am new with Python but trying to write a code which add a column on multiple .xlsx files and saves this files with the origin name to a new folder. I have started with some coding beneath, but missing some code in open all files and saving to my DestPath. Would be pleased if any has a solution for this: from os import listdir, path import pandas as pd import xlrd SourcePath = 'C:\' #Source Path DestPath = 'C:\' #Destination Path # Listing up all .xlsx files from Source def find_xlsx_filenames( path_to_dir, suffix=".xlsx" ): filenames = listdir(path_to_dir) return [ filename for filename in filenames if filename.endswith( suffix ) ] filenames = find_xlsx_filenames(SourcePath) fname = path.join(SourcePath, filenames[0]) # Tar første fil i mappa. outname = path.join(outputdata, filenames[0]) for i in range(len(filenames)): fname = path.join(SourcePath, filenames[i]) df = pd.read_excel(fname) #Read Excel file as a DataFrame df['new_col'] = 'Sort Data' #Adding a new column named &lt;Sort Data&gt; #To save it back as Excel df.to_excel(DestPath, outname) #Write DateFrame back as Excel file Thanks in Advance
has title: Python: Collect all xlsx. - Open - Add Column - Save in new folder
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50039709
score: 0

http://stackoverflow.com/comment/87039808
type: QuestionComment
has text: When you say "copy a line" and use `f.write()` (is `f` pointing to the input file or a different file? you need to show the definition of `f`). Are you trying to output a new (summary) file, overwrite the original file, or just get a list in memory of lines 3 lines before matches?
score: 0
comment on: http://stackoverflow.com/q/50011572
type: Comment

http://stackoverflow.com/q/50066331
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50067004
accepted answer: http://stackoverflow.com/a/50067004
favorite count: 0
type: AnsweredQuestion
has title: Django - Filter based on number of times a field comes up
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/50067180
type: Question
has answer: http://stackoverflow.com/a/50067180
has body: I have a model that tracks the number of impressions for ads. class Impression(models.Model): ad = models.ForeignKey(Ad, on_delete=models.CASCADE) user_ip = models.CharField(max_length=50, null=True, blank=True) clicked = models.BooleanField(default=False) time_created = models.DateTimeField(auto_now_add=True) I want to find all the user_ip that has more than 1000 impressions. In other words, if a user_ip comes up in more than 1000 instances of Impression. How can I do that? I wrote a function for this but it is very inefficient and slow because it loops over every impression. def check_ip(): for i in Impression.objects.all(): if Impression.objects.filter(user_ip=i.user_ip).count() &gt; 1000: print(i.user_ip)
answer count: 2
tagged with: django-queryset
upvote count: 1

http://stackoverflow.com/q/50037548
upvote count: 11
linked to: http://stackoverflow.com/q/35275026
has title: python is operator behaviour with string
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87091506
has comment: http://stackoverflow.com/comment/87091376
has comment: http://stackoverflow.com/comment/87091492
has comment: http://stackoverflow.com/comment/87091389
linked to: http://stackoverflow.com/q/2858603
has body: I am unable to understand the following behaviour. I am creating 2 strings, and using is operator to compare it. On the first case, it is working differently. On the second case, it works as expected. What is the reason when I use comma or space, it is showing False on comparing with is and when no comma or space or other characters are used, it gives True Python 3.6.5 (default, Mar 30 2018, 06:41:53) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; a = 'string' &gt;&gt;&gt; b = a &gt;&gt;&gt; b is a True &gt;&gt;&gt; b = 'string' &gt;&gt;&gt; b is a True &gt;&gt;&gt; a = '1,2,3,4' &gt;&gt;&gt; b = a &gt;&gt;&gt; b is a True &gt;&gt;&gt; b = '1,2,3,4' &gt;&gt;&gt; b is a False Is there a reliable information on why python interprets strings in different way? I understand that initially, a and b refers to same object. And then b gets a new object, still b is a says True. It is little confusing to understand the behaviour. When I do it with 'string' - it produces same result. What's wrong when I use '1,2,3,4' - they both are strings. What's different from case 1 and case 2 ? i.e is operator producing different results for different contents of the strings.
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87091862
duplicate of: http://stackoverflow.com/q/16756699
linked to: http://stackoverflow.com/q/1392433
has comment: http://stackoverflow.com/comment/87091614
favorite count: 0
score: 9
type: Question
has comment: http://stackoverflow.com/comment/87091634
has comment: http://stackoverflow.com/comment/87091412
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2987958
has comment: http://stackoverflow.com/comment/87091601
tagged with: python-internals
linked to: http://stackoverflow.com/q/40694470
has comment: http://stackoverflow.com/comment/87105187
tagged with: python
accepted answer: http://stackoverflow.com/a/50037786
has comment: http://stackoverflow.com/comment/87091579
tagged with: identity
linked to: http://stackoverflow.com/q/1504717
has answer: http://stackoverflow.com/a/50037786

http://stackoverflow.com/comment/87792627
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50371810
has text: @SARANYA make sure you are using the latest pydoop version, currently 2.0a3: `pip install --upgrade --pre pydoop`. Pydoop 1.x does not support Python 3
type: Comment

http://stackoverflow.com/comment/87152042
comment on: http://stackoverflow.com/q/50067808
score: 0
has text: Either you have to iterate over the dataset, in which case this looks pretty efficient, or you can localize the time point by point as the dataset grows.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57513626
score: 5
answers question: http://stackoverflow.com/q/49938766
downvote count: 0
upvote count: 5
type: Answer
has body: There is a trick in this, instead of searching for the Button (Log In) there is a better way to log in without it. how? let's see: Import the packages you need: from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep #Select the driver, In our case we will use Chrome. chromedriver_path = 'chromedriver.exe' # Change this to your own chromedriver path! webdriver = webdriver.Chrome(executable_path=chromedriver_path) sleep(2) webdriver.get('https://www.instagram.com/accounts/login/?source=auth_switcher') sleep(3) username = webdriver.find_element_by_name('username') username.send_keys('yourUsername') password = webdriver.find_element_by_name('password') password.send_keys('yourPassword') #instead of searching for the Button (Log In) you can simply press enter when you already selected the password or the username input element. submit = webdriver.find_element_by_tag_name('form') submit.submit() You can copy the code and run it directly (even without a real username or password) To get the webdriver (chromedriver.exe) from ChromeDriver

http://stackoverflow.com/q/49941795
tagged with: python
has title: Are unused imports acceptable if they run a function on import?
tagged with: import
has comment: http://stackoverflow.com/comment/86899565
has body: I use a lot of different basic scripts to push data around at different times, pull reports, etc. These have a cron entry to run on a VM. When each of these scripts starts, I want to run a function which is shared. However my current way of doing this feels unclear. A basic example, I have: sharedmodule.py: def script_start_func() # do stuff script_start_func() and then I import this module into each of the scripts that are running, so that the function is run when the module is imported, like so: one_of_many_different_scripts.py: import sharedmodule #flagged in IDE as unused # do normal script stuff It feels like there should be a better way of achieving the same end, although at the time it seemed like a reasonable way of not requiring sharedmodule.script_start_func() at the top of every script. Is there a preferred way of actioning this? I'm starting to think that actually calling the function is only one extra line and is clear as to what is happening? I've searched for this topic but can't seem to find an existing answer. Thanks
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49942942
upvote count: 1
has answer: http://stackoverflow.com/a/49942942
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86900166
type: Question

http://stackoverflow.com/comment/87153627
type: AnswerComment
has text: @MarcusGrass, I updated the answer, added the automatical inference of the content type. It is optional, but if you don't Django will just shove in the default encoding from your project's settings (often text content type), so it's better to specify it if possible, although nothing will break most of the time, because most of modern browsers can handle such things... but sometimes they can not.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50065481

http://stackoverflow.com/comment/87064660
type: QuestionComment
has text: I am not sure but why is pip not in the vpy36/ folder and in the vpy36/local/ folder ? I might be wrong here.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50023985

http://stackoverflow.com/q/49981741
upvote count: 6
score: 6
accepted answer: http://stackoverflow.com/a/50003990
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86979924
has answer: http://stackoverflow.com/a/50003990
tagged with: python
has title: I got an error Attempted relative import beyond top-level package
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/55502383
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/55502383
has comment: http://stackoverflow.com/comment/86983857
has body: I am writing a python application and trying to manage the code in a structure. The directory structure that I have is something like the following:- package/ A/ __init__.py base.py B/ __init__.py base.py app.py __init__.py so I have a line in A/init.py that says from .base import * No problem there, but when I put the same line in B/init.py from .base import * I get an error E0402: Attempted relative import beyond top-level package. Isn't the two supposed to be identical? what exactly am I doing wrong here? I am using Python 3.6, the way I ran the application is from the terminal with &gt; python app.py Thanks UPDATE: Sorry, The error is from somewhere else. In A/base.py i have class ClassA(): ... In B/base.py I have from ..A import ClassA class ClassB(ClassA): ... The error came from the import statement in B/base.py from ..A import ClassA UPDATE #2 @JOHN_16 app.py is as follows:- from A import ClassA from B import ClassB if __name__ == &quot;__main__&quot;: ... Also updated directory to include empty init.py as suggested.
has comment: http://stackoverflow.com/comment/86985745

http://stackoverflow.com/q/50018657
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/87053477
has comment: http://stackoverflow.com/comment/87053548
answer count: 0
has comment: http://stackoverflow.com/comment/87053645
type: UnansweredQuestion
tagged with: types
downvote count: 0
upvote count: 1
tagged with: isinstance
favorite count: 0
has title: python instance() or type() cannot get the right result
linked to: http://stackoverflow.com/q/13181559
has body: Your any help would be great. Thanks in advance! I have 2 files, like below file1: import file2 class Foo(): pass if __name__ == '__main__': foo = file2.dummy() print("right?", isinstance(foo, Foo)) print("right?", type(foo)==Foo) file2: import file1 def dummy(): foo = file1.Foo() return foo if __name__ == '__main__': pass Actually, I expect that isinstance(foo, Foo) is True, type(foo) == Foo is also True, but I get two False. How do I get my expectations?
score: 1
has comment: http://stackoverflow.com/comment/87053530
has comment: http://stackoverflow.com/comment/87053579
duplicate of: http://stackoverflow.com/q/13181559

http://stackoverflow.com/comment/87113325
type: QuestionComment
comment on: http://stackoverflow.com/q/50048539
score: 1
has text: Can you show the expected output?
type: Comment

http://stackoverflow.com/comment/87143219
type: QuestionComment
score: 0
has text: Thanks, I'll try and comeback later :D
comment on: http://stackoverflow.com/q/50059421
type: Comment

http://stackoverflow.com/a/49934587
has comment: http://stackoverflow.com/comment/86885965
score: 1
type: AcceptedAnswer
has body: The procedure is similar to that for pure Python as explained in: Retrieving python module path as you can still look up __file__ on a C extension object. &gt;&gt;&gt; import wrapt._wrappers &gt;&gt;&gt; wrapt._wrappers.__file__ '/Users/graham/Python/wrapt-py36/lib/python3.6/site-packages/wrapt/_wrappers.cpython-36m-darwin.so' In C code, you just need to work through the steps using the C API. PyObject *module = NULL; PyObject *file = NULL; module = PyImport_ImportModule('package.module'); if (module) { PyObject *dict = NULL; dict = PyModule_GetDict(module); file = PyDict_GetItemString(dict, "__file__"); if (file) { ... } Py_XDECREF(file); } Py_XDECREF(module); You then need to drop the last segment of the path to get the directory and construct the path to the other file. I don't show code for that, as depends on whether want to do it yourself in C code, or muck around with trying to call the os.path functions from Python. Also, it is often better to wrap your C extension within a thin Python package wrapper. That way these sorts of things which are easier to do in Python code can be done there as a function. Your C API code can then call your pure Python function if it really needs to. In other words, can save yourself a lot of work by only putting the stuff that needs to be in C code in the extension and do other work in the Python wrapper.
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49934314
type: Answer
answers question: http://stackoverflow.com/q/49934314

http://stackoverflow.com/comment/86882737
comment on: http://stackoverflow.com/q/49933481
has text: Thanks for pointing out the differences and yes I’m actually referring to attributes, not properties. I’ve made the changes in the edits. Same goes to `self.sc`, it should be `self.theta`. I expect to get a copy of theta where I can change its values without changing the attribute in the object. I expect to see exceptions with each of the assertions.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87125923
type: QuestionComment
has text: I'm just building it to learn, not to actually make use of the results, so I'm just trying to understand why the network is not working properly.
comment on: http://stackoverflow.com/q/50054466
score: 1
type: Comment

http://stackoverflow.com/q/49978649
has body: I need to access the PK/ID of a field in the default Django error message. I need this because I add/update multiple fields. How can I display which piece of data failed ? Here is a simple use case of my problem. I got a simple model : class User(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) And a basic serializer : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('__all__') Now, sometime, when adding a list of users with the following function, I get errors : def add_users(data): serializer = UserSerializer( data=data, many=True) if serializer.is_valid(): serializer.save() else: for index in range(0, len(serializer.errors)): logger.error("Validation failed: {0}".format(serializer.errors[index])) Errors are displayed by default like this : Validation failed: {'name': ['This field may not be null.']} Validation failed: {'name': ['This field may not be null.']} But I have 100 different users in my list. I would like to know the PK/id values of the ones who trigger the errors. How can I do that ?
upvote count: 1
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52487589
accepted answer: http://stackoverflow.com/a/52487589
tagged with: django-rest-framework
favorite count: 0
type: Question
tagged with: serialization
has comment: http://stackoverflow.com/comment/86973838
has comment: http://stackoverflow.com/comment/91916553
tagged with: django
tagged with: python
has title: Django Rest Framework : Access primary key of field in serializer.is_valid -> serializer.errors
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/86973695
has answer: http://stackoverflow.com/a/49980207
possible better answer: http://stackoverflow.com/a/49980207

http://stackoverflow.com/comment/87054806
score: 0
type: Comment
has text: @enon97 not as it is, but it can be fixed by a very simple change to the regex (the second `(\d+)` should be changed to `(-?\d+)`).
type: AnswerComment
comment on: http://stackoverflow.com/a/50018109

http://stackoverflow.com/q/49996410
type: AnsweredQuestion
has body: df = DataFrame({'A':['Cat had a nap','Dog had puppies','Did you see a Donkey','kitten got angry','puppy was cute'],'Cat':[1,0,0,1,0],'Dog':[0,1,0,0,1]}) A Cat Dog 0 Cat had a nap 1 0 1 Dog had puppies 0 1 2 Did you see a Donkey 0 0 3 kitten got angry 1 0 4 puppy was cute 0 1 EDIT 1: How can I map every row with a concatenated column names which have '1' in that row? Expected Output: A Cat Dog Category 0 Cat had a nap 1 0 Cat, Dog 1 Dog had puppies 0 1 Dog 2 Did you see a Donkey 0 0 NaN 3 kitten got angry 1 0 Cat, Dog 4 puppy was cute 0 1 Dog
has title: Subset dataframe on Axis 1 based on a condition for rows
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49996451
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49996451
favorite count: 0
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/87043710
comment on: http://stackoverflow.com/a/49988940
type: AnswerComment
has text: Many repeated moves: for instance - left 7 2104 right 8 2105 left 7 2106 right 8 2107 left 7 2108 right 8 left 7 2104 right 8 2105 left 7 2106 right 8 2107 left 7 2108 right 8
score: 0
type: Comment

http://stackoverflow.com/q/49947367
tagged with: artifactory
has title: Authenticate with API key
score: 2
has answer: http://stackoverflow.com/a/49947535
downvote count: 0
has body: I am using the artifactory python module, and my repo does not allow anonymous login, so I need to log in. The first attempt was with the username and password; although I do not want to include that in the code; so I was looking at how to use the API key from my server. The documentation does not seem to include any option for using the artifactory API key. Is there a way to generate a connection with artifactory, using the key, and then use the artifactory python module?
tagged with: python
favorite count: 0
type: Question
upvote count: 2
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49968119

http://stackoverflow.com/q/50024292
type: UnansweredQuestion
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50024478
has comment: http://stackoverflow.com/comment/87064668
answer count: 2
score: 3
has answer: http://stackoverflow.com/a/50024419
has body: How do you print Laguerre polynomials in python? I'm looking for something like Laguerre(n,x) which would give me the Laguerre polynomial L_n(x)
downvote count: 2
has comment: http://stackoverflow.com/comment/87070397
favorite count: 0
has comment: http://stackoverflow.com/comment/87064756
type: Question
has title: Laguerre Polynomials in python

http://stackoverflow.com/a/50055876
has comment: http://stackoverflow.com/comment/87130157
score: 0
answers question: http://stackoverflow.com/q/50040093
has body: Maybe because you didn't use print function You can view the result directly by using IPython (i.e. Jupyter Notebook) Your function looks fine and I would suggest you to eliminate the function like print((dict[in_curr] / dict[out_curr]) * value) #python 3 or change the function into: def currency_converter (value = value,in_curr = in_curr,out_curr = out_curr): Then use print(currency_converter()) to display the final result
type: Answer

http://stackoverflow.com/q/49932549
score: 0
duplicate of: http://stackoverflow.com/q/3490738
has comment: http://stackoverflow.com/comment/86881065
tagged with: python
linked to: http://stackoverflow.com/q/3490738
has title: How to sum list of nested dicts with common keys in their values?
has body: How can I take a list of dicts like this: ps = [{'one': {'a': 30, "b": 30}, 'two': {'a': -1000}}, {'three': {'a': 44}, 'one': {'a': -225}}, {'one': {'a': 2000, "b": 30}}] and produce a dict of dicts like this: {"one": {"a": 1805, "b": 60}, "two": {"a": -1000}, "three": {"a": 44}} I'm pretty sure I can use a collections.Counter() to do this, but what I have so far doesn't work. it just returns whatever the last value of a or b was for each element: res = Counter(ps[0]) for t in ps[1:]: for key, vals in t.items(): res.update(vals) if key not in res.keys(): res[key] = vals else: res[key].update(vals) # Wrong! res Counter({'one': {'a': 2000, 'b': 30}, 'two': {'a': -1000}, 'a': 1819, 'b': 30}) I'm new to python so excuse what I'm sure is ugly code.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86881012
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49932643
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87083980
comment on: http://stackoverflow.com/q/50033903
score: 0
type: QuestionComment
has text: Follow this article https://packaging.python.org/guides/using-testpypi/#using-test-pypi
type: Comment

http://stackoverflow.com/comment/87147202
comment on: http://stackoverflow.com/q/50064950
score: 0
type: Comment
type: QuestionComment
has text: try specifying a cert when attempting to install a package with: "!pip --cert path/to/cert install Scrapy

http://stackoverflow.com/a/49967020
type: Answer
has body: I believe need create new DataFrame by flattenting by chain.from_iterable with splited values with repeating rows by numpy.repeat and for column Text2 use map by Series created from original DataFrame with casting to integer for same types: print (df) Article Reference Text 1 1 3, 4, 5 xyz1 2 2 5, 9, 10 xyz2 3 3 1, 2, 3 xyz3 from itertools import chain s = df['Reference'].str.split(',\s+') lens = s.str.len() df1 = pd.DataFrame({ 'Article2' : list(chain.from_iterable(s)), 'Article1' : df['Article'].values.repeat(lens), 'Text1' : df['Text'].values.repeat(lens), }, columns=['Article1','Text1','Article2']) df1['Text2'] = df1['Article2'].astype(int).map(df.set_index('Article')['Text']) print (df1) Article1 Text1 Article2 Text2 0 1 xyz1 3 xyz3 1 1 xyz1 4 NaN 2 1 xyz1 5 NaN 3 2 xyz2 5 NaN 4 2 xyz2 9 NaN 5 2 xyz2 10 NaN 6 3 xyz3 1 xyz1 7 3 xyz3 2 xyz2 8 3 xyz3 3 xyz3
score: 0
answers question: http://stackoverflow.com/q/49966967

http://stackoverflow.com/q/50000807
has title: Getting the pk from url in Django
type: Question
answer count: 2
downvote count: 0
upvote count: 1
tagged with: django
has body: here is my URL structure that I use to get the item pk in the link : urls.py path('categories/&lt;int:item_category&gt;/', views.item_category, name="item_category"), views.py def item_category(request, pk): item_category = get_object_or_404(Categories, pk=pk) ids = [self.kwargs.get('pk')] cat_id = Categories.objects.get(pk=ids) return render(request, 'items_modal.html', {'item_category': item_category, 'cat_id': cat_id }) Now I want to use the pk to get the result on the new link here is my HTML &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="exampleModalLabel"&gt;{{ cat_id }}&lt;/h5&gt;
has answer: http://stackoverflow.com/a/50000943
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50000833
possible better answer: http://stackoverflow.com/a/50000833
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/50000943
favorite count: 0

http://stackoverflow.com/q/50073397
has answer: http://stackoverflow.com/a/50073557
downvote count: 0
has body: I am currently coding a game with pygame and I have ran into a problem with objects as arguments. So, 1) I have an object class, and 2) A function that takes in a object and an integer and appends the object into an array X times, where X equals integer, then the function returns the array, and 3) A run function that initializes the objects. Each of these parts are in different files. They each import pygame and 3) imports 1) and 2) 1) File: Objects import pygame class Obstacle(pygame.sprite.Sprite): def __init__(self, screen, settings): # Initialize the lander #make the lander a sprite pygame.sprite.Sprite.__init__(self) #Keep local copy of screen self.screen = screen self.image = pygame.image.load('lander.png') self.imageCopy = self.image.copy() self.rect = self.image.get_rect() #Start with each new lander at the top of the screen self.rect.centerx = random.randint(50, settings.screen_width - 50) self.rect.centery = 0 2) File: GameMethods import pygame def random_array(number_needed, object): #Takes in the number of objects to be created in an array #and returns that new array #Use: to make an array that holds randomly located objects number_assigned = 0 array = [] while number_assigned &lt; number_needed: array.append(object) number_assigned += 1 return array 3) File: Main from Objects import Obstacles import GameMethods as gm def run_game(): """Main function to start game and run top-level loop""" # Initialize pygame, settings and screen object. pygame.init() .... some unrelated code .... number_of_fixed_Obstacles_needed = 5 fixed_Obstacles_array = gm.random_array(number_of_fixed_Obstacles_needed, fixedObstacle(screen, settings) The Problem arises in 3) when I call gm.random_array. I am not 100% sure but when I call fixedObstacle as an argument, it is taking the instance or the memory reference of the object and appending the SAME Obstacle 5 times. I am trying to make it append 5 DIFFERENT Obstacle to the array. If I put this inside the run function instead, it …
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87163464
tagged with: pygame
has title: Take object as argument and NOT as instance/reference
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50073557
has comment: http://stackoverflow.com/comment/87163268

http://stackoverflow.com/a/50070257
answers question: http://stackoverflow.com/q/50069223
has comment: http://stackoverflow.com/comment/87157870
has comment: http://stackoverflow.com/comment/87157903
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87157698
has comment: http://stackoverflow.com/comment/87157792
has comment: http://stackoverflow.com/comment/87158026
downvote count: 0
has body: You passed function as a result of lambda, that's why it is a result value in your "after" screenshot. Execute the function in lambda: bank_data['Years in current job'] = bank_data['Years in current job'].apply( lambda x: year_converter(x)) or pass it directly to apply so apply executes it properly instead: bank_data['Years in current job'] = bank_data['Years in current job'].apply( year_converter)
type: Answer
has comment: http://stackoverflow.com/comment/87157840

http://stackoverflow.com/comment/87116338
comment on: http://stackoverflow.com/a/49957768
type: Comment
type: AnswerComment
has text: Ok, sounds like your txt file has duplicate symbols. Add .unique() to filter out duplicates.
score: 0

http://stackoverflow.com/a/49918607
has body: I guess it depends on what system your script is running on, and what resources (such as memory) you have available. But with the popular saying "memory is cheap", you can simply read the file into memory. As a test, I created a file with 2 million lines, each line 1024 characters long with the following code: ms = 'a' * 1024 with open('c:\\test\\2G.txt', 'w') as out: for _ in range(0, 2000000): out.write(ms+'\n') This resulted in a 2 GB file on disk. I then read the file into a list in memory, like so: my_file_as_list = [a for a in open('c:\\test\\2G.txt', 'r').readlines()] I checked the python process, and it used a little over 2 GB in memory (on a 32 GB system) Access to the data was very fast, and can be done by list slicing methods. You need to keep track of the index of the list, when your system crashes, you can start from that index again. But more important... if your system is "crashing" then you need to find out why it is crashing... surely a couple of million lines of data is not a reason to crash anymore these days...
answers question: http://stackoverflow.com/q/49918099
type: Answer
score: 0

http://stackoverflow.com/comment/87028192
type: AnswerComment
has text: Yes the input leads with space it is a dummy list i have created. But the actual list is having 48 lines which and it has a space in it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50004680

http://stackoverflow.com/a/50051900
has comment: http://stackoverflow.com/comment/87121605
downvote count: 1
upvote count: 5
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/87125042
has comment: http://stackoverflow.com/comment/87150396
answers question: http://stackoverflow.com/q/50050040
has body: If you remove the first data point, you will get a much better fit. Using lmfit (https://lmfit.github.io/lmfit-py), which provides a higher-level and easier to use interface to curve-fitting, your fitting script would look like this: import matplotlib.pyplot as plt import numpy as np from lmfit import Model t = np.array([15474.6, 15475.6, 15476.6, 15477.6, 15478.6, 15479.6, 15480.6, 15481.6, 15482.6, 15483.6, 15484.6, 15485.6, 15486.6, 15487.6, 15488.6, 15489.6, 15490.6, 15491.6, 15492.6, 15493.6, 15494.6, 15495.6, 15496.6, 15497.6, 15498.6, 15499.6, 15500.6, 15501.6, 15502.6, 15503.6, 15504.6, 15505.6, 15506.6, 15507.6, 15508.6, 15509.6, 15510.6, 15511.6, 15512.6, 15513.6]) v = np.array([4.082, 4.133, 4.136, 4.138, 4.139, 4.14, 4.141, 4.142, 4.143, 4.144, 4.144, 4.145, 4.145, 4.147, 4.146, 4.147, 4.148, 4.148, 4.149, 4.149, 4.149, 4.15, 4.15, 4.15, 4.151, 4.151, 4.152, 4.152, 4.152, 4.153, 4.153, 4.153, 4.153, 4.154, 4.154, 4.154, 4.154, 4.154, 4.155, 4.155]) def func(t, a, b, alpha): return a + b * np.exp(-alpha * t) # remove first data point, take offset from t tx = t[1:] - t[0] vx = v[1:] # turn your model function into a Model amodel = Model(func) # create parameters with initial values. Note that parameters # are named from the arguments of your model function. params = amodel.make_params(a=v[0], b=0, alpha=1.0/(t[-1]-t[0])) # fit the data to the model with the parameters result = amodel.fit(vx, params, t=tx) # print the fit statistics and resulting parameters print(result.fit_report()) # plot data and fit plt.plot(t, v, 'o', label='data') plt.plot(t, result.eval(result.params, t=(t-t[0])), '--', label='fit') plt.legend() plt.show() This will print out these results Model Model(func) Fit Statistics # fitting method = leastsq # function evals = 44 # data points = 39 # variables = 3 chi-square = 1.1389e-05 reduced chi-square = 3.1635e-07 Akaike info crit = -580.811568 Bayesian info crit = -575.820883 Variables a: 4.15668660 +/- 5.0662e-04 (0.01%) (in…
has comment: http://stackoverflow.com/comment/87145355
has comment: http://stackoverflow.com/comment/87123075
has comment: http://stackoverflow.com/comment/87125717

http://stackoverflow.com/a/49964597
upvote count: 1
has comment: http://stackoverflow.com/comment/86945636
has comment: http://stackoverflow.com/comment/86950604
has comment: http://stackoverflow.com/comment/86950570
has comment: http://stackoverflow.com/comment/86950614
has comment: http://stackoverflow.com/comment/86950670
has comment: http://stackoverflow.com/comment/86950432
type: Answer
has comment: http://stackoverflow.com/comment/86950706
has comment: http://stackoverflow.com/comment/86945475
accepted answer of: http://stackoverflow.com/q/49964558
has comment: http://stackoverflow.com/comment/86950629
has body: EDIT: print (df2) cl4 cl5 cl6 0 43 1 text 1 21 0 text2 2 31 1 text3 3 32 4 text4 #shift column for test next row df2['a'] = df2['cl4'].shift(-1) #join together next cl6 value df2['new'] = df2['cl6'] + ', ' + df2['cl6'].shift(-1) #remove last row of Dataframe because NaN df2 = df2.iloc[:-1] #create list of sets by actual and nex values df2_sets = [set(x) for x in zip(df2['cl4'], df2['a'].astype(int))] df1_sets = [set(x) for x in zip(df1['col1'], df1['col2'])] #compare values and at least one True return True #filter by boolena indexing s = df2.loc[[any(x == y for y in df1_sets) for x in df2_sets], 'new'] print (s) 0 text, text2 2 text3, text4 Name: new, dtype: object
answers question: http://stackoverflow.com/q/49964558
has comment: http://stackoverflow.com/comment/86950471
has comment: http://stackoverflow.com/comment/86951047
has comment: http://stackoverflow.com/comment/86950617
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/q/49929580
has comment: http://stackoverflow.com/comment/86875253
has answer: http://stackoverflow.com/a/49929711
tagged with: arrays
has answer: http://stackoverflow.com/a/49929719
type: Question
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49929711
answer count: 3
has comment: http://stackoverflow.com/comment/86875226
has answer: http://stackoverflow.com/a/49929661
tagged with: python
has body: I am currently doing a data analysis project involving text mining. As of now, I am stuck on filtering out certain phrases. Suppose I have this tokenized array of words arr = ['hello' ',' , 'how', 'is' , 'your', 'day', 'going', '?' , '#', 'HelloWorld'] (hello, how is your day going? #HelloWorld) and I want to remove the #HelloWorld from the sentence. My original logic was traverse through the array and check for the # , once it the # has been found, I would replace the # and the element after the # with a blank space as followed: N = 0 for index to arr: if arr[N] == '#': arr[N] = (' ') arr[N+1] = (' ') N += 1 unfortunately, I got the error list assignment index out of range at line 5. I tried to use the .append() but it only allows modification at N . Is there another approach to this?
has comment: http://stackoverflow.com/comment/86877689
has title: Modifying N+1th element in an array at Nth iteration?
accepted answer: http://stackoverflow.com/a/49929661

http://stackoverflow.com/q/50004657
downvote count: 1
favorite count: 0
tagged with: linechart
has comment: http://stackoverflow.com/comment/87025814
score: 3
tagged with: chart.js
has answer: http://stackoverflow.com/a/57442543
has body: Is it possible to add drag and zoom on ChartJS? I would like to do something similar like here. Here is how I draw my line chart: &lt;canvas class="square_margin_less" id="myChart" width="100" height="30" &gt; &lt;/canvas&gt; &lt;script&gt; new Chart(document.getElementById("myChart").getContext('2d'), { type: 'line', data: { labels:, datasets: [{ label: 'x', data: {{ data.x }}, borderColor: 'rgba(233,105,118,1)', }, { label: 'y', data: {{ data.y }}, borderColor: 'rgba(96,143,239,1)' }, { label: 'z', data: {{ data.z }}, borderColor: 'rgba(144,247,136,1)' }] }, }); &lt;/script&gt; There is some way of personalizing this?
tagged with: python
type: Question
upvote count: 4
type: UnansweredQuestion
answer count: 1
has title: ChartJS line chart drag and zoom
tagged with: django
tagged with: javascript

http://stackoverflow.com/a/50007510
type: Answer
has body: Try this : df.groupby(['index', 'city_id'], as_index=False).sum() This will group the first 2 columns and sum up the remaining ones.
has comment: http://stackoverflow.com/comment/87031704
answers question: http://stackoverflow.com/q/50006950
score: 0

http://stackoverflow.com/q/50022954
upvote count: 0
downvote count: 2
has title: What does getattr() do and how to call functions dynamically (Python)
has comment: http://stackoverflow.com/comment/87062008
has comment: http://stackoverflow.com/comment/87062067
has comment: http://stackoverflow.com/comment/87062074
has body: I know this is a duplicate but I don't understand previous answers, so I'm trying anyway. I need to call different functions, all with the same name, from different classes. so lets say I have this : names = ["classA", "classB"] for a in names: value = a.function() How can I do this easily? I don't understand exactly what getattr() does and how it can help me with my problem. PS - I'm not a native English speaker, so please explain me as simply as possible
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87062230
type: Question
has answer: http://stackoverflow.com/a/50023156
has comment: http://stackoverflow.com/comment/87062091
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/50023156
type: AnsweredQuestion

http://stackoverflow.com/q/50073110
type: AnsweredQuestion
has body: I have a problem running the python code below on Jupyter-notebook. It's okay when I iterate once, but if I change the code to iterate twice, I get errors, why is that? this is the right answer when I iterate once. this is the error when I iterate twice import csv csvfile = open("sales_rank.csv") reader=csv.reader(csvfile) header=next(reader) category={} rank={} for row in reader: category.setdefault(row[1],[]).append(row[4]) for each in reader: rank.setdefault(row[3],[]).append(row[0])
possible better answer: http://stackoverflow.com/a/50073144
linked to: http://stackoverflow.com/q/2106820
score: 1
has answer: http://stackoverflow.com/a/50073144
downvote count: 1
accepted answer: http://stackoverflow.com/a/50073141
favorite count: 0
has answer: http://stackoverflow.com/a/50073141
has comment: http://stackoverflow.com/comment/87162740
has comment: http://stackoverflow.com/comment/87162747
type: Question
has comment: http://stackoverflow.com/comment/87162776
answer count: 2
has title: error when itertating twice on python
tagged with: jupyter-notebook
tagged with: python
upvote count: 2

http://stackoverflow.com/q/50054195
tagged with: python
upvote count: 19
has answer: http://stackoverflow.com/a/50054399
has title: AttributeError: module 'datetime' has no attribute 'strftime'
type: AnsweredQuestion
has body: I've been trying to get today's year, month, and day using datetime. So, I imported the datetime module using import datetime. However, I also needed the timedelta command, so I used from datetime import timedelta. I'm also using strftime, which I believe is gotten from from datetime import datetime. However, I can't run all of these at once. So, how can I use the datetime module, with strftime, and timedelta? Any help is appreciated!
answer count: 2
has answer: http://stackoverflow.com/a/50054282
possible better answer: http://stackoverflow.com/a/50054282
downvote count: 1
accepted answer: http://stackoverflow.com/a/50054399
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87124997
score: 18

http://stackoverflow.com/comment/87008696
has text: Thank you so much! I knew it was something obvious and stupid
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49983562

http://stackoverflow.com/comment/87108654
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50045518
has text: I think merge is not what you want. see my answer.

http://stackoverflow.com/comment/87126734
score: 0
comment on: http://stackoverflow.com/q/50053228
has text: `{"many": False}` in the POST request doesn't mean anything to the serializer. Are you passing in the keyword arg `many=False` when instantiating the serializer in your API View? You should add code for your view here.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86951019
comment on: http://stackoverflow.com/q/49967434
has text: -static -search -images -style.css
type: Comment
type: QuestionComment
score: 0

minimax
type: Tag
tag name: minimax
tags question: http://stackoverflow.com/q/49925045

http://stackoverflow.com/a/50045242
answers question: http://stackoverflow.com/q/50044825
type: Answer
has body: this line ob = Resource.objects may be considered as the key of your bug def handle(self, *args, **options): self.stdout.write('Filling Resource Table') out = '' ob = Resource.objects.all() # Edit here for r in Resource.Label_Choices: if not ob.filter(type=r[0]): Resource.objects.create(type=r[0]) # Edit here out = out + ":" + str(r[0]) else: out = out + ":" + '*' self.stdout.write(self.style.SUCCESS(out))
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50044825

http://stackoverflow.com/comment/87054995
type: QuestionComment
has text: Have you seen https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa or other similar questions?
score: 0
comment on: http://stackoverflow.com/q/50019435
type: Comment

http://stackoverflow.com/comment/87076372
has text: The better solution would be to just check if `frame == None` which is what is returned when [`VideoCapture::read()`](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-read) reaches the end of a file. catching and ignoring exceptions is a bad habit to get into.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50030017

http://stackoverflow.com/comment/86857891
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49918386
type: Comment
has text: About the native "counter" function, I'm afraid that since it relies on the .split function it would not perfectly tokenize the text. This is why I would have rather relied on a function inherent to spaCy, because it could be based on a tokenization made for text mining. I cannot test it right now though, so, maybe it could do the job well after all... Also, I'm afraid that the counter function, which counts every occurrence of every word pre-emptively (if I get it right?) would be really heavy on larger corpora (100M words for example)? Thanks for all the suggestions, it really helps! : )

set-theory
type: Tag
tag name: set-theory
tags question: http://stackoverflow.com/q/50025532

http://stackoverflow.com/comment/86923599
type: Comment
type: QuestionComment
has text: yes. Even `for key,value in dict1.items(): html += r" {} {} ".format(key,value) html += " "` gave me output what i want.
comment on: http://stackoverflow.com/q/49952480
score: 0

http://stackoverflow.com/comment/87115064
type: Comment
has text: what do you want, what should happen with 'last_login_date' filed? i think its behaving correctly.
type: QuestionComment
comment on: http://stackoverflow.com/q/50045251
score: 0

http://stackoverflow.com/comment/86927377
type: QuestionComment
comment on: http://stackoverflow.com/q/49938782
has text: `web.DataReader` returns a MultiIndex DataFrame so your indices do not match when you iteratively assign a new column. Try `data[sym] = web.DataReader(sym, data_source='morningstar')['Close'].reset_index(level='Symbol', drop=True)` (This will get rid of the first level of the index, namely Symbol, since you already have that as a column).
score: 1
type: Comment

attributeerror
tags question: http://stackoverflow.com/q/49968581
tags question: http://stackoverflow.com/q/49971708
tags question: http://stackoverflow.com/q/50051165
tag name: attributeerror
tags question: http://stackoverflow.com/q/49959561
type: Tag
tags question: http://stackoverflow.com/q/50048472
tags question: http://stackoverflow.com/q/49991545

http://stackoverflow.com/q/49944729
score: -1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/136097
downvote count: 2
has answer: http://stackoverflow.com/a/49944817
has comment: http://stackoverflow.com/comment/86905864
upvote count: 1
accepted answer: http://stackoverflow.com/a/49944817
has comment: http://stackoverflow.com/comment/86905783
answer count: 1
has comment: http://stackoverflow.com/comment/86905719
favorite count: 0
type: Question
has title: How to only call __init__ if no other function within a class is called?
has comment: http://stackoverflow.com/comment/86905706
has body: Sorry for a bad explanation in advance - I have searched for a solution for my issue but have not found one. Basically, I am trying to define a class with an init that only gets called if no function within the class is called. For example: class ThisClass(): def __init__(self): print "hello" def otherFunc(self): print "yeet" If I call ThisClass() I would like it to print "hello", but if I call ThisClass().otherFunc() I would like to print "yeet" but NOT print "hello". Anyone know how to help? Again, sorry for a bad explanation but I wasn't sure how to make it better.
tagged with: python

http://stackoverflow.com/a/50017503
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87140583
answers question: http://stackoverflow.com/q/50017243
has comment: http://stackoverflow.com/comment/87052714
has comment: http://stackoverflow.com/comment/87056280
has comment: http://stackoverflow.com/comment/87143906
has comment: http://stackoverflow.com/comment/87143608
has comment: http://stackoverflow.com/comment/87056876
has comment: http://stackoverflow.com/comment/87052613
has comment: http://stackoverflow.com/comment/87143967
has comment: http://stackoverflow.com/comment/87140558
has comment: http://stackoverflow.com/comment/87144261
type: Answer
has body: Here's a way without collections. The idea is to iterate union of dictionary keys and then to utilise the default parameter of dict.get. d1 = {'apple': ['5', '65'], 'blue': ['9', '10', '15', '43'], 'is': ['5', '6', '13', '45', '96'], 'yes': ['1', '2', '3', '11'], 'zone': ['5', '6', '9', '10', '12', '14', '18', '19', '29', '45']} d2 = {'apple': ['43'], 'appricote': ['1', '2', '3', '4', '5', '6'], 'candle': ['1', '2', '4', '5', '6', '9'], 'delta': ['14', '43', '47'], 'dragon': ['23', '24', '25', '26'], 'eclipse': ['11', '13', '15', '19'], 'island': ['1', '34', '35']} res = {} for key in set().union(*(d1, d2)): res[key] = sorted(d1.get(key, []) + d2.get(key, []), key=int) Result: {'apple': ['5', '43', '65'], 'appricote': ['1', '2', '3', '4', '5', '6'], 'blue': ['9', '10', '15', '43'], 'candle': ['1', '2', '4', '5', '6', '9'], 'delta': ['14', '43', '47'], 'dragon': ['23', '24', '25', '26'], 'eclipse': ['11', '13', '15', '19'], 'is': ['5', '6', '13', '45', '96'], 'island': ['1', '34', '35'], 'yes': ['1', '2', '3', '11'], 'zone': ['5', '6', '9', '10', '12', '14', '18', '19', '29', '45']} Or via the equivalent dictionary comprehension: res = {key: sorted(d1.get(key, []) + d2.get(key, []), key=int) for key in set().union(*(d1, d2))} For an ordered dictionary, use collections.OrderedDict afterwards. from collections import OrderedDict res = OrderedDict(sorted([(k, v) for k, v in res.items()]))
has comment: http://stackoverflow.com/comment/87052485
accepted answer of: http://stackoverflow.com/q/50017243
has comment: http://stackoverflow.com/comment/87056174
downvote count: 0
has comment: http://stackoverflow.com/comment/87052556

http://stackoverflow.com/a/50025051
score: 2
has comment: http://stackoverflow.com/comment/87066928
type: Answer
has body: f1 = open('test.txt', 'r') f2 = open('test2.txt', 'w') lines = f1.readlines() find = (input('Enter word to find: ')) replace = input('Enter Word to replace with: ') for line in lines: print('current line: {}'.format(line)) if not find in line: print('world {} not found in this line. Moving to next line'.format(find)) continue print('World {} found in this line'.format(find)) replace_action = input('Are you sure you want to replace for this line y or n') if replace_action.lower() == 'y': line = line.replace(find.lower(), replace) f2.write(line) print("New line: {}".format(line)) else: print('You have cancelled this operation') print("") f1.close() f2.close()
upvote count: 2
has comment: http://stackoverflow.com/comment/87066372
has comment: http://stackoverflow.com/comment/87066496
downvote count: 0
answers question: http://stackoverflow.com/q/50024939
has comment: http://stackoverflow.com/comment/87066518
has comment: http://stackoverflow.com/comment/87066873
has comment: http://stackoverflow.com/comment/87067075

http://stackoverflow.com/q/50016862
answer count: 4
type: AnsweredQuestion
has body: I'm using pytest to test my app. pytest supports 2 approaches (that I'm aware of) of how to write tests: In classes: test_feature.py -&gt; class TestFeature -&gt; def test_feature_sanity In functions: test_feature.py -&gt; def test_feature_sanity Is the approach of grouping tests in a class needed? Is it allowed to backport unittest builtin module? Which approach would you say is better and why?
downvote count: 0
has comment: http://stackoverflow.com/comment/87050535
linked to: http://stackoverflow.com/q/32055287
score: 137
upvote count: 137
possible better answer: http://stackoverflow.com/a/62176555
favorite count: 0
has answer: http://stackoverflow.com/a/62176555
linked to: http://stackoverflow.com/q/52044490
has title: Grouping tests in pytest: Classes vs plain functions
type: Question
tagged with: pytest
accepted answer: http://stackoverflow.com/a/50028551
tagged with: python
has answer: http://stackoverflow.com/a/78410813
has answer: http://stackoverflow.com/a/50028551
has answer: http://stackoverflow.com/a/57532692

http://stackoverflow.com/comment/87116075
comment on: http://stackoverflow.com/q/50049962
type: QuestionComment
type: Comment
has text: Hi! Can you provide us with what "not working" means? Is there an error (and what is it)? Is the output different from what you are expecting (what are you expecting?) etc.
score: 0

http://stackoverflow.com/comment/86897714
has text: Having run a few more tests, I think this is a front-end error, to do with the way the file is passed from axios and saved. Seems the zip works fine, apologies for the confusion!
comment on: http://stackoverflow.com/q/49940292
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86968783
type: AnswerComment
comment on: http://stackoverflow.com/a/49976310
has text: Ah, great. That's a relief! Thanks for the tip.
score: 0
type: Comment

http://stackoverflow.com/comment/87120638
score: 0
comment on: http://stackoverflow.com/q/50051672
type: Comment
type: QuestionComment
has text: do you got multiple python interpreters installed?

http://stackoverflow.com/q/49986887
has comment: http://stackoverflow.com/comment/86993878
type: AnsweredQuestion
score: 0
tagged with: importerror
has comment: http://stackoverflow.com/comment/86990555
has comment: http://stackoverflow.com/comment/86990169
possible better answer: http://stackoverflow.com/a/49987025
linked to: http://stackoverflow.com/q/2325923
tagged with: sudo
accepted answer: http://stackoverflow.com/a/49999140
has answer: http://stackoverflow.com/a/49987025
type: Question
linked to: http://stackoverflow.com/q/18247333
answer count: 2
tagged with: installation
has answer: http://stackoverflow.com/a/49999140
has body: Similar to this question, I have problems importing my own modules and get an ImportError: No module named .... For example, I have a module at myfolder/mymodule.py that I try to load with from myfolder import mymodule. The difference to the other question is that it was working fine before and the problem only occurs on one machine (it works on two other machines). Also I think I know what might have caused the problem: I ran sudo pip install numpy to install NumPy. Now, I read that you should never use sudo with pip install, but it's too late. Is it possible that sudo pip install broke something here? If so, how can I fix it? So far, I didn't mess with PYTHONPATH as suggested by the top answer because I also read that you shouldn't have to touch it when using pip and I don't want to further break the system. Just to clarify; numpy installed correctly, works and is listed when running pip freeze. The problem is really with importing my own module. I don't have a setup.py yet. And again, it worked before - so why would I suddenly need to set a variable or path?
has title: ImportError: No module named... After 'sudo pip install..'
tagged with: pip
tagged with: python

http://stackoverflow.com/a/50047885
accepted answer of: http://stackoverflow.com/q/50047689
answers question: http://stackoverflow.com/q/50047689
has body: L1 = b stores b in the variable L1. So L1 = L[1] and L1 = [1] just change what L1 points to. The second assignment doesn't care what was in L1 before. L[a] = b is essentially equivalent to L.__setitem__(a, b). So while it looks similar to variable assignment, it's a completely different kind of thing. There is no name/variable/pointer/reference L[1]. Also, in your second block of code, L1 = L[1] isn't having any effect. You can remove it and the outcome will be the same.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/q/49949225
has comment: http://stackoverflow.com/comment/86915134
upvote count: 1
duplicate of: http://stackoverflow.com/q/1156087
answer count: 1
favorite count: 0
has title: How to index over specific column in list of arrays?
type: Question
has answer: http://stackoverflow.com/a/49949757
has comment: http://stackoverflow.com/comment/86914979
tagged with: python
linked to: http://stackoverflow.com/q/13084619
score: -1
has comment: http://stackoverflow.com/comment/86914978
accepted answer: http://stackoverflow.com/a/49949757
tagged with: list
linked to: http://stackoverflow.com/q/1156087
duplicate of: http://stackoverflow.com/q/13084619
type: AnsweredQuestion
downvote count: 2
has body: I have list1 = [[50,0.43],[45,0.66]] And I want to get all the second elements in each array so I would like: [0.43,0.66] Also, if I want to check if 50 is in list1, how do I do that? Because using 50 in list1 returns False.

http://stackoverflow.com/a/49954963
answers question: http://stackoverflow.com/q/49954262
downvote count: 0
upvote count: 1
score: 1
has body: The problem is: output = [] for user in users: ... output.append({'extensions' : output}) # here you are adding output to the output check this example: out = [] for i in range(2): out.append({'ext': out}) # output [{'ext': [...]}, {'ext': [...]}] You have the same output. I am sure this is not what you want. So change the line with problem to this one: output.append({'extensions' : user_data})
type: Answer

http://stackoverflow.com/q/49978605
tagged with: python
has answer: http://stackoverflow.com/a/49978881
has answer: http://stackoverflow.com/a/49978924
has title: Spliting an int array into a list of several int arrays in C#
has body: I must convert from python language to C# some code and I'm having difficulties with one part of it. def split_data(seq, length): return [seq[i:i + length] for i in range(0, len(seq), length)] print(split_data([4,5,6,8,5],2)) The purpose of this code is to give an int array in parameters and split it in arrays of the length parameter. For instance here the result of this print will be : [[4, 5], [6, 8], [5]] The thing is I need to have the same thing in C#. So I started to create a List&lt;int[]&gt;. I know how to add int[] inside of it but I have no idea how to split them as in Python, especially using this length parameter. I tried to achieve it using for, foreach loops or even IEnumerable but I couldn't make it work Maybe there is a very easy way to finish it or something I didn't notice yet. My low knowledge about C# is not helping me either :). Thanks for your help anyway.
type: AnsweredQuestion
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/13731796
downvote count: 0
has comment: http://stackoverflow.com/comment/86973935
favorite count: 0
type: Question
tagged with: c#
linked to: http://stackoverflow.com/q/13709626
answer count: 2
has comment: http://stackoverflow.com/comment/86973977
tagged with: arrays
linked to: http://stackoverflow.com/q/419019
possible better answer: http://stackoverflow.com/a/49978881
accepted answer: http://stackoverflow.com/a/49978924

http://stackoverflow.com/a/50033705
score: 1
answers question: http://stackoverflow.com/q/50033671
has body: You can't just assign into a non-existant index for a list to add items to it: &gt;&gt;&gt; a = [] &gt;&gt;&gt; a[0] = 1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: list assignment index out of range Instead you should look at using the .append() method for lists. (The reason you aren't seeing the IndexError debugging details is because your except clause prevents it from being displayed. Bare except clauses are often considered an antipattern because they mask unexpected errors like this and make it harder to tell what went wrong - they catch any exception, not just ones due to bad user input.)
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86909856
comment on: http://stackoverflow.com/a/49946619
score: 0
type: AnswerComment
has text: @twitsnatch621 That's a bad way of doing it, because if two people upload a file really close to each other they'll get the same score, but one person's score will be the other person's score instead of their score. Instead, see if you can send the file directly to the program by modifying it to be a web socket server. Instead of `print`ing, send it back to the user.
type: Comment

http://stackoverflow.com/comment/86935368
type: AnswerComment
has text: I actually have the models & views of posts as well https://stackoverflow.com/questions/49954840/django-createviews-with-2-arguements-user-and-post
comment on: http://stackoverflow.com/a/49958931
type: Comment
score: 0

http://stackoverflow.com/q/49937576
has comment: http://stackoverflow.com/comment/86891065
has body: I am getting the following error in the cnn_utils.py file when doing Coursera CNN example. I did everything I needed to convert the float to the int, but did not get the result. Please help me TypeError Traceback (most recent call last) &lt;ipython-input-22-ddfc1f084c11&gt; in &lt;module&gt;() ----&gt; 1 _, _, parameters = model(X_train, Y_train, X_test, Y_test) &lt;ipython-input-12-a206d32574f3&gt; in model(X_train, Y_train, X_test, Y_test, learning_rate, num_epochs, minibatch_size, print_cost) 36 num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set 37 seed = seed + 1 ---&gt; 38 minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed) 39 40 for minibatch in minibatches: /root/sharedfolder/cnn_utils.py in random_mini_batches(X, Y, mini_batch_size, seed) 49 # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case. 50 num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning ---&gt; 51 for k in range(0, num_complete_minibatches): 52 mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:,:,:] 53 mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:] TypeError: range() integer end argument expected, got float.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86903142
has title: how to solve 'range() integer end argument expected, got float'?
score: 0
has comment: http://stackoverflow.com/comment/86891521
answer count: 0
has comment: http://stackoverflow.com/comment/86891021
has comment: http://stackoverflow.com/comment/86890668
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/102227207
has text: I am facing same issue, can you help me?
type: Comment
comment on: http://stackoverflow.com/a/49982812
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86859093
score: 0
comment on: http://stackoverflow.com/a/49921641
type: Comment
type: AnswerComment
has text: Wow, that's so weird. From this (when I put a list in the place of "col2", I get the actual column names as the values after the "col1" field... so when I use that, it works perfectly for ONE column. I'm after doing the same for an arbitrary number of columns.

http://stackoverflow.com/q/49977576
has answer: http://stackoverflow.com/a/49978375
favorite count: 0
has answer: http://stackoverflow.com/a/49989397
type: Question
has comment: http://stackoverflow.com/comment/86972706
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49978520
has comment: http://stackoverflow.com/comment/87006673
tagged with: django
has comment: http://stackoverflow.com/comment/86993883
tagged with: django-models
tagged with: python
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86972568
answer count: 4
has title: Django queryset custom order with some objects on specified positions
has comment: http://stackoverflow.com/comment/87005656
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/86983061
has answer: http://stackoverflow.com/a/69576100
has body: I have the model: class Article(models.Model): site = models.ForeignKey('Site') published_at = models.DateTimeField(_('Published at')) promoted = models.BooleanField(_('Promoted')) position = models.PositiveSmallIntegerField( _('Position'), null=True, blank=True, ) valid_from = models.DateTimeField(_('Valid from')) valid_to = models.DateTimeField(_('Valid to')) // (...) I want to get the queryset with a specified position of some objects in specified time range. The rest of them should be ordered by published date. The way I do it now works but it is slow and not efficient, which is a problem because I want to use it on the homepage. def get_articles_list(site): articles = Article.objects.filter( site=site, published_at__lte=now(), ).order_by( '-published_at', ) promoted_articles = Article.objects.filter( site=site, promoted=True, valid_from__lte=now(), valid_to__gte=now(), position__isull=False, ) // create a list with no promoted articles on it (to avoid duplicates) articles_list = list(articles.exclude(id__in=promoted_articles)) // put promoted articles on the specific positions of the list if promoted_articles: for promoted in promoted_articles: articles_list.insert(promoted.position - 1, promoted) return articles_list Is there a way to optimize the process? UPDATE For example I have five Article objects: article_1 site: 1 published_at: 2018-04-01 promoted: True position: 4 valid_from: 2018-04-01 valid_to: &lt;tomorrow&gt; article_2 site: 1 published_at: 2018-04-02 promoted: False position: - valid_from: - valid_to: - article_3 site: 1 published_at: 2018-04-03 promoted: False position: - valid_from: - valid_to: - article_4 site: 1 published_at: 2018-04-04 promoted: False position: - valid_from: - valid_to: - article_5 site: 1 published_at: 2018-04-05 promoted: True position: 2 valid_from: 2018-04-05 valid_to: &lt;tomorrow&gt; The order I want to achieve is: [article_4, article_5, article_3, article_1, article_2]
downvote count: 0
has comment: http://stackoverflow.com/comment/87004132
has comment: http://stackoverflow.com/comment/86992186

http://stackoverflow.com/a/50035045
accepted answer of: http://stackoverflow.com/q/50034601
type: AcceptedAnswer
has body: Your code works. A recursive call gameLoop() is in progress. Or I didn't understand the question. What is your name? Vladmir Hello, Vladmir! how old are you? 45 Your age is: 45 and your name is: Vladmir Vladmir you are totally blankable gameloopworks Would you like to play a game? maybe C'mon, let,'s play... OK elif works gameloopworks Would you like to play a game? maybe C'mon, let,'s play... OK elif works gameloopworks Would you like to play a game? maybe C'mon, let,'s play... ys elif works gameloopworks Would you like to play a game? yes you are playing a game Process finished with exit code 0
type: Answer
answers question: http://stackoverflow.com/q/50034601
has comment: http://stackoverflow.com/comment/87124599
score: 0

http://stackoverflow.com/comment/87127720
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50055600
has text: Possible duplicate of https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format
type: Comment

http://stackoverflow.com/comment/109622261
comment on: http://stackoverflow.com/q/49997934
type: QuestionComment
has text: This question is a duplicate of [Formatting only selected tick labels](https://stackoverflow.com/questions/41924963/formatting-only-selected-tick-labels)
score: 1
type: Comment

http://stackoverflow.com/q/49943278
score: 0
tagged with: typeerror
has answer: http://stackoverflow.com/a/49943589
has title: Tensorflow: TypeError: 'numpy.float32' object is not iterable
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/49943589
type: Question
tagged with: numpy
tagged with: tensor
has body: I am a beginner in the world of neural nets, I am building a neural net and want to predict the values in 'yy' by taking 'xx' as an input but I am getting a TypeError: 'numpy.float32' object is not iterable. I have tried changing somethings but it results in some other error. can anyone tell me why I am getting this error and how to correct it? import tensorflow as tf xx=( [178.72,218.38,171.1], [211.57,215.63,173.13], [196.25,196.69,116.91], [121.88,132.07,85.02], [117.04,135.44,112.54], [118.13,124.04,97.98], [116.73,125.88,99.04], [118.75,125.01,110.16], [109.69,111.72,69.07], [76.57,96.88,67.38], [91.69,128.43,87.57], [117.57,146.43,117.57] ) yy=( [212.09], [195.58], [127.6], [116.5], [117.95], [117.55], [117.55], [110.39], [74.33], [91.08], [121.75], [127.3] ) x=tf.placeholder(tf.float32,[None,3]) y=tf.placeholder(tf.float32,[None,1]) n1=5 n2=5 classes=12 def neuralnetwork(data): hl1={'weights':tf.Variable(tf.random_normal([3,n1])),'biases':tf.Variable(tf.random_normal([n1]))} hl2={'weights':tf.Variable(tf.random_normal([n1,n2])),'biases':tf.Variable(tf.random_normal([n2]))} op={'weights':tf.Variable(tf.random_normal([n2,classes])),'biases':tf.Variable(tf.random_normal([classes]))} l1=tf.add(tf.matmul(data,hl1['weights']),hl1['biases']) l1=tf.nn.relu(l1) l2=tf.add(tf.matmul(l1,hl2['weights']),hl2['biases']) l2=tf.nn.relu(l2) output=tf.matmul(l2,op['weights'])+op['biases'] return output def train(x): pred=neuralnetwork(x) # cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y)) sq = tf.square(pred-y) loss=tf.reduce_mean(sq) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) #optimizer=tf.train.RMSPropOptimizer(0.01).minimize(cost) epochs=10 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(epochs): for i in range (int(1)): batch_x=xx batch_y=yy # a=tf.shape(xx) #print(sess.run(a)) i,c=sess.run(loss,feed_dict={x:batch_x, y: batch_y}) epoch_loss+=c print("Epoch ",e…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/86992180
type: QuestionComment
comment on: http://stackoverflow.com/q/49987288
score: 0
has text: You may easily get them with two steps: 1) extract places capturing the part with ages and the Places number ([`('age': .*?;) Place: (\d+).*?(?://|$)`](https://regex101.com/r/v15EzG/2)), 2) extract ages from Group 1 of the previous matches ([`'age':\s*(\d+)`](https://regex101.com/r/v15EzG/3/)).
type: Comment

http://stackoverflow.com/comment/87060490
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50022220
has text: Ok, then the duplicate is correct. Store all the intermediate results in a list or dict.
score: 0

http://stackoverflow.com/comment/86975115
score: 0
comment on: http://stackoverflow.com/q/49975098
type: Comment
type: QuestionComment
has text: please fix your indentation so we can check on "your" code

http://stackoverflow.com/comment/86885341
has text: So I'm guessing your Raspberry Pi has an open *browser* window to some server? And based on something that server sends your browser, you want the browser to trigger a Python script? Is that right? Or are you running Node on the Raspberry Pi?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49934730

http://stackoverflow.com/q/49949796
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86916965
has comment: http://stackoverflow.com/comment/86916935
has body: Currently attempting to create a function where I divide columns in my DataFrame called DF_1 and group them by a dimension column in the same DataFrame. The below code is attempting to achieve this by first grouping by the dimension column and applying a lambda function to each of the columns that I am trying to divide in order to get the average of each of the metrics i.e. cost per conversions, or cost per click. Unfortunately, I am unsure how to accomplish this. The below code gives an error of TypeError: lambda() takes 2 positional arguments but 3 were given calc_1 = DF_1'Conversions_10D', 'Total_Revenue', 'Total_Revenue', 'Clicks', 'Spend' calc_2 = DF_1'Impressions', 'Spend', 'Conversions_10D', 'Impressions', 'Clicks' def agg_avg(df, group_field, list_a, list_b): grouped = df.groupby(group_field, as_index = False).apply(lambda x, y: x/y, list_a, list_b) grouped = pd.DataFrame(grouped).reset_index(drop = True) return grouped {'Date': {0: '2018-02-28', 1: '2018-02-28', 2: '2018-02-28', 3: '2018-02-28', 4: '2018-02-28'}, 'Audience_Category': {0: 'Affinity', 1: 'Affinity', 2: 'Affinity', 3: 'Affinity', 4: 'Affinity'}, 'Demo': {0: 'F25-34', 1: 'F25-34', 2: 'F25-34', 3: 'F25-34', 4: 'F25-34'}, 'Gender': {0: 'Female', 1: 'Female', 2: 'Female', 3: 'Female', 4: 'Female'}, 'Device': {0: 'Android', 1: 'Android', 2: 'Android', 3: 'Android', 4: 'Android'}, 'Creative': {0: 'Bubble:15', 1: 'Bubble:30', 2: 'Wide :15', 3: 'Oscar :15', 4: 'Oscar :30'}, 'Impressions': {0: 3834, 1: 3588, 2: 3831, 3: 3876, 4: 3676}, 'Clicks': {0: 2.0, 1: 0.0, 2: 4.0, 3: 2.0, 4: 1.0}, 'Conversions_10D': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}, 'Total_Revenue': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}, 'Spend': {0: 28.600707059999991, 1: 25.95319236000001, 2: 28.29383795999998, 3: 29.287063200000013, 4: 26.514734159999968}, 'Demo_Category': {0: 'Narrow', 1: 'Broad', 2: 'Narrow', 3: 'Broad', 4: 'Narrow'} 'CPM_Efficiency': {0: 'Low CPM', 1: 'Low CPM', 2: 'Low CPM', 3: 'Low CPM', 4: 'Low CPM'}}
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86916765
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86916731
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/86916573
tagged with: pandas
answer count: 0
has title: Applying a lambda function with three arguments within a Group By
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86916974
downvote count: 0
has comment: http://stackoverflow.com/comment/86916691

http://stackoverflow.com/q/49939282
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86894246
has comment: http://stackoverflow.com/comment/86894793
has comment: http://stackoverflow.com/comment/86894164
has comment: http://stackoverflow.com/comment/86895086
has comment: http://stackoverflow.com/comment/86894525
linked to: http://stackoverflow.com/q/7602639
has answer: http://stackoverflow.com/a/49939375
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86895557
has body: I am getting an error when trying to run my script. The purpose of my script is to split PDFs based on the bookmarks given to them and move them into specific folders. However I'm getting this error when trying to read the PDF. Traceback (most recent call last): File "I:\Harry\[Scripts]\013 - [Blackstone Changes]\3. Split Invoice &amp; SuppDocs.py", line 280, in &lt;module&gt; split(path, filename) File "I:\Harry\[Scripts]\013 - [Blackstone Changes]\3. Split Invoice &amp; SuppDocs.py", line 115, in split pdf = pyPdf.PdfFileReader(open(os.path.join(path, filename), 'rb'), strict=False) TypeError: __init__() got an unexpected keyword argument 'strict' This is my code: def split(path, filename): idx = 1 name_fmt = 'CD_%s_%s.pdf' with open('+Split.csv', 'ab') as fout: writer = csv.writer(fout) print os.path.join(path, filename) pdf = pyPdf.PdfFileReader(open(os.path.join(path, filename), 'rb'), strict=False) filename_no_ext, ext = os.path.splitext(filename) invoice_folder = os.path.join('+Renamed', 'Invoice') sdoc_folder = os.path.join('+Renamed', 'Supporting Docs') try: os.makedirs(invoice_folder) except OSError: pass try: os.makedirs(sdoc_folder) except OSError: pass bookmark_list = list(bookmarks(pdf)) if not bookmark_list: print '\t -&gt;', os.path.join(invoice_folder, filename) shutil.copy( os.path.join(path, filename), os.path.join(invoice_folder, filename) ) return errors = find_errors(bookmark_list) if errors: print &gt;&gt;sys.stderr, os.path.join(path, filename) for error in errors: print &gt;&gt;sys.stderr, error print &gt;&gt;sys.stderr return Does anyone have any ideas on ANYTHING that might be able to help me? Also I'm new to Python so try and dumb it down for me! Thanks!
has title: TypeError: __init__() got an unexpected keyword argument 'strict'
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86894220
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86894366
has comment: http://stackoverflow.com/comment/86895225
has comment: http://stackoverflow.com/comment/86894349
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86894294

http://stackoverflow.com/a/49962510
type: Answer
has comment: http://stackoverflow.com/comment/86941224
score: 2
has comment: http://stackoverflow.com/comment/86941389
accepted answer of: http://stackoverflow.com/q/49962404
upvote count: 2
has body: Well the correlation matrix will always be ordered the same for the data you gave, so it will look like Angola Cases Pop Rate Angola Cases 1.000000 -0.500364 0.779077 Pop -0.500364 1.000000 -0.274885 Rate 0.779077 -0.274885 1.000000 and so you can just select the value you want with .iloc() Just create a dictionary (or list or whatever you want) before the loop and append the country and the value to it with the correct locations. corr_dict = {} df=df2.unstack().fillna(0) for country in df.columns.get_level_values(0).unique(): country_df = df[[c for c in df.columns if c[0] == country]] for c in [c for c in country_df.columns if c[1] in ['Cases', 'Rate']]: country_df = country_df[country_df[c] &gt; 0] corr_dict[country] = country_df.corr().iloc[0,2] corr_dict #{'Afghanistan': -0.6404117984998553, # 'Albania': -0.12115398350489878, # 'Algeria': 0.5031318694416725, # 'Andorra': -0.6933752452815364, # 'Angola': 0.779077493398456}
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86941163
answers question: http://stackoverflow.com/q/49962404

http://stackoverflow.com/comment/86995892
comment on: http://stackoverflow.com/q/49988922
score: 0
has text: i would use [PyTuple_GetItem](https://docs.python.org/2/c-api/tuple.html) and copy the values into a map. Or write a swig typemap that does it for you.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/102320655
type: Comment
has text: Thanks for the detailed explanation. Am running Advanced Python Scheduler (APS) and was wondering how to tweak my code. One of the processes that I want to run with APS is CPU bound.. So am thinking I can move this out of APS and into a Celery process so that it can take advantage of any server that has got more than one CPU. Else if I run all of them under APS then all processes will run on a single CPU
comment on: http://stackoverflow.com/a/49993798
score: 0
type: AnswerComment

executable
tags question: http://stackoverflow.com/q/49950710
type: Tag
tags question: http://stackoverflow.com/q/50062168
tag name: executable
tags question: http://stackoverflow.com/q/49944462

http://stackoverflow.com/q/50067494
upvote count: 4
has answer: http://stackoverflow.com/a/50067935
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87151583
has comment: http://stackoverflow.com/comment/87151869
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87151579
has title: Where can I find the tests made to verify the functions in the python standard library?
tagged with: github
has comment: http://stackoverflow.com/comment/128801161
favorite count: 0
tagged with: python-3.x
type: Question
has body: I am currently in a group project in school. We are using the python standard-library, and we are wondering if it has been tested by the python team. In other words, is there any documentation or open source unit tests for the entire python standard-library, and if so, where can we read more about this?
downvote count: 5
tagged with: python
tagged with: standard-library
answer count: 1
accepted answer: http://stackoverflow.com/a/50067935
score: -1

http://stackoverflow.com/q/49916838
has answer: http://stackoverflow.com/a/49917007
has answer: http://stackoverflow.com/a/49917080
accepted answer: http://stackoverflow.com/a/49917007
has title: List index out of range even when loops don't iterate on the lists
has answer: http://stackoverflow.com/a/49917137
tagged with: python
has body: I'm a beginner at python coding and I've been trying to do this exercise to remove all adjacent characters from a list of integers to a single element using the following block of code: #nums is a list of integers with repeating adjacent characters. For eg. [1,2,2,2,3,3] length = len(nums) for i in range(length): while nums[i] == nums[i+1]: del(nums[i+1]) length-=1 I keep getting the list index out of range error on the while loop, but since neither of the loops depends on the indices of nums directly, then how am I violating the bounds of the list? I have previously checked with other answers to the same problem which all have solutions that relate to list comprehension which I don't want to apply to my code. Also, I'm aware of other approaches to removing adjacent elements but I would like to know what was wrong with my bit of code here for learning purposes. Thanks in advance.
has comment: http://stackoverflow.com/comment/86849034
has answer: http://stackoverflow.com/a/49916983
tagged with: indexing
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49916983
score: 0
has comment: http://stackoverflow.com/comment/86849113
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/86849091

http://stackoverflow.com/comment/86912455
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49947878
has text: The problem is that I'm working with a pretty big architecture and can't really put all that code here. I was hoping someone might know this to be a general problem.

http://stackoverflow.com/comment/86959265
type: QuestionComment
comment on: http://stackoverflow.com/q/49971679
score: 1
has text: @dfundako exactly
type: Comment

http://stackoverflow.com/a/50024547
type: Answer
accepted answer of: http://stackoverflow.com/q/49980978
answers question: http://stackoverflow.com/q/49980978
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I have gotten help from the github. If you have the similar problem, you can get help from The net using while_loop with batch_normalization can't train
score: 1

http://stackoverflow.com/q/49991435
favorite count: 0
has answer: http://stackoverflow.com/a/49991554
possible better answer: http://stackoverflow.com/a/49991554
type: AnsweredQuestion
tagged with: escaping
tagged with: terminal
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49991880
accepted answer: http://stackoverflow.com/a/49991880
type: Question
tagged with: replace
upvote count: 0
answer count: 2
tagged with: subprocess
downvote count: 1
has title: using Python to send subprocess commands with escape characters
has body: I'm using a python script which uses subprocess to pass a commmand to the terminal. Part of the command that I'm passing involves paths which contain parentheses. Python handles strings with parentheses fine, but of course terminal does not handle these without escape characters. I'm trying to pass variables to a command line program by feeding a string into subprocess, but here's simple example to reproduce the error: import subprocess path = '/home/user/Desktop/directory(2018)' command_str = 'rmdir ' + path print (subprocess.run(command_str)) which gives me this error: Traceback (most recent call last): File "ex.py", line 7, in &lt;module&gt; print (subprocess.run(command_str)) File "/usr/lib/python3.6/subprocess.py", line 403, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'rmdir /home/user/Desktop/directory(2018)': 'rmdir /home/user/Desktop/directory(2018)' When I write it directly into the terminal with escape characters it works great. $ rmdir /home/user/Desktop/directory\(2018\) But in Python when I try to add escape characters to the strings before calling subprocess: command_str = command_str.replace('(','\(') command_str = command_str.replace(')','\)') I get the same error as before because, unlike print, the subprocess string adds a second escape character which gets passed to the terminal. Traceback (most recent call last): File "ex.py", line 7, in &lt;module&gt; print (subprocess.run(command_str)) File "/usr/lib/python3.6/subprocess.py", line 403, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child rai…

http://stackoverflow.com/q/49958640
favorite count: 0
type: Question
tagged with: opencv
type: AnsweredQuestion
tagged with: hierarchy
has comment: http://stackoverflow.com/comment/86938573
tagged with: python
has comment: http://stackoverflow.com/comment/86944276
has comment: http://stackoverflow.com/comment/86936254
has comment: http://stackoverflow.com/comment/86938632
upvote count: 4
has comment: http://stackoverflow.com/comment/86936701
tagged with: contour
has title: Sort associated Hierarchy with already sorted Contours in OpenCv in Python
has comment: http://stackoverflow.com/comment/86937004
has answer: http://stackoverflow.com/a/49961085
accepted answer: http://stackoverflow.com/a/49961085
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86936648
score: 4
has body: I am extracting innermost Contours from an Image(input.png) by using the following Code (I am using Python 3.6.3 and opencv-python==3.4.0.12) input.png import copy import cv2 BLACK_THRESHOLD = 200 THIN_THRESHOLD = 10 ANNOTATION_COLOUR = (0, 0, 255) img = cv2.imread('input.png') orig = copy.copy(img) gray = cv2.cvtColor(img, 6) thresh = cv2.threshold(gray, thresh=BLACK_THRESHOLD, maxval=255, type=cv2.THRESH_BINARY_INV)[1] # Find the contours _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) hierarchy = hierarchy[0] # get the actual inner list of hierarchy descriptions idx = 0 # For each contour, find the bounding rectangle and extract it for component in zip(contours, hierarchy): currentContour = component[0] currentHierarchy = component[1] x, y, w, h = cv2.boundingRect(currentContour) roi = img[y+2:y + h-2, x+2:x + w-2] # Skip thin contours (vertical and horizontal lines) if h &lt; THIN_THRESHOLD or w &lt; THIN_THRESHOLD: continue if h &gt; 300 and w &gt; 300: continue if h &lt; 40 or w &lt; 40: continue if currentHierarchy[3] &gt; 0: # these are the innermost child components idx += 1 cv2.imwrite(str(idx) + '.png', roi) Result: As you can see extracted Images are not in any particular order. So to fix this I sorted contours on the basis of their x-axis coordinates. Below is the code: import copy import cv2 BLACK_THRESHOLD = 200 THIN_THRESHOLD = 10 ANNOTATION_COLOUR = (0, 0, 255) img = cv2.imread('input.png') orig = copy.copy(img) gray = cv2.cvtColor(img, 6) thresh = cv2.threshold(gray, thresh=BLACK_THRESHOLD, maxval=255, type=cv2.THRESH_BINARY_INV)[1] # Find the contours _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # Sort Contours on the basis of their x-axis coordinates in ascending order def sort_contours(cnts, method="left-to-right"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method…

http://stackoverflow.com/comment/87316024
score: 0
type: Comment
has text: Hi again, after all, I realized that I had some clusters in my data which contained sometime two or more identical paired sequences. In other words: in one cluster I can have for exemple: sp1 vs sp 2 89, sp1 vs sp2 70 and sp3 vs sp4 50 and what I need to add at the scrip is to keep these two homologous paired sequences, not juste keep the first one which has the best pident score (in fact they are RHP I do not know if you know the what it means?). Do you think it is possible? Thanks you :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49989909

http://stackoverflow.com/comment/86900405
comment on: http://stackoverflow.com/q/49942050
score: 0
has text: I tried to see what is passed as key argument when I use `min(tupleList, key=(lambda key: print(key), key[1]))`, so thats the context nothing too serious. posted here because I thought its a quick syntax question that hasnt been asked yet
type: Comment
type: QuestionComment

excel
tags question: http://stackoverflow.com/q/50027429
tags question: http://stackoverflow.com/q/49996856
tags question: http://stackoverflow.com/q/49943753
tags question: http://stackoverflow.com/q/49990107
tags question: http://stackoverflow.com/q/49949033
tags question: http://stackoverflow.com/q/50038373
tags question: http://stackoverflow.com/q/49949244
tags question: http://stackoverflow.com/q/49947610
tags question: http://stackoverflow.com/q/49941079
tags question: http://stackoverflow.com/q/49988311
tags question: http://stackoverflow.com/q/49986396
tag name: excel
tags question: http://stackoverflow.com/q/49990790
tags question: http://stackoverflow.com/q/50010257
tags question: http://stackoverflow.com/q/50011476
tags question: http://stackoverflow.com/q/49954080
tags question: http://stackoverflow.com/q/49972988
tags question: http://stackoverflow.com/q/50009698
tags question: http://stackoverflow.com/q/50007815
tags question: http://stackoverflow.com/q/49959503
tags question: http://stackoverflow.com/q/49984377
tags question: http://stackoverflow.com/q/50054238
type: Tag
tags question: http://stackoverflow.com/q/49990152
tags question: http://stackoverflow.com/q/49993801
tags question: http://stackoverflow.com/q/50033236
tags question: http://stackoverflow.com/q/50019210
tags question: http://stackoverflow.com/q/49990066
tags question: http://stackoverflow.com/q/49940522
tags question: http://stackoverflow.com/q/49954777
tags question: http://stackoverflow.com/q/49950976
tags question: http://stackoverflow.com/q/49932064
tags question: http://stackoverflow.com/q/49927837
tags question: http://stackoverflow.com/q/49993057
tags question: http://stackoverflow.com/q/50034590
tags question: http://stackoverflow.com/q/49937041
tags question: http://stackoverflow.com/q/50020659
tags question: http://stackoverflow.com/q/49938293
tags question: http://stackoverflow.com/q/50065860
tags question: http://stackoverflow.com/q/49929988
tags question: http://stackoverflow.com/q/49969966

http://stackoverflow.com/a/49979311
has body: Try something like this: import os import os.path home = os.getenv("A_HOME") filepath = os.path.join(home, "components", "xxx", "etc", "static-data", "GenericEntityList.xml") with open(filepath, 'r') as f: for line in f: print(line)
answers question: http://stackoverflow.com/q/49977495
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/86974771
has comment: http://stackoverflow.com/comment/86974845
downvote count: 0
has comment: http://stackoverflow.com/comment/86975298
upvote count: 1

http://stackoverflow.com/a/50002908
score: 0
has body: d = {'actions': [1, 2, 1, 6, 4], 'fraud': [True, False, True, True, False]} df = pd.DataFrame(data=d) print (pd.concat([frauds.sample(n = 1, replace = 'False'), normal.sample(n = 1, replace = 'False')]))
answers question: http://stackoverflow.com/q/50002579
type: Answer

http://stackoverflow.com/comment/87141404
comment on: http://stackoverflow.com/q/50062029
type: Comment
type: QuestionComment
has text: I see, thanks for the info. was useful
score: 0

http://stackoverflow.com/q/50012376
upvote count: 4
has answer: http://stackoverflow.com/a/50012617
has title: Python does not free memory when variable goes out of scope
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87041729
answer count: 2
has answer: http://stackoverflow.com/a/50012705
downvote count: 0
has comment: http://stackoverflow.com/comment/87041249
tagged with: memory
favorite count: 0
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/1316767
accepted answer: http://stackoverflow.com/a/50012705
has comment: http://stackoverflow.com/comment/87041273
possible better answer: http://stackoverflow.com/a/50012617
has comment: http://stackoverflow.com/comment/87041713
tagged with: python
has body: When I initialize a Numpy array inside a function, Python does not free the memory after the function returns as shown in the code example below. Is there any way I can free this memory? Using gc.collect() did not work and the same problem also occurs in Python2 and Python3. import numpy as np import resource def function(): x = np.random.random([10000, 10000]) print('Memory usage: %s (kb)'% resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) function() print('Memory usage: %s (kb)'% resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) Code output: Memory usage: 20560 (kb) Memory usage: 801832 (kb)
score: 4

http://stackoverflow.com/q/49940299
has title: Run Images in Loop Tkinter
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/gif
has answer: http://stackoverflow.com/a/49959679
tagged with: raspberry-pi3
has body: I am creating an app that will allow users to scan a ticket and a message will be displayed. I have created a short GIF animation to play when the app starts to show users where to scan their ticket. I am having trouble understanding how to play a GIF image using tkinter in Python 3. I have tried many solutions and I came across a piece of code where you select the folder and the images in that folder will play in a loop but it's not working. I think I'm not understanding the code. Here is my code for my app: from tkinter import * from tkinter import messagebox import tkinter.filedialog from tkinter.filedialog import askdirectory import requests import simplejson as json import os #from json import JSONEncoder #class MyEncoder(JSONEncoder): #def default(self, o): #return o.__dict__ #Connect to API function def apiconnect(statusvar): ticektid = e1.get() def to_serializable(ticketid): return str(ticketid) url = "https://staging3.activitar.com/ticket_api/tickets" data = {'ticket_id':e1.get(),'direction': 'up'} headers = {'Content-Type': 'application/json','Authorization' :'J0XDvDqVRy9hMF9Fo7j5'} r = requests.post(url,data=json.dumps(data), headers=headers) requestpost = requests.post(url, headers=headers, json=data) response_data = requestpost.json() statusvar = (response_data["status"]) messagevar = (response_data["message"]) json.dumps(url,data) # MyEncoder().encode(ticketid) #'{"ticekt_id": "/foo/bar"}' #19 February 2018 #def from_json(json_object): # if 'ticket_id' in json_object: # return FileItem(json_object['ticket_id']) # ticketid = JSONDecoder(object_hook = from_json).decode('{"ticket_id": "/foo/bar"}') #Including GPIO config if statusvar == "failed": messagebox.showinfo("Cape Point", messagevar) else: statusvar == "successful" #Run at full screen automatically: #---------------Function &amp; Class--------------------------------# class FullScreenApp(object): def __init__(self, master, **kwargs): self.master=master pad=3 self._geom='200x200+0+0' master.geometr…
tagged with: python
linked to: http://stackoverflow.com/q/43770847
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/28518072
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter

http://stackoverflow.com/comment/87012338
comment on: http://stackoverflow.com/q/49996737
type: Comment
has text: I'm doing this program for my A-level computing, it was a big jump from GCSE and we were forced to use tkinter and sql without any help at all. I have watched many tutorials and not many help with this issue. I will take into account what you have said and try to fix the issue and will also search elsewhere. Thanks for your help!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86902938
score: 0
type: Comment
type: QuestionComment
has text: < If i Count the number of files in the folder ... > If you only have files named `Capture_##.jpg` and there is no gaps yes, if not you'll need to filter them as I suggested with `glob.glob('Capture_*.jpg')`. I provided a suggestion which works in the more general case with the info I had.
comment on: http://stackoverflow.com/q/49943195

http://stackoverflow.com/a/49961859
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49961854
type: Answer
answers question: http://stackoverflow.com/q/49961854
score: 2
type: AcceptedAnswer
downvote count: 0
has body: re.sub("[^0-9.]", "", str1) will keep the decimal dot too. Is there any other punctuation you want to keep? Note that this will still fail to produce a valid integer on inputs with more than one decimal dot, such as 123..45 or 1.2.3 or . or 1. or anything that looks weird. The code discards everything but numbers and points, with no regard as to how many points or numbers are there. An infeasible number such that 223523523948231472389523 will still be kept, and depending on the way your database works (whether or not it can store numbers above 64 bits), the resulting number stored in the database may be negative or truncated!

http://stackoverflow.com/comment/86894292
type: QuestionComment
has text: Please also delete your answer below (it is not an answer) and move it into the question. A code formatting tool is provided, please use that. Thanks!
type: Comment
comment on: http://stackoverflow.com/q/49939098
score: 1

http://stackoverflow.com/comment/86916286
comment on: http://stackoverflow.com/q/49949814
type: Comment
score: 7
type: QuestionComment
has text: Hint: try going through `x_list` _backwards_. Do you notice any clear patterns? :)

http://stackoverflow.com/q/49993689
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87004018
tagged with: list
has comment: http://stackoverflow.com/comment/87004253
has comment: http://stackoverflow.com/comment/87004261
upvote count: 3
has comment: http://stackoverflow.com/comment/87035651
possible better answer: http://stackoverflow.com/a/49993893
has comment: http://stackoverflow.com/comment/87005036
has comment: http://stackoverflow.com/comment/87004426
has comment: http://stackoverflow.com/comment/87003951
has comment: http://stackoverflow.com/comment/87003877
has comment: http://stackoverflow.com/comment/87003879
has body: I would like to split a list and return the bounds so in extend no single element should exist. E.g split(list(range(1,101)),2) # should return [[1,50],[51,100]] split(list(range(1,101)),3) # should return [[1,33],[34,66],[67,100]] split(list(range(1,6)),3) # should return [[1,2],[3,5]] # Ideally last element should merge with last if last one has no pair. So far I tried def split(l, n): x = list(range(1, l+1)) return [x[i:i+n] for i in range(0, len(x), int(len(x)/n))] print(split(20, 2)) which returns [[1, 2], [11, 12]] instead of [[1, 10], [11, 20]]
has answer: http://stackoverflow.com/a/49994246
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49994055
tagged with: split
has answer: http://stackoverflow.com/a/49994055
has title: Split list in almost equal parts and return bounds
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49994035
has comment: http://stackoverflow.com/comment/87043206
has comment: http://stackoverflow.com/comment/87004236
has answer: http://stackoverflow.com/a/49993893
has comment: http://stackoverflow.com/comment/87004010
has comment: http://stackoverflow.com/comment/87003983
has comment: http://stackoverflow.com/comment/87035520
answer count: 4
has comment: http://stackoverflow.com/comment/87043119
has comment: http://stackoverflow.com/comment/87004166
has comment: http://stackoverflow.com/comment/87043057

http://stackoverflow.com/comment/87015814
score: 0
has text: Thanks, but the pulsar-client is only for produce and consume clients not admin clients. OK, then it is Jackson data-binding I have issues with since the server states: org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.HashSet` out of START_OBJECT token
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49999623

http://stackoverflow.com/comment/86935668
type: Comment
type: AnswerComment
has text: @VarunVu It seems that `status_lookup` is not a coroutine. Is tweepy asyncio aware at all?
score: 0
comment on: http://stackoverflow.com/a/49956568

http://stackoverflow.com/q/49978817
answer count: 1
has answer: http://stackoverflow.com/a/49978907
has comment: http://stackoverflow.com/comment/86973736
favorite count: 0
type: Question
tagged with: tkinter
has title: SyntaxError: invalid character in identifier python 3.6
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has body: from tkinter import * from tkinter import messagebox as ms import sqlite3 with sqlite3.connect('quit.db') as db: c = db.cursor() c.execute('CREATE TABLE IF NOT EXISTS user (username TEXT NOT NULL ,password TEXT NOT NULL);') db.commit() db.close() class main: def __init__(self, master): # Window self.master = master # Some Usefull variables self.username = StringVar() self.password = StringVar() self.n_username = StringVar() self.n_password = StringVar() # Create Widgets self.widgets() # Login Function def login(self): # Establish Connection with sqlite3.connect('quit.db') as db: c = db.cursor() # Find user If there is any take proper action find_user = ('SELECT * FROM user WHERE username = ? and password = ?') c.execute(find_user, [(self.username.get()), (self.password.get())]) result = c.fetchall() if result: self.logf.pack_forget() self.head['text'] = self.username.get() + '\n Loged In' self.head['pady'] = 150 else: ms.showerror('Oops!', 'Username Not Found.') def new_user(self): # Establish Connection with sqlite3.connect('quit.db') as db: c = db.cursor() # Find Existing username if any take proper action find_user = ('SELECT * FROM user WHERE username = ?') c.execute(find_user, [(self.username.get())]) if c.fetchall(): ms.showerror('Error!', 'Username Taken Try a Diffrent One.') else: ms.showinfo('Success!', 'Account Created!') self.log() # Create New Account insert = 'INSERT INTO user(username,password) VALUES(?,?)' c.execute(insert, [(self.n_username.get()), (self.n_password.get())]) db.commit() # Frame Packing Methords def log(self): self.username.set('') self.password.set('') self.crf.pack_forget() self.head['text'] = 'LOGIN' self.logf.pack() def cr(self): self.n_username.set('') self.n_password.set('') self.logf.pack_forget() self.head['text'] = 'Create Account' self.crf.pack() # Draw Widgets def widgets(self): self.head = Label(self.master, text='LOGIN', font=('', 35), pady=10) self.head.pack() self.logf = Frame(self.master, padx=10, pady=10) Label(self.lo…
linked to: http://stackoverflow.com/q/7297888
has comment: http://stackoverflow.com/comment/86974132
downvote count: 3

http://stackoverflow.com/comment/87013651
type: QuestionComment
has text: The function body formatting is not right. Can you please correct that?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49997220

http://stackoverflow.com/q/49934606
tagged with: dbscan
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55742780
tagged with: python
upvote count: 4
score: 2
downvote count: 2
has body: I'm looking for a way to cluster set of features with DBSCAN algorithm in tensorflow however I'm unable to find anything related. TensorFlow offers K-Means clustering (tf.contrib.learn.KMeansClustering), but I need DBSCAN algorithm. Can anybody suggest me any existing wrappers written in python/java? Any pointers on how to implement it from scratch? P.S. I am aware of sklearn and similar libraries that has DBSCAN, but I specifically need in TensorFlow.
tagged with: cluster-analysis
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: How to implement DBSCAN clustering in tensorflow?

http://stackoverflow.com/q/50072678
has comment: http://stackoverflow.com/comment/87171290
tagged with: android
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/87172325
has comment: http://stackoverflow.com/comment/87204235
score: 0
has title: My kivy app won't work in my phone(just a black scren), but works in my computer and with kivy launcher
tagged with: buildozer
answer count: 0
has comment: http://stackoverflow.com/comment/87191734
has comment: http://stackoverflow.com/comment/87165392
has comment: http://stackoverflow.com/comment/87175504
type: Question
has comment: http://stackoverflow.com/comment/87176151
has body: I'm learning kivy and after successfully using buildozer in a simple label app, I made a kivy app that is a little more complex with buttons, the strange thing is that this kivy app runs perfectly in my computer and with kivy launcher, but when I use buildozer to create and apk and install it in my phone the app doesn't do anything; when I launch the app the loading screen appears with the kivy logo, after that a black screen without anything. I'm not importing any library except from kivy, to test I made a really simple 1 button kivy app and the same happens. -I'm only importing kivy in the the main.py, therefore I don't think that adding anything in the libraries to be imported by buildozer has anything to do with the problem. -The logs don't show anything, the logs from an app that worked with a ping pong game and the app with buttons that doesn't work are exactly the same. -The app doesn't crash just stays with a black screen so I think that something is not running properly in the apk, but it works in my computer and with the kivy launcher in my phone, that is why I believe that probably is some configuration in the creation of the app with buildozer that makes the app behave strange in the phone. -The only difference with the other apps that worked are the buttons, maybe something makes the app to not work properly because of the buttons?, but it would be strange that more complex things like an animation works but buttons do not. If anyone has any idea I would appreciate the help. main.py file from kivy.app import App from kivy.uix.floatlayout import FloatLayout class ButtonTest(FloatLayout): pass class BtnTestApp(App): def build(self): return ButtonTest() if __name__=='__main__': BtnTestApp().run() BtnTest.kv file: &lt;ButtonTest&gt;: Button: text:'A' on_press: self.text= self.text + 'A' The buildozer file: [app] # (str) Title of your application title = Test 5 # (str) Package name package.name = test5 # (str) Package domain (needed for android/ios packaging…
type: UnansweredQuestion

http://stackoverflow.com/a/49949320
has body: You have a hidden character in your html template: {&lt;200c&gt;{book.name }} Delete your opening curly braces and re-type them. It should work fine after that.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49947105

http://stackoverflow.com/a/49920649
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You can use: EntryDate = df2.index.get_level_values('EntryDate') ExitDate = df2.index.get_level_values('ExitDate') idx = np.concatenate([pd.date_range(s, e) for s, e in zip(EntryDate, ExitDate)]) df = df1[df1.index.get_level_values('EntryDate').isin(np.unique(idx))] Explanation: First get values of MultiIndex by get_level_values Create date_ranges in loop and join together Last filter by isin with boolean indexing only by unique datetimes
accepted answer of: http://stackoverflow.com/q/49920357
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49920357

http://stackoverflow.com/comment/86915102
score: 1
comment on: http://stackoverflow.com/q/49948000
type: QuestionComment
has text: Can it be that your angles in degrees are taken as radians?
type: Comment

http://stackoverflow.com/comment/86857678
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49920557
has text: Change the `CONTENT-TYPE` in your header to `application/json`

http://stackoverflow.com/a/49980100
type: Answer
upvote count: 1
has body: I noticed a couple of things in your code that if you did them slightly different maybe it would be easier to control the program's flow. For starters, use more descriptive variable names, if you have a list of instances for example, a good name would simply be instances. Here is an example of how you could do this: import boto3 client = boto3.client('ec2',region_name='ap-south-1') data = client.describe_instances() count=0 reservations = data["Reservations"] for reservation in reservations: instances = reservation["Instances"] for instance in instances: tags = instance["Tags"] instanceId = instance['InstanceId'] hasOwner = len([tag for tag in tags if tag["Key"] == "Owner"]) &gt; 0 print "The following Instance does not have Owner Tag: " + instanceId Notice how I also added some spacing to increase readability. Lastly, if you have a string, namely "Owner", it would be silly to put thin into a variable called owner, since that would only be confusing if it were ever changed.
answers question: http://stackoverflow.com/q/49979677
score: 1
downvote count: 0

http://stackoverflow.com/a/50004680
has comment: http://stackoverflow.com/comment/87029762
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87028295
answers question: http://stackoverflow.com/q/50003922
has comment: http://stackoverflow.com/comment/87026800
has comment: http://stackoverflow.com/comment/87028192
accepted answer of: http://stackoverflow.com/q/50003922
has body: Edited to fit OP's format requirements: names=[' HE XF, Wei W, Liu ZZ, Shen XL',' STARK LE, AARON FIN, LEO DE CAP, ADAM FORTH, KARAN SINGH',' ELSWICK RICK Jr, ASTO FON, SAM MARLON, KIM ZENG'] names1 = [] for l1 in names: names1.append(l1.split(',')) first_names=[] last_names=[] for sub_list in names1: temp_sub_firsts ="" temp_sub_lasts ="" for full_name in sub_list: full_name_split = full_name.split(' ') full_name_split.pop(0) temp_sub_lasts += full_name_split.pop(0) if full_name != sub_list[-1]: temp_sub_lasts += ', ' temp_first = "" for sub_first in full_name_split: temp_first += sub_first + ' ' temp_sub_firsts += temp_first if full_name != sub_list[-1]: temp_sub_firsts += ', ' first_names.append(temp_sub_firsts) last_names.append(temp_sub_lasts) print(first_names) print(last_names) Outputs: first_names[]= ['XF , W , ZZ , XL ', 'LE , FIN , DE CAP , FORTH , SINGH ', 'RICK Jr , FON , MARLON , ZENG '] last_names[]= ['HE, Wei, Liu, Shen', 'STARK, AARON, LEO, ADAM, KARAN', 'ELSWICK, ASTO, SAM, KIM']
type: Answer

http://stackoverflow.com/comment/87068239
score: 0
has text: Check that you don't have too many opened connections to google hosts, netstat could help to count them.
type: Comment
comment on: http://stackoverflow.com/q/50025441
type: QuestionComment

http://stackoverflow.com/q/50034577
has title: Programatically running Python programs in virtual environments (conda or venv)
has comment: http://stackoverflow.com/comment/87085445
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am planning to implement some functionality in Python to be used as part of a larger non-Python project, so as to take advantage of some Python libraries. I have done some scripting in Python before, but nothing this substantial. From the advice I've gotten, it seems like we will definitely want to use a virtual environment to manage dependencies. I am exploring venv and conda and haven't committed to either yet, though it seems like conda would have the advantage of providing pre-built versions of Cython dependencies. With both conda and venv, though, the documentation I've been finding seems to be oriented toward working interactively inside the environment. For our purposes, I want to be able to run the programs we've written in Python programmatically, without going through the system shell. Is there an established, recommended way to do this? I've been trying to look at what the Bash scripts to activate a virtual environment actually do, and it looks like they basically just set up some environment variables. Both add their virtual environment's bin directory to the beginning of the PATH, venv sets VIRTUAL_ENV, and conda sets a bunch of CONDA_ environment variables. Interestingly, it doesn't look like either sets, say, PYTHONPATH. For programmatic use, is it sufficient to set these environment variables and then run the equivalent of python3 -m mymodule, or is there more setup that needs to be done? I would particularly like to know if this is documented anywhere, for conda, venv, or both: relying on having figured out what environment variables need to be set to what values seems a bit fragile.
has comment: http://stackoverflow.com/comment/87086438
tagged with: anaconda
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87086300
tagged with: python
tagged with: conda
upvote count: 2
tagged with: python-venv
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/87152839
comment on: http://stackoverflow.com/q/50067957
type: QuestionComment
score: 0
has text: @mathisfun I wish I could pick your answer as the best answer but since it is posted as a comment but not an answer, I cannot
type: Comment

http://stackoverflow.com/q/49957157
has comment: http://stackoverflow.com/comment/86930870
has comment: http://stackoverflow.com/comment/86930899
has comment: http://stackoverflow.com/comment/86933624
has comment: http://stackoverflow.com/comment/86930552
has comment: http://stackoverflow.com/comment/86932957
type: AnsweredQuestion
tagged with: list
has body: I have multiple lists namely, X, Y, VX, VY, R, T, KE, PE, TE, for which I need to delete their (i+1)th value off once their iterations break. The way I can do it currently is if I do: del X[i+1:] del Y[i+1:] del VX[i+1:] del VY[i+1:] del R[i+1:] del T[i+1:] del KE[i+1:] del PE[i+1:] del TE[i+1:] Which I think it looks rather ugly. Is there a way to minimize the use of lines in this case. Maybe a loop which does that but in just 1 or 2 lines? Edit: I didn't want to include the body of my code because I'm aware that a lot of my colleagues are doing the same problem and I don't want anyone to plagiarize. Anyway, here's what I did. def F_1(X): return VX def F_2(X): return VY def F_3(X, Y): return -G*EM*X/((X**2 + Y**2)**(3/2)) def F_4(X, Y): return -G*EM*Y/((X**2 + Y**2)**(3/2)) def RKutta(F_1, F_2, F_3, F_4, XSTART, YSTART, VXSTART, VYSTART): N = 100000 X, Y = np.zeros([N+1]), np.zeros([N+1]) VX, VY = np.zeros([N+1]), np.zeros([N+1]) R, T = np.zeros([N+1]), np.zeros([N+1]) KE, PE, TE = np.zeros([N+1]), np.zeros(N+1), np.zeros([N+1]) X[0], Y[0] = XSTART, YSTART VX[0], VY[0] = VXSTART, VYSTART T[0] = 0 # KE[0], PE[0], TE[0] = KE, PE, TE for i in range (1,N): K_1X = F_1(VX[i-1]) K_1Y = F_2(VY[i-1]) K_1VX = F_3(X[i-1], Y[i-1]) K_1VY = F_4(X[i-1], Y[i-1]) K_2X = F_1(VX[i-1] + (H*K_1VX/2)) K_2Y = F_2(VY[i-1] + (H*K_1VY/2)) K_2VX = F_3(X[i-1] + (H*K_1X/2), Y[i-1] + (H*K_1Y/2)) K_2VY = F_4(X[i-1] + (H*K_1X/2), Y[i-1] + (H*K_1Y/2)) K_3X = F_1(VX[i-1] + (H*K_2VX/2)) K_3Y = F_2(VY[i-1] + (H*K_2VY/2)) K_3VX = F_3(X[i-1] + (H*K_2X/2), Y[i-1] + (H*K_2Y/2)) K_3VY = F_4(X[i-1] + (H*K_2X/2), Y[i-1] + (H*K_2Y/2)) K_4X = F_1(VX[i-1] + H*K_3VX) K_4Y = F_2(VY[i-1] + H*K_3VY) K_4VX = F_3(X[i-1] + H*K_3X, Y[i-1] + H*K_3Y) K_4VY = F_4(X[i-1] + H*K_3X, Y[i-1] + H*K_3Y) X[i] = X[i-1] + (H/6)*(K_1X + 2*K_2X + 2*K_3X + K_4X) Y[i] = Y[i-1] + (H/6)*(K_2Y + 2*K_2Y + 2*K_3Y + K_4Y) VX[i] = VX[i-1] + (H/6)*(K_1VX + 2*K_2VX + 2*K_3VX + 2*K_4VX) VY[i] = VY[i-1] + (H/6)*(K_1VY + 2*K_2VY + 2*K_3VY + 2*K_4…
downvote count: 3
has title: A more elegant way of deleting the last value of multiple lists?
has answer: http://stackoverflow.com/a/49958331
has comment: http://stackoverflow.com/comment/86931420
has comment: http://stackoverflow.com/comment/86930468
has comment: http://stackoverflow.com/comment/86932421
has comment: http://stackoverflow.com/comment/86930850
favorite count: 0
has comment: http://stackoverflow.com/comment/86930426
has comment: http://stackoverflow.com/comment/86930851
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86930856
has comment: http://stackoverflow.com/comment/86930876
answer count: 2
accepted answer: http://stackoverflow.com/a/49957193
upvote count: 2
has comment: http://stackoverflow.com/comment/86932776
has answer: http://stackoverflow.com/a/49957193
possible better answer: http://stackoverflow.com/a/49958331
has comment: http://stackoverflow.com/comment/86932586
has comment: http://stackoverflow.com/comment/86931465
has comment: http://stackoverflow.com/comment/86934664
tagged with: python
score: -1

http://stackoverflow.com/q/49925100
has title: How to handle swapping variables in a pythonic way?
accepted answer: http://stackoverflow.com/a/49925397
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49925397
score: 0
answer count: 1
upvote count: 1
tagged with: loops
linked to: http://stackoverflow.com/q/6190468
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86866619
tagged with: python-3.x
has body: I often have the case where I use two variables, one of them being the "current" value of something, another one a "newly retrieved" one. After checking for equality (and a relevant action taken), they are swapped. This is then repeated in a loop. import time import random def get_new(): # the new value is retrieved here, form a service or whatever vals = [x for x in range(3)] return random.choice(vals) current = None while True: # get a new value new = get_new() if new != current: print('a change!') else: print('no change :(') current = new time.sleep(1) This solution works but I feel that it is a naïve approach and I think I remember (for "write pythonic code" series of talks) that there are better ways. What is the pythonic way to handle such mechanism?
tagged with: infinite-loop
tagged with: python
has comment: http://stackoverflow.com/comment/86866460

http://stackoverflow.com/comment/87000392
has text: are you asking how to define your python connection or are you asking how to address your oracle database that's running on the virtualbox linux image?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49981067
type: Comment

http://stackoverflow.com/comment/87049789
comment on: http://stackoverflow.com/q/50016584
type: Comment
type: QuestionComment
score: 0
has text: Perhaps you mean to use `>= 10` instead of just `> 10`?

http://stackoverflow.com/comment/86983798
comment on: http://stackoverflow.com/q/49983339
type: Comment
type: QuestionComment
score: 0
has text: @JeruLuke it returns me the same attribute error with this new path.

http://stackoverflow.com/q/49952556
has answer: http://stackoverflow.com/a/71320744
score: 5
accepted answer: http://stackoverflow.com/a/49954206
downvote count: 0
tagged with: ubuntu
favorite count: 0
possible better answer: http://stackoverflow.com/a/71320744
type: Question
tagged with: docker
tagged with: odoo
upvote count: 5
has comment: http://stackoverflow.com/comment/86921919
has answer: http://stackoverflow.com/a/49954206
tagged with: python
tagged with: cmd
has body: When you install the Odoo (version 10) docker image, how to reproduce this command: odoo-bin scaffold openacademy addons
has title: Odoo docker image: how to scaffold?
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/86900533
has text: Why are you using a lambda to print()?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49942050

http://stackoverflow.com/comment/86936299
type: QuestionComment
has text: Interesting - so if I use Qt5 or TkAgg and save via the GUI, it works great; however, the savefig method still screws it up. Not sure what's going on here...
score: 0
comment on: http://stackoverflow.com/q/49959546
type: Comment

http://stackoverflow.com/q/50060764
accepted answer: http://stackoverflow.com/a/50061075
has body: I am trying to fetch multiple images for a particular post-id and i have a piece of code which is working for me but I am not able to understand why/how? If anyone can explain and/or give me some documentation for the same I would be able to use it in future as well. This is the code I am trying to understand. Thanks. {% for posts in posts %} {{ posts.id }} {% for image in posts.post.all %} {{ image.image }} {% endfor %} {% endfor %} view.html: *{% extends 'base.html' %} {% block main_content %} {% if posts %} {% for post in posts %} {{ post.created_at }} {% for posts in posts %} {{ posts.id }} {% for image in posts.post.all %} {{ image.image }} {% endfor %} {% endfor %} Delete {% endfor %} {% else %} No Entry yet!!Please add entry. {% endif %} {% endblock %}* views.py: def view(request): if request.user.is_authenticated(): #or request.session.get_expiry_age()> 10): request.session.set_expiry(600000) user = request.user #dogs=Post.objects.all() #For seeing all entries post= Post.objects.filter(created_by_user = user).order_by('-created_at')#[:4] #For seeing user specific entries #post_image=Post_image.post.all() print post_image context={'posts': post} return render(request, 'view.html', context) else: messages.info(request, 'Session Expired') return redirect("/login") models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.db import models from django.conf import settings from django.contrib.auth.models import User class Post(models.Model): # user = models.ForeignKey(User, unique=True) title=models.CharField(max_length=100) description=models.CharField(max_length=4500) created_at=models.DateTimeField(auto_now_add = True) updated_at=models.DateTimeField(auto_now= True) # user = models.OneToOneField(User, null=True) created_by_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True…
type: Question
has comment: http://stackoverflow.com/comment/87137799
has comment: http://stackoverflow.com/comment/87138058
answer count: 1
tagged with: django
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50061075
has comment: http://stackoverflow.com/comment/87137893
has title: Reverse relation in Django
tagged with: python

http://stackoverflow.com/comment/87056025
comment on: http://stackoverflow.com/q/50019588
type: Comment
score: 0
has text: @ThomasUpson if you put "continue" instead of 'pass', it will still give syntax error. Try it.
type: QuestionComment

http://stackoverflow.com/a/50054294
has comment: http://stackoverflow.com/comment/87125907
answers question: http://stackoverflow.com/q/50054238
has comment: http://stackoverflow.com/comment/87125580
downvote count: 0
has body: Using pivot df.reset_index().pivot(index='index',columns='Source',values='Data').fillna('') Out[179]: Source Primary Secondary index 0 2.2134e+07 1 2.75434e+07 2 2.2129e+07 3 2.95794e+07 4 2.37812e+07 5 1.00019e+09 6 2.21355e+07 7 2.21302e+07 8 2.21378e+07 9 2.75434e+07 After concat df.Data=df.Data.astype(str) pd.concat([df,df.reset_index().pivot(index='index',columns='Source',values='Data').fillna('')],axis=1) Out[182]: Source Dummy Data Primary Secondary 0 Secondary DUMMY 22134007 22134007 1 Secondary DUMMY 27543350 27543350 2 Secondary DUMMY 22128972 22128972 3 Primary DUMMY 29579399 29579399 4 Secondary DUMMY 23781175 23781175 5 Primary DUMMY 1000185771 1000185771 6 Primary DUMMY 22135458 22135458 7 Secondary DUMMY 22130241 22130241 8 Primary DUMMY 22137751 22137751 9 Primary DUMMY 27543359 27543359
has comment: http://stackoverflow.com/comment/87125360
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87125982

http://stackoverflow.com/q/50026534
has title: Python - Best way to recursively create a list?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87069562
tagged with: python
has comment: http://stackoverflow.com/comment/87070409
has body: # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None sum = 25 ans = [] def recurse(s, traverse, ls): #append tuple ls = ls + (traverse.val,) if (traverse.right): recurse(s, traverse.right, ls) if (traverse.left): recurse(s, traverse.left, ls) if (s==sum): #convert touple and add to answer tmp = list(ls) ans.append(tmp) a = tuple() recurse(0, root, a) In this code I am dynamically appending lists to a list (ans). In this example, I am using recursion and using tuples to build every sublist because it is immutable. Then, I convert it to a list and append it to my answer. If I were to only use lists, I would not be able to pass copies each time my function is called. Are there any performance downsides to using tuples this way? Is there a better way to recursively create a list for similar problems? Also, this method would not really work with a 2d list... Whats the best way to make a 2D immutable list?
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/87069834
answer count: 1
has answer: http://stackoverflow.com/a/50027955
type: Question
tagged with: tuples

http://stackoverflow.com/q/49970453
answer count: 1
has body: When a command is executed via subprocess.run, what permissions is the command executed with? Is it the permissions of the enclosing python file? Is it user permissions? For example, if a python file were run with sudo: sudo python3 file.py and file.py contained the line subprocess.run([ 'chmod', '+x', 'file.sh' ]) Would chmod be run with super user permissions?
has comment: http://stackoverflow.com/comment/86957377
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49970479
accepted answer: http://stackoverflow.com/a/49970479
tagged with: python
tagged with: permissions
tagged with: unix
has comment: http://stackoverflow.com/comment/86956819
has title: Python subprocess permission
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86956864
tagged with: subprocess
downvote count: 0
has comment: http://stackoverflow.com/comment/86956908
score: 1
upvote count: 1

http://stackoverflow.com/a/49972299
type: Answer
has body: The sharing feature is on the code (notebook) only. But you and your friend each run the code in a separate instance machine. So, if you want to share, it's best to use reading from Google Drive that each of you can do oneself.
accepted answer of: http://stackoverflow.com/q/49972084
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49972084
score: 8
upvote count: 8

http://stackoverflow.com/comment/86880794
has text: You are right about the indent problem. I fixed it and edited the post, but the indentation didn't seem to fix the problem. I guess I'm not sure what else I should post with this to make it a complete source. What do you suggest?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49932426

installation
tags question: http://stackoverflow.com/q/50070717
tags question: http://stackoverflow.com/q/49923671
tags question: http://stackoverflow.com/q/50040052
tags question: http://stackoverflow.com/q/49969308
tags question: http://stackoverflow.com/q/49944516
tags question: http://stackoverflow.com/q/50035634
tag name: installation
tags question: http://stackoverflow.com/q/49986887
tags question: http://stackoverflow.com/q/49988987
tags question: http://stackoverflow.com/q/49948580
type: Tag

http://stackoverflow.com/comment/86893823
comment on: http://stackoverflow.com/q/49938884
score: 0
type: Comment
type: QuestionComment
has text: @shivsn: Thanks! Category can be any value by the way - no correlation like that.

http://stackoverflow.com/q/50054427
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50054578
accepted answer: http://stackoverflow.com/a/50054578
answer count: 3
has title: Remove the tuple and create a new sorted list
tagged with: pyspark
downvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50058426
has body: I have a RDD which I created using PySpark and sizes around 600 GB after joining by key value which looks exactly like this. [('43.72_-70.08', (('0744632', -70.08, 43.72, '2.4'), '18090865')), ('43.72_-70.08', (('0744632', -70.08, 43.72, '2.4'), '18090865')), ('43.25_-67.58', (('0753877', -67.58, 43.25, '7.2'), '18050868')), ('43.01_-75.24', (('0750567', -75.24, 43.01, '7.2'), '18042872'))] I want something like this and sorted by the first element: ['0744632', '18090865', '2.4', '0744632', '18090865', '2.4', '0750567', '18042872', '7.2', '0753877', '18050868', '7.2'] Is there a way I can get data from tuples out and get the output in required format. Note: This is a 600 GB RDD, with more than a million different values in first column and approx. 15 billion rows, I would really appreciate an optimized way if possible.
type: Question
upvote count: 0
tagged with: apache-spark-sql
tagged with: pyhdfs-client
has comment: http://stackoverflow.com/comment/87126262
has comment: http://stackoverflow.com/comment/87125516
linked to: http://stackoverflow.com/q/3076692
has comment: http://stackoverflow.com/comment/87125349
has comment: http://stackoverflow.com/comment/87126253
possible better answer: http://stackoverflow.com/a/50054773
has comment: http://stackoverflow.com/comment/87125677
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/50054773

http://stackoverflow.com/comment/86994612
has text: @enumaris thank you for your answer. I'll try to explain my approach a bit: basically I pushed the video frames through resnet model and got fature shapes of k x 2048 . I have the data into train/validation and test folders.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49988950

http://stackoverflow.com/a/49951206
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49950985
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49950985
has body: In other to achieve what you want, use can use this function def find_denom(amount): banknotes = [100, 50, 20, 10, 5, 2, 1] for note in banknotes: counter = 0 # reassign zero to counter for every loop if note &lt;= amount: number_of_notes = amount // note # get the number of each note in amount amount = amount % note # assign the remaining amount to amount while counter &lt; number_of_notes: # check it the number of counter has exceeded the number of notes print('$'+str(note)) #convert note to str and concatenate $ with it and display the note counter += 1 amount = int(input("Enter initial amount ($): ")) find_denom(amount)
type: Answer
has comment: http://stackoverflow.com/comment/86919030

http://stackoverflow.com/a/50008416
type: Answer
answers question: http://stackoverflow.com/q/50006738
upvote count: 3
score: 3
downvote count: 0
has body: Help message categories are separated by cogs. You can add cogs by using bot.add_cog(cog). class SomeCategory: """Category documentations""" @commands.command(pass_context=True) async def ping(self, ctx): """Pong""" await bot.say(":ping_pong: Pong!") print ("user has pinged") bot.add_cog(SomeCategory())
has comment: http://stackoverflow.com/comment/129881811

http://stackoverflow.com/q/50033145
answer count: 1
downvote count: 0
tagged with: string-to-datetime
favorite count: 0
type: Question
score: 3
tagged with: time-series
type: UnansweredQuestion
has title: Pandas to_datetime has inconsistent behavior on non-american dates
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/50033387
has body: I am confused by the behavior of pandas to_datetime on non-American dates. In this trivial example, Pandas correctly infers the months on both the 2nd and 3rd row, but fails on the 1st and 4th. Apparently it is treating the 2nd and 3rd line as dd/mm/yyyy dates (because the 13 and 27 clearly can't be months), but treating the remaining dates as being mm/dd/yyyy. My expectation would be that to_datetime would infer from the entire series, and then treat every entry the same. import pandas as pd results = pd.DataFrame() european_dates = pd.Series(['05/04/2007', # &lt;-- April 5th, 2007 '13/04/2006', # &lt;-- April 13th, 2006 '27/12/2014', # &lt;-- December 27th, 2014 '02/07/2010']) # &lt;-- July 2nd, 2010 # note: the same happens with infer_datetime_format=False inferred_dates = pd.to_datetime(european_dates, infer_datetime_format=True) results['day'] = inferred_dates.dt.day results['month'] = inferred_dates.dt.month results['year'] = inferred_dates.dt.year results Note: I'm aware that to_datetime has a dayfirst argument, and a format argument, my question is mostly about why the infer_datetime_format fails in such a trivial case.
linked to: http://stackoverflow.com/q/46842793
tagged with: pandas
upvote count: 3

http://stackoverflow.com/a/49940366
answers question: http://stackoverflow.com/q/49940180
type: Answer
score: 2
has body: Your regex for registering the viewset should not end with /$. Rest framework will add the slash by default, and you don't want the dollar because it matches the end of the string. router.register(r'OffresByRecruteur/(?P&lt;idRecruteur_id&gt;\d+)/', OffreRecruteurViewSet, base_name='inoutreports') Secondly, when you get the queryset, you should get idRecruteur_id from self.kwargs. You would use self.request.GET to fetch from the querystring, e.g. if the URL was /scrumboard/OffresByRecruteur/?idRecruteur_id=1. def get_queryset(self, *args, **kwargs): return self.queryset.filter(idRecruteur_id=self.kwargs['idRecruteur_id']))
accepted answer of: http://stackoverflow.com/q/49940180
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49917974
upvote count: 2
type: UnansweredQuestion
has title: PySpark: Should we update a dataframe iteratively?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49919671
favorite count: 0
tagged with: optimization
type: Question
has comment: http://stackoverflow.com/comment/86853655
linked to: http://stackoverflow.com/q/41670103
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/86853949
tagged with: pyspark
has body: My question has two parts to it. First one is to understand the way Spark works and the second one is on optimization. I have a spark dataframe which has multiple categorical variables. For each of these categorical variables I am adding a new column wherein each row is the frequency of the corresponding level. For example Date_Built Square_Footage Num_Beds Num_Baths State Price Freq_State 01/01/1920 1700 3 2 NY 700000 4500 Here for State (a categorical variable), I am adding a new variable Freq_State. The level NY appears 4500 times in the dataset so this row gets 4500 in the Freq_State column. I have multiple such columns where I am adding a column bearing frequency of corresponding levels. This is the code I am using for achieving this def calculate_freq(df, categorical_cols): for each_cat_col in categorical_cols: _freq = df.select(each_cat_col).groupBy(each_cat_col).count() df = df.join(_freq, each_cat_col, "inner") return df Part 1 Here, as you can see, I am updating the dataframe in the for loop. Is this way of updating a dataframe advisable when I'm running this code on a cluster? I wouldn't have been concerned about this if it was a pandas dataframe. But I am not certain when the context changes to spark. Also, would it make a difference if I was simply running the above process in a loop and not inside a function? Part 2 Is there a more optimized way to do this? Here I am joining each time I enter a loop? Can this be avoided
tagged with: python
score: 2

http://stackoverflow.com/comment/87050224
type: QuestionComment
score: 0
has text: This code has an error here: `if x_player >= sef_x and x_player !`. It is probaly just a copy-paste error, so what belongs there?
comment on: http://stackoverflow.com/q/50016131
type: Comment

http://stackoverflow.com/comment/87947115
type: AnswerComment
comment on: http://stackoverflow.com/a/49982967
has text: thank you, looks like PyTorch doesn't support negative strides. I need a solution that doesn't have negative strides.
score: 0
type: Comment

remove-method
tags question: http://stackoverflow.com/q/50006951
type: Tag
tag name: remove-method

http://stackoverflow.com/q/50017227
tagged with: import
has title: Can‘t import my own module in Python 3.6.5/Pycharm
has comment: http://stackoverflow.com/comment/87051040
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87050709
has body: I am using python 3.6.5 and Pycharm. I have two ".py" files named make_pizza.py and pizza.py. The picture below shows the path of the two files: And details of two .py files are shown below: 1) pizza.py: def make_pizza(size,*toppings): """Describe the pizza you want to make""" print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) 2) making_pizza.py: import pizza pizza.make_pizza(16, 'pepperoni') As shown above, I want to import module "pizza.py" in "making_pizzas.py" and use the "make_pizza" functions. However, when I run "making_pizza.py", it will not work and an error will show up: Traceback (most recent call last): File "C:/Softwares/Python3.6/Project0/making_pizzas.py", line 1, in &lt;module&gt; import pizza ModuleNotFoundError: No module named 'pizza' I am sure I put these two .py files in one folder named "Project0", and I marked the folder path as Sources Root. but the error is still there.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108202176
has comment: http://stackoverflow.com/comment/87051064
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87050933
has comment: http://stackoverflow.com/comment/87051251
tagged with: module

http://stackoverflow.com/comment/99210883
score: 2
has text: How can you detect the xpath of the temporary overlay? I tried to detect it on Chrome Dev Tool, but since it disappears quickly I could not know the xpath.
type: Comment
comment on: http://stackoverflow.com/a/49939793
type: AnswerComment

http://stackoverflow.com/comment/86938766
type: Comment
type: QuestionComment
has text: Why do you want this behavior? Trying to determine if this is an XY problem...
comment on: http://stackoverflow.com/q/49961175
score: 0

http://stackoverflow.com/a/49970718
answers question: http://stackoverflow.com/q/49967927
has body: The problem is that the string that you're looking for is XML escaped (note the "&amp;amp;"s), while when parsing the file, the strings are unescaped (&amp;amp; converted to &amp; - and some more others). For more details check [Python.Wiki]: Escaping XML. code.py: #!/usr/bin/env python3 import sys from xml.etree import ElementTree as ET from xml.sax.saxutils import escape, unescape INPUT_FILE_NAME = "guide.xml" OUTPUT_FILE_NAME = "PhasedGuide.xml" SRC_ATTR_TEXT = "http://images.radiotimes.com/assets/images/holding/tv.png?quality=60&amp;amp;mode=crop&amp;amp;width=130&amp;amp;height=100&amp;amp;404=tv" SRC_ATTR_REPLACE_TEXT = "quality=60&amp;amp;mode=crop&amp;amp;width=130&amp;amp;height=100" SRC_ATTR_REPLACE_WITH_TEXT = "quality=100&amp;amp;mode=crop&amp;amp;width=1200&amp;amp;height=723" def main(): tree = ET.parse(INPUT_FILE_NAME) tv_node = tree.getroot() for programme_node in tv_node.findall("programme"): icon_node = programme_node.find("icon") if icon_node is not None: print(icon_node.get("src", "")) src_attr = escape(icon_node.get("src", "")) if src_attr == SRC_ATTR_TEXT: programme_node.remove(icon_node) elif src_attr: icon_node.set("src", unescape(src_attr.replace(SRC_ATTR_REPLACE_TEXT, SRC_ATTR_REPLACE_WITH_TEXT))) tree.write(OUTPUT_FILE_NAME) if __name__ == "__main__": print("Python {:s} on {:s}\n".format(sys.version, sys.platform)) main() Notes: The algorithm loads and parses the file, and gets the root node (tv) Iterates through all its programme children For each, tries to find an icon child, if found get its src attribute (the value is escaped) Then, depending on the attribute (escaped) value, it performs the required operation Output: (py35x64_test) e:\Work\Dev\StackOverflow\q049967927&gt;"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 (py35x64_test) e:\Work\Dev\StackOverflow\q049967927&gt;type PhasedGuide.xml &lt;tv&gt; &lt;programme channel="BBC Red B…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87123095
score: 0
accepted answer of: http://stackoverflow.com/q/49967927
type: Answer

http://stackoverflow.com/comment/86983805
type: Comment
type: QuestionComment
has text: Ah, I understand. So first up, the index in the last line is wrong, yes. That was the one bit of the MWE I didnt check, and is copied from my real code where 3 is a valid index. It appears I need lots of ,None in my array indices, otherwise the shape gets confused. Thanks.
comment on: http://stackoverflow.com/q/49981956
score: 0

http://stackoverflow.com/comment/86993375
score: 0
type: QuestionComment
has text: @DebanjanB added relevant HTML. If you search for 'easily apply' you will find the class.
comment on: http://stackoverflow.com/q/49988239
type: Comment

http://stackoverflow.com/comment/87067924
score: 0
comment on: http://stackoverflow.com/q/50022829
has text: I will test that, thank u :)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49994443
has body: Use csv.DictReader Ex: import csv labels1 = [] with open(file_path, 'r') as f: reader = csv.DictReader(f, delimiter='\t') for line in reader: labels1.append(line) MoreInfo
has comment: http://stackoverflow.com/comment/87005298
has comment: http://stackoverflow.com/comment/87005212
type: Answer
accepted answer of: http://stackoverflow.com/q/49994379
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49994379
has comment: http://stackoverflow.com/comment/87005237

http://stackoverflow.com/q/50036765
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: pyramid
answer count: 0
downvote count: 0
has body: I'm beginner of pyramid framework.I tried to start a session in application but session not working.Here is the following code: init.py from pyramid.config import Configurator from pyramid.session import SignedCookieSessionFactory def main(global_config, **settings): my_session_factory = SignedCookieSessionFactory('itsaseekreet') config = Configurator(settings=settings) config.set_session_factory(my_session_factory) config.add_route('next', '/next') views.py @view_config(route_name="next") def next(request): try: query=request.dbsession.query(UserMaster) global user_id,password user_id=request.params['uname'] password=request.params['password'] session=request.session session['username']=user_id two=query.filter(UserMaster.user_id==user_id,UserMaster.password==password).first() if two is None: print('Invaid Username or password') return render_to_response('../templates/login.jinja2', {}, request=request) else: return render_to_response('../templates/menu.jinja2', {}) except DBAPIError: return Response(db_err_msg, content_type='text/plain', status=500) @view_config(route_name='index') def index(request): try: name = request.session.get('username') return render_to_response('../templates/index.jinja2', {'name':name}, request=request) except DBAPIError: return Response(db_err_msg, content_type='text/plain', status=500) @view_config(route_name='logout', renderer='../templates/login.jinja2') def logout(request): try: request.session().invalidate() except DBAPIError: return Response(db_err_msg, content_type='text/plain', status=500) I got TypeError: 'CookieSession' object is not callable
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87091465
tagged with: deform
has comment: http://stackoverflow.com/comment/87090835
has comment: http://stackoverflow.com/comment/87093551
has comment: http://stackoverflow.com/comment/87090486
has title: How do I add start session in pyramid framework?

http://stackoverflow.com/q/49923765
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86863397
has title: python pause infinite loop for code outside loop to be executed
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49923969
downvote count: 0
has comment: http://stackoverflow.com/comment/86863405
upvote count: 1
has body: I am wondering if this is possible. I want to have an infinite while loop but still wont the rest of the code outside the while loop to continue running while the loop is on. like a way to break the while loop after each iteration for instance. i need to find a way for the second print statement to be executed without breaking the while loop completely. while True: print('i will loop forever') print('this code will never be executed because of the while loop')
favorite count: 0
type: Question

http://stackoverflow.com/comment/124665415
type: Comment
type: AnswerComment
has text: @SaiKiran Would be good to accept this as an answer if it answered your question.
comment on: http://stackoverflow.com/a/50012407
score: 0

http://stackoverflow.com/q/50027858
downvote count: 0
has body: I am trying to plot a tree from a Pandas dataframe but I don't know which is the correct data structure I must use and how can I solve it. The dataset has 4 columns: source, destination, application and timemark. For example, a row in the dataset could be: 192.168.1.1 | 192.168.1.200 | ping | 10:00AM I would like to plot a tree graph generating a node for each of the sources, and showing the adjacency of each source with the destinations who has communicated with, and an adjacency of each destination with all the applications that this destination has used with the source and finally showing the adjacency of each (source, destination, application) leaf, with all the timemarks of the sessions that used this application between this destination and this source. Could you please tell me how can I find a Python solution for this? Thanks a lot!
upvote count: 1
score: 1
answer count: 1
favorite count: 0
tagged with: graph
type: Question
has title: Plot tree graph from Pandas dataset in Python
type: UnansweredQuestion
tagged with: python
tagged with: tree
tagged with: pandas
has answer: http://stackoverflow.com/a/50028293

http://stackoverflow.com/q/49934730
type: Question
has comment: http://stackoverflow.com/comment/86885041
has comment: http://stackoverflow.com/comment/86885326
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/86885132
has comment: http://stackoverflow.com/comment/86885147
has body: We need to run a Python code which will control the GPIO of Raspberry Pi 3 from within the JavaScript. (JavaScript is listening for changes on database and when changes are made, function gets triggered and it should run the Python Code. (This code is not working, like the alert message will pop-up but the python code isn't running which otherwise should turn the LED on. What am i doing wrong?) index.html file function runPython() { $.ajax({ type: "POST", url: "/home/pi/Desktop/Web/led.py", data :{}, success: callbackFunc }); } function callbackFunc(response) { alert("working"); } led.py file import RPi.GPIO as GPIO import timemGPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) print "LED on" GPIO.output(18, GPIO.HIGH) time.sleep(10) print "LED off" GPIO.output(18,GPIO.LOW)
has comment: http://stackoverflow.com/comment/86884882
upvote count: 3
type: UnansweredQuestion
downvote count: 2
tagged with: gpio
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/86885294
has comment: http://stackoverflow.com/comment/86885464
has comment: http://stackoverflow.com/comment/86892454
has comment: http://stackoverflow.com/comment/86885109
favorite count: 0
has comment: http://stackoverflow.com/comment/86884976
has comment: http://stackoverflow.com/comment/86885341
has comment: http://stackoverflow.com/comment/86884857
has comment: http://stackoverflow.com/comment/86885475
has comment: http://stackoverflow.com/comment/86884918
has comment: http://stackoverflow.com/comment/86885182
score: 1
has comment: http://stackoverflow.com/comment/86885140
has comment: http://stackoverflow.com/comment/86884922
tagged with: python
has comment: http://stackoverflow.com/comment/86885361
has comment: http://stackoverflow.com/comment/86885431
has title: Run Python scripts from JavaScript functions
has answer: http://stackoverflow.com/a/49951294
has comment: http://stackoverflow.com/comment/86885308
has comment: http://stackoverflow.com/comment/86884890

http://stackoverflow.com/q/50051040
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87118607
type: UnansweredQuestion
has body: Code: import csv import numpy raw_data = open('C:\\Users\\train.csv', 'rt') data = numpy.loadtxt(raw_data, delimiter=",") print(data.shape) Below is the sample data used Time Freq 8:00 91.1 8:03 91.1 8:06 91.1 8:09 91.1 8:12 91.1 8:15 91.1 8:18 91.1 8:21 91.1 8:24 91.1 8:27 91.1 8:30 91.1 Error: ValueError: could not convert string to float: b'Time'
tagged with: python
has answer: http://stackoverflow.com/a/50051291
has answer: http://stackoverflow.com/a/50051418
answer count: 2
score: 1
linked to: http://stackoverflow.com/q/12319969
has title: Could not convert string to float while using numpy.loadtxt
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87118866

http://stackoverflow.com/comment/86894301
has text: @MartinEvans post updated
score: 0
comment on: http://stackoverflow.com/q/49925105
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87071528
has text: i think the `np.where` solution is the cleanest and probably fastest too.
score: 0
comment on: http://stackoverflow.com/q/50027430
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49959311
tagged with: python-3.x
has body: I am trying to make python execute a random line of code from a given file. Let's say I have a file called "code_lines". This file contains random pieces of python code, ex. print("This is a random message") print("This is another message") print("This is getting boring") Is it possible for python to select a random line from that file and run it as code?
linked to: http://stackoverflow.com/q/31704916
possible better answer: http://stackoverflow.com/a/49959358
tagged with: python
has answer: http://stackoverflow.com/a/49959468
has answer: http://stackoverflow.com/a/49959358
has comment: http://stackoverflow.com/comment/86934964
has comment: http://stackoverflow.com/comment/86934953
type: AnsweredQuestion
score: 0
tagged with: random
answer count: 2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86935172
accepted answer: http://stackoverflow.com/a/49959468
duplicate of: http://stackoverflow.com/q/31704916
favorite count: 0
type: Question
has title: Execute code from non .py file in python

http://stackoverflow.com/comment/134604602
has text: woah, calm down @floydn ; I'm not saying it as bad; it's just the fact of your code.
type: Comment
comment on: http://stackoverflow.com/a/49945912
score: 0
type: AnswerComment

http://stackoverflow.com/q/49926897
has comment: http://stackoverflow.com/comment/86869848
score: 13
has title: How can I know the type of a pandas dataframe cell
type: Question
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/86869844
linked to: http://stackoverflow.com/q/41262370
tagged with: dataframe
has comment: http://stackoverflow.com/comment/86869803
favorite count: 0
has comment: http://stackoverflow.com/comment/86869820
has answer: http://stackoverflow.com/a/73125707
upvote count: 15
downvote count: 2
answer count: 2
has body: I have a dataframe, for example: 1 1.3 2,5 4 5 With the following code, I am trying to know what are the types of the different cells of my pandas dataframe: for i in range(len(data.columns)): print(" lenth of columns : " + str(len(data.columns))) for j in range(len(data[i])): data[i][j] = re.sub(r'(\d*)\.(\d*)', r'\1,\2', str(data[i][j])) print(data[i][j]) print(" est de type : "type(data[i][j])) if str(data[i][j]).isdigit(): print(str(data[i][j]) + " contain a number ") The problem is when a cell of the dataframe contain a dot, pandas thinks it is a string. So I used regex, in order to change the dot into a comma. But after that, the types of all my dataframe cells changed to string. My question is: How can I know if a cell of the dataframe is an int or a float? I already tried isinstance(x, int) edit: How can I count the number of int and float, with the output of the df.apply(type) for example, I want to know how many cells of my column are int or float My second question is, why when I have 2.5, the dataframe give him the str type? 0 <class 'int'> 1 <class 'str'> 2 <class 'float'> 3 <class 'float'> 4 <class 'int'> 5 <class 'str'> 6 <class 'str'>
tagged with: python
has answer: http://stackoverflow.com/a/49927321
type: UnansweredQuestion

http://stackoverflow.com/q/50068185
score: 2
type: AnsweredQuestion
has title: Snakemake using multi inputs
has answer: http://stackoverflow.com/a/50068541
accepted answer: http://stackoverflow.com/a/50068541
has body: I'm starting to write a pipeline for my bioinformatics project and I'm using the Snakemake as workflow. I made all the tutorial of the official site and I some of the documentation. I want to run a single shell command, like that: fastp -i input-1 -I input-2 -o output-1 -O output-2 My code in Snakefile: SAMPLES = ['1', '2', '3', '4'] rule fastp: input: reads1=expand("sample{sample}.R1.fq.gz", sample=SAMPLES), reads2=expand("sample{sample}.R2.fq.gz", sample=SAMPLES) output: reads1out=expand("sample{sample}.R1.fq.gz.out", sample=SAMPLES), reads2out=expand("sample{sample}.R2.fq.gz.out", sample=SAMPLES) shell: "fastp -i {input.reads1} -I {input.reads2} -o {output.reads1out} -O {output.reads2out}" But the program run this single line of code: fastp -i sample1.R1.fq.gz sample2.R1.fq.gz sample3.R1.fq.gz sample4.R1.fq.gz -I sample1.R2.fq.gz sample2.R2.fq.gz sample3.R2.fq.gz sample4.R2.fq.gz -o sample1.R1.fq.gz.out sample2.R1.fq.gz.out sample3.R1.fq.gz.out sample4.R1.fq.gz.out -O sample1.R2.fq.gz.out sample2.R2.fq.gz.out sample3.R2.fq.gz.out sample4.R2.fq.gz.out How can I write the program to do a different shell command for each sample? I tried a for i in SAMPLES: after the rule fastp: but doesn't worked and I don't know what I can try now. Sorry if this topic is too basic in some way, but I'm a noob in Python. Thank you.
type: Question
tagged with: pipeline
answer count: 2
upvote count: 2
tagged with: snakemake
has answer: http://stackoverflow.com/a/50068889
possible better answer: http://stackoverflow.com/a/50068889
downvote count: 0
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/86989265
type: Comment
type: QuestionComment
score: 1
has text: This is a typical bad question. "Have some problem (which is not demonstrated in the question) and I want to solve it with a regex". A regex is obviously the wrong approach here.
comment on: http://stackoverflow.com/q/49985863

http://stackoverflow.com/comment/86925259
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49954330
has text: There's no use in having an `else:` clause if all it contains is `pass` - and repeating `i += 1` in both the `if` and `else` doesn't make it better...
type: AnswerComment

http://stackoverflow.com/comment/110105358
has text: Thanks. This works but images are saved in a separate directory along with the html. Is there a way to embed the images within the exported html. So, html -> with toc, no code and embedded images.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/54030005
type: AnswerComment

http://stackoverflow.com/q/49972581
has answer: http://stackoverflow.com/a/49972639
linked to: http://stackoverflow.com/q/2687225
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86961253
has body: My python rest API receives a JSON and extracts the values from keys. Problem: The program throws a keyError and exits if any one key is not present or if the keys' value is null. The function is not inside a loop. I want the program to continue execution even if the key is not present.
tagged with: python
has comment: http://stackoverflow.com/comment/86961313
has comment: http://stackoverflow.com/comment/86961289
answer count: 1
score: -1
downvote count: 1
has title: How to handle keyError in python and continue execution?
favorite count: 0
type: Question

http://stackoverflow.com/a/50024019
has comment: http://stackoverflow.com/comment/87073951
has body: I found a way but not sure it is the most efficient. You have the input data: import pandas as pd dfa = pd.DataFrame({'Start': [0, 101, 201], 'Stop': [100, 200, 1000], 'Value': [0., 1., 0.]}) dfb = pd.DataFrame({'Start': [0, 51, 301], 'Stop': [50, 300, 1000], 'Value': [0., 1., 0.]}) First I would create the columns Start and Stop of df_out with: df_out = pd.DataFrame({'Start': sorted(set(dfa['Start'])|set(dfb['Start'])), 'Stop': sorted(set(dfa['Stop'])|set(dfb['Stop']))}) Then to get the value of dfa (and dfb) associated to the right range(Start,Stop) in a column named Value_dfA (and Value_dfB), I would do: df_out['Value_dfA'] = df_out['Start'].apply(lambda x: dfa['Value'][dfa['Start'] &lt;= x].iloc[-1]) df_out['Value_dfB'] = df_out['Start'].apply(lambda x: dfb['Value'][dfb['Start'] &lt;= x].iloc[-1]) To get the column SameValue, do: df_out['SameValue'] = df_out.apply(lambda x: 1 if x['Value_dfA'] == x['Value_dfB'] else 0,axis=1) If it matters, you can reorder the columns with: df_out = df_out'Start', 'Stop', 'SameValue', 'Value_dfA', 'Value_dfB' Your output is then Start Stop SameValue Value_dfA Value_dfB 0 0 50 1 0.0 0.0 1 51 100 0 0.0 1.0 2 101 200 1 1.0 1.0 3 201 300 0 0.0 1.0 4 301 1000 1 0.0 0.0
answers question: http://stackoverflow.com/q/50008463
downvote count: 0
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87075157
has comment: http://stackoverflow.com/comment/87076095

http://stackoverflow.com/comment/87108752
has text: Sorry, I thought this was the fastest way to show you what I am doing. In the meantime, I believe I found the solution to my problem (shame on me for not searching properly before): https://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming Apparently, the Python interpreter does not allow parallel exectution of threads...
comment on: http://stackoverflow.com/q/50045500
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87122278
score: 0
comment on: http://stackoverflow.com/q/50052421
type: Comment
has text: Did you take a look at [this](https://stackoverflow.com/questions/39152729/how-to-have-multiple-groups-in-python-statsmodels-linear-mixed-effects-model)?
type: QuestionComment

http://stackoverflow.com/q/50059421
has comment: http://stackoverflow.com/comment/87143146
has comment: http://stackoverflow.com/comment/87143191
has comment: http://stackoverflow.com/comment/87142870
score: 0
answer count: 0
has title: How to select an HTML id in XPath in Python, using a wildcarded string?
has comment: http://stackoverflow.com/comment/87143028
linked to: http://stackoverflow.com/q/1064968
tagged with: webbrowser-control
has comment: http://stackoverflow.com/comment/87143113
has comment: http://stackoverflow.com/comment/87143167
has comment: http://stackoverflow.com/comment/87140598
type: Question
tagged with: xpath
has comment: http://stackoverflow.com/comment/87140656
has comment: http://stackoverflow.com/comment/87143219
has body: For the moment, I'm looking to make a program for a repetitive action which we need to make something like 1000 times by hand otherwise. This action is done throughout a web browser (I'm using Chrome). My actual issue is the XPATH selector is changing at every connection but only one number. So, I use the recognition on the webpage linked using Selenium and associated WebDrivers. The fact is my code run sometimes when the selector has the right name. Indeed, as the css selector is changing permanently, it happens that this is the right one ! So, after making a headless browser, login to the company webpage, I have to recognize then click on a specific object on the navigator : The problematic code is the following: wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="__xmlview0--settingsButton-img"]'))) OT = driver.find_element_by_xpath('//*[@id="__xmlview0--settingsButton-img"]') OT.click() wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#__select1-label'))) driver.save_screenshot("screenshot.png") I have an idea but I don't know how to do it: Is it possible to add a random number instead of the 0 in xmlview0, which is the number issue within the CSS selector ? I'm not a Python veteran and I really don't want to do the job by hand.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21405267
tagged with: python

http://stackoverflow.com/comment/140065973
comment on: http://stackoverflow.com/a/50070958
has text: How would you use that in a `json.dump` call to serialize to file with indentation etc.?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49938732
tagged with: pandas
has answer: http://stackoverflow.com/a/49939548
favorite count: 0
has body: I just started coding in python. As a beginner, I tested different ways of coding to see their efficiency. I had a dataframe review storing a number of columns and I want to concatenate each row of two columns - country and variety - with a delimiter '-'. If I try lambda expression for doing the job, it will be like this: start = time.time() ans = reviews'country','variety' ans = ans.dropna(axis = "index", how = "any") ans = ans.apply(lambda srs: srs.country + " - " + srs.variety, axis = "columns") ans.value_counts() end = time.time() print(end - start) # time elapsed: 3.825517416000366 If I try str.cat method, it will be like this: start = time.time() ans = reviews'country','variety' ans = ans.dropna(axis = "index", how = "any") ans = ans.country.str.cat(ans.variety, sep = ' - ') ans.value_counts() end = time.time() print(end - start) # time elapsed: 0.14058899879455566 I wonder why there is such a big discrepancy in efficiency?
type: Question
has comment: http://stackoverflow.com/comment/86893426
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Why str.cat is much faster than lambda expression in python?
upvote count: 3
score: 3

http://stackoverflow.com/comment/87107397
score: 0
type: QuestionComment
has text: Welcome to SO. Can you share a part of the dataframe you're using?
type: Comment
comment on: http://stackoverflow.com/q/50045537

http://stackoverflow.com/comment/87145900
score: 0
comment on: http://stackoverflow.com/q/50033186
type: Comment
type: QuestionComment
has text: I want to keep it vanilla, this will strengthen my understanding of the language.

http://stackoverflow.com/a/49998719
score: 1
upvote count: 1
downvote count: 0
has body: Decoding the string using "UTF-8" print test_str.decode("utf-8") u'Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at anу timе bеfore Арril 28? Indicаtоr: 60.76%' As it still has some non-ASCII characters (such as CYRILLIC SMALL LETTER U), we can translate it further. Full list here: Cyrillic Script Wiki Using unidecode import unidecode unidecode.unidecode(test_str.decode("utf-8")) 'Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at anu time before Arril 28? Indicator: 60.76%' unidecode.unidecode(test_str.decode("utf-8")).split("before ") ['Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at anu time ', 'Arril 28? Indicator: 60.76%'] Note: If you do not want to use unidecode, I found this article explains another way in much detail: Transliterating non-ASCII characters with Python
answers question: http://stackoverflow.com/q/49998198
has comment: http://stackoverflow.com/comment/87014866
type: Answer

http://stackoverflow.com/q/49992636
tagged with: django-2.0
tagged with: python
has body: I written a base html for another html base.html {% for foo in subjectType %} {{ foo.type_name }} {% endfor %} and my navbar extends from base.html，but other html extends base.html，Can't display correct navbar.because other cant get "subjectType" How can I code this? I use python3.6.5 and django2.0
has answer: http://stackoverflow.com/a/49994471
has title: Django：Html templates
type: Question
tagged with: django-templates
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/87001856
has answer: http://stackoverflow.com/a/49992732
tagged with: python-3.6

http://stackoverflow.com/q/50036183
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/87090526
has comment: http://stackoverflow.com/comment/87090230
has comment: http://stackoverflow.com/comment/87089441
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50038162
has body: I am currently trying to filter my QuerySet results by the day of the week in Django 2.0. I can't for the life of me get the django week_day filter datetime__week_day to return any results. Model class Session(models.Model): def __str__(self): return str.join(', ', (str(self.game.name), str(self.datetime_created), str(self.start))) game = models.ForeignKey( 'Game', on_delete=models.PROTECT, blank=False, null=False, ) datetime_created = models.DateTimeField(auto_now_add=True,) start = models.DateTimeField(blank=True, null=True,) end_time = models.TimeField(blank=True, null=True,) competitive = models.BooleanField(default=False,) Filtering filtered_sessions = Session.objects.filter( start__week_day=2, ).exclude(start__isnull=True) I currently have an entry in the sessions table (MySQL backend) which contains the datetime 2018-04-30 23:51:42.000000, so I would expect this QuerySet to contain that 'Session' as it occurs on a Monday. Referring back to the documentation, The week goes from Sunday(1) to Saturday(7). I have USE_TZ in my settings, TIME_ZONE='UTC'. Irrespective of these settings, I have also tried replacing the start__week_day=2 with values from 0-8 (inclusive, just in case) My question is this: Why is what I am trying is not returning any results? Please let me know if I've left out something that would help answer my query. Thanks! EDIT: I have since attempted to run a direct query in the database (SELECT * FROM mysite_session WHERE DAYOFWEEK('start') IN (0-8);) No result in the database.
accepted answer: http://stackoverflow.com/a/50038162
has comment: http://stackoverflow.com/comment/87089572
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/87089009
has comment: http://stackoverflow.com/comment/87088633
answer count: 1
has comment: http://stackoverflow.com/comment/87090451
has comment: http://stackoverflow.com/comment/87089466
tagged with: django
has comment: http://stackoverflow.com/comment/87089266
has comment: http://stackoverflow.com/comment/87089153
has comment: http://stackoverflow.com/comment/87090701
has comment: http://stackoverflow.com/comment/87089343
type: Question
has comment: http://stackoverflow.com/comment/87088668
has title: Django QuerySet Filter by week_day returning nothing
has comment: http://stackoverflow.com/comment/87090786
has comment: http://stackoverflow.com/comment/87090434

http://stackoverflow.com/q/49943958
has body: I use the below code to find a .csv file with a certain pattern. I would then like to pass it into the read_csv() function, but it seems that it only accepts a string. What can I do to pass my variable "csv_file" into the function? Code: csv_file = glob.glob('******* Output.csv') Tried print(csv_file) ['1815910 Output.csv'] d = pd.read_csv(csv_file) TypeError: 'function' object has no attribute 'getitem'
has comment: http://stackoverflow.com/comment/86904027
tagged with: pandas
has comment: http://stackoverflow.com/comment/86904064
upvote count: 1
has comment: http://stackoverflow.com/comment/86904029
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86904156
favorite count: 0
type: Question
has title: Using a variable for pandas read_csv()
has comment: http://stackoverflow.com/comment/86904207
tagged with: glob
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86904211
tagged with: python
has answer: http://stackoverflow.com/a/49944025
score: 0

http://stackoverflow.com/comment/86938925
score: 0
has text: At the top where it says `def check_file(filename, phrase):` what does "phrase" mean?
type: Comment
comment on: http://stackoverflow.com/a/49961153
type: AnswerComment

http://stackoverflow.com/q/49945187
answer count: 2
has answer: http://stackoverflow.com/a/49945746
has body: I'd like to categorise parts using dataframes. Simplifying the problem to try and show the issue: data = {'col1': ['engine','blue engine cover','spark plug', 'rear panel','black rear panel', 'blue engine']} desc_df = pd.DataFrame(data=data) catg = {'bodywork': ['engine cover','side panel','rear panel'],'underhood':['engine','spark plug','oil filter'], 'Glass':['Windscreen','window','demister']} catg_df = pd.DataFrame(data=catg) catg_df Glass bodywork underhood 0 Windscreen engine cover engine 1 window side panel spark plug 2 demister rear panel oil filter desc_df col1 0 engine 1 blue engine cover 2 spark plug 3 rear panel 4 black rear panel 5 blue engine I would like to end up with : col1 Category 0 engine underhood 1 blue engine cover underhood 2 spark plug underhood 3 rear panel bodywork 4 black rear panel bodywork 5 blue engine underhood The closest I have come up with is: d=catg_df.apply('|'.join).to_dict() desc_df['Category'] = desc_df['col1'].apply(lambda x : ''.join([z if pd.Series(x).str.contains(y).values else '' for z,y in d.items()])) But I end up with finding both "engine" and "engine cover" in the string: desc_df col1 Category 0 engine underhood 1 blue engine cover bodyworkunderhood 2 spark plug underhood 3 rear panel bodywork 4 black rear panel bodywork 5 blue engine underhood Is there some method I could use to perhaps if it finds "engine Cover" first then categorises using this category and does not move onto "engine".
has title: pandas if full string contained in another pandas dataframe
tagged with: python
tagged with: dictionary
score: 4
has answer: http://stackoverflow.com/a/49945327
favorite count: 0
accepted answer: http://stackoverflow.com/a/49945327
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
tagged with: dataframe
upvote count: 4
possible better answer: http://stackoverflow.com/a/49945746
type: Question

http://stackoverflow.com/comment/87146897
comment on: http://stackoverflow.com/a/50065108
score: 0
type: Comment
has text: I'm sorry, when I try to run this after copy and paste, I got this error importError : cannot import name 'izip_longest'
type: AnswerComment

http://stackoverflow.com/q/49948311
has answer: http://stackoverflow.com/a/49948389
possible better answer: http://stackoverflow.com/a/49948389
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49948352
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86913217
has title: Print multiple sentences from a paragraph in separate lines
has body: Whish to change the document below into a txt file (with text) and enter the file changing it so that every sentence is on it's own line. I tried with open() and get an error. Anyone know how to handle this one? When I write the following I get an IndexError: string index out of range document = "Hello World. Goodbye World" def sentence_separator(document): pos = 0 for char in document: if char[pos] == ".": char[pos] = "\n" pos += 1 print(sentence_separator(document)) Desired output is each sentence on its separate lines: Hello World Goodby World
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49948376
accepted answer: http://stackoverflow.com/a/49948352
has comment: http://stackoverflow.com/comment/86913172
downvote count: 0
has answer: http://stackoverflow.com/a/49948381
answer count: 5
has comment: http://stackoverflow.com/comment/86913214
tagged with: python
has answer: http://stackoverflow.com/a/49948514

http://stackoverflow.com/comment/87137462
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50060307
has text: Django models already compares using pk, so the correct test is `user == request.user`

http://stackoverflow.com/comment/86995122
has text: It's an example of [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection).
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49989263

http://stackoverflow.com/a/56027515
has body: If you have changed the interpreter and are running the code in Interactive mode; then just close the python console tab and open a new one. That should do the trick. Somehow I think Python console doesn't reference to the new python interpreter even if you change the Project interpreter.
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49969416

http://stackoverflow.com/comment/87020186
has text: @CasimiretHippolyte yes i can do that but the sentences are user inputs, so I need to deal with misspellings. Stemming or lemmatizing "kat" won't give me "cat"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50001328

http://stackoverflow.com/comment/86892557
score: 0
type: Comment
type: QuestionComment
has text: That regex will not match that string. For example, what does `f+` mean? Where are the parts that match spaces? Round parentheses? Dots?
comment on: http://stackoverflow.com/q/49938058

http://stackoverflow.com/comment/87155639
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50069309
score: 0
has text: i did what u told, bank_data.update({k: year_converter(v) for k, v in bank_data.items()})

http://stackoverflow.com/q/49973141
tagged with: python
has answer: http://stackoverflow.com/a/49973253
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49973253
tagged with: python-3.x
has body: Consider the program: def wrap(): print(66) print(77,77) wrap() The dis module (3.5.2) reports that this code means: 1 0 LOAD_CONST 0 (&lt;code object wrap at 0x7f9d3b538c90, file "&lt;dis&gt;", line 1&gt;) 3 LOAD_CONST 1 ('wrap') 6 MAKE_FUNCTION 0 9 STORE_NAME 0 (wrap) 4 12 LOAD_NAME 1 (print) 15 LOAD_CONST 2 (77) 18 LOAD_CONST 2 (77) 21 CALL_FUNCTION 2 (2 positional, 0 keyword pair) 24 POP_TOP 5 25 LOAD_NAME 0 (wrap) 28 CALL_FUNCTION 0 (0 positional, 0 keyword pair) 31 POP_TOP 32 LOAD_CONST 3 (None) 35 RETURN_VALUE This compiled bytecode includes two CALL_FUNCTION operations, but I count three function calls in the code. Why doesn't the print(66) appear?
tagged with: assembly
tagged with: bytecode
has title: more function calls than CALL_FUNCTIONs in dis bytecode

http://stackoverflow.com/q/49949570
tagged with: google-cloud-storage
upvote count: 6
has title: How to batch delete buckets
favorite count: 0
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49987405
score: 6
type: AnsweredQuestion
has body: How do I delete buckets in a batch? Here's what i've tried. def deleteAllBuckets(): batch = storage_client.batch() with batch: for bucket in storage_client.list_buckets(): bucket.delete() Technically it works because the buckets get deleted, however i'm not convinced i'm sending a single batch request. It looks like i'm sending one request per bucket. Compare the above code to a batch request in Google Cloud Datastore def deleteAllEntities(): query = datastore_client.query(kind="Charge") queryIter = query.fetch() batch = datastore_client.batch() with batch: for entity in queryIter: batch.delete(entity.key) You can see that i'm calling a delete method on the batch object. With the storage code, i'm calling delete on the bucket object. Unfortunately the cloud storage python API doesn't have any examples.
has answer: http://stackoverflow.com/a/49987405
tagged with: python

http://stackoverflow.com/a/50024993
answers question: http://stackoverflow.com/q/50024383
score: 0
type: Answer
has body: You can try this, import regex as re print(re.sub(r'(?&lt;="[^"]*);(?=[^"]*")',',',a)) May I also say, "[^"]*(;)[^"]*" in your regex matches all string inside double quotes and replaces it with ',', so such output resulted.

http://stackoverflow.com/q/50051326
upvote count: 1
tagged with: intervals
favorite count: 0
type: Question
tagged with: split
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/50051379
has answer: http://stackoverflow.com/a/71274843
has title: How to split interval in two
tagged with: python
has answer: http://stackoverflow.com/a/50051407
answer count: 4
has body: How can i split this interval using python? I have this interval: x = [10, 30] I want to split it in 2 using python code to get this: y = [10, 20] z = [20, 30]
has answer: http://stackoverflow.com/a/50051412
has comment: http://stackoverflow.com/comment/87118988
downvote count: 3

http://stackoverflow.com/comment/87023401
comment on: http://stackoverflow.com/q/50003534
score: 0
type: Comment
has text: In python, indentation matters. `def __init__(self, name, city, addr, pin):` needs to be under the class definition. As stands, your class only has the default `__init__`.
type: QuestionComment

http://stackoverflow.com/comment/86885109
comment on: http://stackoverflow.com/q/49934730
type: Comment
has text: @MagnusEriksson When the function is called, alert dialog will pop-up but the python code is'nt running. (led is not turning ON)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87060179
comment on: http://stackoverflow.com/q/50020093
score: 0
has text: Is possible create sample data with duplicates and expected output? e.g. change `10/01/2018 ACA 134,4` to `09/01/2018 ACA 100` ?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49984596
has body: Doing just one more iteration in one of your loops (here over width) fixes this : import numpy as np import matplotlib.pyplot as plt width = 416 height = 416 heatmap = np.zeros((width,height),dtype='float') box = [60,50,100,100] value = 0 while box[0] &lt; box[2]: width = box[2] - box[0] height = box[3] - box[1] for i in range(width+1): heatmap[box[1]][box[0] + i] = value heatmap[box[3]][box[0] + i] = value for j in range(height): heatmap[box[1] + j][box[0]] = value heatmap[box[1] + j][box[2]] = value value = value + 0.1 box[0] += 1 box[1] += 1 box[2] += -1 box[3] += -1 plt.imshow(heatmap) plt.show()
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49984445

http://stackoverflow.com/comment/86983133
score: 0
comment on: http://stackoverflow.com/q/49981145
has text: Wow! this is the point! :) I am quite new to Celery and all tasks I used - didn't returned anything, so I thought that tasks might not have returns at all. If you want some points - write an answer, I will accept. P.S. `return serializers.serialize('json', queryset)` is required.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87106442
comment on: http://stackoverflow.com/q/50044626
type: Comment
type: QuestionComment
has text: hope the answer below is helpful
score: 0

http://stackoverflow.com/a/50016046
score: 0
has body: For long process it's always good to generate a log file. where you could put for example: input filenameInput -&gt;output succeed filenameOutput input filenameInput -&gt;output failed filenameOutput and then do a script that read this log file and rerun (with different input parameter I guess) the process which failed.
answers question: http://stackoverflow.com/q/50015784
has comment: http://stackoverflow.com/comment/87048541
has comment: http://stackoverflow.com/comment/87048408
type: Answer

http://stackoverflow.com/comment/87090234
comment on: http://stackoverflow.com/a/50028443
has text: awesome ! this works perfectly. I have a question though. How could I find that in the documentation? If I look at the QMessageBox, I cannot find the qt_msgboxex_icon_label QLabel object. I mean how could I know that the QMessageBox had a QLabel child that I could modify? I have still so much to learn about Qt :) Again, a big thanks to you.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86864080
type: AnswerComment
comment on: http://stackoverflow.com/a/49924059
score: 0
type: Comment
has text: Close, but the OP specified that a given solution must have the constraint that every item in the list is included at least once i.e. an item can't be bought zero times.

http://stackoverflow.com/a/50347106
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50056785
has body: Thanks @Pp jym & @chezou for response ! However,the problem happened because java was trying to run a java 7 VM where it found a JRE 8.Steps suggested in the question Registry key Error: Java version has value '1.8', but '1.7' is required helped to fix the error.

http://stackoverflow.com/comment/87143113
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50059421
has text: Possible duplicate of [XPath: using regex in contains function](https://stackoverflow.com/questions/21405267/xpath-using-regex-in-contains-function)

http://stackoverflow.com/a/50084044
upvote count: 2
has body: class multiprocessing.connection.Listener([address[, family[, backlog[, authkey]]]]) A wrapper for a bound socket or Windows named pipe which is ‘listening’ for connections.address is the address to be used by the bound socket or named pipe of the listener object.
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50074545

http://stackoverflow.com/q/49976003
tagged with: python
has comment: http://stackoverflow.com/comment/86970488
tagged with: regex
has comment: http://stackoverflow.com/comment/86968367
has title: Understanding Regex to fetch ip address :
duplicate of: http://stackoverflow.com/q/6908725
has comment: http://stackoverflow.com/comment/86968261
has comment: http://stackoverflow.com/comment/86970141
score: 0
answer count: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86970082
has comment: http://stackoverflow.com/comment/86968017
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86968663
has body: Regex 1: \b(([01]?\d\d?|2[0-4]\d|25[0-5])(\.|\b)){4}\b Regex 2: \b(([01]?\d\d?|2[0-4]\d|25[0-5])(\.|$)){4}\b Sample String : 123.105.114.142 010.000.000.011 240.000.000.240 121.122.221.123 224.152.255.152 240.345.334.123 ..@102.021.031.246@@@@@@02.021.031.246@@@@..@ 255.255.251.255 10.1.1.2 23.124.23.144# Regex 1 is able to fetch all the ip addresses from the sample string. My question is why regex 2 is not able to do so?
type: UnansweredQuestion
tagged with: javascript

http://stackoverflow.com/comment/87173419
score: 0
type: AnswerComment
has text: Ok here is a way around : https://code.visualstudio.com/#alt-downloads download the setup and install manually then install anaconda without selecting VSCode option in installer. You have to manually run VScode every time and it wont be available in anaconda.
type: Comment
comment on: http://stackoverflow.com/a/50061060

http://stackoverflow.com/comment/86899883
type: Comment
score: 0
has text: because of `'#' + word + '#'`
type: AnswerComment
comment on: http://stackoverflow.com/a/49941920

http://stackoverflow.com/q/49970241
has answer: http://stackoverflow.com/a/49974690
upvote count: 1
tagged with: python
has body: I'm trying to convert a shapefile to a list of latitude and longitude points that represent every point defined by the shapefile. Reading the file with geopandas and using the .plot() function displays these points as a graph, but I would like the raw points. I attempted to iterate through the polygons in geopandas .geometry and store all the points within the polygons. I plotted these points to test if they gave an accurate representation of the area, but they do not. I did all this with the following code: import re import geopandas as gpd import matplotlib.pyplot as plt def geoToList(geodataframe): points = [] for s in geodataframe.geometry:iq s = str(s) s = re.sub('[^0-9., ]+', '', s).split(',') s = map(lambda x: x.strip(), s) s = map(lambda x: (float(x.split()[0]), float(x.split()[1])), s) points.extend(list(s)) return points habitat = gpd.read_file('desktop/species_19377/species_19377.shp') #borough = borough.to_crs(epsg=4326) points = geoToList(habitat) x = [point[0] for point in points] y = [point[1] for point in points] plt.scatter(x, y) plt.show() #representation of the points in all polygons habitat.plot() #representtation of the points I want I would like some function that returns a list of points that could be plotted and look identical to the output of habitat.plot() My next idea is to store the graphs as images and assign the pixel values latitude and longitude values based on the scale of the graph, but I'm sure this is more complicated than it needs to be. Any help would be appreciated!
has title: How to convert a shapefile to a complete list of latitude and longitude points
type: AnsweredQuestion
tagged with: geopandas
score: 1
favorite count: 0
tagged with: shapefile
type: Question
accepted answer: http://stackoverflow.com/a/49974690
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87038369
score: 0
comment on: http://stackoverflow.com/q/50010703
type: QuestionComment
type: Comment
has text: @fferri true, I am trying to take the extra comma after the last word

http://stackoverflow.com/comment/87149830
has text: I did not include a dictionary in my example for the sake of keeping it simple
comment on: http://stackoverflow.com/q/50065610
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50048539
has answer: http://stackoverflow.com/a/50048977
linked to: http://stackoverflow.com/q/47776318
has comment: http://stackoverflow.com/comment/87114189
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87113325
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87115377
has title: Assign Color to Specific Value in matplotlib through Python?
linked to: http://stackoverflow.com/q/47774935
has answer: http://stackoverflow.com/a/79504892
has comment: http://stackoverflow.com/comment/87115670
has body: I've got a chart produced in matplotlib that's basically a checkered grid. I've got four values and I want to assign each specific value a color on the grid. I do not want to use a colormap because that shows a gradient of values and that's not what I want. I have the values -1, 0, 1, 10. Is there a way to do this? I don't think I can include the code without including the entirety of it because it's just a couple lines that relate to the grid but there's a lot of stuff that intermingles. Let's just say I have something that looks like |1|-1|0|0|-1|1| |0|1|1|-1|0|1| |-10|1|1|0|1|1| and because the way color maps work, the -10 is skewing the outcome because 1,0,-1 are all much closer to each other than -10. Instead I would like each number to just be assigned one color.
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87113480

http://stackoverflow.com/a/50039709
answers question: http://stackoverflow.com/q/50038373
has comment: http://stackoverflow.com/comment/87096895
has comment: http://stackoverflow.com/comment/87097058
has comment: http://stackoverflow.com/comment/87097791
has comment: http://stackoverflow.com/comment/87104666
has comment: http://stackoverflow.com/comment/87099034
score: 0
has comment: http://stackoverflow.com/comment/87100057
has comment: http://stackoverflow.com/comment/87097331
has body: check if this works import os import pandas as pd path = 'C:/' for roots, dirs, files in os.walk(path): xlsfile = [ _ for _ in files if _.endswith('.xlsx')] for xlsf in xlsfile: df = pd.read_excel(os.path.join(roots, xlsf)) df['Sort Data'] = ' ' df.to_excel(os.path.join(roots, xlsf), index = False)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50038373
has comment: http://stackoverflow.com/comment/87101323
type: Answer
has comment: http://stackoverflow.com/comment/87096322

http://stackoverflow.com/a/59760303
type: Answer
has body: the simplest way to save this is to just read to an array and then do numpy.save('file',data,allow_pickle =False) to load it you then to data = numpy.load('file') remember to set the batch size to 1 and torch.to_numpy() everything once you do this its fairly simple to just rebuild your data loader and reload data loader with your dataset use numpy.load('file', mmap_mode='r') if you need to get at the data without loading it all to ram (helps with those pesky 600gb datasets) for those asking why numpy.save() whole datasets? : sometimes your data needs post processing, batching, reshaping, and this takes a lot of CPU time. You don't want to be using that cpu time re-crunching your data before you send it to your model. the next step up is to start using databases and servers, it does this, but better with more SQL! in terms of using slices of data its just a mater of reloading your dataset with dataset(data[k:],label[k:]) instead of dataset(data,label)
answers question: http://stackoverflow.com/q/49987614
has comment: http://stackoverflow.com/comment/133577024
score: 1
has comment: http://stackoverflow.com/comment/127785996
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49983971
favorite count: 0
has comment: http://stackoverflow.com/comment/86986624
type: Question
has title: Asyncio not running things in parallel
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: python
tagged with: concurrency
has body: I am running this asyncio example import asyncio from aiohttp import ClientSession async def fetch(url, session, index): async with session.get(url) as response: print("Before " + str(index)) buffer = await response.read() print("After " + str(index)) async def run(r): url = "http://google.com" tasks = [] # Fetch all responses within one Client session, # keep connection alive for all requests. async with ClientSession() as session: for i in range(r): task = asyncio.ensure_future(fetch(url, session, i)) tasks.append(task) responses = await asyncio.gather(*tasks) # you now have all response bodies in this variable print(responses) def print_responses(result): print(result) loop = asyncio.get_event_loop() future = asyncio.ensure_future(run(4)) loop.run_until_complete(future) The results are something like this Before 1 After 1 Before 3 After 3 Before 2 After 2 Before 0 After 0 This looks like the things are running serially. The fetch part itself takes some milliseconds. I ran it several times, but the results are not intermingled. Any suggestions?
tagged with: aiohttp
score: 1
has answer: http://stackoverflow.com/a/49986564
answer count: 1
downvote count: 0
upvote count: 1

pygobject
type: Tag
tags question: http://stackoverflow.com/q/49964906
tag name: pygobject

http://stackoverflow.com/comment/87027687
score: 0
has text: Also, even if you fix that, your code could easily miss an alarm. Let's say it's `08:29:59.977`. Then you `sleep(1)`, and next time through the loop it's `08:30:01.013`. If your alarm was set for `08:30:00`, you'd have jumped right over it. You probably want to compare `alarm <= clock`, and then disable the alarm when it fires. (If you want it to fire every day, either keep track of whether the alarm has fired today, or use a `datetime` rather than a `time` and reset the alarm to "same time tomorrow" after it fires. But if you only want to fire it once, you can keep it simpler.)
comment on: http://stackoverflow.com/q/50005404
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49966522
tagged with: python
has comment: http://stackoverflow.com/comment/86952804
tagged with: opencv
score: 0
tagged with: anaconda
tagged with: raspberry-pi2
has body: I am trying to install opencv using annaconda into raspberry pi. I have tried - conda install opencv conda install -c menpo opencv I have also tried using conda search -t opencv I changed the channel as well using - conda install --channel https://conda.annaconda.org/poppy-project opencv3 However, it adds /linux-armv7l/ to the channel and gives the following error message - Could not connect to https://conda.annaconda.org/poppy-project/noarch/ .Could not connect to https://conda.annaconda.org/poppy-project/linux-armv7l/ ..... Error: No packages found in current linux-armv7l channels matching: opencv3 You can search for this package on anaconda.org with anaconda search -t conda opencv3 I need to install for python 2.7 Could anyone please help me install this?
type: Question
has title: Installing opencv on raspberry pi b+ using annaconda
has comment: http://stackoverflow.com/comment/86949903
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59075545
answer count: 1

http://stackoverflow.com/q/50012909
has comment: http://stackoverflow.com/comment/87042561
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87042375
downvote count: 2
tagged with: delay
has comment: http://stackoverflow.com/comment/87042600
upvote count: 1
has body: I recently made a program in Python that calculates the prime numbers under 1,000,000 and puts them in a list, primelist. Here it is: import math import time max = 1000000 intlist = [] iflist = [] primelist = [2] sqrt = round(math.sqrt(max)) counter = 3 start = time.clock() while (counter &lt; max) : intlist.append(counter) iflist.append(0) counter += 2 counter = 0 counter2 = 0 while intlist[counter] &lt; sqrt: if (iflist[counter] == 0): current = intlist[counter] counter2 = counter + current while (counter2 &lt; len(iflist)): iflist[counter2] = 1 counter2 += current counter += 1 counter = 0 while counter &lt; len(iflist): if iflist[counter] == 0: primelist.append(intlist[counter]) counter += 1 print(time.clock() - start) In no way is this program optimized; it's just a basic implementation of the sieve of eratosthenes. Recently I decided to learn how to code in C++. I wrote a direct translation of my Python code into C++, here it is: #include "stdafx.h" #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;math.h&gt; #include &lt;time.h&gt; using namespace std; int main() { auto start = clock(); int max = 1000000; int squareroot = ceil(sqrt(max)); int current = 0; vector&lt;int&gt; primelist = { 2 }; vector&lt;int&gt; sieve; vector&lt;bool&gt; conditions; vector&lt;int&gt; primes; for (int n = 3; n &lt; max; n += 2) { sieve.push_back(n); conditions.push_back(0); } for (int n = 0; sieve[n] &lt; squareroot; n++) { if (conditions[n] == 0) { current = sieve[n]; for (int x = n + current; x &lt; conditions.size(); x += current) { conditions[x] = 1; } } } for (int n = 0; n &lt; conditions.size(); n++) { if (conditions[n] == 0) { primes.push_back(sieve[n]); } } /*for (int n = 0; n &lt; primes.size(); n++) { cout &lt;&lt; primes[n] &lt;&lt; endl; }*/ cout &lt;&lt; clock() - start &lt;&lt; endl; } From what I've heard, C++ is much faster at number crunching than Python. But, the Python script took 0.74 seconds to run and the C++ script took 13.29 seconds to run(acco…
tagged with: primes
has comment: http://stackoverflow.com/comment/87042633
has comment: http://stackoverflow.com/comment/87042380
favorite count: 0
has comment: http://stackoverflow.com/comment/87042397
has answer: http://stackoverflow.com/a/50013104
has title: Why is C++ Running Slower than Python?
tagged with: performance
has comment: http://stackoverflow.com/comment/87042425
answer count: 1
tagged with: python
score: -1
tagged with: c++
type: Question
has comment: http://stackoverflow.com/comment/87042362

http://stackoverflow.com/comment/117173586
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50063554
has text: Layer weight shape (3, 8) not compatible with provided weight shape (2, 8). Old: `model = keras.Sequential(keras.layers.LSTM(units=2, input_shape=(2, 2)) )`, New: `model2 = keras.Sequential(keras.layers.LSTM(units=2, input_shape=(2, 3)) )`.
type: AnswerComment

http://stackoverflow.com/a/50066662
upvote count: 2
score: 2
downvote count: 0
has body: exec_() is blocking so the data you get is data before the new window is displayed, you must obtain the data that closes the window, that is, after exec_(): def dialogOpen(self): sub = subDialog() if sub.exec_(): check = str(sub.checkbox.isChecked()) spin = str(sub.spinbox.value()) self.label1.setText('spinbox value is ' + spin) self.label2.setText('Checkbox is ' + check)
answers question: http://stackoverflow.com/q/50066500
type: Answer

http://stackoverflow.com/comment/87114117
type: QuestionComment
comment on: http://stackoverflow.com/q/50048718
score: 0
has text: @SukirtiSen As long as you are refreshing the `app.route` that is doing this excel reading and returns the table, then the data will refresh accordingly...
type: Comment

http://stackoverflow.com/a/49930031
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49929905
has comment: http://stackoverflow.com/comment/86876751
has body: The way you put the question is very abstract, but it seems you're trying to use the itertools.tee function that can split an iterator in two x1, x2 = itertools.tee(your_generator, 2) then skip the first 4 elements from the first iterator: x1 = itertools.islice(x1, 4, None) pass the x1 to one function and x2 to the other, and x1 will be 4 elements ahead, no extra elements will be consumed unless needed (the tee function context will store the 4 elements internally in its scope)
score: 2
has comment: http://stackoverflow.com/comment/86876293
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49929905

apache-spark
tags question: http://stackoverflow.com/q/49923921
tags question: http://stackoverflow.com/q/49917008
tags question: http://stackoverflow.com/q/50028730
tags question: http://stackoverflow.com/q/50043101
tags question: http://stackoverflow.com/q/50052385
tags question: http://stackoverflow.com/q/49946283
tags question: http://stackoverflow.com/q/50063668
tags question: http://stackoverflow.com/q/50037057
tags question: http://stackoverflow.com/q/49957950
tags question: http://stackoverflow.com/q/50070775
tags question: http://stackoverflow.com/q/50063685
tags question: http://stackoverflow.com/q/49973200
tags question: http://stackoverflow.com/q/49930657
tags question: http://stackoverflow.com/q/49947159
tags question: http://stackoverflow.com/q/50047493
tags question: http://stackoverflow.com/q/49926504
tags question: http://stackoverflow.com/q/49962987
tags question: http://stackoverflow.com/q/49933172
tags question: http://stackoverflow.com/q/50061577
tags question: http://stackoverflow.com/q/49971903
tags question: http://stackoverflow.com/q/50068131
tags question: http://stackoverflow.com/q/50055916
type: Tag
tags question: http://stackoverflow.com/q/49940084
tags question: http://stackoverflow.com/q/49967984
tag name: apache-spark
tags question: http://stackoverflow.com/q/49934648
tags question: http://stackoverflow.com/q/49983555
tags question: http://stackoverflow.com/q/50019417
tags question: http://stackoverflow.com/q/49936190
tags question: http://stackoverflow.com/q/49917974
tags question: http://stackoverflow.com/q/50009413

http://stackoverflow.com/comment/86921064
score: 0
type: Comment
has text: Thank you, that make sense.
comment on: http://stackoverflow.com/a/49947066
type: AnswerComment

http://stackoverflow.com/comment/87418760
has text: You are welcome, happy coding! Is everything explained clearly?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50200351
type: Comment

http://stackoverflow.com/comment/86862026
comment on: http://stackoverflow.com/q/49923103
type: Comment
type: QuestionComment
has text: If there are three separate dates wouldn't there be two *gaps*?
score: 0

http://stackoverflow.com/a/63768513
score: 17
has body: Here is a command-line solution with jq and iconv. Tested on Linux. cat message_1.json | jq . | iconv -f utf8 -t latin1 &gt; m1.json
has comment: http://stackoverflow.com/comment/122281241
downvote count: 0
answers question: http://stackoverflow.com/q/50008296
upvote count: 17
type: Answer
has comment: http://stackoverflow.com/comment/122123275

http://stackoverflow.com/comment/86939253
comment on: http://stackoverflow.com/a/49931165
type: Comment
score: 0
type: AnswerComment
has text: examples of strings that pass or don't pass: # has_subpattern("a") == False #no repeated shorter sub-pattern, just one character # has_subpattern("aaaa") == True #just one character repeated # has_subpattern("abcd") == False #no repetitions # has_subpattern("babababababababa") == True #repeated "ba" # has_subpattern("bbabbaaabbaaaabb") == True #same as above, just shuffled #

http://stackoverflow.com/comment/87130739
type: Comment
comment on: http://stackoverflow.com/a/50056714
score: 0
type: AnswerComment
has text: I'm using an older version of Pandas (0.17.1, don't ask...), and it works fine.

http://stackoverflow.com/q/49982147
accepted answer: http://stackoverflow.com/a/49983856
upvote count: 2
has comment: http://stackoverflow.com/comment/86980968
has title: Hide current QMainWindow when next QMainWindow is called
has comment: http://stackoverflow.com/comment/86980668
tagged with: pyqt5
downvote count: 1
type: AnsweredQuestion
has body: I have multiple windows in a Python GUI application using PyQt5. I need to hide current window when a button is clicked and show the next window. This works fine from WindowA to WindowB but I get an error while going from WindowB to WindowC. I know there is some problem in initialization as the initialization code in WindowB is unreachable, but being a beginner with PyQt, i can't figure out the solution. WindowA code: from PyQt5 import QtCore, QtGui, QtWidgets from WindowB import Ui_forWindowB class Ui_forWindowA(object): def setupUi(self, WindowA): # GUI specifications statements here self.someButton = QtWidgets.QPushButton(self.centralwidget) self.someButton.clicked.connect(self.OpenWindowB) # More GUI specifications statements here def retranslateUi(self, WindowA): # More statements here def OpenWindowB(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_forWindowB() self.ui.setupUi(self.window) WindowA.hide() self.window.show() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) WindowA = QtWidgets.QMainWindow() ui = Ui_forWindowA() ui.setupUi(WindowA) MainWindow.show() sys.exit(app.exec_()) WindowB code: from PyQt5 import QtCore, QtGui, QtWidgets from WindowB import Ui_forWindowB class Ui_forWindowB(object): def setupUi(self, WindowB): # GUI specifications statements here self.someButton = QtWidgets.QPushButton(self.centralwidget) self.someButton.clicked.connect(self.OpenWindowC) # More GUI specifications statements here def retranslateUi(self, WindowB): # More statements here def OpenWindowB(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_forWindowC() self.ui.setupUi(self.window) WindowB.hide() # Error here self.window.show() # The below code doesn't get executed when Ui_forWindowB is called from A if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) WindowB = QtWidgets.QMainWindow() ui = Ui_forWindowB() ui.setupUi(WindowB) MainWindow.show() sys.exit(app.exec_()) It works fine from A to B where W…
score: 1
has answer: http://stackoverflow.com/a/49983856
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86982792
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86982210
tagged with: python-3.x

http://stackoverflow.com/comment/87042468
type: Comment
comment on: http://stackoverflow.com/a/49993413
score: 0
type: AnswerComment
has text: So how do I download it for my version of Python

http://stackoverflow.com/comment/87110799
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50047055
type: Comment
has text: It is useful. People just assume Python 3 :)

http://stackoverflow.com/q/49924590
has answer: http://stackoverflow.com/a/49924884
type: UnansweredQuestion
score: 1
tagged with: save
has body: I run my code and it works properly. Because it contains random numbers, some of these numbers lead to invalid values for the functions in code (it is normal and we don't know which number leads to invalid value). But in printing Python continues printing and just shows this error one or two times for those numbers: RuntimeWarning: invalid value encountered in... as the following: . . . 174.45044049634845 0.2462826944657234 0.07030551312264746 0.5748635625886386 173.507852282145 0.22849596593782928 0.02418486733987143 0.5342742271386651 172.72866355236476 0.23561628491593717 0.00276512493464073 0.5299714003809053 Warning (from warnings module): File "C:\... return (Om*(1+z)**3+omg0*(1+z)**6+(1-Om-omg0))**(-0.5) RuntimeWarning: invalid value encountered in double_scalars Warning (from warnings module): File "C:\...", line 364 warnings.warn(msg, IntegrationWarning) IntegrationWarning: The occurrence of roundoff error is detected, which prevents the requested tolerance from being achieved. The error may be underestimated. Warning (from warnings module): File "C:\...", line 1874 r = _umath_linalg.det(a, signature=signature) RuntimeWarning: invalid value encountered in det 172.72866355236476 0.23561628491593717 0.00276512493464073 0.5299714003809053 172.83987258470256 0.23561628491593717 0.00276512493464073 0.521804452272765 172.94243737214325 0.23561628491593717 0.00276512493464073 0.5142747330950714 173.81824790232395 0.2447458303542599 -0.014745034802849322 0.3863934727161802 173.81824790232395 0.2447458303542599 -0.014745034802849322 0.3863934727161802 175.04959056025322 0.2447458303542599 -0.014745034802849322 0.2964727561196514 . . . Python continue to print but I can not save them in a file, I have to copy and paste. It cannot possible if we have 5,000,000 data. Is there any way to write these outputs in a file?
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49927240
has title: How to pass RuntimeWarning in printing outputs?
tagged with: runtime
tagged with: python
answer count: 2
tagged with: compiler-errors

state
tag name: state
type: Tag
tags question: http://stackoverflow.com/q/50013449

http://stackoverflow.com/a/50047777
has body: Your code is near perfect but before you start looking out for the &lt;select&gt; tag you have to switch to the desired &lt;iframe&gt; with id as blockrandom inducing proper WebDriverWait as follows : from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver=webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe') driver.get("http://www.dubaitrade.ae/ja-terminal-1") WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"blockrandom"))) Select(driver.find_element_by_xpath('//*[@id="terminal1"]')).select_by_visible_text('General Cargo')
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50047392
has comment: http://stackoverflow.com/comment/87148776
type: Answer
has comment: http://stackoverflow.com/comment/87148883
score: 0
accepted answer of: http://stackoverflow.com/q/50047392

http://stackoverflow.com/q/49984954
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86986383
has body: I thought that sys.stdout.encoding would be the definitive way of knowing the encoding used by print, but that is demonstrably false: &gt;&gt;&gt; hello_in_chinese = '\u4f60\u597d' &gt;&gt;&gt; print(sys.stdout.encoding, hello_in_chinese) cp1252 你好 &gt;&gt;&gt; hello_in_chinese.encode(sys.stdout.encoding) Traceback (most recent call last): File "&lt;pyshell#65&gt;", line 1, in &lt;module&gt; hello_in_chinese.encode(sys.stdout.encoding) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\encodings\cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1: character maps to &lt;undefined&gt; This was in IDLE under Python 3.6.3, on Windows 7. How can you get the encoding that's actually being used?
has comment: http://stackoverflow.com/comment/86986612
has title: Foolproof way of getting output encoding?
has comment: http://stackoverflow.com/comment/86986492
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
tagged with: stdout
tagged with: python
has comment: http://stackoverflow.com/comment/86986560
tagged with: character-encoding
upvote count: 3

http://stackoverflow.com/q/49959942
has answer: http://stackoverflow.com/a/49963447
score: 1
has comment: http://stackoverflow.com/comment/86942282
tagged with: python
has comment: http://stackoverflow.com/comment/86939823
has comment: http://stackoverflow.com/comment/86940699
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/86941676
has title: Socket receive slower in python
has body: I am doing some profiling of my python code. I am using async api for rpc calls async def rpc_call(): return client.call(params) // makes rpc calls over tcp async def test(): await rpc_call() start = time.time() loop = asyncio.get_event_loop() tasks = [] for i in range(10000): tasks.append(asyncio.ensure_future(test())) print("Starting the loop") loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print("Total time: {}".format(end - start)) It took almost like 25 seconds to finish it which is really slow I took the cProfile dump of the process ncalls tottime percall cumtime percall filename:lineno(function) 10001 13.362 0.001 13.362 0.001 {method 'recv_into' of '_socket.socket' objects} 10004 0.760 0.000 0.802 0.000 {built-in method _socket.getaddrinfo} 1477355/1477208 0.404 0.000 0.812 0.000 {built-in method builtins.isinstance} 70008 0.334 0.000 0.837 0.000 /usr/lib/python3.6/_collections_abc.py:824(update) 20004 0.326 0.000 0.326 0.000 {method 'sendto' of '_socket.socket' objects} 310031 0.313 0.000 0.373 0.000 /usr/lib/python3.6/urllib/parse.py:109(_coerce_args) 20002 0.296 0.000 0.296 0.000 {method 'sendall' of '_socket.socket' objects} 100010 0.272 0.000 0.828 0.000 /usr/lib/python3.6/urllib/parse.py:359(urlparse) 140014 0.252 0.000 0.460 0.000 /usr/lib/python3.6/urllib/parse.py:392(urlsplit) 1963120 0.250 0.000 0.250 0.000 {method 'lower' of 'str' objects} 250161 0.236 0.000 0.408 0.000 /usr/lib/python3.6/abc.py:178(__instancecheck__) 70007 0.222 0.000 0.427 0.000 /usr/lib/python3.6/http/client.py:1195(putheader) 270027 0.221 0.000 0.762 0.000 /usr/lib/python3.6/_collections_abc.py:742(__iter__) 10001 0.185 0.000 23.543 0.002 /home/me/venv2/lib/python3.6/site-packages/requests/sessions.py:589(send) 394556/394200 0.185 0.000 0.198 0.000 {built-in method builtins.hasattr} 10001 0.175 0.000 17.859 0.002 /home/me/venv2/lib/python3.6/site-packages/urllib3/connectionpool.py:322(_make_request) 330445 0.171 0.000 0.171 0.000 /usr/lib/python3.6…
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86942954
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86941009
has comment: http://stackoverflow.com/comment/86939826
tagged with: network-programming
tagged with: python-asyncio

http://stackoverflow.com/comment/86881065
has text: You can do `def red(x,y): ... keys = set(x).union(set(y)) ... return { k: {j: x.get(k, {}).get(j,0) + y.get(k, {}).get(j,0) for j in (x.get(k,{}).keys()+y.get(k,{}).keys())} for k in keys` and `reduce(red, ps)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49932549

regex
tags question: http://stackoverflow.com/q/49948461
tags question: http://stackoverflow.com/q/49967832
tags question: http://stackoverflow.com/q/49933635
tags question: http://stackoverflow.com/q/50037702
tags question: http://stackoverflow.com/q/49993754
tags question: http://stackoverflow.com/q/50029759
tags question: http://stackoverflow.com/q/50022491
tags question: http://stackoverflow.com/q/49934383
tags question: http://stackoverflow.com/q/50033374
tags question: http://stackoverflow.com/q/49918300
tags question: http://stackoverflow.com/q/50017534
tags question: http://stackoverflow.com/q/49994402
tags question: http://stackoverflow.com/q/49989125
tags question: http://stackoverflow.com/q/50027605
tags question: http://stackoverflow.com/q/49963710
tags question: http://stackoverflow.com/q/50041089
tags question: http://stackoverflow.com/q/49938058
tags question: http://stackoverflow.com/q/49961865
tags question: http://stackoverflow.com/q/50034397
tags question: http://stackoverflow.com/q/50037319
tags question: http://stackoverflow.com/q/49936612
tags question: http://stackoverflow.com/q/49930932
tags question: http://stackoverflow.com/q/50016381
tags question: http://stackoverflow.com/q/50024383
tags question: http://stackoverflow.com/q/49951554
tags question: http://stackoverflow.com/q/49921980
tags question: http://stackoverflow.com/q/49997716
tags question: http://stackoverflow.com/q/50046647
tags question: http://stackoverflow.com/q/49987288
tags question: http://stackoverflow.com/q/49919765
tags question: http://stackoverflow.com/q/50003922
tags question: http://stackoverflow.com/q/49974923
tags question: http://stackoverflow.com/q/50043499
tags question: http://stackoverflow.com/q/50001328
tags question: http://stackoverflow.com/q/50056999
tag name: regex
tags question: http://stackoverflow.com/q/49943270
tags question: http://stackoverflow.com/q/50036647
tags question: http://stackoverflow.com/q/50051627
tags question: http://stackoverflow.com/q/49950261
tags question: http://stackoverflow.com/q/50008592
tags question: http://stackoverflow.com/q/50048484
tags question: http://stackoverflow.com/q/49996636
tags question: http://stackoverflow.com/q/50046913
tags question: http://stackoverflow.com/q/50005577
tags question: http://stackoverflow.com/q/50002258
tags question: http://stackoverflow.com/q/49923212
tags question: http://stackoverflow.com/q/49937891
tags question: http://stackoverflow.com/q/50019396
tags question: http://stackoverflow.com/q/50004111
tags question: http://stackoverflow.com/q/50059079
tags question: http://stackoverflow.com/q/49948239
tags question: http://stackoverflow.com/q/49952204
tags question: http://stackoverflow.com/q/50066830
tags question: http://stackoverflow.com/q/50073779
tags question: http://stackoverflow.com/q/50042655
tags question: http://stackoverflow.com/q/49927752
tags question: http://stackoverflow.com/q/50057299
tags question: http://stackoverflow.com/q/49953107
tags question: http://stackoverflow.com/q/50044830
tags question: http://stackoverflow.com/q/50015804
tags question: http://stackoverflow.com/q/49944330
tags question: http://stackoverflow.com/q/49992790
tags question: http://stackoverflow.com/q/49931313
tags question: http://stackoverflow.com/q/49944602
tags question: http://stackoverflow.com/q/49962356
tags question: http://stackoverflow.com/q/49951620
tags question: http://stackoverflow.com/q/49970366
tags question: http://stackoverflow.com/q/49932008
tags question: http://stackoverflow.com/q/49951850
tags question: http://stackoverflow.com/q/49978532
tags question: http://stackoverflow.com/q/50013854
tags question: http://stackoverflow.com/q/50003805
tags question: http://stackoverflow.com/q/50055600
tags question: http://stackoverflow.com/q/49985012
tags question: http://stackoverflow.com/q/50040600
tags question: http://stackoverflow.com/q/50033317
tags question: http://stackoverflow.com/q/50031377
tags question: http://stackoverflow.com/q/49918449
tags question: http://stackoverflow.com/q/49985863

http://stackoverflow.com/a/49981856
has comment: http://stackoverflow.com/comment/86980451
accepted answer of: http://stackoverflow.com/q/49981755
upvote count: 1
answers question: http://stackoverflow.com/q/49981755
has body: Don't os.chdir(), otherwise the relative path p1 will not work outside of the initial working directory. Explanation: suppose you start in /home/you, and you want to reach /home/you/some/folder. At the first step you choose some, the current directory changes to /home/you/some, then you choose folder, which gets concatenated with some, so from directory /home/you/some you try to chdir() into some/folder which does not exist. Pass p1 to os.walk() instead: def fun(path1,path2): p1=os.path.join(path1,path2) print('currently in ',p1) print('folders currently in this directories are:') print(next(os.walk(p1))[1]) p2=input('which folder you wanna access among these:') fun(p1,p2)
type: Answer
has comment: http://stackoverflow.com/comment/86980116
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87067068
has text: pip is likely not in your path, and therefore windows is unable to discover it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50025451
score: 2

http://stackoverflow.com/q/49960589
downvote count: 0
accepted answer: http://stackoverflow.com/a/49970534
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86950060
type: AnsweredQuestion
tagged with: django-views
score: 1
answer count: 1
tagged with: django-urls
upvote count: 1
has answer: http://stackoverflow.com/a/49970534
favorite count: 0
has body: I have a delete view with 2 conditions "post" and "user". The user requirement is fulfilled by self.object.user = self.request.user and post requirement is fulfilled by slug = self.kwargs['slug'](I think this may be the culprit) Are my views correct? I am new to python please forgive any silly mistakes. Views.py class ProofDelete(LoginRequiredMixin, DeleteView): model = Proof def delete(self, *args, **kwargs): return super().delete(*args, **kwargs) def get_success_url(self, *args, **kwargs): slug = self.kwargs['slug'] print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.made.all(): obj.made.remove(user) else: obj.made.add(user) return url_ models.py User = get_user_model() class Proof(models.Model): user = models.ForeignKey(User, related_name='proofmade') post = models.ForeignKey(Post, related_name='proofmade') made_at = models.DateTimeField(auto_now=True) image_of_proof= models.ImageField() proof_ = models.ImageField() suggestions = models.TextField(max_length=1000) def __str__(self): return self.post.title urls.py app_name = 'proof' urlpatterns = [ url(r'^new_proof/(?P&lt;slug&gt;[-\w]+)/$', views.ProofCreate.as_view(), name='new_proof'), url(r'^proof_delete/(?P&lt;pk&gt;\d+)/$', views.ProofDelete.as_view(),name='proof_delete'), also tried url (r'^proof_delete/(?P&lt;slug&gt;[-\w]+)/(?P&lt;pk&gt;\d+)/$', views.ProofDelete.as_view(), name='proof_delete'), I get the below error. Indicating error in the views Error Message Click to see Error message Same error message after scrolling down. Click to open
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86950391
has comment: http://stackoverflow.com/comment/86950217
has title: DeleteView with 2 arguements post and user

http://stackoverflow.com/a/50033300
score: 1
has body: Try to add a time sleep right after sending the request, sometimes the response payload for your request are only incomplete, then when you try to convert in a JSON object it throws a error import time ... r = requests.post(post_url, data=payload, headers=self.header) time.sleep(2) output = r.json() #output = self.post_request(post_url,payload) package_names = [] Another thing you may want to try is surrond the json converter line with "try except" statement, to your script do not stop when a error is thrown: import time ... r = requests.post(post_url, data=payload, headers=self.header) time.sleep(2) try: output = r.json() except: print('response error: ' + r.status_code) return False package_names = []
has comment: http://stackoverflow.com/comment/87086069
has comment: http://stackoverflow.com/comment/87123098
has comment: http://stackoverflow.com/comment/87122747
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50033061

http://stackoverflow.com/q/49950769
has answer: http://stackoverflow.com/a/49950861
possible better answer: http://stackoverflow.com/a/49951048
has title: Permutations interleaved with special values
has answer: http://stackoverflow.com/a/49951048
tagged with: python
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/49950861
type: AnsweredQuestion
score: 2
answer count: 2
upvote count: 3
has body: I am having a real brain block trying to figure this out. I am trying to write a function that will return all the permutations of a list, interleaved with some number of special values. The function signature: def interleaved_permutations(values, num_special_values) An example: &gt;&gt;&gt; interleaved_permutations([1,2,3,4], 2) [1,x,x,2,3,4] [1,x,2,x,3,4] [1,x,2,3,x,4] [1,2,x,x,3,4] ... An extra requirement is that the special values can not be first or last in the list. I know that there must be a way with some crazy itertools foo, but I have not been able to come up with anything remotely close. the closest I have gotten is just getting the permutations of the input values with itertools.permutations I am hoping somebody more pythonic than me will be able to help!
has comment: http://stackoverflow.com/comment/86918326
has comment: http://stackoverflow.com/comment/86918636
tagged with: permutation
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49980758
score: 2
has title: Python matplotlib fill between
has answer: http://stackoverflow.com/a/49983749
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: Given the four curves in the image below, I am trying to fill everything above the top curve in red. My code below: # Fitting curve IV popt, _ = curve_fit(exponenial_func,xD, divider(yD), p0=(1,1,1), maxfev=10000) expZeroFitC = exponenial_func(x, *popt) plt.plot(x, expZeroFitC, label='Curve IV', color='#000000') alpha=1 plt.fill_between(x, expZeroFit, expZeroFitA, color='#4CFF33', alpha=alpha) plt.fill_between(x, expZeroFitA, expZeroFitB, color='#F7E508', alpha=alpha) plt.fill_between(x, expZeroFitB, expZeroFitC, color='#FFC300', alpha=alpha) d = scipy.zeros(len(expZeroFit)) plt.fill_between(x, expZeroFit, where=expZeroFit&gt;=d, interpolate=True, color='#3ECB1E') d = scipy.zeros(len(expZeroFitC)) plt.fill_between(x, expZeroFitC, where=expZeroFitC&lt;=d, interpolate=True, color='#DA3716') The fill_between call works well to color everything below expZeroFit in green, but seems to fail in coloring everything above expZeroFitC in red. Any advice?
tagged with: python

http://stackoverflow.com/comment/86855973
type: QuestionComment
comment on: http://stackoverflow.com/q/49920154
type: Comment
score: 5
has text: 23% seems suspiciously close to a cpu stuck at 100% in a 4-cpu configuration... are you sure you don't have a crazy loop somewhere in your code ? Could you post a minimal working example reproducing your problem ?

http://stackoverflow.com/a/50053545
accepted answer of: http://stackoverflow.com/q/50053520
score: 1
has comment: http://stackoverflow.com/comment/87123638
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You're very close, but your -2 is on the wrong side of the : You want to access from the last 3 rows, but only up until the last 2 columns: In [52]: data[-3:, :-2] Out[52]: array([[20, 21, 22], [25, 26, 27], [30, 31, 32]]) -2: == Last two columns :-2 == Up until the last two columns If you explicitly want the last 3 rows and the first 3 columns, you could also use: In [53]: data[-3:, :3] Out[53]: array([[20, 21, 22], [25, 26, 27], [30, 31, 32]])
type: Answer
answers question: http://stackoverflow.com/q/50053520
has comment: http://stackoverflow.com/comment/87123669

http://stackoverflow.com/q/50013008
tagged with: list-comprehension
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50013064
answer count: 1
has title: Python multiple list comprehension
type: Question
has answer: http://stackoverflow.com/a/50013064
tagged with: python
has body: def test(): return 1,2 a, b = [test() for _ in range(5)] How do I get a=[1,1,1,1,1] and b=[2,2,2,2,2] using list comprehension?

http://stackoverflow.com/q/50007085
has comment: http://stackoverflow.com/comment/87062454
linked to: http://stackoverflow.com/q/49941426
upvote count: 8
has title: Converting Pytorch model .pth into onnx model
answer count: 3
tagged with: deep-learning
has answer: http://stackoverflow.com/a/70596224
score: 7
has comment: http://stackoverflow.com/comment/87033511
has body: I have one pre-trained model into format of .pth extension. I want to convert that into Tensorflow protobuf. But I am not finding any way to do that. I have seen onnx can convert models from pytorch into onnx and then from onnx to Tensorflow. But with that approach I got following error in the first stage of conversion. from torch.autograd import Variable import torch.onnx import torchvision import torch dummy_input = Variable(torch.randn(1, 3, 256, 256)) model = torch.load('./my_model.pth') torch.onnx.export(model, dummy_input, "moment-in-time.onnx")` It gives error like this. File "t.py", line 9, in &lt;module&gt; torch.onnx.export(model, dummy_input, "moment-in-time.onnx") File "/usr/local/lib/python3.5/dist-packages/torch/onnx/__init__.py", line 75, in export _export(model, args, f, export_params, verbose, training) File "/usr/local/lib/python3.5/dist-packages/torch/onnx/__init__.py", line 108, in _export orig_state_dict_keys = model.state_dict().keys() AttributeError: 'dict' object has no attribute 'state_dict' What is possible solution ?
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87063547
tagged with: pytorch
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57230515
has comment: http://stackoverflow.com/comment/87063935
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51939330

http://stackoverflow.com/comment/86917242
type: Comment
comment on: http://stackoverflow.com/q/49950172
score: 0
type: QuestionComment
has text: I copied your code and input and it worked fine.

http://stackoverflow.com/a/49943684
answers question: http://stackoverflow.com/q/49943543
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You are referencing the same dict twice (parsedData[0] is parsedData[1] evaluates to true). To stop this from happening, just create the dict in the loop: parsedData = [] jsondict=[{u'Name': u'BILL', u'ID': u'1028', u'CARS': [u'BMW', u'AUDI']}, {u'Name ': u'TOM', u'ID': u'1029', u'CARS': [u'TOYOTA', u'FERRARI']}] for distro in jsondict: userData = {} userData['Name'] = distro['Name'] userData['ID'] = distro['ID'] userData['CARS1'] = distro['CARS'][0] userData['CARS2'] = distro['CARS'][1] parsedData.append(userData)
accepted answer of: http://stackoverflow.com/q/49943543
type: Answer

python-2.7
tags question: http://stackoverflow.com/q/49950127
tags question: http://stackoverflow.com/q/50067494
tags question: http://stackoverflow.com/q/49943380
tags question: http://stackoverflow.com/q/50047475
tags question: http://stackoverflow.com/q/50061352
tags question: http://stackoverflow.com/q/49928202
tags question: http://stackoverflow.com/q/49956520
tags question: http://stackoverflow.com/q/49941299
tags question: http://stackoverflow.com/q/50003849
tags question: http://stackoverflow.com/q/50041473
tags question: http://stackoverflow.com/q/50042645
tags question: http://stackoverflow.com/q/50048048
tags question: http://stackoverflow.com/q/50058599
tags question: http://stackoverflow.com/q/49960195
tags question: http://stackoverflow.com/q/50020885
tags question: http://stackoverflow.com/q/50068604
tags question: http://stackoverflow.com/q/49943847
tags question: http://stackoverflow.com/q/50035874
tags question: http://stackoverflow.com/q/49950554
tags question: http://stackoverflow.com/q/50065138
tags question: http://stackoverflow.com/q/49993080
tags question: http://stackoverflow.com/q/50073293
tags question: http://stackoverflow.com/q/49985447
tags question: http://stackoverflow.com/q/49955430
tags question: http://stackoverflow.com/q/50055307
tags question: http://stackoverflow.com/q/50028413
tags question: http://stackoverflow.com/q/49936714
tags question: http://stackoverflow.com/q/49923934
tags question: http://stackoverflow.com/q/50033692
tags question: http://stackoverflow.com/q/49999474
tags question: http://stackoverflow.com/q/50010858
tags question: http://stackoverflow.com/q/49964779
tags question: http://stackoverflow.com/q/50012528
tags question: http://stackoverflow.com/q/50017003
tags question: http://stackoverflow.com/q/49998198
tags question: http://stackoverflow.com/q/49919371
tags question: http://stackoverflow.com/q/49972705
tags question: http://stackoverflow.com/q/50063930
tags question: http://stackoverflow.com/q/49917743
tags question: http://stackoverflow.com/q/49998584
tags question: http://stackoverflow.com/q/50071126
tags question: http://stackoverflow.com/q/50041459
tags question: http://stackoverflow.com/q/50035087
tags question: http://stackoverflow.com/q/49994727
type: Tag
tags question: http://stackoverflow.com/q/49938137
tags question: http://stackoverflow.com/q/50004142
tags question: http://stackoverflow.com/q/50071280
tags question: http://stackoverflow.com/q/49982064
tags question: http://stackoverflow.com/q/49933598
tags question: http://stackoverflow.com/q/49985035
tags question: http://stackoverflow.com/q/50071618
tags question: http://stackoverflow.com/q/50003760
tags question: http://stackoverflow.com/q/50010268
tags question: http://stackoverflow.com/q/50065913
tags question: http://stackoverflow.com/q/50053747
tags question: http://stackoverflow.com/q/49971958
tags question: http://stackoverflow.com/q/49998268
tags question: http://stackoverflow.com/q/50025236
tags question: http://stackoverflow.com/q/49988928
tags question: http://stackoverflow.com/q/49947946
tags question: http://stackoverflow.com/q/50072603
tags question: http://stackoverflow.com/q/49943662
tags question: http://stackoverflow.com/q/49974542
tags question: http://stackoverflow.com/q/50011031
tags question: http://stackoverflow.com/q/50067472
tags question: http://stackoverflow.com/q/50061087
tags question: http://stackoverflow.com/q/49959994
tags question: http://stackoverflow.com/q/50051163
tags question: http://stackoverflow.com/q/50017886
tags question: http://stackoverflow.com/q/49923899
tags question: http://stackoverflow.com/q/50032126
tags question: http://stackoverflow.com/q/49989288
tags question: http://stackoverflow.com/q/49931186
tags question: http://stackoverflow.com/q/50048844
tags question: http://stackoverflow.com/q/50051606
tags question: http://stackoverflow.com/q/49945999
tags question: http://stackoverflow.com/q/50005404
tags question: http://stackoverflow.com/q/50052606
tags question: http://stackoverflow.com/q/50066747

http://stackoverflow.com/q/49983951
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86986901
has comment: http://stackoverflow.com/comment/87030553
answer count: 1
has comment: http://stackoverflow.com/comment/86984506
has comment: http://stackoverflow.com/comment/86984534
type: Question
has comment: http://stackoverflow.com/comment/86993395
score: 0
has comment: http://stackoverflow.com/comment/86987057
tagged with: file-io
has title: gzip multiple files in python
has answer: http://stackoverflow.com/a/75143850
tagged with: gzip
tagged with: python
has comment: http://stackoverflow.com/comment/86985598
has body: I have to compress a lot of XML files into and split them by the data in the file name, just for clarification's sake, there is a parser which collects information from XML file and then moves it to a backup folder. My code needs to gzip it according to the date in the filename and group those files in a compressed .gz file. Please find the code bellow: import os import re import gzip import shutil import sys import time # timestr = time.strftime("%Y%m%d%H%M") logfile = 'D:\\Coleta\\log_compactador_xml_tar'+timestr+'.log' ptm_dir = "D:\\PTM\\monitored_programs\\" count_files_mdc = 0 count_files_3gpp = 0 count_tar = 0 # for subdir, dir, files in os.walk(ptm_dir): for file in files: path = os.path.join(subdir, file) try: backup_files_dir = path.split(sep='\\')[4] parser_id = path.split(sep='\\')[3] if re.match('backup_files_*', backup_files_dir): if file.endswith('xml'): # print(time.strftime("%Y-%m-%d %H:%M:%S"), path) data_arq = file[1:14] if parser_id in ('parser-924'): gzip_filename_mdc = os.path.join(subdir,'E4G_PM_MDC_IP51_'+timestr+'_'+data_arq) with open(path, 'r')as f_in, gzip.open(gzip_filename_mdc + ".gz", 'at') as f_out_mdc: shutil.copyfileobj(f_in, f_out_mdc) count_files_mdc += 1 f_out_mdc.close() f_in.close() print(time.strftime("%Y-%m-%d %H:%M:%S"), "Compressing file MDC: ",path) os.remove(path) except PermissionError: print(time.strftime("%Y-%m-%d %H:%M:%S"), "Permission error on file:", fullpath, file=logfile) pass except IndexError: print(time.strftime("%Y-%m-%d %H:%M:%S"), "IndexError: ", path, file=logfile) pass As long as I seem it creates a stream of data, then compress and write it to a new file with the specified filename. However, instead of grouping each XML file independently inside a ".gz" file, it does creates inside the "gzip" file, a big file (big stream of data?) with the same name of the output "gzip" file, but without any extension. After the files are totally compressed, it's not possible to uncompress the big file generated inside t…

http://stackoverflow.com/a/49935670
type: Answer
has comment: http://stackoverflow.com/comment/86886953
accepted answer of: http://stackoverflow.com/q/49935601
has comment: http://stackoverflow.com/comment/86886998
has body: You can use argument list unpacking to pass the values of a list as arguments to a function like so: values_list(*fieldlist)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86887204
answers question: http://stackoverflow.com/q/49935601
score: 8
upvote count: 8
downvote count: 0

http://stackoverflow.com/q/50017784
possible better answer: http://stackoverflow.com/a/50018849
has comment: http://stackoverflow.com/comment/87052205
type: Question
has comment: http://stackoverflow.com/comment/87051836
has answer: http://stackoverflow.com/a/50018109
has comment: http://stackoverflow.com/comment/87053495
has comment: http://stackoverflow.com/comment/87051797
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87051770
has answer: http://stackoverflow.com/a/50018849
has comment: http://stackoverflow.com/comment/87051869
upvote count: 1
tagged with: mathematical-expressions
downvote count: 1
has body: I'm trying to develop a simple python method that will allow me to compute basic mathematical operations. The point here is that I can't use eval(), exec() or any other functions that evaluate python statemets, so I have to do it manually. Up to now, I've came across with this piece of code: solutionlist = list(basicoperationslist) for i in range(0, len(solutionlist)): if '+' in solutionlist[i]: y = solutionlist[i].split('+') solutionlist[i] = str(int(y[0]) + int(y[1])) elif '*' in solutionlist[i]: y = solutionlist[i].split('*') solutionlist[i] = str(int(y[0]) * int(y[1])) elif '/' in solutionlist[i]: y = solutionlist[i].split('/') solutionlist[i] = str(int(y[0]) // int(y[1])) elif '-' in solutionlist[i]: y = solutionlist[i].split('-') solutionlist[i] = str(int(y[0]) - int(y[1])) print("The solutions are: " + ', '.join(solutionlist)) So we have two lists of Strings, the basicoperationlist has operations of the following format: 2940-81, 101-16, 46/3, 10*9, 145/24, -34-40. They will always have two numbers, and one operand in the middle. The problem with my solution is that when I have an operation like the last one, the .split() method splits my list into an empty list and a list with the complete operation. In summary, this solution does not work well when we mix negative numbers an the minus operation. I don't know if it fails in any other case because I've only managed to notice the error I previously described. The idea is that at the end of the method, I have the solutionlist as a list of Strings that are going to be the ordered answers to the basic mathematical operations. This is the error that prompts out whenever my code encounters an operation like the last one: ValueError: invalid literal for int() with base 10: '' The basicoperationslist is defined here: basicoperationslist = re.findall('[-]*\d+[+/*-]+\d+', step2processedoperation) As you see, I use a regex to extract the basicoperations from a larger operation. The step2processedoperation is an String t…
has comment: http://stackoverflow.com/comment/87051856
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87052363
has title: Solve basic mathematical operations in python 3
tagged with: solver
has comment: http://stackoverflow.com/comment/87051951
tagged with: python
has comment: http://stackoverflow.com/comment/87052123
accepted answer: http://stackoverflow.com/a/50018109

http://stackoverflow.com/comment/116006677
type: Comment
has text: but beeware does not support image and other widgets
type: AnswerComment
comment on: http://stackoverflow.com/a/50595676
score: 0

http://stackoverflow.com/a/50034701
has comment: http://stackoverflow.com/comment/87118816
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87126786
score: 1
type: AcceptedAnswer
has body: There are multiple issues in your code below: def general_info(c_name): for key, val in countries[c_name].items(): # overwrites info in every iteration # you are saving return value of print function info = print(c_name.title() + " " + key + " is " + val) return info # return only last iteration "info" def specific_info(c_name, info): if c_name in countries and info in countries[c_name].keys(): # you can simply write info in countries[c_name]. No need of ".keys()" method return (info.title() + " from " + c_name.title() + " is " + countries[c_name][info]) To return general info you should do as follows: def general_info(c_name): general_info = [] for key, val in countries[c_name].items(): info = (c_name.title() + " " + key + " is " + val) general_info.append(info ) return general_info Also to format strings, you should try format function. I would re-write info as: info = "{country}: {key} is {val}".format(country=c_name.title(), key=key, val=val) This makes you code more readable and easy to write as well.
accepted answer of: http://stackoverflow.com/q/50034420
type: Answer
answers question: http://stackoverflow.com/q/50034420

http://stackoverflow.com/comment/86890524
score: 0
type: Comment
type: AnswerComment
has text: Well then you could read the file and write it into e.g. a suitable csv format and use `LOAD DATA INFILE` using mysql tools directly.
comment on: http://stackoverflow.com/a/49937272

heroku
tags question: http://stackoverflow.com/q/50003486
tags question: http://stackoverflow.com/q/49950347
tags question: http://stackoverflow.com/q/50059102
type: Tag
tags question: http://stackoverflow.com/q/49986166
tags question: http://stackoverflow.com/q/50014616
tags question: http://stackoverflow.com/q/49953699
tags question: http://stackoverflow.com/q/50026190
tags question: http://stackoverflow.com/q/50072357
tags question: http://stackoverflow.com/q/49982298
tags question: http://stackoverflow.com/q/50063975
tags question: http://stackoverflow.com/q/50023430
tag name: heroku

http://stackoverflow.com/comment/87087759
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters)
comment on: http://stackoverflow.com/q/50035642

http://stackoverflow.com/q/49989537
has answer: http://stackoverflow.com/a/49989642
has title: Python Pandas conditional flagging
has body: Working with python pandas dataframe df: product_id |transaction_id | category | color 234 54 A black 349 54 B silver 213 46 A silver 490 46 A black 245 87 A black 249 87 B black 294 87 A silver I want to flag transaction_IDs that have category of A and B with the same color. So in the scenario above transaction 87 has a product A black and a product B black. Desired output: product_id |transaction_id | category | color | flag 234 54 A black 349 54 B silver 213 46 A silver 490 46 A black 245 87 A black X 249 87 B black X 294 87 A silver X I was trying to create a unique key between category and color and then groupby, but it got messy and I still have to go manually through it. There must be a simpler way. df['key']=df['category']&amp;df['color'] df['transaction_analysis']= df.groupby('transaction_id').key.transform(lambda x : '&amp;'.join(set(x)))
type: AnsweredQuestion
tagged with: conditional-statements
answer count: 2
tagged with: pandas
score: 1
possible better answer: http://stackoverflow.com/a/49989987
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49989987
favorite count: 0
type: Question
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/49989642
tagged with: python

http://stackoverflow.com/q/50063093
has body: Basically, I'm reading the documentation https://hmmlearn.readthedocs.io/en/latest/api.html#hmmlearn.base._BaseHMM, and trying to use the _BaseHMM class. But being new to Python, I'm having lot of trouble. Somewhat more generally, I'm trying to verify that an HMM can learn from sequential data and give us more accurate prediction. Toward this direction, I'm considering the case where the algorithm determines the classes of 6 images into 3 classes, and I consider the sample to be ordered or sequenced. Suppose I define the parameters for this HMM. What I'd like to see is the output and the accuracy of this HMM with custom made emission probabilities.See the code below, I'm sure I made a basic mistake, but a sample code would be great! import numpy as np from hmmlearn import hmm #confusion matrix from sklearn.metrics import confusion_matrix y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] C_old= confusion_matrix(y_true, y_pred, labels=["cat", "ant", "bird"]) model = hmm.GaussianHMM(n_components=3, covariance_type="full") model.startprob_ = np.array([0.333, 0.333, 0.333]) model.transmat_ = np.array([[0.5, 0.5, 0], [0.5, 0, 0.5], [0, 1, 0]]) X=y_true from hmmlearn import _BaseHMM hmm._base._BaseHMM._init(X,len(X)) I'm getting: ImportError: cannot import name _BaseHMM Note that, I defined the emission probability. Now since my emission probabilities are custom-made, it seems I've to use the class _BaseHMM. This is where I'm stuck, and I'd really appreciate a sample code using this class and the final confusion matrix after using the HMM. Am using Python 2.7.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87533106
has comment: http://stackoverflow.com/comment/87145862
tagged with: machine-learning
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/87142964
has comment: http://stackoverflow.com/comment/87145154
has title: Can you give me an example of how to train in Python an HMM with customized emission probabilities?
answer count: 0
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/87146006
downvote count: 1
favorite count: 0
type: Question
tagged with: hidden-markov-models

http://stackoverflow.com/q/50061352
tagged with: python
tagged with: python-2.7
has title: Getting a traceback while inheriting from imported files
score: 1
has answer: http://stackoverflow.com/a/50061452
answer count: 1
downvote count: 0
tagged with: multiple-inheritance
upvote count: 1
has body: @first.py class first(): def fun1(): print 'first one' @second.py class second(): def fun2(): print 'second one' @third.py import first import second class third (first, second): def fun3(): f= first() s= second() f.fun1() s.fun2() print 'third one' on running the third.py, i'm getting a traceback Traceback (most recent call last): File "C:\Python27\third.py", line 4, in &lt;module&gt; class third (first, second): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given)
has comment: http://stackoverflow.com/comment/87139021
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87139201

http://stackoverflow.com/q/50064785
score: 0
possible better answer: http://stackoverflow.com/a/50065073
linked to: http://stackoverflow.com/q/24342047
answer count: 3
linked to: http://stackoverflow.com/q/22214086
has answer: http://stackoverflow.com/a/50065130
has answer: http://stackoverflow.com/a/50065073
has title: Get the minimum successive value count, if any
downvote count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50065003
has body: I have a list, e.g. [True, True, True, True, False, False, True, False, True, True, False] and I want to know the minimal count that True is successive, hence 1 in this case. Or in in the following list it is 2, [True, True, False, True, True, False, False, False, False, True, True, True] Thanks for the help!
has comment: http://stackoverflow.com/comment/88753825
type: Question
has answer: http://stackoverflow.com/a/50065003
linked to: http://stackoverflow.com/q/34443946
has comment: http://stackoverflow.com/comment/87146349
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/34443946
duplicate of: http://stackoverflow.com/q/24342047
type: AnsweredQuestion

http://stackoverflow.com/a/49982904
has body: The built-in csv module provides this functionality: import csv with open('data.dat', 'r') as csvfile: reader = csv.reader(csvfile, delimiter=' ') first_column = [ row[0] for row in reader ] This code extracts the first column into a list as requested.
answers question: http://stackoverflow.com/q/49982672
score: 0
type: Answer

http://stackoverflow.com/comment/86962891
has text: In your case, the element is getting visible but not able to click. So, you have to wait until that element is not getting clickable. `wait.until(EC.element_to_be_clickable((By.XPATH, 'xpath_of_element')))`. and then click the element.
score: 0
comment on: http://stackoverflow.com/q/49972306
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49931402
has body: I have this code: class mrp_worksheet_contract(models.Model): _inherit = 'mrp.worksheet.contract' _name = 'mrp.worksheet.contract' start_date = fields.Date('From') end_date = fields.Date('To') @api.multi def generate_report(self): data = {'start_date': self.start_date, 'date_stop': self.end_date,} report_name = 'bsi.report_contract_worksheet' return self.env['report'].get_pdf(self, report_name, data=data) My module is called bsi, the report_contract_worksheet is this one: <?xml version="1.0" encoding="utf-8"?> <t t-call="report.html_container"> <t t-set="data_report_margin_top" t-value="12"/> <t t-set="data_report_header_spacing" t-value="9"/> <t t-set="data_report_dpi" t-value="110"/> <t t-foreach="docs" t-as="o"> <t t-call="report.internal_layout"> : COntract Worksheet Order No.: Date: Language: Title/Description: I.S.B.N.: Specification/Description: </t> </t> </t> On my view, I call the generate_report function like this: Contract Worksheet Report mrp.worksheet.contract <separator string="Contract Worksheet "/> <newline/> or Contract Worksheet Report mrp.worksheet.contract ir.actions.act_window form tree,form {} new <menuitem icon="STOCK_PRINT" name="Contract Worksheet" action="action_report_contract_worksheet_view" id="menu_general_prod_child_1" parent="menu_general_prod_1" /> It doesn't print anything, and also, it creates a new mrp.contract.worksheet everytime I click on the generate_report button. Any ideas?
tagged with: odoo
has comment: http://stackoverflow.com/comment/86878831
tagged with: python
has comment: http://stackoverflow.com/comment/86881695
has comment: http://stackoverflow.com/comment/86893159
answer count: 0
score: 0
has title: Report not printing from wizard - Odoo v8
type: UnansweredQuestion
type: Question

ogr
tags question: http://stackoverflow.com/q/49983853
tag name: ogr
type: Tag

http://stackoverflow.com/q/49953407
score: 0
tagged with: metadata
answer count: 0
tagged with: pypdf
tagged with: http://stackoverflow.com/tag/pdf
type: Question
has title: Python: How to set BaseUrl in pdf metadata?
has body: I would like to add metadata to PDF in python. I have used PyPDF2 and it works fine with metadata (tags) except of "BaseUrl" Code: dict_1['/BaseUrl'] = 'http://bud-arch.pollub.pl/wp-content/uploads/Bud-arch_171_2018_005-012_Boruci%C5%84ska%E2%80%93Bie%C5%84kowska_Maciejko.pdf' writer = PyPDF2.PdfFileWriter() writer.addMetadata(dict_1) The result is metadata "BaseUrl" in the section for creator free tags. not in section "advanced". How to solve this issue? Łukasz (source: pokazywarka.pl)
has comment: http://stackoverflow.com/comment/86924050
has comment: http://stackoverflow.com/comment/86923329
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86924003
tagged with: python

http://stackoverflow.com/q/50031264
duplicate of: http://stackoverflow.com/q/2612610
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50031300
has answer: http://stackoverflow.com/a/50031297
answer count: 3
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/87078659
downvote count: 1
has body: I would like to be able to select the class' property by it's name. This is my code: class example(object): def __init__(self): self.one = "1" self.two = "2" x = example() list = ["one", "two"] # I want to get x.one here by referring to it by list[0] How can I do this? Worked example: class example(object): def __init__(self): self.one = "one" self.two = "two" def test(self): list = ["one", "two"] print(getattr(self, list[1])) x = example() x.test()
favorite count: 0
linked to: http://stackoverflow.com/q/3061
type: Question
possible better answer: http://stackoverflow.com/a/50031297
has title: How to call a Python class instance from a list?
linked to: http://stackoverflow.com/q/2612610
accepted answer: http://stackoverflow.com/a/50031299
has comment: http://stackoverflow.com/comment/87078629
has comment: http://stackoverflow.com/comment/87078695
tagged with: python
has answer: http://stackoverflow.com/a/50031299

filesplitting
type: Tag
tag name: filesplitting
tags question: http://stackoverflow.com/q/49963492

http://stackoverflow.com/comment/115183393
has text: @phd thats correct, haven't seen the links destination. Anyhow I m currently in the process of integrating sage into Windows to use it in python scripts. But I am still struggling with that..
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50048379
score: 1

http://stackoverflow.com/q/49982459
tagged with: python
has comment: http://stackoverflow.com/comment/86981201
tagged with: shell
linked to: http://stackoverflow.com/q/2225564
type: Question
has answer: http://stackoverflow.com/a/49982989
upvote count: 2
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: sh
has comment: http://stackoverflow.com/comment/86981347
favorite count: 0
score: 0
has title: How to convert shell script into python script?
tagged with: http://stackoverflow.com/tag/json
has body: I have a lengthy shell script, where I am trying to convert into a python script but I am struck in a line. cat $projects_list | while read line do list=`find . -name "*.json" -exec grep -l "project_name.*\"$line\"" {} \; | grep -vw project` Wat actually I need is Parse all the folders expect "project" from current folder and get the files with .json extension. Parse each json file and search for the value whose key is "project_name" Store the the json file path whose value is found in the json file Project_list contains a list of values which is to be matched with the key 'project name' And below is the json format { "artifactory_space_MiB": 1, "enovia": { "name": "", "product": "", "release": "", "release_notes_url": "http://example.com/ld+Release" }, "goldmine": { "build_type_list": [ "product", "prodspec" ] }, "goldmine_monitor_flag": false, "image_list": [ { "image": "framework-image", "machine": "qemux86-64", "name": "qemu" } ], "item_status": "inactive", "jira": { "key": "cdtest", "version": "1.0" }, "product_name": "cdtest", "product_release": "1.0", "project_name": "cdtest-1.0", "testlink": { "proj_name": "__TESTLINK_PROJ_NAME__" }, "warios_repo_list": [], "zone_tracking": { "inactivation": { "deletion_time": "2018-02-16_1516", "inactivation_time": "2018-02-16_1516" }, "previous_values": { "artifactory_space_MiB": 1 } } } I have tried below code using python.. with open(projects_list, 'r') as f: for line in f: # Ignore "project" files... only interested in downstream product files. json_list = subprocess.check_output(["find . -name '*.json' " , "-exec grep -l 'project_name.*\"" + line + "\"' {} \; " , "| grep -vw project"], shell=True)

http://stackoverflow.com/q/50054419
has comment: http://stackoverflow.com/comment/87125464
tagged with: python
has answer: http://stackoverflow.com/a/50055502
has answer: http://stackoverflow.com/a/67001091
has answer: http://stackoverflow.com/a/50067576
has comment: http://stackoverflow.com/comment/87131479
type: AnsweredQuestion
tagged with: keras-layer
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/50067123
accepted answer: http://stackoverflow.com/a/50067123
upvote count: 7
score: 7
has title: Extremely poor prediction: LSTM time-series
has comment: http://stackoverflow.com/comment/136809997
possible better answer: http://stackoverflow.com/a/50055502
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has body: I tried to implement LSTM model for time-series prediction. Below is my trial code. This code runs without error. You can also try it without dependency. import numpy as np, pandas as pd, matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import LSTM, Dense, TimeDistributed, Bidirectional from sklearn.metrics import mean_squared_error, accuracy_score from scipy.stats import linregress from sklearn.utils import shuffle fi = 'pollution.csv' raw = pd.read_csv(fi, delimiter=',') raw = raw.drop('Dates', axis=1) print (raw.shape) scaler = MinMaxScaler(feature_range=(-1, 1)) raw = scaler.fit_transform(raw) time_steps = 7 def create_ds(data, t_steps): data = pd.DataFrame(data) data_s = data.copy() for i in range(time_steps): data = pd.concat([data, data_s.shift(-(i+1))], axis = 1) data.dropna(axis=0, inplace=True) return data.values ds = create_ds(raw, time_steps) print (ds.shape) n_feats = raw.shape[1] n_obs = time_steps * n_feats n_rows = ds.shape[0] train_size = int(n_rows * 0.8) train_data = ds[:train_size, :] train_data = shuffle(train_data) test_data = ds[train_size:, :] x_train = train_data[:, :n_obs] y_train = train_data[:, n_obs:] x_test = test_data[:, :n_obs] y_test = test_data[:, n_obs:] x_train = x_train.reshape(1, x_train.shape[0], x_train.shape[1]) y_train = y_train.reshape(1, y_train.shape[0], y_train.shape[1]) x_test = x_test.reshape(1, x_test.shape[0], x_test.shape[1]) print (x_train.shape) print (y_train.shape) print (x_test.shape) print (y_test.shape) model = Sequential() model.add(LSTM(64, return_sequences=True, input_shape=(None, x_train.shape[2]), stateful=True, batch_size=1)) model.add(LSTM(32, return_sequences=True, stateful=True)) model.add(LSTM(n_feats, return_sequences=True, stateful=True)) model.compile(loss='mse', optimizer='rmsprop') model.fit(x_train, y_train, epochs=10, batch_size=1, verbose=2) y_predict = model.predict(x_test) y_predict = y_predict.reshape(y_predict.s…
has answer: http://stackoverflow.com/a/56431733
answer count: 5

http://stackoverflow.com/comment/87070758
type: Comment
type: AnswerComment
has text: Have you added the dt and time variables? What is the error message, you are being extremely hard to work with.
comment on: http://stackoverflow.com/a/50022745
score: 0

doctest
type: Tag
tag name: doctest
tags question: http://stackoverflow.com/q/49922547

http://stackoverflow.com/comment/87060042
type: QuestionComment
comment on: http://stackoverflow.com/q/50021228
has text: You're file Consist of Non-Text format, pdf file generate with may be images. so while reading pypdf2 showing empty list. add what you're tried to code, resolve those problem
score: 0
type: Comment

http://stackoverflow.com/q/50050383
answer count: 1
linked to: http://stackoverflow.com/q/23268277
type: Question
tagged with: numpy
has body: x = numpy.arange(0.0, 5, 1) y = numpy.array([np.nan,2,3,4,5]) plt.plot(x,y) I am trying to plot, but the graph always starts with 1 instead of 0. Can I force it to start with 0 ?
accepted answer: http://stackoverflow.com/a/50050553
has answer: http://stackoverflow.com/a/50050553
tagged with: python
has comment: http://stackoverflow.com/comment/87119937
type: AnsweredQuestion
score: 0
has title: plotting with nan in samples with numpy

http://stackoverflow.com/a/50025647
upvote count: 19
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50025280
score: 19
accepted answer of: http://stackoverflow.com/q/50025280
type: Answer
has body: RGB image is composed of three grayscale images. You can make three grayscale images like rgb = np.random.randint(255, size=(900,800,3),dtype=np.uint8) cv2.imshow('RGB',rgb) cv2.waitKey(0)

http://stackoverflow.com/comment/86964244
type: AnswerComment
has text: Python.. sqlalchemy..?
comment on: http://stackoverflow.com/a/49974123
type: Comment
score: 2

http://stackoverflow.com/q/49943360
has comment: http://stackoverflow.com/comment/86910068
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49955508
upvote count: 2
has answer: http://stackoverflow.com/a/49955508
has comment: http://stackoverflow.com/comment/86904646
answer count: 1
downvote count: 0
has title: Grouping points by distance
has body: What I am trying to do is group locations that all meet a minimum distance apart from one another and exclude those that don't meet that distance. Additionally, I am trying to get a group of 10. An example, say I have 4 sets of coordinates for A, B, C, and D. I am trying to group them such that they are at least 1 mile apart from one another. The first point in the list, A, will be the starting point. B is 1.5 miles from A: Include in list C is 2 miles from B and is 2.2 miles from A: Include in list D is 0.5 miles from C, 0.8 miles from B, and 1.1 miles from A: Don't include So A, B, and C would be grouped together. I have that working, but I run into an issue where I can't get a group of 10 points because of the possibility that one point can prevent a handful of other points from meeting the criteria. How should I go forward to achieve my end goal? Thanks! import csv from geopy import distance flag = 0 LocationIDs = [] Latitudes = [] Longitudes = [] with open('data.csv') as data: dataRead = csv.reader(data) for row in dataRead: LocationIDs.append(row[0]) Latitudes.append(row[1]) Longitudes.append(row[2]) group = [LocationIDs[0]] groupLat = [Latitudes[0]] groupLong = [Longitudes[0]] LocationIDs.remove(LocationIDs[0]) Latitudes.remove(Latitudes[0]) Longitudes.remove(Longitudes[0]) for x in range(len(LocationIDs)): flag = 0 for y in range(len(group)): currGroupLoc = (groupLat[y], groupLong[y]) dist = distance.distance(currGroupLoc, (Latitudes[x], Longitudes[x])).miles print("Testing Location " + str(LocationIDs[x]) + " against " + str(group[y])) print(dist) if dist &lt; 15: flag = 1 if flag == 0 and dist &lt; 18: print("Adding " + str(LocationIDs[x])) group.append(LocationIDs[x]) groupLat.append(Latitudes[x]) groupLong.append(Longitudes[x]) LocationIDs.remove(LocationIDs[x]) Latitudes.remove(Latitudes[x]) Longitudes.remove(Longitudes[x])
favorite count: 0
type: Question

list
tags question: http://stackoverflow.com/q/50047773
tags question: http://stackoverflow.com/q/49935866
tags question: http://stackoverflow.com/q/49928553
type: Tag
tags question: http://stackoverflow.com/q/49987100
tags question: http://stackoverflow.com/q/49978600
tags question: http://stackoverflow.com/q/50018265
tags question: http://stackoverflow.com/q/49943206
tags question: http://stackoverflow.com/q/50026206
tags question: http://stackoverflow.com/q/49983239
tags question: http://stackoverflow.com/q/49959648
tags question: http://stackoverflow.com/q/49998436
tags question: http://stackoverflow.com/q/50022220
tags question: http://stackoverflow.com/q/49953791
tags question: http://stackoverflow.com/q/49932098
tags question: http://stackoverflow.com/q/50066830
tags question: http://stackoverflow.com/q/50021296
tags question: http://stackoverflow.com/q/49945806
tags question: http://stackoverflow.com/q/49949814
tags question: http://stackoverflow.com/q/50005229
tags question: http://stackoverflow.com/q/50074564
tags question: http://stackoverflow.com/q/49972651
tags question: http://stackoverflow.com/q/49992458
tags question: http://stackoverflow.com/q/49986865
tags question: http://stackoverflow.com/q/50011031
tags question: http://stackoverflow.com/q/50063358
tags question: http://stackoverflow.com/q/49975482
tags question: http://stackoverflow.com/q/50067472
tags question: http://stackoverflow.com/q/50046983
tags question: http://stackoverflow.com/q/49959038
tags question: http://stackoverflow.com/q/50063717
tags question: http://stackoverflow.com/q/50030460
tags question: http://stackoverflow.com/q/50026534
tags question: http://stackoverflow.com/q/49998740
tags question: http://stackoverflow.com/q/49960345
tags question: http://stackoverflow.com/q/50039242
tags question: http://stackoverflow.com/q/50007762
tags question: http://stackoverflow.com/q/49976576
tags question: http://stackoverflow.com/q/50036882
tags question: http://stackoverflow.com/q/50054775
tags question: http://stackoverflow.com/q/50029537
tags question: http://stackoverflow.com/q/49959442
tags question: http://stackoverflow.com/q/50005148
tags question: http://stackoverflow.com/q/49918545
tags question: http://stackoverflow.com/q/50044281
tags question: http://stackoverflow.com/q/49991280
tags question: http://stackoverflow.com/q/49965507
tags question: http://stackoverflow.com/q/50035326
tags question: http://stackoverflow.com/q/49972313
tags question: http://stackoverflow.com/q/50001509
tags question: http://stackoverflow.com/q/50027034
tags question: http://stackoverflow.com/q/49963044
tags question: http://stackoverflow.com/q/49984224
tags question: http://stackoverflow.com/q/50027104
tags question: http://stackoverflow.com/q/49980809
tags question: http://stackoverflow.com/q/49949960
tags question: http://stackoverflow.com/q/49932964
tags question: http://stackoverflow.com/q/49987789
tags question: http://stackoverflow.com/q/49948987
tags question: http://stackoverflow.com/q/50006951
tags question: http://stackoverflow.com/q/50009266
tags question: http://stackoverflow.com/q/50006255
tags question: http://stackoverflow.com/q/50070397
tags question: http://stackoverflow.com/q/50013845
tags question: http://stackoverflow.com/q/49935141
tags question: http://stackoverflow.com/q/49959177
tags question: http://stackoverflow.com/q/50070041
tags question: http://stackoverflow.com/q/50069340
tags question: http://stackoverflow.com/q/49990473
tags question: http://stackoverflow.com/q/49969862
tags question: http://stackoverflow.com/q/49947163
tags question: http://stackoverflow.com/q/49988110
tags question: http://stackoverflow.com/q/50049786
tags question: http://stackoverflow.com/q/50074446
tags question: http://stackoverflow.com/q/49951041
tags question: http://stackoverflow.com/q/49987869
tags question: http://stackoverflow.com/q/49956943
tags question: http://stackoverflow.com/q/50055307
tags question: http://stackoverflow.com/q/49991429
tags question: http://stackoverflow.com/q/50006424

http://stackoverflow.com/q/50068528
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/15026698
accepted answer: http://stackoverflow.com/a/50068588
has title: pandas read .csv file without suitable delimiter. (only seperate first column vs "rest")
has body: I try importing a .csv file into python pandas as the following: dataframe = pd.read_csv(inputfile, sep=delimiter, header=None) However, each line of the (huge) inputfile consists of an integer, followed by some string. Like this: 1234 this string % might; contain 눈 anything The result should be a two column dataframe which has said Integer on position 1 and the rest of the line in position 2. Since any character can occur in the string I am unable to use a single character as a separator. Trying to use a highly unlikely long string sequence like "khlKiwVlZdsb9oVKq5yG" as a delimiter for one feels like a dirty workaround, secondly may not be 100% reliable and thirdly causes the following "error/inconvenience": ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'. So my question is: Is there any better way to deal with my Problem? Maybe some option to tell pandas to ignore any further delimiters after the first in a line has been encountered? Thank you for any suggestions!
tagged with: python
tagged with: delimiter
has comment: http://stackoverflow.com/comment/87153498
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50068588
downvote count: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/86956026
score: 0
comment on: http://stackoverflow.com/q/49969871
type: Comment
has text: Which python version? There was a change 3.5 ish to stop using unicode on Windows. https://bugs.python.org/issue26227. This is in the C socket implementation so a `socket.py` hack is not enough.
type: QuestionComment

http://stackoverflow.com/a/50074953
score: 0
has body: The logical error is that you're confusing "the index where the run starts" with "the length of the (last) run". You need a variable like max_run_start_index. Look at the code: if rollValue == run_count: print("(", exampleList[rollValue], end = " ") Read it back to yourself 'if the index of the next output is equal to the length of the last run, output open bracket before it'. So if the length of the last run is 3 the longest run starts at index 3? Surely not... I'm not a Python coder, so you'll need to fix it yourself...
type: Answer
answers question: http://stackoverflow.com/q/50072670

http://stackoverflow.com/comment/86906120
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49944574
has text: @COLDSPEED I changed the order of the data inputs and it still worked!, I added the updated version, can you explain further why this won't work?
type: Comment

pypi
tags question: http://stackoverflow.com/q/50033903
tags question: http://stackoverflow.com/q/49966325
tags question: http://stackoverflow.com/q/49929675
tags question: http://stackoverflow.com/q/50017785
tags question: http://stackoverflow.com/q/50049505
tags question: http://stackoverflow.com/q/50035420
type: Tag
tag name: pypi
tags question: http://stackoverflow.com/q/49968266

http://stackoverflow.com/q/50062201
tagged with: matplotlib
has title: Boxplot in pandas with confidence intervals and bootstrap returns exception - Reproducible example with iris dataset
tagged with: boxplot
has answer: http://stackoverflow.com/a/50067258
tagged with: python
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50067258
has comment: http://stackoverflow.com/comment/87142366
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87143550
answer count: 1
favorite count: 0
has body: I tried to plot a boxplot with confidence intervals but I got an exception. from sklearn import datasets iris = datasets.load_iris() iris = iris.data iris = pd.DataFrame(iris) iris.columns = ['a', 'b', 'c', 'd'] iris.boxplot(column='a', figsize=(15,20), showmeans = True, patch_artist = True, conf_intervals = True, bootstrap = 100) plt.show() IndexError: tuple index out of range How can I resolve this error?
type: Question

http://stackoverflow.com/comment/86894464
has text: Sorry I didn't check properly. It indeed works very well. It's applying the categories (ones you provided in last line) on df1's column values alphabetically, right?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49939040
type: AnswerComment

http://stackoverflow.com/comment/87072677
has text: Thanks for your solution! altough i already found a workaround for my problem, this might be useful for the future when i need more decimal cases :)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50004508

http://stackoverflow.com/a/50056332
has body: import pandas as pd n = {"year":[], "month":[], "day":[]} for i in df['reg_date']: n["year"].append(i.split("T")[0].split("-")[0]) n["month"].append(i.split("T")[0].split("-")[1]) n["day"].append(i.split("T")[0].split("-")[2]) #Now 'n' is the dictionary contains separated day, month and year from df["reg_date"].. Another approach df["reg_date"] = df["reg_date"].apply(lambda x: x.split("T")[0]) #Here df["reg_date"] converts to column containing date for each records
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50055085

http://stackoverflow.com/a/49960813
has body: You are referencing the local variables fname, lname, and idNo that you last set in the while loop. The variables that you want are stored separately in each instance of the Student class. Try this for loop instead: for item in studentList: print item.fname, item.lname, item.idNo
accepted answer of: http://stackoverflow.com/q/49960790
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86939534
has comment: http://stackoverflow.com/comment/86940811
type: Answer
answers question: http://stackoverflow.com/q/49960790
score: 2

http://stackoverflow.com/a/50008460
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49991731
answers question: http://stackoverflow.com/q/49991731
has body: After talking with a mod on the plotly forums, the following steps fixed the problem: upgrade from dash-core-components==0.21.0 to dash-core-components==0.22.1 provide actual info about the figure Without the populated dictionary for figure={...}, the issue still persisted. import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import pandas as pd from functools import partial import datetime as dt from SupplyChainReportingTool import server, session, blu, cache, CACHE_TIMEOUT app_tst = dash.Dash(__name__, server=server, url_base_pathname='/ie_test/') app_tst.css.config.serve_locally = True app_tst.scripts.config.serve_locally = True layout = go.Layout( yaxis=dict(title='Count',range=[0, 100],fixedrange=True,side='right',zeroline=False,showgrid=False), yaxis2=dict(title='percent',range=[0, 1],fixedrange=True,side='left',overlaying='y') ) data = [go.Scatter(x=[],y=[],name='Data',mode='lines+markers')] app_tst.layout = html.Div([ dcc.Graph( id='graphtest', figure={'data': data, 'layout': layout} ) ]) With this working, I still need to move back to dash-core-components==0.21.0 to see if that really was an issue.
type: Answer

http://stackoverflow.com/q/49992442
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87001623
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87001694
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/87001671
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87001481
upvote count: 1
tagged with: sorting
has body: I had this program in Python regarding baby names in Texas. Solved quite a bit of it, but got stuck in the counting part. I converted the list to the dictionary. The output has to be such that the program displays the top 5 most popular baby names in the time span provided by the user (begin year, end year). def count_names(file_data, begin, end, sex): import operator as op x=[] c=[] a=[] t=[] number_names = 5 for d in range (begin,end+1): x.append(str(d)) for y in file_data: if y[5:9] in x: c.append(y) for q in c: p=q.split(',') if (p[1]=='M'): t.append(p) elif(p[1]=='F'): a.append(p) if(sex=='M'): dm={} for h in t: dm[h[3]]=h[4] elif(sex=='F'): df={} for j in a: df[j[3]]=j[4] def main(): #Open the data file and save the data in a list called file_data. #Each element of the list is a string in the format: # 'TX,GENDER,YEAR_OF_BIRTH,BABY_NAME,OCCURRENCES\n' file_data = open('TX19010-2016.csv').readlines() sex = 'M' cmd = '' while cmd != 'quit()': cmd = input('&gt; ') if cmd == 'girl': sex = 'F' elif cmd == 'boy': sex ='M' elif cmd != 'quit': years = cmd.split() begin = int(years[0]) if len(years) &gt; 1: end = int(years[1]) else: end = begin count_names(file_data, begin, end, sex) main()
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87002138
has title: Top 5 baby names in Texas in a time span (python)

http://stackoverflow.com/comment/86924656
has text: You can read about regular expressions [here](https://docs.python.org/3/howto/regex.html).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49950905

http://stackoverflow.com/a/50000281
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50000250
downvote count: 0
has comment: http://stackoverflow.com/comment/87021635
has comment: http://stackoverflow.com/comment/87020649
accepted answer of: http://stackoverflow.com/q/50000250
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/87021186
has comment: http://stackoverflow.com/comment/87020978
has body: Use | for regex or in str.contains with cast boolean to integer by astype: df['Cat'] = df['A'].astype(str).str.contains('Cat|kitten').astype(int) df['Dog'] = df['A'].astype(str).str.contains('Dog|puppy').astype(int) Similar: a = df['A'].astype(str) df['Cat'] = a.str.contains('Cat|kitten').astype(int) df['Dog'] = a.str.contains('Dog|puppy').astype(int) print (df) A Cat Dog 0 Cat had a nap 1 0 1 Dog had puppies 0 1 2 Did you see a Donkey 0 0 3 kitten got angry 1 0 4 puppy was cute 0 1 More dynamic solution with dictionary of lists: dic = {'Cat':['Cat','kitten'],'Dog':['Dog','puppy']} for k, v in dic.items(): df[k] = df['A'].astype(str).str.contains('|'.join(v)).astype(int) print (df) A Cat Dog 0 Cat had a nap 1 0 1 Dog had puppies 0 1 2 Did you see a Donkey 0 0 3 kitten got angry 1 0 4 puppy was cute 0 1

http://stackoverflow.com/comment/87154552
has text: I want File1.txt to be appended to column3 for row1 and similarly File2.txt to be appended to column3 of row2. I don't want to consolidate the files into one file.
type: AnswerComment
comment on: http://stackoverflow.com/a/50068729
score: 0
type: Comment

http://stackoverflow.com/comment/86993137
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49988217
has text: Thank you! Is there any way to make it work for more than just 2 repeating elements?
type: AnswerComment

http://stackoverflow.com/q/50006951
tagged with: list
downvote count: 0
accepted answer: http://stackoverflow.com/a/50007035
has title: How can I delete integers from list (of integers and strings) by taking which value to delete from user input?
type: Question
upvote count: 2
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/87030486
has body: I am doing a menu driven program in python to insert and delete items in a list. I have a list containing integers and strings. I want to delete integer. So I take input from user as list = [1, 2, 3, "hi", 5] x = input("enter the value to be deleted") # input is given as 2 list.remove(x) But it gives me a ValueError I typecasted the input to int and it worked for integers but not for the string.
has answer: http://stackoverflow.com/a/50007035
tagged with: python
possible better answer: http://stackoverflow.com/a/50007397
tagged with: remove-method
favorite count: 0
has answer: http://stackoverflow.com/a/50007397
score: 2
type: AnsweredQuestion

keyboard
tags question: http://stackoverflow.com/q/50028823
tag name: keyboard
type: Tag
tags question: http://stackoverflow.com/q/50029691

http://stackoverflow.com/q/49932522
score: 0
answer count: 1
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49933642
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49933642
has title: BeautifulSoup Webscraping Text overflows the cell and goes to next one. I want to keep the information in one cell instead of separated
tagged with: python
has body: Beginner here trying to get this down. I feel like the solution is very easy at this point as I have tried numerous things but none of it worked. I've been trying this for the whole day with no avail. I tried looking on stack but was unable to find the answer. I'm trying to scrape the date text and the deal post from spoofee.com The format is Date and then Info about the deal. I tried to do that but failed miserably as the text overflowed to next cells. Tried bunch of solutions but none worked. First I'm trying to write the Date and the Title of the Deal. Once I'm able to accomplish that I will do the Info. Here's my Code. from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as bs html_url = 'http://www.spoofee.com/' uClient = uReq(html_url) page_html = uClient.read() uClient.close() page_soup = bs(page_html, 'html.parser') titles = page_soup.findAll("td",{"class":"dealtitle"}) date = page_soup.findAll("td",{"class":"date"}) filename = "spoofeedeals.csv" f = open(filename,"w") headers = "Date and Deals\n" f.write(headers) for day in date: f.write('\n'+day.text+'\n\n') for title in titles: f.write(title.text+'\n') f.close() This is what I get. Resulting data in csv How can I get the date to be in one cell and not the next two cells? I tried get_text(separator=",") but that didn't work. When I try other solutions, the rest of the info titles get screwed up. This is step 1 before going to my step 2 of pulling more data from this page but I'm stuck. I have a feeling I'm going to get this with a easy solution that I'm going to facepalm myself. Thank you for the help.
type: AnsweredQuestion

http://stackoverflow.com/comment/86917161
type: AnswerComment
has text: @Chi if you edit that second question into your question above, I can answer
comment on: http://stackoverflow.com/a/49950023
score: 0
type: Comment

http://stackoverflow.com/comment/87112876
type: AnswerComment
comment on: http://stackoverflow.com/a/50043059
type: Comment
has text: Thanks, I'm not sure this is quite "the Answer", because I still get the pathological behaviour (that is, not the initial timeout on a slow loading page, but the following ones on fast loading pages) even when setting the options you recommended: I suspect a chrome/selenium bug. But I'll vote up the answer.
score: 0

http://stackoverflow.com/q/50039505
has comment: http://stackoverflow.com/comment/87095435
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31845482
answer count: 2
score: 1
downvote count: 0
has title: My dictionary counts letter instead of words
duplicate of: http://stackoverflow.com/q/31845482
accepted answer: http://stackoverflow.com/a/50039573
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50039573
has body: I have made a text string and removed all non alphabetical symbols and added whitespaces in between the words, but when I add them to a dictionary to count the frequency of the words it counts the letters instead. How do I count the words from a dictionary? dictionary = {} for item in text_string: if item in dictionary: dictionary[item] = dictionary[item]+1 else: dictionary[item] = 1 print(dictionary)
possible better answer: http://stackoverflow.com/a/50039615
has comment: http://stackoverflow.com/comment/87095195
has comment: http://stackoverflow.com/comment/87095038
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50039615

http://stackoverflow.com/comment/86955743
comment on: http://stackoverflow.com/q/49969687
score: 0
type: Comment
type: QuestionComment
has text: I have no clue, just wanted to point it out

http://stackoverflow.com/comment/86965551
has text: Yes, great idea! Works like a charm and is easily integrated in some pre- and post-test setup. Thanks!
comment on: http://stackoverflow.com/a/49942877
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86972123
comment on: http://stackoverflow.com/a/49977707
has text: thank you for showing me however when i use the above code of yours with mine, i am getting this error - NameError: name 'do_send_mail' is not defined and i only want to check all lines in fileTwo exist in fileOne. i have done that on purpose.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86896698
type: AnswerComment
comment on: http://stackoverflow.com/a/49940082
score: 1
type: Comment
has text: I think you don't have to use DISTINCT,but I wasn't sure, that`s why I added it to the answer

http://stackoverflow.com/comment/86977856
score: 0
comment on: http://stackoverflow.com/q/49980510
type: QuestionComment
has text: Yes that's correct. I've followed the linked tutorial word for word so not sure why it is not working.
type: Comment

http://stackoverflow.com/a/49994471
score: 0
type: Answer
has body: The main reason is that you are passing context from view in different html. while extending other html the one you include or extend won't be able to access context which you passed in your template hence you need to override that particular block in template You can work with templates as below: base.html {% block navbar %} base {% endblock %} {% block body %} base {% endblock %} Now if you render home.html from view it should be: home.html {% extends 'base.html' %} &lt;!-- the blocks you override here only replaced --&gt; {% block navbar %} {% for foo in subjectType %} &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="{% url "type" foo.type_name %}"&gt;{{ foo.type_name }}&lt;/a&gt; &lt;/li&gt; {% endfor %} {% endblock %} So if you pass context using template home.html you need to override navbar if you want to use context Also you can create another html and include in template as: navbar.html {% for foo in subjectType %} &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="{% url "type" foo.type_name %}"&gt;{{ foo.type_name }}&lt;/a&gt; &lt;/li&gt; {% endfor %} home.html {% extends 'base.html' %} &lt;!-- the blocks you override here only replaced --&gt; {% block navbar %} {% include 'navbar.html' %} {% endblock %}
answers question: http://stackoverflow.com/q/49992636
has comment: http://stackoverflow.com/comment/87007126
has comment: http://stackoverflow.com/comment/87007091

http://stackoverflow.com/q/50002314
type: UnansweredQuestion
tagged with: ascii
has comment: http://stackoverflow.com/comment/87020802
duplicate of: http://stackoverflow.com/q/12934997
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50002354
type: Question
has title: Is it possible to check if a Letter is in a Range of the ASCII Alphabet?
linked to: http://stackoverflow.com/q/227459
has answer: http://stackoverflow.com/a/50002451
has body: USR_PWD = raw_input ("Please Input A 10 Digit Password") if USR_PWD[0] == chr(range(65,90)) print "True" Line 2 does not work, I'm attempting to check and see if the input's first character is a capital letter (65 is A and 90 is Z). Not even sure if this is the best way to go about it either. I'm a beginner so I could be making a very easy mistake but, thanks for the help.
tagged with: python

http://stackoverflow.com/comment/86895587
has text: Can you check answer?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49939801
score: 0

http://stackoverflow.com/q/49990790
type: Question
upvote count: 2
has title: Python- Deleting a sheet in excel without it prompting you
has comment: http://stackoverflow.com/comment/87000378
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86998209
tagged with: python
tagged with: excel
favorite count: 0
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/86998265
has body: How do you delete a sheet in excel without it prompting you? I am doing this with Dispatch in win32com.client. import time, os.path, os from win32com.client import Dispatch path1 = 'C:\\example.xlsx' path2 = 'C:\\Todolist2.xlsx' xl = Dispatch("Excel.Application") xl.Visible = True wb1= xl.Workbooks.Open(Filename=path1) wb2= xl.Workbooks.Open(Filename=path2) ws1 = wb1.Worksheets(1) ws2 = xl.ActiveSheet ws1.Copy(Before=wb2.Worksheets(1)) ws2 = xl.ActiveSheet ws2.Delete()

http://stackoverflow.com/q/49996597
has body: Afternoon, I have duplicates (id and ticker combination) in my df which I would like to display then remove based on criteria in another column. I have seen a number of sorting solutions but would prefer to resolve this by filtering. display(df) id ticker state 396219 ACGB 3 1/4 04/21/29 Ended 396496 NULL Done 396496 ACGB 5 3/4 05/15/21 Done 396521 ACGB 4 1/2 04/15/20 Ended 396523 ACGB 1 3/4 11/21/20 Ended 396581 TCV 5 1/2 11/15/18 Order Sent 396588 TCV 5 1/2 11/15/18 Order Sent 396588 TCV 5 1/2 11/15/18 Done 396680 KBN 3.4 07/24/28 Done Display all duplicates for information purposes. id ticker state 396588 TCV 5 1/2 11/15/18 Order Sent 396588 TCV 5 1/2 11/15/18 Done I tried df[df.duplicated(['id','ticker'])]) but it shows all rows For each set of duplicates only keep the one where df['state'] == 'Done' id ticker state 396588 TCV 5 1/2 11/15/18 Done Display all the original data, without the duplicates i.e. unique id.ticker records 396219 ACGB 3 1/4 04/21/29 Ended 396496 NULL Done 396496 ACGB 5 3/4 05/15/21 Done 396521 ACGB 4 1/2 04/15/20 Ended 396523 ACGB 1 3/4 11/21/20 Ended 396581 TCV 5 1/2 11/15/18 Order Sent 396588 TCV 5 1/2 11/15/18 Done 396680 KBN 3.4 07/24/28 Done
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/49996704
tagged with: pandas
upvote count: 1
score: 1
has title: Display pandas dataframe duplicates based on one column then keep based on a criteria
answer count: 1
tagged with: duplicates
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49996704

http://stackoverflow.com/q/49948628
answer count: 0
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86916623
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87030860
type: Question
has body: I am using Skikit Learn's train_test_split function it returns all the arrays fine apart from X_test which returns weird values not from the data set This is the code below. from sklearn.model_selection import train_test_split heart_data = np.genfromtxt("cleveland.txt", delimiter=",") hd_y = heart_data[:,13] X_train, X_test, y_train,y_test = train_test_split(heart_data,hd_y, test_size=0.2, random_state=42) print(X_train,y_train) print(X_test,y_test) Returns this - (Shortened the arrays, as they were to long) #X_train [[58. 1. 3. ... 0. 7. 0.] [50. 0. 3. ... 0. 3. 0.] [70. 1. 4. ... 0. 7. 4.] ... [61. 1. 4. ... 1. 7. 2.] [35. 1. 2. ... 0. 3. 0.] [49. 1. 3. ... 3. 7. 3.]] #y_train [0. 0. 4. 2. 1. 3. 0. 0. 0. 0. 0. 2. 3. 1. 1. 0. 0. 2. 0. 0. 0. 0. 2. 4. 0. 0. 0. 1. 1. 0. 0. 2. 1. 2. 1. 3. 2. 0. 1. 0. 1. 2. 2. 2. 1. 3. 0. 1 0. 1. 0. 0. 1. 1. 1. 0. 0. 3. 2. 0. 3.] #X_test [[5.30e+01 1.00e+00 4.00e+00 1.40e+02 2.03e+02 1.00e+00 2.00e+00 1.55e+02 1.00e+00 3.10e+00 3.00e+00 0.00e+00 7.00e+00 1.00e+00] [4.00e+01 1.00e+00 4.00e+00 1.52e+02 2.23e+02 0.00e+00 0.00e+00 1.81e+02 0.00e+00 0.00e+00 1.00e+00 0.00e+00 7.00e+00 1.00e+00] [5.10e+01 0.00e+00 4.00e+00 1.30e+02 3.05e+02 0.00e+00 0.00e+00 1.42e+02 1.00e+00 1.20e+00 2.00e+00 0.00e+00 7.00e+00 2.00e+00]] #y_test [1. 1. 0. 0. 0. 3. 0. 1. 1. 0. 1. 0. 0. 0. 0. 0. 3. 2. 4. 3. 0. 1. 0. 0. 0. 1. 1. 0. 2. 0. 0. 0. 3. 0. 0. 3. 0. 4. 1. 0. 0. 0. 1. 4. 3. 2. 0. 0. 0. 1. 1. 0. 0. 3. 3. 0. 0. 2.]
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87036199
has title: Skikit learn train_test_split return weird values
score: 0
has comment: http://stackoverflow.com/comment/86913818
has comment: http://stackoverflow.com/comment/86922519

http://stackoverflow.com/a/50045126
answers question: http://stackoverflow.com/q/50044698
accepted answer of: http://stackoverflow.com/q/50044698
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87108052
has comment: http://stackoverflow.com/comment/87106682
score: 0
type: Answer
has body: What am I doing wrong? Well quite obviously, assuming that .json() can take whatever piece of broken markup and automagically turns it into something json-compliant is plain wrong ;) Oh and yes - the source of the problem is that - as often with php stuff - what was probably supposed to be a proper json response is polluted by php: Warning: Invalid argument supplied for foreach() in /home/pedicure/public_html/pedicuremotorkopen.be/wp-content/plugins/woocommerce-parcelpro_1-2-8/admin/data/parcelpro-shipping-settings-services.php on line 88 [{"id":25348,"name":"Star Design Spa & Massage","slug":"star-design-spa-massage","permalink":"https:\/\/en.pedicuremotorkopen.be\/product\/star-design-spa-massage\/","date_created":"2018-01-23T11:46:28","date_modified":"2018-02- etc... EDIT: How can I make sure the json doesn't consider the Warning? As I mentionned, the source problem is with PHP itself. If you have admin access to this site, you can change the php settings to prevent it from displaying spurious warning messages (which I would recommand if the site is actually on production). For a more general answer, I'd say that a site returning anything else than well formed json for what is supposed to be "application/json" content-type is broken and that it's not your responsability (as the person writing client code) to "fix" it - just warn the site's admin about the problem and wait until he fixes it (cf above). Now You could of course try to be "tolerant" and fix the response content by yourself but you'll have to do so manually and it will be brittle at best since you have no failsafe way to tell what's part of the json and what's not (such php pollution can happen just anywhere in the response content).

http://stackoverflow.com/a/50011992
score: 1
downvote count: 0
has body: When defining data sets variables are represented in columns and observations in rows. So, if you have three independent variables, one dependent variable and 20 measurements, your data set would be represented as a 20 x 4 matrix - that is 20 rows and 4 columns. By default, train_test_split splits the data set into a 0.75 fraction of measurements as a training set and a 0.25 fraction as a testing set. For the example with 20 x 4 data set, the split will be 15 x 4 for training and 5 x 4 for testing. As for you code, here is what happens if the dimensions are reversed: import sklearn.model_selection as skl_ms import numpy as np A = np.random.normal(0, 1, [100, 1]); (A_train, A_test) = skl_ms.train_test_split(A); A_train.shape Out[105]: (75, 1) A_test.shape Out[106]: (25, 1)
answers question: http://stackoverflow.com/q/50011348
type: Answer
upvote count: 1

http://stackoverflow.com/q/49927254
tagged with: pandas
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86871413
tagged with: python
has comment: http://stackoverflow.com/comment/86870838
type: Question
accepted answer: http://stackoverflow.com/a/49927479
has title: Change a number represented as an object to a long or other format within dataframe
has answer: http://stackoverflow.com/a/49927479
has body: So I am working with python 3.6.5 and have a dataframe like below but much larger. Date Open High Low Close Volume 0 2018-04-16 8337.57 8371.15 7925.73 8058.67 5,631,310,000 \ 1 2018-04-15 7999.33 8338.42 7999.33 8329.11 5,244,480,000 2 2018-04-14 7874.67 8140.71 7846.00 7986.24 5,191,430,000 Market Cap 0 141,571,000,000 1 135,812,000,000 2 133,682,000,000 I am able to plot the different columns: Open, High, Low, Close But unable to graph volume and market cap df.plot(x='Date', y = 'Volume', kind = 'line') TypeError: Empty 'DataFrame': no numeric data to plot also when running df.plot() ValueError: view limit minimum -36839.658058149995 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units But I am certain that the df['Date'] is a datetime object print(df.dtypes) Date datetime64[ns] Open float64 High float64 Low float64 Close float64 Volume object Market Cap object dtype: object
answer count: 1
has comment: http://stackoverflow.com/comment/86870854
tagged with: python-3.6
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50069725
has comment: http://stackoverflow.com/comment/87157854
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/87156606
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87156802
has body: I have a dataset for multi-label binary (0/1) classification; some of the labels will never exist (the combination of row/column indices is impossible in my application), and this has been denoted in the input with -1. I don't want the network to learn weights associated with the -1 values, and I don't want the loss function to be affected by them. To prevent this, I'm using a Masking layer. I'm trying to modify the accepted answer here to work in the multi-label case. The dataset (X) consists of numpy arrays of size (124, 124) with (0/1/-1) values. There is a sequence of 7 such numpy arrays. The labels (y_true) are (0/1/-1) in another (124, 124) array. The accepted answer recommends using one-hot encoding for the binary values and the masking value, and Keras LSTM expects input to be in the shape [num_samples, num_timesteps, num_features]. These two things mean my X and y_true shapes become (1, 7, 124*124*3) and (1, 124*124*3) below, respectively. from keras.layers import Input, Masking, LSTM, Dense from keras.models import Model import numpy as np import tensorflow as tf from keras import backend as K from keras.utils import to_categorical from keras.optimizers import adam import sys #Creating some sample data #Matrix has size 124*124, values -1, 0, 1 X = np.random.rand(1, 7, 124, 124).flatten() X[X &lt; 0.2] = 0. X[X &gt; 0.4] = -1. X[(X &gt; 0.2) &amp; (X &lt; 0.4)] = 1. #Categories are 0, 1, -1 one-hot encoded X = to_categorical(X, num_classes=3) X = np.reshape(X, (7, 3, 124*124)) #X needs to be shape (num_samples, num_timesteps, num_features) Y = np.random.rand(124, 124).flatten() Y[Y &lt; 0.2] = 0. Y[Y &gt; 0.4] = -1. Y[np.where((Y &gt; 0.2) &amp; (Y &lt; 0.4))] = 1. Y = to_categorical(Y, num_classes=3) y_true = np.reshape(Y, (1, 3, 124*124)) #predicting a single timestep #Building the model mask_val = np.tile([0,0,1], 124*124).reshape((3, 124*124)) input_tensor = Input(shape=(3, 124*124)) masking_input = Masking(mask_value=mask_val)(input_tensor) lstm = LSTM…
has title: Keras: masking layer for multi-label classification via LSTM
tagged with: python
linked to: http://stackoverflow.com/q/47057361

http://stackoverflow.com/a/50006977
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50006900
has comment: http://stackoverflow.com/comment/87030554
type: Answer
answers question: http://stackoverflow.com/q/50006900
score: 2
has body: You need to access the first element of that json response array. Like this: await client.say(Data[0]["items"][0]["variables_values"]["Steam64ID"])
upvote count: 2
type: AcceptedAnswer

object-detection
tags question: http://stackoverflow.com/q/50025883
tags question: http://stackoverflow.com/q/49994979
tags question: http://stackoverflow.com/q/50027635
type: Tag
tag name: object-detection
tags question: http://stackoverflow.com/q/50017241
tags question: http://stackoverflow.com/q/49997382
tags question: http://stackoverflow.com/q/49936431
tags question: http://stackoverflow.com/q/49923123
tags question: http://stackoverflow.com/q/49960126
tags question: http://stackoverflow.com/q/49951422

http://stackoverflow.com/comment/87150694
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50067059
has text: I access the values within `_ConfigItem`, just removed it from this example since it's not important. [Actual file is here](https://github.com/Peter92/MouseTracks/blob/master/core/ini.py) but a bit harder to understand on a quick glance :P
score: 0

http://stackoverflow.com/q/49990882
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/50401718
type: Question
has body: Keras has many different ways of merging inputs like Add(), Subtract(), Multiply(), concatenate(), etc... Do they all have the same effect or are there situations where one is preferable?
has answer: http://stackoverflow.com/a/50402350
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/86998578
score: 4
has comment: http://stackoverflow.com/comment/86998711
upvote count: 4
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50402350
has comment: http://stackoverflow.com/comment/87817737
downvote count: 0
accepted answer: http://stackoverflow.com/a/50401718
has title: Which merge layers to use in keras?

http://stackoverflow.com/a/50007339
answers question: http://stackoverflow.com/q/50004263
has body: By default, when crontab runs a script, it sets the $HOME variable to be /. AWS looks for its credentials in a location which resolves to $HOME/.aws. So, you need to either move your .aws directory into the root dir, which is probably not a good idea, or redefine $HOME to point to the folder that contains your .aws directory. The easiest way to do this, if you are running your python script from a shell script, is to add: export /HOME=/home/pi/ To the start of your shell script.
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/50004263
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86949190
score: 0
type: QuestionComment
has text: The `click()` you used within `execute_script()` method is the **Javascript** `click()` leaving out the **WebDriver** [`click()`](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html#selenium.webdriver.remote.webelement.WebElement.click) which is proven and powerful. My question is _why so_?
comment on: http://stackoverflow.com/q/49952697
type: Comment

http://stackoverflow.com/comment/87044614
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50011937
has text: i did something like this stmt=stmt.where(and_(rate.columns.journal_ctrl_num==fund.columns.journal_ctrl_num,fund.columns.account_code==selected_acc,rate.columns.date_entered.between(convert,convert1))) result_proxy=connection.execute(stmt) for a in result_proxy: test=datetime.date.fromordinal(int(a.date_entered)) after passing the parameter to the template i select the rage of date for example from date to end date. it only display start date not end date
type: Comment

http://stackoverflow.com/q/49991831
has title: StatsModels in Python: What is measured on the horizontal axis?
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49992253
accepted answer: http://stackoverflow.com/a/49992253
type: AnsweredQuestion
score: 0
has body: I run the following Python code to generate the attached figure of Kernel density with the horizontal axis from 0 to 500. Given that the code generates 100 observations between -2.157 and 2.830, I would expect the horizontal axis shows values like between -3 and 3. What is actually measured on the horizon taxis? import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt np.random.seed(1234567) k = np.random.normal(0, 1, 100) dens = sm.nonparametric.KDEUnivariate(k) dens.fit() plt.plot(dens.density) Thanks for your help in advance.
answer count: 1
type: Question
tagged with: statsmodels

http://stackoverflow.com/q/49953598
has answer: http://stackoverflow.com/a/49953661
accepted answer: http://stackoverflow.com/a/49953661
has comment: http://stackoverflow.com/comment/86923802
has comment: http://stackoverflow.com/comment/86923949
type: Question
answer count: 2
tagged with: python
has body: I made a program that takes values from treeview and calculate something when button is pressed. I put try / except statement inside that function. def SumAll(): try: #do something (calculate) except ValueError: Error=messagebox.showinfo("Enter proper values") pass The problem is, program keeps running when messagebox.showinfo appears, and it gives the ValueError. How can I fix that, and how can I put more than one error exception (IndexError, etc)?
has answer: http://stackoverflow.com/a/49953663
possible better answer: http://stackoverflow.com/a/49953663
type: AnsweredQuestion
has title: Stop program from running after try / except python
score: 0

http://stackoverflow.com/a/49941280
type: AcceptedAnswer
downvote count: 3
upvote count: 1
answers question: http://stackoverflow.com/q/49941192
score: -2
accepted answer of: http://stackoverflow.com/q/49941192
type: Answer
has body: Making __add__ return self does the trick: class Problem: def __init__(self): self.lItems = [] def __add__(self, other): self.lItems.append(other) return self problem = Problem() problem += 'text' print(problem) print(problem.lItems) outputs : &lt;__main__.Problem object at 0x04BBDCD0&gt; ['text'] EDIT: You should consider the use of __iadd__ special method instead.

http://stackoverflow.com/comment/87157832
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50070421
has text: I don't know, I've been running this code for 10 times with this url and it worked perfectly...

http://stackoverflow.com/q/50013542
linked to: http://stackoverflow.com/q/19951816
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87043470
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
has title: I did'nt assign 2 y's but how it got assigned?
has answer: http://stackoverflow.com/a/50013565
tagged with: python
has body: I assigned only one y, but how internally it got assigned with 2 y's? x=[['', 'a', 'b'], ['', 'c', 'd']]*2 print(x) x[0][0]='y' print('\n') print(x) output [['', 'a', 'b'], ['', 'c', 'd'], ['', 'a', 'b'], ['', 'c', 'd']] [['y', 'a', 'b'], ['', 'c', 'd'], ['y', 'a', 'b'], ['', 'c', 'd']]
score: -1
has comment: http://stackoverflow.com/comment/87043430
duplicate of: http://stackoverflow.com/q/240178
upvote count: 0
linked to: http://stackoverflow.com/q/3459098
answer count: 1
linked to: http://stackoverflow.com/q/2739552

http://stackoverflow.com/comment/104683045
score: 1
has text: Version 1.17 implements the new multi field view approach. Read the docs and release notes.
type: Comment
comment on: http://stackoverflow.com/a/50032792
type: AnswerComment

http://stackoverflow.com/q/50052344
tagged with: django
type: UnansweredQuestion
answer count: 1
tagged with: postgresql
type: Question
has answer: http://stackoverflow.com/a/50052345
tagged with: architecture
tagged with: python
has body: I am a relatively new to Django web development with about one year of experience with programming as a whole, and a few months less with Django web development. With two friends we came up with a business idea, and we are developing that. And even though I (I am the person programming the most, together with one more experienced friend guiding me) am quite new to this, I would like to make this project a success. So, to come to the point, I would like to set up the project in such a way that the project could handle large loads with grace, in the future. I am thinking about a worldwide platform, and so, a very large number of visitors. We are using Django Rest Framework to build an API which serves a ReactJS powered front-end, using PostgreSQL as our database. Short description of application: The web application will be a platform where (registered) users will be able to manage their storage. Other users (registered or not) will be able to search within the total storage. It will not be a website that handles a lot of media (images, videos). And their will not be a lot of different categories of items to store. I can give more details if needed. What advice would you advice a beginner who wants to learn about setting up a project in such a way that it is capable of scaling. Some beginner friendly resources (courses, books, websites, etc.) would also be great. Since the resources we have are limited (one beginner doing the main programming), I would like to not dive into too much of theory, since I want a good balance between study and actual production. It would be nice if you could keep that in mind when answering the question. I am sure that are a lot of other beginners in Django programming for who'm the answers to this question could be very beneficial. Thanks!
favorite count: 0
upvote count: 2
score: 2
has title: Django scaling beginner advice / resources
downvote count: 0
tagged with: web-applications

http://stackoverflow.com/a/50171671
type: AcceptedAnswer
has body: Found a solution with openCV. import numpy as np import cv2 resizeto = 2 small_lable = cv2.resize(mask, (mask.shape[1]//resizeto, mask.shape[0]//resizeto), interpolation=cv2.INTER_NEAREST) small_lable = (np.array(small_lable)).astype('uint8') print(small_lable.shape, np.unique(small_lable)) plt.imshow(small_lable) output: (15, 10) [ 0 30 70]
accepted answer of: http://stackoverflow.com/q/50038263
type: Answer
answers question: http://stackoverflow.com/q/50038263
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87605172
score: 0
comment on: http://stackoverflow.com/q/50012126
has text: Do you want to find only one image or *all* images that match? The Python code finds only one image. The C# code will find all matches
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49937041
has body: I would like to export data from dataframe to an excel, that has already its format-layout (colours, cells, etc.) This code overwrite the all sheet, instead I would like the export data without changing excel layout. is that possible? Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter('C:/pandas_positioning.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='my_data', startrow=7, startcol=4, header=False, index=False) Close the Pandas Excel writer and output the Excel file. writer.save()
upvote count: 2
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
has title: pandas exporting to excel without format
favorite count: 0
tagged with: excel
tagged with: pandas.excelwriter
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54119943

http://stackoverflow.com/a/51383349
upvote count: 8
answers question: http://stackoverflow.com/q/49987244
downvote count: 0
has body: With Qt 4.8 and python2.7, i use partial to pass multi arguments to signal. from functools import partial ... def initGui(self): ... self.btn1.clicked.connect(partial(self.btnListener, "btn1")) self.btn2.clicked.connect(partial(self.btnListener, "btn2")) ... def btnListener(self, button_name): print('button_name {}'.format(button_name)) ... With this method, you can know which button is clicked. I hope that help you to find the same in QT5.
type: Answer
score: 8

http://stackoverflow.com/q/50018700
answer count: 1
downvote count: 1
tagged with: unit-testing
favorite count: 0
has comment: http://stackoverflow.com/comment/87053613
type: Question
has answer: http://stackoverflow.com/a/50019006
tagged with: python
type: UnansweredQuestion
has title: Is it more pythonic to import inside tests instead of at the start of the module?
has comment: http://stackoverflow.com/comment/87074660
score: 6
has comment: http://stackoverflow.com/comment/87053678
linked to: http://stackoverflow.com/q/128478
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87073629
has body: "PyCharm knew that in testing you do the import inside the unit test not at module start" is a quote from the "Getting Started with PyCharm 7/8: Testing" video about testing capabilities provided by PyCharm. From PEP8: Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. In this other SO question, the concept of where to import in python has already been addressed as a broder concept. However, there's no mention of the special case when unit testing. What advantages would we get from importing inside tests instead of at the start of the module? If different tests use the same modules, does the module have to be imported each time?
has comment: http://stackoverflow.com/comment/87055683
upvote count: 7

integral
tags question: http://stackoverflow.com/q/50041121
tag name: integral
type: Tag
tags question: http://stackoverflow.com/q/50039222

http://stackoverflow.com/q/49928120
has body: I have a model like this: class Product(models.Model): name = models.CharField(_('name')) ... user = models.ForeignKey(User, related_name='products', on_delete=models.CASCADE, verbose_name=_('user')) ... and i want: if the user authenticated: return the user products else if user did not authenticate: return all products in linq C# we can solve this problem with: Product.Where(!request.user.is_authenticated() || user.id == request.user.id) i know that in python can solve it with if else: if request.user.is_authenticated: return Product.objects.filter(user=request.user) else: return Product.objects.all() Question: is there a solution like the C# linq?
type: Question
score: 0
tagged with: python
has title: Get object or all in django query_set
tagged with: django-queryset
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49928653
tagged with: django

tableofcontents
tag name: tableofcontents
type: Tag
tags question: http://stackoverflow.com/q/49984691

http://stackoverflow.com/a/50033110
has body: I think you'll have to operate on the indices/values independently. import numpy as np import tensorflow as tf def sparse_not_equal(sparse_tensor, value): indices = sparse_tensor.indices values = sparse_tensor.values condition = tf.squeeze(tf.where(tf.not_equal(values, value)), axis=-1) indices = tf.gather(indices, condition) values = tf.ones(shape=(tf.shape(indices)[0],), dtype=tf.bool) return tf.SparseTensor( indices, values, sparse_tensor.dense_shape) def get_sparse(): vals = tf.constant([2, 3, 4, 2]) indices = tf.constant(np.array([[1], [4], [5], [10]])) dense_shape = [16] return tf.SparseTensor(indices, vals, dense_shape) sparse_tensor = get_sparse() sparse_filtered = sparse_not_equal(sparse_tensor, 2) with tf.Session() as sess: s = sess.run(sparse_filtered) print(s)
answers question: http://stackoverflow.com/q/50032815
type: Answer
score: 0

http://stackoverflow.com/q/49978657
has body: I have a function that should not hang. Specifically, it detects the condition that would cause it to hang and raises an error instead. Simplified, my function is similar to this one: def chew_repeated_leading_characters(string: str, leader: str): if len(leader) == 0: # Without this, will hang on empty string raise ValueError('leader cannot be empty') while True: if string.startswith(leader): string = string[len(leader):] else: break return string I would like to write a unit test in pytest to ensure this behavior. I know how to assert that a test should raise an exception. However, in this case, if the test fails, it does not actually fail; the entire test apparatus simply hangs. How do I generate a test failure on endless looping?
has comment: http://stackoverflow.com/comment/86974719
has comment: http://stackoverflow.com/comment/86974252
favorite count: 0
has comment: http://stackoverflow.com/comment/86973623
score: 2
tagged with: pytest
answer count: 3
has comment: http://stackoverflow.com/comment/86974793
has title: Assert no infinite looping in pytest
has comment: http://stackoverflow.com/comment/86974550
linked to: http://stackoverflow.com/q/944592
has comment: http://stackoverflow.com/comment/86974437
type: Question
has answer: http://stackoverflow.com/a/49978751
has answer: http://stackoverflow.com/a/49978733
has comment: http://stackoverflow.com/comment/86974395
tagged with: infinite-loop
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86974885
downvote count: 0
has answer: http://stackoverflow.com/a/49978707
tagged with: python

http://stackoverflow.com/comment/87036019
type: Comment
type: QuestionComment
score: 0
has text: @pault Tried both (with space and escape with space, bot occassions got same error, "java.io.FileNotFoundException: File does not exist: hdfs://hadoop/path/part_date=2018-04-20%2015%253A01%253A21/000000_0". It is adding the encoding %20 by itself, is it?
comment on: http://stackoverflow.com/q/50009413

http://stackoverflow.com/q/49931251
has answer: http://stackoverflow.com/a/49932431
tagged with: dataframe
tagged with: python
tagged with: loops
has comment: http://stackoverflow.com/comment/86880298
has body: Need help labeling different states into new dataframe column based on the conditions of two oscillating values; Column X &amp; Y. Using Column Y, as the state interval. State interval starts at 0 and ends at 0. Please note the values in Column Y will always stay in a positive or negative range. Each interval cycle will be in sequence order as all being +,-,+,- etc. Labeling starts when Column Y values become positive going above 0 and stops at 0 before becoming negative; is the end of the cycle and would start the next range or cycle going into negative range. There is a total of 6 patterns: A,B,C,D,E,F as cycle states. I'm trying to figure out the logic and how to add the label for each of the states into new dataframe column called state. Labeling happens for each cycle and starts over again with each new cycle state. +-------+-------------+---------+ | State | X | Y | +-------+-------------+---------+ | A | from - to + | + | | B | + | + | | C | - | + | | D | + | - | | E | - | - | | F | from + to - | - | +-------+-------------+---------+ For State A &amp; F, (Column X) has values goes from + to - or vice versa with crossover over 0. Values in Column Y will always stay in a positive or negative range. States B,C,D,E have no crossing overs in (Column X). The following are example dataframe values and example new column with the resulting state. +----+---------+---------+-------+ | # | X | Y | State | +----+---------+---------+-------+ | 1 | -0.0034 | 0.0056 | A | Cycle 1 (+) | 2 | -0.0001 | 0.0070 | A | | 3 | 0.0019 | 0.0073 | A | | 4 | 0.0039 | 0.0075 | A | | | | | | | 5 | 0.0273 | -0.0037 | D | Cycle 2 (-) | 6 | 0.0237 | -0.0059 | D | | | | | | | 7 | 0.0047 | 0.0028 | B | Cycle 3 (+) | 8 | 0.0044 | 0.0020 | B | | | | | | | 9 | -0.0034 | -0.0006 | E | Cycle 4 (-) | 10 | -0.0045 | -0.0014 | E | | | | | | | 11 | -0.0021 | 0.0006 | C | Cycle 5 (+) | 12 | -0.0019 | 0.0007 | C | | | | | | | 13 | 0.0041 | -0.0054 | F | Cycle 6 (-) | 14 | 0.0017 | -0.0060 | F | | 15 | -0…
tagged with: iterator
type: AnsweredQuestion
score: 0
answer count: 1
has title: Python - Iterating dataframe using +/- oscillating values and create new column based on condition
has comment: http://stackoverflow.com/comment/86880227
type: Question
accepted answer: http://stackoverflow.com/a/49932431
tagged with: pandas

http://stackoverflow.com/q/50053647
has comment: http://stackoverflow.com/comment/87139401
answer count: 0
linked to: http://stackoverflow.com/q/5996650
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: selenium-firefoxdriver
tagged with: selenium
has comment: http://stackoverflow.com/comment/87131543
favorite count: 0
has comment: http://stackoverflow.com/comment/87148632
type: Question
has comment: http://stackoverflow.com/comment/87148273
has title: Selenium Python quit() method not working from command line
has comment: http://stackoverflow.com/comment/87136381
has comment: http://stackoverflow.com/comment/87123979
tagged with: python
has body: Using python 3.6.2 and FF (geckodriver-v0.20.1-win64), I have a try/except block setup to close selenium upon any exceptions, which I'm expecting to close all instances of the FF browser opened by selenium. I have this code: while 1: try: print(now() + " [+] GETTING OBJECT...") browser.get(url) obj = browser.find_element_by_class_name('search_result_row') objID = browser.execute_script( 'return document.getElementsByClassName( ' '"search_result_row" )[0].children[1].innerText.trim()') print("\nObject " + objID + " received @ " + now()) objDSC = browser.execute_script( 'return document.getElementsByClassName( ' '"search_result_row" )[0].children[2].innerText.trim()') print('\n' + objDSC) for type in objTypes: print("CHECKING IF OBJECT IS: " + type + "...") if type in objDSC: print("OBJECT IS OF USEABLE TYPE.") else: print("OBJECT IS NOT OF USEABLE TYPE.\n") time.sleep(5) except: while(browser): print('Quitting browser...') browser.quit() time.sleep(3) sys.exit(0) When I start the script from a command prompt using "python filename.py", I see 4x FF processes started in task manager, however upon an error or SIGINT, "Quitting browser..." just loops, as expected, but the 4x FF processes do not end (I've waited for several minutes, to be sure). I've also tried browser.close() before the quit() method with no luck. I'm not sure what I'm missing/doing wrong?
has comment: http://stackoverflow.com/comment/87139375
has comment: http://stackoverflow.com/comment/87148345
has comment: http://stackoverflow.com/comment/87139307

http://stackoverflow.com/q/50023644
score: 2
has body: I am using Python 2--I am behind moving over my code--so perhaps this issue has gone away. Using pandas, I can create a datetime like this: import pandas as pd big_date= pd.datetime(9999,12,31) print big_date 9999-12-31 00:00:00 big_date2 = pd.to_datetime(big_date) . . . Out of bounds nanosecond timestamp: 9999-12-31 00:00:00 I understand the reason for the error in that there are obviously too many nanoseconds in a date that big. I also know that big_date2 = pd.to_datetime(big_date, errors='ignore') would work. However, in my situation, I have a column of what are supposed to be dates (read from SQL server) and I do indeed want it to change invalid data/dates to NaT. In effect, I was using pd.to_datetime as a validity check. To Pandas, on the one hand, 9999-12-31 is a valid date, and on the other, it's not. That means I can't use it and have had to come up with something else. I've played around with the arguments in pandas to_datetime and not been able to solve this. I've looked at other questions/problems of this nature, and not found an answer.
has title: Python Pandas to_datetime Out of bounds nanosecond timestamp on a pandas.datetime
upvote count: 2
has answer: http://stackoverflow.com/a/57269917
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: datetime
tagged with: python
type: Question

http://stackoverflow.com/q/49982437
type: AnsweredQuestion
has title: Get the ASCII number of a character(Python3)
has comment: http://stackoverflow.com/comment/86981245
has comment: http://stackoverflow.com/comment/86981293
has body: I wrote a code that converts numbers 1 - 501 in ASCII, it works but I'm looking for a shorter path. l = list(range(1,501)) for i in l: ix = [int(d) for d in str(i)] ix = str(ix).replace("[","") ix = ix.replace("]","") ix = ix.replace(",","") ix = ix.replace(" ","") ix = [ord(x) for x in ix] print(ix) I tried to write, as shown below, but an error occurs. l = list(range(1,501)) for i in l: i = [ord(x) for x in i] &gt;&gt;TypeError: 'int' object is not iterable print(i) Someone can help me?
answer count: 1
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/86981551
has answer: http://stackoverflow.com/a/49982748
accepted answer: http://stackoverflow.com/a/49982748
favorite count: 0
type: Question
score: -2
has comment: http://stackoverflow.com/comment/86981187
has comment: http://stackoverflow.com/comment/86981237
tagged with: python
tagged with: ascii

http://stackoverflow.com/comment/87280412
score: 0
type: Comment
type: QuestionComment
has text: like fitness or minimum error from some vector/population
comment on: http://stackoverflow.com/q/49978307

nested-lists
tags question: http://stackoverflow.com/q/49985965
tags question: http://stackoverflow.com/q/49978967
tags question: http://stackoverflow.com/q/49949960
tags question: http://stackoverflow.com/q/49935141
type: Tag
tags question: http://stackoverflow.com/q/50039968
tag name: nested-lists

http://stackoverflow.com/q/49927501
tagged with: multi-index
has title: Pandas: Collapse a mxn multi-index dataframe into a series by repeating each row index n times
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49927711
has answer: http://stackoverflow.com/a/49927711
type: Question
tagged with: pandas
has body: I have a two dimensional dataframe in Pandas with two levels of indexing. For a sample, it looks like this: Location 1 2 3 4 5 Time 0 2 4 6 8 10 1 1 3 5 7 9 2 0 0 0 0 0 I want to collapse this into a single-indexed dataframe where the main index repeats for each column index, which would look like this: Time Location Value 0 1 2 0 2 4 0 3 6 0 4 8 0 5 10 ... so on. How can I achieve this in pandas?
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/86910475
type: Comment
type: AnswerComment
has text: I think the values are not integers mostly because of the equalization step performed earlier. Your code work, but the problem is the new image has the mask as the output. Instead of the mask I wanted the foreground image. I'll edit the answer to explain what is happening.
comment on: http://stackoverflow.com/a/49946864
score: 0

http://stackoverflow.com/q/49951922
accepted answer: http://stackoverflow.com/a/49952137
type: Question
tagged with: continuous-fourier
answer count: 1
tagged with: python
tagged with: simpsons-rule
has title: Plotting Fourier Series coefficients in Python using Simpson's Rule
tagged with: numerical-integration
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/26500293
score: 0
has body: I want to 1. express Simpson's Rule as a general function for integration in python and 2. use it to compute and plot the Fourier Series coefficients of the function . I've stolen and adapted this code for Simpson's Rule, which seems to work fine for integrating simple functions such as , or Given period , the Fourier Series coefficients are computed as: where k = 1,2,3,... I am having difficulty figuring out how to express . I'm aware that since this function is odd, but I would like to be able to compute it in general for other functions. Here's my attempt so far: import matplotlib.pyplot as plt from numpy import * def f(t): k = 1 for k in range(1,10000): #to give some representation of k's span k += 1 return sin(t)*sin(k*t) def trapezoid(f, a, b, n): h = float(b - a) / n s = 0.0 s += f(a)/2.0 for j in range(1, n): s += f(a + j*h) s += f(b)/2.0 return s * h print trapezoid(f, 0, 2*pi, 100) This doesn't give the correct answer of 0 at all since it increases as k increases and I'm sure I'm approaching it with tunnel vision in terms of the for loop. My difficulty in particular is with stating the function so that k is read as k = 1,2,3,... The problem I've been given unfortunately doesn't specify what the coefficients are to be plotted against, but I am assuming it's meant to be against k.
has answer: http://stackoverflow.com/a/49952137

http://stackoverflow.com/q/50046134
has answer: http://stackoverflow.com/a/50046248
type: Question
tagged with: multidimensional-array
tagged with: shapes
tagged with: python
has comment: http://stackoverflow.com/comment/87108567
accepted answer: http://stackoverflow.com/a/50140146
has comment: http://stackoverflow.com/comment/87108548
tagged with: numpy
type: AnsweredQuestion
score: 0
has body: If I have a multidimensional numpy array like: &gt;&gt; x = np.array([ np.array([0, 1, 2, 3, 4, 5]), np.array([0, 1, 2, 3, 4]), np.array([0, 1, 2, 3]), np.array([0, 1, 2, 3, 4]), np.array([0, 1, 2, 3, 4, 5, 6]), ]) &gt;&gt; x.shape (5,) Is there a "pythonic way" to find the shortest shape of arrays inside x?
answer count: 2
has answer: http://stackoverflow.com/a/50140146
has title: How to get the shortest array shape in a python numpy multidimensional array?
possible better answer: http://stackoverflow.com/a/50046248
tagged with: arrays

http://stackoverflow.com/comment/87072551
score: 0
type: AnswerComment
has text: Great answer. Thanks a lot. I will check out pytype. I'm really looking forward to finding bugs like [this](https://ideone.com/lEv0RS) more early.
type: Comment
comment on: http://stackoverflow.com/a/50027452

http://stackoverflow.com/a/49949060
downvote count: 1
answers question: http://stackoverflow.com/q/49949017
has body: The answer is in the output of bin(): &gt;&gt;&gt; bin(12345) '0b11000000111001' As you can see, it only outputs the first 14 ones and zeros. This is because it removes any leading zeros. Why does it do this? Well, python doesn't use a fixed size for integers like many other languages. The ints might be any number of bytes in practice, depending on the system and implementation. So instead of 00000000000000001111111111111111 becoming 11111111111111110000000000000000, it becomes 1111111111111111 instead
type: Answer
score: 0
upvote count: 1

http://stackoverflow.com/q/50052940
accepted answer: http://stackoverflow.com/a/50053050
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/50053050
has answer: http://stackoverflow.com/a/50053078
type: AnsweredQuestion
score: 0
has title: Adding column in df with function
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50053051
has body: Date Visitor V_PTS Home H_PTS \ 0 2012-10-30 19:00:00 Washington Wizards 84 Cleveland Cavaliers 94 1 2012-10-30 19:30:00 Dallas Mavericks 99 Los Angeles Lakers 91 2 2012-10-30 20:00:00 Boston Celtics 107 Miami Heat 120 3 2012-10-31 19:00:00 Sacramento Kings 87 Chicago Bulls 93 4 2012-10-31 19:30:00 Houston Rockets 105 Detroit Pistons 96 Trying to add on to a scraped dataset to do an analysis on NBA game attendance. I'm trying to add a few columns such as arena played and also capacity. Here is a piece of the function I wrote to add the arena. Is there a better way to do this? I have the dates in datetime so how would I extract the year properly to assign the right arena to teams who built newer arenas in the last few years(Sacramento Kings). Also is there anyway to add stadium capacity to this and kill two birds with one stone instead of creating another function? def label_arena (hometeam): if hometeam == 'Toronto Raptors' : return 'Air Canada Centre' if hometeam == 'Miami Heat' : return 'American Airlines Arena' if hometeam == 'Dallas Mavericks' : return 'American Airlines Center' if hometeam == 'Orlando Magic' : return 'Amway Center' if hometeam == 'San Antonio Spurs' : return 'AT&amp;T Center' if hometeam == 'Indiana Pacers' : return 'Bankers Life Fieldhouse' if hometeam == 'Brooklyn Nets' : return 'Barclays Center' if hometeam == 'Milwaukee Bucks' : return 'Bradley Center' if hometeam == 'Washington Wizards' : return 'Capital One Arena' if hometeam == 'Oklahoma City Thunder' : return 'Chesapeake Energy Arena' if hometeam == 'Memphis Grizzlies' : return 'FedExForum' if hometeam == 'Sacramento Kings' and df['Date'] &lt; 2016: return 'Sleep Train Arena' if hometeam == 'Sacramento Kings' and df['Date'] &gt; 2016: return 'Golden 1 Center'
has answer: http://stackoverflow.com/a/50053051
has comment: http://stackoverflow.com/comment/87122283
type: Question
has comment: http://stackoverflow.com/comment/87122386
has comment: http://stackoverflow.com/comment/87122445
tagged with: datetime

http://stackoverflow.com/q/49929070
score: 1
upvote count: 1
tagged with: keras
favorite count: 0
type: AnsweredQuestion
has body: I've been looking for simple implementations of triplet embedding in deep learning. I wanted to use Keras as it is what I am slightly more familiar (although still very inexperienced in it). Here is a reference on one of the inspiration works: paper on embedded triplets I've found a pretty good example to start off with, working with the mnist dataset, as far as I can tell it is working pretty well. Problems arise on the implementation of the merge of the 3 embedded layers. def build_model(input_shape): base_input = Input(input_shape) x = Conv2D(32, (3, 3), activation='relu')(base_input) x = MaxPooling2D((2, 2))(x) x = Conv2D(64, (3, 3), activation='relu')(x) x = MaxPooling2D((2, 2))(x) x = Dropout(0.25)(x) x = Flatten()(x) x = Dense(2, activation='linear')(x) embedding_model = Model(base_input, x, name='embedding') anchor_input = Input(input_shape, name='anchor_input') positive_input = Input(input_shape, name='positive_input') negative_input = Input(input_shape, name='negative_input') anchor_embedding = embedding_model(anchor_input) positive_embedding = embedding_model(positive_input) negative_embedding = embedding_model(negative_input) inputs = [anchor_input, positive_input, negative_input] outputs = [anchor_embedding, positive_embedding, negative_embedding] triplet_model = Model(inputs, outputs) triplet_model.add_loss(K.mean(triplet_loss(outputs))) triplet_model.compile(loss=None, optimizer='adam') # &lt;-- CRITICAL LINE return embedding_model, triplet_model With the currently implementation the loss is added through model.add_loss and I haven't find many examples like this. The real issue though, is that I cannot load the saved model. The lines triplet_model.save('triplet.h5') model = load_model('triplet.h5') return: ValueError: The model cannot be compiled because it has no loss to optimize. Adding a parameter to the 'loss' argument raises another error when I try to compile the model. I wanted to ask how can I circumvent this issue or if there is a better way …
tagged with: deep-learning
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49931396
has title: Triplet embedded layer with custom (None) loss on Keras 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49931396

http://stackoverflow.com/a/49962255
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86940727
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86941141
score: 3
answers question: http://stackoverflow.com/q/49962221
type: Answer
has body: The problem is that you are opening the file outF with the w flag but should use the a flag instead. changing outF = open("C:\\Users\\####\\Desktop\\bnc.txt", "w") to outF = open("C:\\Users\\####\\Desktop\\bnc.txt", "a") should solve the problem. You could also use w+ which will not truncate the file the way w does. But here's another idea altogether (which will work with w) #!/usr/bin/env python3 import glob import xml.etree.ElementTree as ET filenames = glob.glob("C:\\Users\\####\\Desktop\\BNC2\\[A00-A0B]*.xml") out_lines = [] for filename in filenames: with open(filename, 'r', encoding="utf-8") as content: tree = ET.parse(content) root = tree.getroot() for w in root.iter('w'): lemma = w.get('hw') pos = w.get('pos') tag = w.get('c5') out_lines.append(w.text + "," + lemma + "," + pos + "," + tag) with open("C:\\Users\\####\\Desktop\\bnc.txt", "w") as out_file: for line in out_lines: out_file.write("{}\n".format(line))
accepted answer of: http://stackoverflow.com/q/49962221

http://stackoverflow.com/q/50040470
tagged with: python
has body: Let's say I have the following DataFrame, where the data column contains a nested JSON string that I want to parse into separate columns: import pandas as pd df = pd.DataFrame({ 'bank_account': [101, 102, 201, 301], 'data': [ '{"uid": 100, "account_type": 1, "account_data": {"currency": {"current": 1000, "minimum": -500}, "fees": {"monthly": 13.5}}, "user_name": "Alice"}', '{"uid": 100, "account_type": 2, "account_data": {"currency": {"current": 2000, "minimum": 0}, "fees": {"monthly": 0}}, "user_name": "Alice"}', '{"uid": 200, "account_type": 1, "account_data": {"currency": {"current": 3000, "minimum": 0}, "fees": {"monthly": 13.5}}, "user_name": "Bob"}', '{"uid": 300, "account_type": 1, "account_data": {"currency": {"current": 4000, "minimum": 0}, "fees": {"monthly": 13.5}}, "user_name": "Carol"}' ]}, index = ['Alice', 'Alice', 'Bob', 'Carol'] ) df I've found the json_normalize function, and am currently parsing the JSON in a list comprehension; the result is correct, but this takes long. 1000 rows take 1-2 seconds, and I have about a million rows in my real run: import json from pandas.io.json import json_normalize parsed_df = pd.concat([json_normalize(json.loads(js)) for js in df['data']]) parsed_df['bank_account'] = df['bank_account'].values parsed_df.index = parsed_df['user_id'] parsed_df Is there a faster way to parse this data into a nice-looking DataFrame?
score: 15
has title: How to parse a pandas column of JSON content efficiently?
type: AnsweredQuestion
tagged with: performance
answer count: 3
has answer: http://stackoverflow.com/a/70887230
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50041860
possible better answer: http://stackoverflow.com/a/62932035
tagged with: http://stackoverflow.com/tag/json
upvote count: 15
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50041860
has answer: http://stackoverflow.com/a/62932035

http://stackoverflow.com/q/49978208
accepted answer: http://stackoverflow.com/a/49978402
tagged with: cmake
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/34795816
type: AnsweredQuestion
upvote count: 9
score: 8
tagged with: c++
type: Question
has comment: http://stackoverflow.com/comment/86978083
answer count: 1
has title: Python and C++: How to use pybind11 with Cmakelists including GSL libraries
tagged with: pybind11
has body: I want to be able to call my C++ code as a python package. To do this I am using pybind11 with CMakelists (following this example https://github.com/pybind/cmake_example). My problem is that I have to include GSL libraries in the compilation of the code, and these need an explicit linker -lgsl . If I were just to compile and run the C++ without wrapping it with python, the following Cmakelists.txt file does the job cmake_minimum_required(VERSION 3.0) set(CMAKE_BUILD_TYPE Debug) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") project(myProject) add_executable( myexecutable main.cpp function1.cpp ) find_package(GSL REQUIRED) target_link_libraries(myexecutable GSL::gsl GSL::gslcblas) but when using pybind11 the template I found doesn't allow the add_executable therefore target_link_libraries doesn't work. I have trie this project(myProject) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED YES) # See below (1) # Set source directory set(SOURCE_DIR "project") # Tell CMake that headers are also in SOURCE_DIR include_directories(${SOURCE_DIR}) set(SOURCES "${SOURCE_DIR}/functions.cpp") # Generate Python module add_subdirectory(lib/pybind11) pybind11_add_module(namr ${SOURCES} "${SOURCE_DIR}/bindings.cpp") FIND_PACKAGE(GSL REQUIRED) target_link_libraries(GSL::gsl GSL::gslcblas) but this produces errors in the building. Any idea ?
tagged with: python
has answer: http://stackoverflow.com/a/49978402

http://stackoverflow.com/comment/87086377
type: AnswerComment
comment on: http://stackoverflow.com/a/50034543
has text: I wanted to agree with you because that was also what I initially thought. But I noticed in my final results that 70 out of 2600 unique IDs have an extra different random key with a small chance. For example, ID 2000000247 received 0.0545 from `random.seed(2000000247); random.random()` 99.9% of time but also received a random key 0.8412. I ran the code many many times, it seems that the inconsistency is also random.
type: Comment
score: 0

http://stackoverflow.com/comment/86862281
type: QuestionComment
has text: Am I missing something, or do you expect us to look at this unreadable code and tell you what it does without any means whatsoever to run it?
comment on: http://stackoverflow.com/q/49923302
score: 1
type: Comment

http://stackoverflow.com/comment/87013596
score: 0
type: Comment
type: AnswerComment
has text: You can write it as `map(list, zip(*[l[i:i+n] for i in range(0,len(l),n)]))`
comment on: http://stackoverflow.com/a/49998627

http://stackoverflow.com/comment/87163747
has text: `errors=` is from a python **3** `open` statement, you are clearly trying to run python 3 code on python 2.
comment on: http://stackoverflow.com/q/50073511
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50023853
tagged with: icons
favorite count: 0
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I would like to have a QMessageBox with a moving GIF as icon. So I made this: from PyQt5.QtGui import * from PyQt5.QtWidgets import * import os import sys def msg_wait(s): msg = QMessageBox() msg.setIconPixmap(QPixmap('wait.gif').scaledToWidth(100)) msg.setText(s) msg.setWindowTitle(" ") msg.setModal(False) # msg.setStandardButtons(QMessageBox.Ok) msg.show() return msg class SurfViewer(QMainWindow): def __init__(self, parent=None): super(SurfViewer, self).__init__() self.parent = parent self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.msg=msg_wait('blablabla') self.msg.setStandardButtons(QMessageBox.Cancel) def main(): app = QApplication(sys.argv) ex = SurfViewer(app) ex.setWindowTitle('NMM Stimulator') ex.showMaximized() ex.show() # ex.move(0, 0) # ex.resizescreen() sys.exit(app.exec_( )) if __name__ == '__main__': main() where the GIF is : But the result is a fixed image. How can I make it animated? I tried something with the QMovie class but I wasn't able to set it in the QMessageBox.setIconPixmap function
tagged with: qmessagebox
has answer: http://stackoverflow.com/a/50028443
tagged with: python
has title: How do I integrate an animated GIF in a QMessageBox?
type: Question
upvote count: 2
tagged with: pyqt
answer count: 1
accepted answer: http://stackoverflow.com/a/50028443
tagged with: pyqt5

http://stackoverflow.com/q/49963360
type: Question
has comment: http://stackoverflow.com/comment/126695049
has body: I have a python program that is running in process A; and I have a shell script like this: #!/bin/bash # Kill the process A # Do something... # Start the process A Actually I want to execute the above shell script from my python program (process A) to kill the process A, do some operations and restart the python program again. I have used the subprocess module to achieve this: subprocess.Popen("./script.sh") The problem is that when the shell script code kills the process A, the process in which the shell script is running, is killed too and the operations is not done. Now my question is How can I start a process B from process A and kill the process A from within the process B, but the process B continues running?
linked to: http://stackoverflow.com/q/49663124
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86942878
has title: Start a new process and Killing the current process in python
linked to: http://stackoverflow.com/q/27624850
score: 2
tagged with: python-2.7
answer count: 0
has comment: http://stackoverflow.com/comment/86942731
upvote count: 2
linked to: http://stackoverflow.com/q/13592219
linked to: http://stackoverflow.com/q/35831291
downvote count: 0
favorite count: 0
tagged with: multiprocessing

http://stackoverflow.com/comment/87106594
type: AnswerComment
comment on: http://stackoverflow.com/a/50045011
has text: You can use `word.islower()` rather than `word.lower() != word`
score: 1
type: Comment

http://stackoverflow.com/comment/86877160
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49929841
has text: Instead of softmax, I want to add a regression layer

http://stackoverflow.com/a/57753523
has body: An alternative without installing Jupyter inside your venv is: $ python -m venv projectname $ source projectname/bin/activate (venv) $ pip install ipykernel (venv) $ ipython kernel install --user --name=projectname (venv) $ conda install -c conda-forge spacy (venv) $ jupyter notebook Credits: https://anbasile.github.io/programming/2017/06/25/jupyter-venv/
score: 0
answers question: http://stackoverflow.com/q/49933974
type: Answer

http://stackoverflow.com/comment/87223054
type: Comment
comment on: http://stackoverflow.com/a/50018487
score: 0
type: AnswerComment
has text: C:\Program Files\Python35\Scripts> pyinstaller main.py main.py is my py code and '...scripts' is the path where pyinstaller is installed, and where I put the py code too I just saw a youtube running exactly like that but for me it does not work. all the venv settings I dd through pycharm, but I have no idea how to access them from outside pycharm and also how it should help my create an exe file

http://stackoverflow.com/comment/86915361
comment on: http://stackoverflow.com/a/49948522
has text: How did you come up with the .5 and 2/5 in the offset?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50037919
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87099442
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/50339467
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50339467
has comment: http://stackoverflow.com/comment/87137507
tagged with: python
has body: I want to construct a variational autoencoder where one sample is an N*M matrix where for each row, there are M categories. Essentially one sample is a list of categorical data where only one category can be selected - a list of one-hot vectors. Currently, I have a working autoencoder for this type of data - I use a softmax on the last dimension to create this constraint and it works (reconstruction cross entropy is low). Now, I want to use tf.distributions to create a variational autoencoder. I was wondering what kind of distribution would be appropriate.
has title: What tensorflow distribution to represent a list of categorical data
answer count: 1

http://stackoverflow.com/comment/86913730
score: 1
has text: No problem. Glad to help!
comment on: http://stackoverflow.com/a/49944258
type: Comment
type: AnswerComment

deconvolution
type: Tag
tags question: http://stackoverflow.com/q/49941091
tag name: deconvolution

http://stackoverflow.com/comment/86929595
type: AnswerComment
comment on: http://stackoverflow.com/a/49955631
has text: Thank you for the response. I'm having quite a trouble figuring out how to redirect the invalid form back to the template. Could you please add some light in that regard. And also, Im not saving UserProfile instance because it is linked via a OneToOneField with the User and is automatically created when User is created for which I have mentioned in its model.
score: 0
type: Comment

http://stackoverflow.com/q/49964379
has title: How to find the nearest neighbour index from one series to another
tagged with: python
tagged with: knn
score: 4
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50068909
has comment: http://stackoverflow.com/comment/87151479
tagged with: vectorization
tagged with: nearest-neighbor
favorite count: 0
has answer: http://stackoverflow.com/a/50068909
type: AnsweredQuestion
has body: I have a target array A, which represents isobaric pressure levels in NCEP reanalysis data. I also have the pressure at which a cloud is observed as a long time series, B. What I am looking for is a k-nearest neighbour lookup that returns the indices of those nearest neighbours, something like knnsearch in Matlab that could be represented the same in python such as: indices, distance = knnsearch(A, B, n) where indices is the nearest n indices in A for every value in B, and distance is how far removed the value in B is from the nearest value in A, and A and B can be of different lengths (this is the bottleneck that I have found with most solutions so far, whereby I would have to loop each value in B to return my indices and distance) import numpy as np A = np.array([1000, 925, 850, 700, 600, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10]) # this is a fixed 17-by-1 array B = np.array([923, 584.2, 605.3, 153.2]) # this can be any n-by-1 array n = 2 What I would like returned from indices, distance = knnsearch(A, B, n) is this: indices = [[1, 2],[4, 5] etc...] where 923 in A is matched to first A[1]=925 and then A[2]=850 and 584.2 in A is matched to first A[4]=600 and then A[5]=500 distance = [[72, 77],[15.8, 84.2] etc...] where 72 represents the distance between queried value in B to the nearest value in A e.g. distance[0, 0] == np.abs(B[0] - A[1]) The only solution I have been able to come up with is: import numpy as np def knnsearch(A, B, n): indices = np.zeros((len(B), n)) distances = np.zeros((len(B), n)) for i in range(len(B)): a = A for N in range(n): dif = np.abs(a - B[i]) ind = np.argmin(dif) indices[i, N] = ind + N distances[i, N] = dif[ind + N] # remove this neighbour from from future consideration np.delete(a, ind) return indices, distances array_A = np.array([1000, 925, 850, 700, 600, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10]) array_B = np.array([923, 584.2, 605.3, 153.2]) neighbours = 2 indices, distances = knnsearch(array_A, array_B, …
has comment: http://stackoverflow.com/comment/87160365

http://stackoverflow.com/comment/87086655
comment on: http://stackoverflow.com/a/50034964
type: Comment
has text: @SarthakTuteja in view try to change `context={'posts': post }` and in template `{% for post in posts %}`
score: 0
type: AnswerComment

http://stackoverflow.com/a/50012407
has comment: http://stackoverflow.com/comment/124665415
has comment: http://stackoverflow.com/comment/87083136
upvote count: 6
has comment: http://stackoverflow.com/comment/87057774
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/50004602
has body: &gt;&gt;&gt; from nltk import word_tokenize, ngrams &gt;&gt;&gt; s = "foo bar sentence" # Word ngrams. &gt;&gt;&gt; list(ngrams(word_tokenize(s), 2)) [('foo', 'bar'), ('bar', 'sentence')] # Character ngrams. &gt;&gt;&gt; list(ngrams(s, 2)) [('f', 'o'), ('o', 'o'), ('o', ' '), (' ', 'b'), ('b', 'a'), ('a', 'r'), ('r', ' '), (' ', 's'), ('s', 'e'), ('e', 'n'), ('n', 't'), ('t', 'e'), ('e', 'n'), ('n', 'c'), ('c', 'e')]
type: Answer

http://stackoverflow.com/q/49923800
has body: I am trying to detect outliers in my data-set with 5000 observations and 800 features. I have followed the simple steps told in http://scikit-learn.org/stable/auto_examples/ensemble/plot_isolation_forest.html There are some examples in stackoverflow and other sources as well, however, I could not find a decent explanation about the interpretation of outliers returned by isolationforest. First, what I did is: from sklearn.ensemble import IsolationForest X_train = trbb[check_cols] clf = IsolationForest(n_jobs=6,n_estimators=500, max_samples=256, random_state=23) clf.fit(X_train) y_pred_train = clf.predict(X_train) y_pred_train This returns array([1, 1, 1, ..., 1, 1, 1]) where -1's are the outliers. The shape of y_pred_train is 5000, which is identical with X_train[0]. So the index of -1 corresponds to the index of X_train. For exp. one of the outlier indices returned by IF is 532. So this means that the point (in 800 dimensional space) in this index is detected as an outlier. After detecting this, how can I approach and use the results to dig more? For example, can I reach the most important features causing the outliers?
tagged with: outliers
downvote count: 0
tagged with: anomaly-detection
has title: Finding outliers via scikit-learn's isolation forest (IF)
tagged with: scikit-learn
tagged with: python
answer count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/49962296
has answer: http://stackoverflow.com/a/65738134
tagged with: python
type: AnsweredQuestion
score: 2
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49963899
has title: Stripe API; {'error': 'invalid_grant', 'error_description': 'This authorization code has already been used
downvote count: 0
has answer: http://stackoverflow.com/a/49963899
tagged with: flask
tagged with: stripe-payments
favorite count: 0
has body: I'm using Stripe API and I'm trying to save the connect account keys in db. But I cannot save them successfully and a weird thing is happening. My code is here resp = stripe_connect_service.get_raw_access_token(method='POST', data=data) connect_account_info = json.loads(resp.text) connect_public_key = connect_account_info['stripe_publishable_key'] connect_access_token = connect_account_info['access_token'] connect_user_id = connect_account_info['stripe_user_id'] connect_refresh_token = connect_account_info['refresh_token'] print(connect_public_key) print(connect_access_token) print(connect_user_id) print(connect_refresh_token) form = Form() if form.validate_on_submit(): data = Data(connect_public_key=connect_public_key, connect_access_token=connect_access_token, connect_user_id=connect_user_id, connect_refresh_token=connect_refresh_token) db.session.add(data) db.session.commit() So after getting the token and finished submitting the form on the page rediercted from Stripe Connect page, I will save the data. print actually shows the connect account keys, but after submitting the form, the error says connect_public_key = connect_account_info['stripe_publishable_key'] KeyError: 'stripe_publishable_key' even though print does work. And when I run debugger, the error says like this {'error': 'invalid_grant', 'error_description': 'This authorization code has already been used. How can I fix this error?
type: Question
possible better answer: http://stackoverflow.com/a/65738134

http://stackoverflow.com/a/56562832
has body: I found a working solution, even though it required a lot of work, compared to what I wanted to do. I did the following : class EnhancedInt(int): """ Does everything a int can do, but can also be addressed bitwise (you can read, write, add and delete a bit at given position) Bit representation is in little endian : the lowest indexes corresponding to the least significant bits """ def __init__(self, x: Union[str, bytes, SupportsInt]) -&gt; None: int.__init__(int(x)) self.__value__ = int(x) def __getitem__(self, key: int) -&gt; int: """Returns the digit number *key* from the binary representation of *self* (little endian) Args: key (int): bit number to be returned Returns: int: value of the bit addressed """ EnhancedInt._check_key_value(key) return (self.__value__ &gt;&gt; key) &amp; 1 def __setitem__(self, key: int, value: int) -&gt; None: """Changes the value of the *key*th bit of *self* (little endian) Args: key (int): index of bit to be modified value (int): bit value (must be 0 or 1) """ EnhancedInt._check_key_value(key) if value != 0 and value != 1: raise ValueError("Value must be 0 or 1, %d given" % value) if (not self[key]) and value: self.__value__ += 1 &lt;&lt; key return None if self[key] and not value: self.__value__ -= 1 &lt;&lt; key I also redefines all the methods used for the class int. This method seems overkill, and has other flaws. I'd like to find a more elegant way, but meanwhile, this will to. The complete code can be found at the following address : https://github.com/assombrance/Quantomatic/blob/master/src/data.py
accepted answer of: http://stackoverflow.com/q/49958474
answers question: http://stackoverflow.com/q/49958474
type: Answer
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/99715728

http://stackoverflow.com/comment/87047600
has text: try `app = Celery("draft1", broker=BROKER_URL)` If you still face same issue then show you project directory structure.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50015628

http://stackoverflow.com/a/49949067
has comment: http://stackoverflow.com/comment/86914699
has body: Your current issue is that you are trying to use letters as indices. To fix your current approach, you could use enumerate while looping through each of your strings. If you want a much simpler approach, you can make use of str.maketrans and str.translate. These two builtin functions help easily solve this problem: import string unenc = string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz decd = unenc[::-1] # zyxwvutsrqponmlkjihgfedcba secrets = str.maketrans(unenc, decd) s = "Yvzs!" print(s.translate(secrets)) Output: Yeah! If you want a looping approach, you can use try and except along with string.index() to achieve a much simpler loop: import string unenc = string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz decd = unenc[::-1] # zyxwvutsrqponmlkjihgfedcba s = "Yvzs!" word = '' for i in s: try: idx = unenc.index(i) except: idx = -1 word += decd[idx] if idx != -1 else i print(word) Output: Yeah!
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86916593
answers question: http://stackoverflow.com/q/49948956

http://stackoverflow.com/comment/87072950
type: Comment
score: 0
has text: @Zaico Click on the recapcha once, tell them you are not a bot and try again :)
type: AnswerComment
comment on: http://stackoverflow.com/a/50028162

http://stackoverflow.com/q/50054034
tagged with: python
tagged with: tweepy
score: 0
answer count: 2
tagged with: sentiment-analysis
has body: Just to preface, this code is from a great guy on Github / Youtube: https://github.com/the-javapocalypse/ I made some minor tweaks for my personal use. One thing that has always stood between myself and sentiment analysis on twitter is the fact that so many bots posts exist. I figure if I cannot avoid the bots altogether, maybe I can just remove duplication to hedge the impact. For example - "#bitcoin" or "#btc" - Bot accounts exist under many different handles posting the same exact tweet. It could say "It's going to the moon! Buy now #btc or forever regret it! Buy, buy, buy! Here's a link to my personal site [insert personal site url here]" This would seem like a positive sentiment post. If 25 accounts post this 2 times per account, we have some inflation if I am only analyzing the recent 500 tweets containing "#btc" So to my question: What is an effective way to remove duplication before writing to the csv file? I was thinking of inputting a simple if statement and point to an array to check if it exists already. There is an issue with this. Say I input 1000 tweets to analyze. If 500 of these are duplication from bots, my 1000 tweet analysis just became a 501 tweet analysis. This leads to my next question What is a way to include a check for duplication and if there is duplication add 1 each time to my total request for tweets to analyze. Example - I want to analyze 1000 tweets. Duplication was found one time, so there are 999 unique tweets to include in the analysis. I want the script to analyze one more to make it 1000 unique tweets (1001 tweets including the 1 duplicate) Small change, but I think it would be effective to know how to remove all tweets with hyperlinks embedded. This would play into the objective of question 2 by compensating for dropping hyperlink tweets. Example - I want to analyze 1000 tweets. 500 of the 1000 have embedded URLs. The 500 are removed from the analysis. I am now down to 500 tweets. I still want 1000. Script needs to keep fetching…
has title: Twitter Sentiment Analysis - Remove bot duplication for more accurate results
type: Question
has answer: http://stackoverflow.com/a/50054099
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53887895

http://stackoverflow.com/q/50026918
accepted answer: http://stackoverflow.com/a/50027108
type: AnsweredQuestion
score: 0
has title: How to extract exact frequencies from signal?
answer count: 1
has body: I have a 1D signal array. This array holds information about some features that I want to analyze with np.fft. As an example I tried the following: My function should be the simple sine wave lambda x : sin(x), in theory when I put an input array through this function I would get a signal array, which when transformed with an fft should tell me that the main component from that signal was (in pseudocode) signal = 1* sin(x). So far I couldnt get any wiser from any of the answers here so I put this question up. Now my question: How do I get the "raw" sine component weights from my signal ? This is where I'm stuck: &gt;&gt;&gt; y = f(x) &gt;&gt;&gt; fqs = np.fft.fft(y) &gt;&gt;&gt; fqs array([ 3.07768354+0.00000000e+00j, 3.68364588+8.32272378e-16j, 8.73514635-7.15951776e-15j, -7.34287625+1.04901868e-14j, -2.15156054+5.10742080e-15j, -1.1755705 +4.87611209e-16j, -0.78767676+3.40334406e-16j, -0.58990993+4.25167217e-16j, -0.476018 -3.43242308e-16j, -0.40636656+1.13055751e-15j, -0.36327126+1.55440604e-16j, -0.33804202-1.07128132e-16j, -0.32634218+2.76861429e-16j, -0.32634218+8.99298797e-16j, -0.33804202+5.02435797e-16j, -0.36327126-1.55440604e-16j, -0.40636656-3.06536611e-16j, -0.476018 -4.57882679e-17j, -0.58990993+4.31587904e-16j, -0.78767676+9.75500354e-16j, -1.1755705 -4.87611209e-16j, -2.15156054-1.87113952e-15j, -7.34287625+1.79193327e-15j, 8.73514635-6.76648711e-15j, 3.68364588-6.60371698e-15j]) &gt;&gt;&gt; np.abs(_) array([3.07768354, 3.68364588, 8.73514635, 7.34287625, 2.15156054, 1.1755705 , 0.78767676, 0.58990993, 0.476018 , 0.40636656, 0.36327126, 0.33804202, 0.32634218, 0.32634218, 0.33804202, 0.36327126, 0.40636656, 0.476018 , 0.58990993, 0.78767676, 1.1755705 , 2.15156054, 7.34287625, 8.73514635, 3.68364588]) &gt;&gt;&gt; where do I find my 1*sin(x) ?
tagged with: signal-processing
tagged with: fft
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50027108

http://stackoverflow.com/comment/86935672
comment on: http://stackoverflow.com/q/49959630
has text: **this is not a good practice** Why are you concerned with that? You're just trying to be as fast as possible, this sometimes precludes good style.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50053576
answer count: 1
downvote count: 0
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/87123914
score: 1
accepted answer: http://stackoverflow.com/a/50053706
favorite count: 0
type: Question
has title: pyqt5 calling function does not give same results
has answer: http://stackoverflow.com/a/50053706
has comment: http://stackoverflow.com/comment/87123694
has comment: http://stackoverflow.com/comment/87123727
tagged with: python
type: AnsweredQuestion
has body: I am trying to develop a GUI to show my robot and obstacles around it. I created a class GUI and it has a member function showObstacle to show obstacle. Since I want to keep all the obstacles in place, I create new obstacle object in a vector to store all the objects. I called this function in class's init function to test and it was successful. But when I call this function in different class, it doesn't show the obstacles on the GUI window. In class TCP_Connection (where I get information about the robot), I created myGui class and I called showObstacle function. After debugging, it turns out it creates the Obstacle Objects whenever it is called, but it doesn't display it on the window #this is file 1, GUI Class import sys from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget from PyQt5.QtCore import Qt from pynput import keyboard class App(QWidget): def __init__(self, OtherWindow): super().__init__() self.setGeometry(100,100,440,800) self.setWindowTitle("New GUI Interface Window") self.currentState = 0 self.obstCounter = 0 self.d = [] #testing showObstacle self.showObstacle(205, 305) #this works self.showObstacle(210,315) #this also works self.show() def showObstacle(self, Obs_x, Obs_y): self.obstImage = QtGui.QImage('obsta_edited.png') self.pixmap_obst = QtGui.QPixmap(self.obstImage) self.d.append("O{0}".format(self.obstCounter)) self.d[self.obstCounter] = QtWidgets.QLabel(self) self.d[self.obstCounter].setPixmap(self.pixmap_obst) self.d[self.obstCounter].move(Obs_x, Obs_y) self.d[self.obstCounter].adjustSize() self.obstCounter += 1 print(self.d) print("Obstacle Run") this is the calling class from myGUI import App from PyQt5.QtWidgets import QWidget,QLabel,QLineEdit, QHBoxLayout,QVBoxLayout,QMainWindow,QPushButton, QFrame, QDesktopWidget, QApplication from PyQt5.Qt import QStackedLayout import sys, random class TCP_Communication: def __init__(self): super().__init__() self.openWindow() def openWindow(self): se…
has comment: http://stackoverflow.com/comment/87123715
tagged with: pyqt

http://stackoverflow.com/comment/87090259
type: AnswerComment
comment on: http://stackoverflow.com/a/50026609
score: 0
type: Comment
has text: You are welcome. Does it answer your question @RomaJain ?

http://stackoverflow.com/q/50043285
tagged with: pygame
has title: Python: AttributeError: 'Settings' object has no attribute 'screen'
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87103265
upvote count: 1
has body: I have problem with AttributeError: 'Settings' object has no attribute 'screen'. Please help me, code below: class Settings(): def __init__(self): self.screen_width=1200 self.screen_height=800 self.bg_color=(230,230,230) import sys import pygame from settings import Settings def run_game(): pygame.init() ai_settings=Settings() screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen.height)) pygame.display.set_caption("Inwazja obcych") while True: screen.fill(ai_settings.bg_color) for event in pygame.event.get(): if event.type==pygame.quit: sys.exit() pygame.display.flip() run_game()
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50043318
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87032385
type: Comment
type: AnswerComment
has text: Yeah, that one blew it out of the water! Thanks for your input, easy and smart to sort axis = 1 and boolean following that, didnt think of it that way.
score: 1
comment on: http://stackoverflow.com/a/50001649

http://stackoverflow.com/a/50076430
has comment: http://stackoverflow.com/comment/87173844
upvote count: 3
answers question: http://stackoverflow.com/q/50069902
has comment: http://stackoverflow.com/comment/87172499
downvote count: 0
has comment: http://stackoverflow.com/comment/87179040
has comment: http://stackoverflow.com/comment/87173492
has comment: http://stackoverflow.com/comment/87173475
has comment: http://stackoverflow.com/comment/87174622
has comment: http://stackoverflow.com/comment/87172473
has comment: http://stackoverflow.com/comment/87173539
has body: Vim has four features that can be used to complete imports in Python: :help 'include' tells Vim how to recognize an "include" in your code. The default value for Python (^\s*\(from\|import\)) is reasonable. :help 'define' can be used to tell Vim how a definition is supposed to look. There's no Python-specific default value but the following would be a good start: :set define=^\\s*def :help compl-define lets you complete from the definitions gathered in included files with &lt;C-x&gt;&lt;C-d&gt;. Or you could customize :help 'complete' to include definitions and simply use &lt;C-p&gt; or &lt;C-n&gt;: :set complete+=d :help 'path' tells Vim where to look for files when you do :find or gf or include/define completion. For it to be of any use, though, 'path' must be set carefully. Everything is here and relatively easy to set up, but there certainly are Python plugins that do all that for you in a smarter way.
has comment: http://stackoverflow.com/comment/87175025
has comment: http://stackoverflow.com/comment/87181832
has comment: http://stackoverflow.com/comment/87176035
has comment: http://stackoverflow.com/comment/87173555
type: Answer
has comment: http://stackoverflow.com/comment/87179216
has comment: http://stackoverflow.com/comment/87173723
score: 3
has comment: http://stackoverflow.com/comment/87174756
has comment: http://stackoverflow.com/comment/87175865

http://stackoverflow.com/q/50008122
has title: How to build a pandas dataframe (or dict) in an efficient way by selecting some lists of data from another bigger dataframe?
type: Question
tagged with: numpy
tagged with: python-3.x
has body: I need to create a DataFrame or dictionary. If N = 3 (number of lists inside other list) the expected output is this: d = { 'xs0': [[7.0, 986.0], [17.0, 6.0], [7.0, 67.0]], 'ys0': [[79.0, 69.0], [179.0, 169.0], [729.0, 69.0]], 'xs1': [[17.0, 166.0], [17.0, 116.0], [17.0, 126.0]], 'ys1': [[179.0, 169.0], [179.0, 1169.0], [1729.0, 169.0]], 'xs2': [[27.0, 276.0], [27.0, 216.0], [27.0, 226.0]], 'ys2': [[279.0, 269.0], [279.0, 2619.0], [2579.0, 2569.0]] } For this I have programmed the following code. But I need this code to run faster: import numpy as np import pandas as pd df_dict = { 'X1': [1, 2, 3, 4, 5, 6, 7, 8, np.nan], 'Y1': [9, 29, 39, 49, np.nan, 69, 79, 89, 99], 'X2': [11, 12, 13, 14, 15, 16, 17, 18, np.nan], 'Y2': [119, 129, 139, 149, np.nan, 169, 179, 189, 199], 'X3': [21, 22, 23, 24, 25, 26, 27, 28, np.nan], 'Y3': [219, 229, 239, 249, np.nan, 269, 279, 289, 299], 'S': [123, 11, 123, 11, 123, 123, 123, 35, 123], 'C': [9, 8, 7, 6, 5, 4, 3, 2, 1], 'F': [1, 1, 1, 1, 2, 3, 3, 3, 3], 'OTHER': [10, 20, 30, 40, 50, 60, 70, 80, 90], } bigger_df = pd.DataFrame(df_dict) plots = [ { 'x': 'X1', 'y': 'Y1', }, { 'x': 'X2', 'y': 'Y2', }, { 'x': 'X3', 'y': 'Y3', } ] N = 3 d = {} s_list = [123, 145, 35] n = 0 for p in plots: # INITIALIZATES THE DICTIONARY ELEMENTS d['xs{}'.format(n)] = [[] for x in range(N)] d['ys{}'.format(n)] = [[] for x in range(N)] # BUILDS THE LISTS FOR THOSE ELEMENTS for index in range(3): df = bigger_df.filter([p['x'], p['y'], 'S', 'F', 'C']) # selects the minimum of columns needed df = df[df['F'].isin([2, 3, 4, 9]) &amp; df[p['x']].notnull() &amp; df[p['y']].notnull() &amp; (df.S == s_list[index])] df.sort_values(['C'], ascending=[True], inplace=True) d['xs{}'.format(n)][index] = list(df[p['x']]) d['ys{}'.format(n)][index] = list(df[p['y']]) n += 1 print(d) I am wondering if instead of building the dictionary on a loop I could do some trick with pandas or numpy. If the result is a pandas dataframe rather than a dictionary is also good for me, or even …
has answer: http://stackoverflow.com/a/50025959
has comment: http://stackoverflow.com/comment/87033644
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87032980
accepted answer: http://stackoverflow.com/a/50025959
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/87032859

http://stackoverflow.com/q/49995552
has comment: http://stackoverflow.com/comment/87013316
type: Question
has comment: http://stackoverflow.com/comment/87008107
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: selenium-webdriver
score: 0
tagged with: pytest
has answer: http://stackoverflow.com/a/49999953
has body: I am using below fixture in conftest.py for open and close browser : conftest.py: @pytest.fixture(scope='session') def browser(): print("Setting up webdriver connection...") global driver if driver is None: profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True profile.set_preference("network.proxy.type",1) driver = webdriver.Firefox(firefox_profile=profile) driver.maximize_window() yield driver driver.quit() print("Webdriver connection closed..") In my Test Class I have below step test_login : def test_login(self, browser): login_page = pagep.LoginPage(browser) login_page.login('hptest376@gmail.com', "test12345*") login_page.login('user', "pwd") assert "Sum" in browser.title And after test_login I have one more test step in my Test Class: def test_ppt(a): a=12 print a Issue : I am getting error in fixture at driver.quit() and browser is not closing. If I remove the "test_ppt(a)" step after "test_login(self, browser)" then the test runs fine. Want to know what i need to update in my fixture "browser()" so that driver.quit() is executed.
has title: Pytest fixture not able to quit the test after execution in python pytest

http://stackoverflow.com/a/50080801
accepted answer of: http://stackoverflow.com/q/50057787
type: Answer
has body: In answer form: The doc is just wrong. divmod does what its builtin equivalent does.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50057787
score: 1

http://stackoverflow.com/q/49958308
type: Question
has answer: http://stackoverflow.com/a/49958403
has answer: http://stackoverflow.com/a/49958448
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86933175
tagged with: python
has comment: http://stackoverflow.com/comment/86932936
has comment: http://stackoverflow.com/comment/86932872
has title: No input prompt
score: 0
answer count: 2
tagged with: python-3.5
has body: Why am I getting no prompt for input when I run this in IDE 3.5 #Main function - discovered in parts from Felicia London def main(): # get the celsius input to convert F1,F2 = eval(input("Enter range for celsius\n")) #print the table header print("Celsius\tFahrenheit") print("Celsius\tFahrenheit") #print the table header print("Celsius\tFahrenheit") #invoke the c to f function celsiusToFahrenheit(fl,f2) #get the fahrenheit input to convert Gl,G2 = eval(input("Enter range for fahrenheit temp")) #print the table header print("Farenheit\tCelcius") print("Fahrenheit\tCelsius")
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50066699
answers question: http://stackoverflow.com/q/50066306
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50066306
downvote count: 0
upvote count: 1
score: 1
has body: Since you have not attempted to make your application first, then I am not going to post code for you. I will however, suggest using: urllib2: A robust module for interacting with webpages. i.e. pull back the html of a webpage. BeautifulSoup (from bs4 import BeautifulSoup): An awesome module to "regex" html to find what is is that you're looking for. Good luck my friend!

http://stackoverflow.com/comment/87083070
type: QuestionComment
has text: how do we know which ones to find and replace? also why is lit3r changed to litr3. and what should happen to centeeerr and centeerrr?
score: 0
comment on: http://stackoverflow.com/q/50033317
type: Comment

http://stackoverflow.com/a/50054206
answers question: http://stackoverflow.com/q/50054160
downvote count: 0
upvote count: 1
has body: As you have it, d is a tuple: &gt;&gt;&gt; type(d) &lt;class 'tuple'&gt; But the first element is a dict: &gt;&gt;&gt; type(d[0]) &lt;class 'dict'&gt; so you can do: pd.DataFrame(data=d[0]) Which returns: Events Number1 Number2 Time 0 ABC xx 1 77 1 DEF xx 1 39 2 GHI 1 xx 15 3 JKL xx 1 21 4 ABC xx xx 21 5 DEF xx 2 64 6 GHI 2 xx 84 7 JKL xx 2 60
type: Answer
score: 1

http://stackoverflow.com/comment/87676034
type: AnswerComment
comment on: http://stackoverflow.com/a/50037402
score: 0
type: Comment
has text: What if I don't want to remember my previous string for e.g. "Version1", I only know that I need to update my version for e.g "Version2" after the string "@VERSION Version2". Can I do that?Simply I don't know the previous version.

timestamp
tags question: http://stackoverflow.com/q/50055360
tags question: http://stackoverflow.com/q/50031872
type: Tag
tag name: timestamp
tags question: http://stackoverflow.com/q/49940538
tags question: http://stackoverflow.com/q/50018415
tags question: http://stackoverflow.com/q/49997700
tags question: http://stackoverflow.com/q/50050810

http://stackoverflow.com/q/49972053
answer count: 2
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49972078
upvote count: 1
has answer: http://stackoverflow.com/a/49972078
favorite count: 0
type: Question
has body: I have a problem with a list in python that I need to convert to a matrix. The list is always random so I have no Idea how to make it. Here's an example : ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '\n', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1', '\n', '1', ' ', ' ', '1', ' ', ' ', '1', '1', '1', '1', '\n', '1', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1', '\n', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '\n', '\n'] And I want it to look like a matrix so that for each '\n' it would make a new list : [['1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1'], ['1', ' ', ' ', '1', ' ', ' ', '1', '1', '1', '1'], ['1', ' ', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1'], ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']] I have no idea how to make this so somebody could help please?
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49972085
has answer: http://stackoverflow.com/a/49972085
tagged with: python
has title: make a matrix from a list in python
type: AnsweredQuestion

http://stackoverflow.com/comment/86935523
type: QuestionComment
comment on: http://stackoverflow.com/q/49959531
has text: no problem. `Happy Coding`!
score: 0
type: Comment

http://stackoverflow.com/q/50071618
type: UnansweredQuestion
tagged with: python
has title: Dynamically changing the message of raw_input
upvote count: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87159923
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/50071941
score: 1
has comment: http://stackoverflow.com/comment/87160055
downvote count: 1
answer count: 1
tagged with: raspberry-pi3
favorite count: 0
type: Question
has body: I'm looking to move a motorised slider using a Raspberry Pi. However, while debugging the system I was wondering if it is possible to use: target = int(raw_input(&lt;message&gt;)) In a way that message could dynamically change before the user inputs a value. For me, it would be great to see the current value that is read from the slider in this &lt;message&gt; for example. And if that isn't possible, is it possible to have a line printed above or below the raw_input that remains changing while the system waits for the users' input?
linked to: http://stackoverflow.com/q/30929661

http://stackoverflow.com/comment/86987343
type: QuestionComment
type: Comment
has text: Too broad of a question for Stackoverflow. Please check [asking](https://stackoverflow.com/help/asking)
comment on: http://stackoverflow.com/q/49985453
score: 0

http://stackoverflow.com/q/50064066
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/50064508
tagged with: python
tagged with: admin
favorite count: 0
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/12354099
has answer: http://stackoverflow.com/a/50064508
answer count: 1
tagged with: django
has body: My question is the following: can you exclude objects that are duplicated from being displayed on the admin page without DB modification, and if yes, how? Thanks for all the help in advance
has title: Exclude duplicates from django admin page
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87145810

http://stackoverflow.com/q/50011969
tagged with: python
linked to: http://stackoverflow.com/q/48335699
favorite count: 0
score: 2
has body: When using an estimator in tensorflow and passing the inputs using tf.estimator.inputs.numpy_input_function(), what are the names of the tensors being created for the features and labels' inputs. If I print out the name of all the placeholders in my graph I get the following: name: "enqueue_input/Placeholder" name: "enqueue_input/Placeholder_1" name: "enqueue_input/Placeholder_2" However, the shape of those tensors were not specified so I cannot tell which is which or why there are 3 of them instead of only one features and one labels tensors. I realize this question was also asked here: TensorFlow: What are the input nodes for tf.Estimator models But no one answered.
tagged with: deep-learning
tagged with: tensorflow
has title: Tensorflow Estimator API Input Tensor Names
type: Question
has answer: http://stackoverflow.com/a/50012537
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89117979
downvote count: 0
answer count: 1
tagged with: machine-learning

http://stackoverflow.com/q/49996738
tagged with: python
has comment: http://stackoverflow.com/comment/87009906
score: 0
has body: I run into trouble when making a text encryption program in python I use both AES then I also use FERNET my code is: from cryptography.fernet import Fernet key = Fernet.generate_key() f = Fernet(key) token = f.encrypt(b"this is my text") print(token) the problem is that I want the text "this is my text" is came from the use but I wasn't able to solve this because of the letter b need any fix with this same in AES there is a b I can't solve how to make it from user input
answer count: 0
has comment: http://stackoverflow.com/comment/87010271
has comment: http://stackoverflow.com/comment/87010339
has comment: http://stackoverflow.com/comment/87010693
tagged with: pycrypto
type: Question
has comment: http://stackoverflow.com/comment/87010319
linked to: http://stackoverflow.com/q/7585435
has title: AES python encryption and Fernet Encryption problem
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/7585435
tagged with: encryption

http://stackoverflow.com/a/49921242
type: Answer
has comment: http://stackoverflow.com/comment/86864530
score: 0
answers question: http://stackoverflow.com/q/49920056
type: AcceptedAnswer
has body: tl;dr Your code is fine, no need to use urllib. The reason why you are getting "stripped" URL is that this is not the initial URL you're looking for. Explanation If you examine requests source code, you can find that r.url is Final URL location of Response So r.url is not the URL you requested, this is URL you have been (finally) redirected to. You can make a simple test: from requests import Request, Session url = 'https://www.booking.com/searchresults.html' # your url params = { # I intentionally shortened this dict for testing purposes 'checkin_monthday': '19', 'checkin_year': '2018', 'checkout_monthday': '20', 'checkout_year': '2018', } req = Request('GET', url, params=params) prepped = req.prepare() print(prepped.url) # you send this URL ... s = Session() resp = s.send(prepped) print(resp.url) # ... but you are redirected to this URL (same as your r.url) Output: https://www.booking.com/searchresults.html?checkin_year=2018&amp;checkin_monthday=19&amp;checkout_monthday=20&amp;checkout_year=2018 https://www.booking.com/ What happens here: You python script sends request with all your parameters. Server processes you request and responds with HTTP/1.1 301 Moved Permanently. Redirect location can be found in headers: Location: https://www.booking.com/searchresults.html?dest_id=-1022488;est_type=city;ss=Pokhara. requests receives this response and goes to this location. The location URL is put to r.url attribute. That's why initial URL and final URL are different.
accepted answer of: http://stackoverflow.com/q/49920056

http://stackoverflow.com/comment/86894220
score: 0
comment on: http://stackoverflow.com/q/49939282
has text: Here's the full traceback error: Traceback (most recent call last): File "I:\Harry\[Scripts]\013 - [Blackstone Changes]\3. Split Invoice & SuppDocs.py", line 280, in <module> split(path, filename) File "I:\Harry\[Scripts]\013 - [Blackstone Changes]\3. Split Invoice & SuppDocs.py", line 115, in split pdf = pyPdf.PdfFileReader(open(os.path.join(path, filename), 'rb'), strict=False) TypeError: __init__() got an unexpected keyword argument 'strict'
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49998198
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/87013083
possible better answer: http://stackoverflow.com/a/49998719
favorite count: 0
accepted answer: http://stackoverflow.com/a/49998412
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87012657
has answer: http://stackoverflow.com/a/49998412
has body: test_str = "Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at anу timе bеfore Арril 28? Indicаtоr: 60.76%" print(test_str) print(test_str.split('before ')) This the output I get after spliting "['Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at an\xd1\x83 tim\xd0\xb5 b\xd0\xb5fore \xd0\x90\xd1\x80ril 28? Indic\xd0\xb0t\xd0\xber: 60.76%']" Demo: https://repl.it/repls/VitalOrganicBackups
tagged with: python
has comment: http://stackoverflow.com/comment/87012572
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49998719
answer count: 2
has comment: http://stackoverflow.com/comment/87013004
has comment: http://stackoverflow.com/comment/87012588
has title: Why does the string change when using python split?
upvote count: 3
has comment: http://stackoverflow.com/comment/87012829

http://stackoverflow.com/q/50047844
tagged with: pandas
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50047891
accepted answer: http://stackoverflow.com/a/50047891
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50048723
has title: How to separate a dataframe according to column value
has answer: http://stackoverflow.com/a/50048723
tagged with: dataframe
tagged with: python
has body: I have a dataframe called raw and it looks like the following: I'm trying to separate the main data frame into two separate data frames (ex. df1 and df2) based on whether BDA is null or not. How can I do this while preserving the other rows?
score: 0
answer count: 2
tagged with: pandas-groupby

http://stackoverflow.com/a/49954887
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49954777
accepted answer of: http://stackoverflow.com/q/49954777
has comment: http://stackoverflow.com/comment/86926551
has body: df = pd.DataFrame(dict(answers=['Yes', 'No', 'no', 'noo', 'yeah', 'Yes, No'])) def typos(l): probs = [e for e in l if e not in ['Yes', 'No']] return ', '.join(probs) if probs else 0 &gt;&gt;&gt; df.answers.str.split(', ').apply(typos) 0 0 1 0 2 no 3 noo 4 yeah 5 0 Name: answers, dtype: object In case your column is mixed-type (i.e., not all entries are strings), you might need to first convert it to a sting, i.e., df.answers.astype(str).str.split(', ').apply(typos)
score: 1
has comment: http://stackoverflow.com/comment/86926475
has comment: http://stackoverflow.com/comment/86926397
has comment: http://stackoverflow.com/comment/86926440
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49972651
has answer: http://stackoverflow.com/a/49972698
has answer: http://stackoverflow.com/a/49972680
has body: How can you combine multiple columns from a dataframe into a list? Input: df = pd.DataFrame(np.random.randn(10000, 7), columns=list('ABCDEFG')) If I wanted to create a list from column A I would perform: df1 = df['A'].tolist() But if I wanted to combine numerous columns into this list it wouldn't be efficient write df['A','B','C'...'Z'].tolist() I have tried to do the following but it just adds the columns headers to a list. df1 = list(df.columns)[0:8] Intended input: A B C D E F G 0 0.787576 0.646178 -0.561192 -0.910522 0.647124 -1.388992 0.728360 1 0.265409 -1.919283 -0.419196 -1.443241 -2.833812 -1.066249 0.553379 2 0.343384 0.659273 -0.759768 0.355124 -1.974534 0.399317 -0.200278 Intended Output: [0.787576, 0.646178, -0.561192, -0.910522, 0.647124, -1.388992, 0.728360, 0.265409, -1.919283, -0.419196, -1.443241, -2.833812, -1.066249, 0.553379, 0.343384, 0.659273, -0.759768, 0.355124, -1.974534, 0.399317, -0.200278]
linked to: http://stackoverflow.com/q/11285613
upvote count: 1
tagged with: python
has title: How to combine multiple columns from a pandas df into a list
has comment: http://stackoverflow.com/comment/86961457
accepted answer: http://stackoverflow.com/a/49972698
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86961474
answer count: 2
possible better answer: http://stackoverflow.com/a/49972680
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/86961891
favorite count: 0
type: Question

http://stackoverflow.com/comment/87162024
has text: WARNING: No route found for IPv6 destination :: (no default route?) Traceback (most recent call last): File "ssid-sniffer-scapy-python.py", line 16, in <module> sniff(iface="mon0", prn = PacketHandler)
type: Comment
comment on: http://stackoverflow.com/q/50061845
score: 0
type: QuestionComment

http://stackoverflow.com/q/50071144
has comment: http://stackoverflow.com/comment/87481657
favorite count: 0
type: Question
has body: new_df['year'].describe() count 10866.000000 mean 2004.009939 std 14.958790 min 1968.000000 25% 1996.000000 50% 2006.000000 75% 2012.000000 max 2067.000000 Name: year, dtype: float64 It seems like the erroneous year values are +100 years off (ie, 2067 should probably be 1967). Therefore, for values above 2018, how do I [year - 100] while leaving the rest of the values untouched?
tagged with: pandas
tagged with: dataframe
tagged with: python
has title: Conditional replace in pandas dataframe
has answer: http://stackoverflow.com/a/50071165
score: 0
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87034100
score: 0
comment on: http://stackoverflow.com/a/50002342
type: Comment
has text: Thanks you very much for your comment. I've spent some time on the documentation of flask-sockets and socketio but got lost
type: AnswerComment

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/50015458
type: Tag
tags question: http://stackoverflow.com/q/49964981
tags question: http://stackoverflow.com/q/50009978
tags question: http://stackoverflow.com/q/49930830
tags question: http://stackoverflow.com/q/50036522

http://stackoverflow.com/q/49984553
tagged with: matrix
answer count: 1
favorite count: 0
type: Question
has title: Reading Matrix File (mtx) using Python: not enough values to unpack
accepted answer: http://stackoverflow.com/a/50318363
has body: I want to read a ".mtx file" using Python. The matrix file (31x31) is given by a transportation simulation tool (visum). I used the following code: from scipy.io import mmread A = mmread('./saclay/demand_visum.mtx') I got the message: ValueError: not enough values to unpack (expected 5, got 1) Thanks a lot for your help.
upvote count: 2
has answer: http://stackoverflow.com/a/50318363
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion

imagedownload
tag name: imagedownload
type: Tag
tags question: http://stackoverflow.com/q/49974970

http://stackoverflow.com/q/49994020
has body: This post is closer to my problem but it did nt goes that way which i had hope: How to split strings into text and number? I have a string which is like this: 'Legal Leaves 2017' I am trying to split into string and year by using this technique: import re match = re.match(r"([a-z]+)([0-9]+)", 'Legal Leaves 2017', re.I) match.groups() But i am not getting any result which means my regular expression is incorrect. Kindly help.
downvote count: 1
favorite count: 0
tagged with: split
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49994091
accepted answer: http://stackoverflow.com/a/49994060
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49994091
tagged with: regex
linked to: http://stackoverflow.com/q/430079
has comment: http://stackoverflow.com/comment/87004325
has answer: http://stackoverflow.com/a/49994060
has title: How to split string and date using regular expression
has comment: http://stackoverflow.com/comment/87004348
type: AnsweredQuestion
score: 0
tagged with: string

http://stackoverflow.com/q/49947109
tagged with: python-xarray
type: AnsweredQuestion
score: 0
has body: When I assign the result of xr.ones_like to a Dataset variable, I lose some of my data assigned to coordinates: import xarray as xr import numpy as np A, B, C = 2, 3, 4 ds = xr.Dataset() ds.coords['source'] = (['a', 'b', 'c'], np.random.random((A, B, C))) ds.coords['unrelated'] = (['a', 'c'], np.random.random((A, C))) print('INITIAL:', ds['unrelated'], '\n') # do 'ones_like' manually ds['dest-1'] = (['a', 'b'], np.ones((A, B))) print('AFTER dest-1:', ds['unrelated'], '\n') ds['dest-2'] = xr.ones_like(ds['source'].isel(c=0)) print('AFTER dest-2:', ds['unrelated'], '\n') Output: INITIAL: &lt;xarray.DataArray 'unrelated' (a: 2, c: 4)&gt; array([[0.185851, 0.962589, 0.772985, 0.570292], [0.905792, 0.865125, 0.412361, 0.666977]]) Coordinates: unrelated (a, c) float64 0.1859 0.9626 0.773 0.5703 0.9058 0.8651 ... Dimensions without coordinates: a, c AFTER dest-1: &lt;xarray.DataArray 'unrelated' (a: 2, c: 4)&gt; array([[0.185851, 0.962589, 0.772985, 0.570292], [0.905792, 0.865125, 0.412361, 0.666977]]) Coordinates: unrelated (a, c) float64 0.1859 0.9626 0.773 0.5703 0.9058 0.8651 ... Dimensions without coordinates: a, c AFTER dest-2: &lt;xarray.DataArray 'unrelated' (a: 2)&gt; array([0.185851, 0.905792]) Coordinates: unrelated (a) float64 0.1859 0.9058 Dimensions without coordinates: a Why did unrelated lose a dimension after using xr.ones_like?
has answer: http://stackoverflow.com/a/49948042
tagged with: python
accepted answer: http://stackoverflow.com/a/49948042
answer count: 1
has title: Why does assigning `xr.ones_like` to a DataSet variable change unrelated coordinates?
type: Question

http://stackoverflow.com/a/50050216
answers question: http://stackoverflow.com/q/50049111
score: 0
has body: This loop structure should be able to create the structure you would like to have. It has to be changed to write to files. Here the length of the generated sequence or the position of the output that was generated is part of the same structure that you would like to print into a file: #!/usr/bin/env python row1 = ["F{i}".format(i=i) for i in range(1,11)] row1.append("label") row2 = ["a{i}".format(i=i) for i in range(1,11)] row2.append("L1") row3 = ["b{i}".format(i=i) for i in range(1,11)] row3.append("L2") for SequenceLength in range(1, len(row1)): for SequencePositionStart in range(len(row1)): if row1[SequencePositionStart:SequenceLength] == []: continue print(','.join(row1[SequencePositionStart:SequenceLength]), row1[-1], sep=",") print(','.join(row2[SequencePositionStart:SequenceLength]), row2[-1], sep=",") print(','.join(row3[SequencePositionStart:SequenceLength]), row3[-1], sep=",")
type: Answer

webbrowser-control
type: Tag
tag name: webbrowser-control
tags question: http://stackoverflow.com/q/50059421

http://stackoverflow.com/q/50032238
type: Question
has answer: http://stackoverflow.com/a/50032615
tagged with: python
has comment: http://stackoverflow.com/comment/87120227
has title: Infinite Loop in War Card Game Simulator
has body: I'm trying to simulate a (tiny) game of War! as an exercise in OOP. I have a loop that plays two decks against each other, but it seems to loop forever, repeating the same sequence again and again. The output gets to the point where one deck has 4 card objects in it, and then the loop repeats. The loop should only be running when both Drawpile objects are greater than zero. ranks = [2,3,4,5,6,7,8,9,10,11,12,13,14] #for use of value comparison via index suits =['Diamonds','Hearts','Clubs','Spades'] rounds = 0 class Card: def __init__(self, rank, suit): self.rank = rank assert rank in ranks assert suit in suits self.suit = suit def __repr_(self): return '{} of {}'.format(self.rank,self.suit) def __str__(self): return '{} of {}'.format(self.rank,self.suit) def __eq__(self, other): if self.rank == other.rank: return True else: return False def __gt__(self, other): #gt compared via ordering of ranks index if self.rank &gt; other.rank: return True else: return False def __lt__(self, other): if self.rank &lt; other.rank: return True else: return False class Drawpile: def __init__(self, pile =[]): self.pile = pile def __len__(self): return len(self.pile) def __getitem__(self, n): return self.pile[n] def add(self, n): self.pile.append(n) def draw(self): if len(self) &lt;= 0: return None return self.pile.pop(0) dp1 = Drawpile([Card(2,'Diamonds'),Card(13,'Hearts'),Card(7,'Clubs')]) dp2 = Drawpile([Card(4,'Hearts'),Card(3,'Hearts'),Card(8,'Spades')]) while len(dp1) &gt; 0 and len(dp2) &gt; 0: rounds += 1 c1 = dp1.draw() c2 = dp2.draw() print('Round ',rounds) print('c1',c1, len(dp1)) print('c2',c2, len(dp2)) if c1 &gt; c2: dp1.add(c1) dp1.add(c2) else: dp2.add(c1) dp2.add(c2) if len(dp1) &gt; len(dp2): print('Pile 1 Won!') else: print('Pile 2 Won!') Can anyone tell me where exactly this loop is getting stuck? I've tried diagramming it out and this is my second rewrite. Any ideas?
has comment: http://stackoverflow.com/comment/87080635
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87080637
tagged with: oop
has comment: http://stackoverflow.com/comment/87080817
answer count: 1
accepted answer: http://stackoverflow.com/a/50032615

http://stackoverflow.com/a/49942512
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86901522
answers question: http://stackoverflow.com/q/49942464
score: 6
has comment: http://stackoverflow.com/comment/86902038
has body: You can use pd.Series.isin for this: res = df[df['Channel'].isin({'A', 'B'})] print(res) # Rec Channel Value1 Value2 # 2 Event A 23 39.0 # 4 Post A 79 11.0 # 5 Post B 88 69.0 To return the second row by index: res2 = res.loc[2] print(res2) # Rec Event # Channel A # Value1 23 # Value2 39 # Name: 2, dtype: object
accepted answer of: http://stackoverflow.com/q/49942464
upvote count: 6
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86995126
has text: Please post the code you tried, along with the error you got.
comment on: http://stackoverflow.com/q/49989288
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86871952
score: 0
comment on: http://stackoverflow.com/a/49927895
type: AnswerComment
has text: I just thought i'd better sort functions into different classes (or we can say categories in my case) so not to make a mess in future when there will be a lot of functions in one file. But thanks for the answer and suggestion. It worked!
type: Comment

http://stackoverflow.com/a/49956409
has body: Coroutine objects, the result of calling async def functions, need to be associated with futures to get access to the returned value. There are several ways of doing this, but if you have a list of coroutine objects, you can use asyncio.gather: twitterData = twitterEngine.lookupTweets(tweets) future = asyncio.gather(*twitterData) loop = asyncio.get_event_loop() loop.run_until_complete(future) print(future.result())
downvote count: 0
has comment: http://stackoverflow.com/comment/86935625
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49953441
has comment: http://stackoverflow.com/comment/86935462
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86934907
answers question: http://stackoverflow.com/q/49953441
has comment: http://stackoverflow.com/comment/86942718
has comment: http://stackoverflow.com/comment/86935290
has comment: http://stackoverflow.com/comment/86935496

http://stackoverflow.com/a/49964248
type: Answer
accepted answer of: http://stackoverflow.com/q/49964078
score: 0
has comment: http://stackoverflow.com/comment/86944676
has body: you're continually appending to l in s_sum so even though you are removing the first element when you call the function you add an element after... you can just remove the l.append part and it works: def s_sum(l): if l == []: return 0 else: print(l[:]) # print(s_sum(l[1:])) return sum_numbers(l[0])) + s_sum(l[1:]) def sum_numbers(l): if l == []: return 0 elif type(l[0]) is int: return l[0] + sum_numbers(l[1:]) elif isinstance( l[0], str ): return sum_numbers(l[1:]) else: return sum_numbers(l[0]) + sum_numbers(l[1:]) but there's an easier way to do all this sum in one function: def recursive_sum(l): result = 0 for i in l: if type(i) is list: result += recursive_sum(i) elif type(i) is int: result += i return result
has comment: http://stackoverflow.com/comment/86948202
answers question: http://stackoverflow.com/q/49964078
type: AcceptedAnswer

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/49932904
tags question: http://stackoverflow.com/q/50037096
tags question: http://stackoverflow.com/q/49931788
tags question: http://stackoverflow.com/q/50042707
tags question: http://stackoverflow.com/q/49945799
type: Tag

http://stackoverflow.com/q/50000399
has answer: http://stackoverflow.com/a/50000911
has comment: http://stackoverflow.com/comment/87020401
upvote count: 3
has comment: http://stackoverflow.com/comment/87016795
tagged with: file-io
has comment: http://stackoverflow.com/comment/87016838
has comment: http://stackoverflow.com/comment/87016931
score: 1
has comment: http://stackoverflow.com/comment/87016879
answer count: 4
favorite count: 0
type: Question
has title: File not found from Python although file exists
has answer: http://stackoverflow.com/a/53656906
has answer: http://stackoverflow.com/a/76950543
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/67995031
has body: I'm trying to load a simple text file with an array of numbers into Python. A MWE is import numpy as np BASE_FOLDER = 'C:\\path\\' BASE_NAME = 'DATA.txt' fname = BASE_FOLDER + BASE_NAME data = np.loadtxt(fname) However, this gives an error while running: OSError: C:\path\DATA.txt not found. I'm using VSCode, so in the debug window the link to the path is clickable. And, of course, if I click it the file opens normally, so this tells me that the path is correct. Also, if I do print(fname), VSCode also gives me a valid path. Is there anything I'm missing? EDIT As per your (very helpful for future reference) comments, I've changed my code using the os module and raw strings: BASE_FOLDER = r'C:\path_to_folder' BASE_NAME = r'filename_DATA.txt' fname = os.path.join(BASE_FOLDER, BASE_NAME) Still results in error. Second EDIT I've tried again with another file. Very basic path and filename BASE_FOLDER = r'Z:\Data\Enzo\Waste_Code' BASE_NAME = r'run3b.txt' And again, I get the same error. If I try an alternative approach, os.chdir(BASE_FOLDER) a = os.listdir() then select the right file, fname = a[1] I still get the error when trying to import it. Even though I'm retrieving it directly from listdir. &gt;&gt; os.path.isfile(a[1]) False

http://stackoverflow.com/q/50054989
has comment: http://stackoverflow.com/comment/87149441
has comment: http://stackoverflow.com/comment/87126693
has comment: http://stackoverflow.com/comment/87150110
has comment: http://stackoverflow.com/comment/87150462
tagged with: tensorflow
tagged with: precision
has comment: http://stackoverflow.com/comment/87149736
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87151204
has title: Tensorflow and Python: Why two same operations have small error in output
has comment: http://stackoverflow.com/comment/87147273
tagged with: python
has comment: http://stackoverflow.com/comment/87126728
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/87150417
has body: I was working on tf.matmul op with multidimensional input arguments. For example given in code below, import tensorflow as tf import numpy as np nn_arch = [100,1200] batch_size = 128 n_ = np.random.normal(size=[batch_size,nn_arch[1],nn_arch[0]]) w_ = np.random.normal(size=[nn_arch[1],nn_arch[0]]) x_ = np.random.normal(size=[batch_size,nn_arch[0],1]) n = tf.constant(n_) w = tf.constant(w_) x = tf.constant(x_) nw = n + w c = tf.matmul(nw,x) sess = tf.InteractiveSession() c_ = np.zeros(shape=[batch_size,nn_arch[1],1]) for i in range(batch_size): c_[i,:] = (n_[i,:,:] + w_).dot(x_[i,:,:]) print(sess.run(c)-c_) print(np.max(np.abs(sess.run(c)-c_))) This function will print the last line with value of the order of 1e-15. Why is there a this small amount of difference between two ops, that are basically doing same calculations at same precision float64?
has comment: http://stackoverflow.com/comment/87144726
score: 0
answer count: 0
duplicate of: http://stackoverflow.com/q/588004

http://stackoverflow.com/comment/87013520
type: Comment
type: QuestionComment
has text: You should profile your code and determine where the bottlenecks are (and what would speed it up the most). Otherwise what you're doing is little more guessing.
score: 0
comment on: http://stackoverflow.com/q/49998268

http://stackoverflow.com/q/50028727
favorite count: 0
has body: I am looking to isolate the top 2 values per group for the following data. Brand | Product | Rank A | P1 | 1000 | P2 | 1210 | P3 | 2000 | P4 | 600 | P5 | 756 | P6 | 867 B | P1 | 549 | P2 | 1572 | P3 | 3490 | P4 | 2341 | P5 | 431 | P6 | 321 C | P1 | 421 | P2 | 121 | P3 | 805 | P4 | 1202 | P5 | 4032 | P6 | 432 I want to be able to the top 2 values for each group (A, B, C). Top_Products = df.nlargest(2, 'Rank') This however only isolates the top 2 products. Is there a way to get the top 2 products per Brand. Desired Output: Brand | Product | Rank A | P3 | 2000 | P2 | 1210 B | P3 | 3490 | P4 | 2341 C | P5 | 4032 | P4 | 1202 Thanks!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50028789
accepted answer: http://stackoverflow.com/a/50028789
tagged with: pandas
has comment: http://stackoverflow.com/comment/87073670
score: 7
duplicate of: http://stackoverflow.com/q/20069009
has comment: http://stackoverflow.com/comment/87073651
type: Question
has comment: http://stackoverflow.com/comment/87109055
linked to: http://stackoverflow.com/q/20069009
linked to: http://stackoverflow.com/q/49983957
answer count: 1
downvote count: 0
tagged with: python
tagged with: sorting
upvote count: 7
has title: Getting the n largest values for groups

http://stackoverflow.com/comment/87027695
score: 0
has text: @GiacomoCatenazzi, the weird characters are usually within ord()>127 and ord()<256, so I have them
comment on: http://stackoverflow.com/q/50001268
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49971395
answers question: http://stackoverflow.com/q/49971340
downvote count: 0
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86958981
has body: You can override the __getitem__ method of an object to implement this alternative behavior: class dict2(dict): def __getitem__(self, k): if isinstance(k, tuple): return tuple(self[x] for x in k) return dict.__getitem__(self, k) Example: &gt;&gt;&gt; d=dict2(a=1, b=2, c=4, d=8) &gt;&gt;&gt; d['a'] 1 &gt;&gt;&gt; d['a', 'd'] (1, 8) &gt;&gt;&gt; d['a', 'b', 'c', 'd'] (1, 2, 4, 8) Note that this will prevent you from using tuples as keys.

http://stackoverflow.com/comment/87040859
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50009710
has text: The OP cannot install `scikit-learn`, how should `sklearn` help? `pip install -U sklearn` installs `scikit-learn` simply because `scikit-learn` is listed as a dependency.
type: Comment

http://stackoverflow.com/a/49948506
type: Answer
answers question: http://stackoverflow.com/q/49948412
score: 0
has body: Some comments: You should include a self is other check, otherwise, under certain conditions, the same object in memory can compare unequal to itself. Here is a demonstration. The instance-check chrisz mentioned in the comments is a good idea as well. The dicts of self and other probably contain many more items than the attributes you are manually checking for in the second version. Therefore, the first one will be slower. (Lastly, but not related to the question, we don't write getters and setters in Python. Access attributes directly with the dot-notation, and if something special needs to happen when getting/setting an attribute, use a property.)

http://stackoverflow.com/a/49994669
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/49994548
upvote count: 3
answers question: http://stackoverflow.com/q/49994548
has body: This is explained in Programming Guidelines in the docs: Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process). In general, what this means is that you want to change the last line of your script from this: main() … to this: if __name__ == '__main__': main() Otherwise, every new child process will start up and immediately try to call main and spawn two new processes. Whether this only goes on deep, or goes infinitely deep and forkbombs your system, or raises an exception depends on all kinds of details that aren't worth getting into, but it will never do the right thing on Windows. If you're wondering why it works on Linux: On Windows, multiprocessing works by launching a completely new Python interpreter and making it import and run your module, so all the top-level code in the module gets run; on Linux, it works by forking a copy of the current interpreter process and then starting the task from there, so it doesn't actually need to rerun the script, so the top-level code usually doesn't get re-executed. In later versions of Python (3.1 is really ancient…), they've cleaned things up a bit, and made them a bit more flexible, so you can do nice things like get the same behavior on both platforms by specifying set_start_method('spawn'). But the basic default results will be the same.

http://stackoverflow.com/q/50061342
score: 42
has answer: http://stackoverflow.com/a/50061489
upvote count: 42
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16739290
has title: Is it possible to reuse python @click.option decorators for multiple commands?
tagged with: python-click
has answer: http://stackoverflow.com/a/67138197
accepted answer: http://stackoverflow.com/a/50061489
has answer: http://stackoverflow.com/a/76464205
downvote count: 0
possible better answer: http://stackoverflow.com/a/70852267
favorite count: 0
has answer: http://stackoverflow.com/a/67740068
type: Question
has answer: http://stackoverflow.com/a/70852267
answer count: 5
has body: I have two Python CLI tools which share a set of common click.options. At the moment, the common options are duplicated: @click.command() @click.option('--foo', is_flag=True) @click.option('--bar', is_flag=True) @click.option('--unique-flag-1', is_flag=True) def command_one(): pass @click.command() @click.option('--foo', is_flag=True) @click.option('--bar', is_flag=True) @click.option('--unique-flag-2', is_flag=True) def command_two(): pass Is it possible to extract the common options in to a single decorator that can be applied to each function?
tagged with: python

http://stackoverflow.com/q/49974708
has title: I can not find a way to click on a button using Python and Selenium
has body: I have a problem, I happen to have a button with these labels, I'm trying to click through Selenium but I can not find a way to click it. I tried to give it taking as reference the XPath, link text, and CSS selector but I do not achieve my goal. This is the code for the button: &lt;a class="btn btn-flat pull-right" data-action="export_report"&gt; &lt;i class = "icon-export"&gt; &lt;/ i&gt; Export &lt;/a&gt; East of the XPath: // * [@ id = "reports"] / div [1] / div [2] / a this selector: #reports&gt; div.span12&gt; div.headline-action-block.pull-right&gt; a This is the button and my code in Python :( Button: My code: I face this error: File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 955, in find_element 'value': value})['value']
has answer: http://stackoverflow.com/a/49975750
has answer: http://stackoverflow.com/a/49977055
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion
tagged with: xpath
tagged with: css-selectors
score: 0
has comment: http://stackoverflow.com/comment/87497284
tagged with: selenium
has comment: http://stackoverflow.com/comment/87392873
tagged with: webdriver
has comment: http://stackoverflow.com/comment/87501888

http://stackoverflow.com/a/49956966
has body: I will try to talk about adversarial examples in a simple way. Basically, for a given example belonging to certain class C_1 , we want to modify this input by adding small value r in such a way that it doesnot change visually much but is classified with very high confidence to another class C_2. To do that you optmize the function: So ideally, we want r to be very small which is obtained by doing L1 regularization over r which is the first part of the equation. And the second term loss is the loss from classifying the input x + r to the new target class C_2. For each iteration while optimizing for loss, x_t = x_(t-1) + r Also make sure x+r is with some range of x i.e allow x to change within some very small range i.e maybe 0.0001. This will give x_t which is an adversarial example to x. I know its confusing but this is all you need to implement the above equation. Hope this helps.
score: 4
has comment: http://stackoverflow.com/comment/87238130
downvote count: 0
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49951492

http://stackoverflow.com/comment/109003592
comment on: http://stackoverflow.com/a/60571991
has text: your code doesn't run. line 29 returns a syntax error for some reason. z = (-normal[0] * xx - normal[1] * yy - d) * 1. / normal[2]. tried it on an external compiler as well, same result
score: 0
type: Comment
type: AnswerComment

memoization
type: Tag
tags question: http://stackoverflow.com/q/49955054
tag name: memoization
tags question: http://stackoverflow.com/q/50029044
tags question: http://stackoverflow.com/q/50055570
tags question: http://stackoverflow.com/q/49929615
tags question: http://stackoverflow.com/q/49957335
tags question: http://stackoverflow.com/q/49933526

http://stackoverflow.com/comment/87135875
comment on: http://stackoverflow.com/a/50057960
type: Comment
score: 0
type: AnswerComment
has text: Is there a way to overcome the "self" parameter error with flask? I am getting a missing argument error while calling the function because of the self parameter I have to use which flask takes it as an extra argument

http://stackoverflow.com/q/50018315
tagged with: python
has answer: http://stackoverflow.com/a/50023433
score: -2
has title: django import error - from . import views in urls under app
has body: I did declare like from . import views in urls.py. To use TemplateView, this urls.py is needed. urls.py from django.urls import path, re_path from . import views app_name = 'scheduler' urlpatterns = [ re_path(r'^service/(?P&lt;status&gt;\w+)', views.SchedulerView.as_view(), name='schedule-service') ] I think nothing but normal implementation. Error occurs like the below. from . import views ImportError: cannot import name 'views' Older versions django did work. But it's not working in django 2.0 App Structure - server - scheduler - templatetags schedule_status.py urls.py models.py views.py - main settings.py urls.py - manage.py I just guess 'scheduler' app's path is incorrect to work "from . import views" Is there anyone who solved or check more things. these problem after django 2.0. ps. sorry, I forgot to add view.py in structure in question. SchedulerView is declared in views.py
upvote count: 0
answer count: 1
tagged with: url
tagged with: import
has comment: http://stackoverflow.com/comment/87052967
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87052984
has comment: http://stackoverflow.com/comment/87053084
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/87052738
tagged with: django

python-xarray
tags question: http://stackoverflow.com/q/49973049
tags question: http://stackoverflow.com/q/49928495
tags question: http://stackoverflow.com/q/50010971
type: Tag
tags question: http://stackoverflow.com/q/50068423
tag name: python-xarray
tags question: http://stackoverflow.com/q/49947109
tags question: http://stackoverflow.com/q/49933327
tags question: http://stackoverflow.com/q/49959850

http://stackoverflow.com/comment/86917152
score: 0
has text: Actually, my list of lists keeps growing throughout the time I run my code. The classification process has to be repeated every time the list populates new nested lists. So it increases the big-O complexity over time. I am trying to find out if there can be any quick filtering process based on column values so that my performance will not drop irrespective of the current dimension of the list.
comment on: http://stackoverflow.com/q/49949960
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86908269
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49945540
has text: @Georgy - i did not think of it this way- thank you :)

webpage-screenshot
type: Tag
tags question: http://stackoverflow.com/q/49971106
tag name: webpage-screenshot

http://stackoverflow.com/comment/86947915
has text: @soon Right. With this line added I'm back with `3.67 ms +/-`. Unfortunately I'm no so good with C to quickly (enough) understand the optimization that is going on there.
type: Comment
comment on: http://stackoverflow.com/q/49965774
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87021142
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49941484
type: QuestionComment
has text: @Gabriel I briefly looked up what a DSL is. Please correct me, if I misinterpret what you suggest: (1) I define a DSL in which modularly define my functions with all conditions in place. (2) Upon initialisation of the simulator, I automatically generate python files with the different function "instances" that are actually needed in the simulation. (3) These functions are then used during runtime and debugging works as expected, since the source files actually exist. (4) After a simulation I can safely throw away the temporary files as I can regenerate them any time given a version number.

http://stackoverflow.com/comment/87040947
type: Comment
type: QuestionComment
has text: In that case you could use a flag in the session: if a user is not logged in, then show the message until he clicks a `dismiss` button (which you store in the session).
score: 0
comment on: http://stackoverflow.com/q/49948280

http://stackoverflow.com/q/50018054
type: UnansweredQuestion
type: Question
downvote count: 0
has title: How to print all rows of a pandas dataframe in the pycharm console?
tagged with: python
duplicate of: http://stackoverflow.com/q/19124601
favorite count: 0
score: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/87053633
has body: An attempt to print 100 rows of a pandas dataframe in the console (i.e. output.iloc[20:120]) returns something like this where there are dots instead of data How can I print the all of the data (no dots)? My goal is to be able to visually inspect the data, so if you have other suggestions please make them. My current workaround is to write a csv and inspect in excel (which, needless to say, is slow and cumbersome)
tagged with: pycharm
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/19124601
has comment: http://stackoverflow.com/comment/87053443

http://stackoverflow.com/comment/86995611
type: Comment
type: AnswerComment
has text: thanks everyone but i will take your responses and look at the notes again
comment on: http://stackoverflow.com/a/49989428
score: 0

http://stackoverflow.com/comment/86854818
type: Comment
comment on: http://stackoverflow.com/a/49919271
has text: That is fine, though I would suggest adding parenthesis for clearer reading. `if (mo[i] > 0 and Wo[i] < 0) or num > 10:` for example would help someone else read your code.
type: AnswerComment
score: 1

http://stackoverflow.com/q/49949849
has title: How to parse the data in tag using beautifulsoup?
accepted answer: http://stackoverflow.com/a/49950905
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49950905
tagged with: python
favorite count: 0
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/49950260
has body: when I am trying to scrape the data from the following website url = https://bedbathandbeyond.ugc.bazaarvoice.com/2009-en_us/1061083288/reviews.djs?format=embeddedhtml&amp;page=4&amp;scrollToTop=true I got this from bedbathbeyond website and if I use request and beautifulsoup, I can't get anything. Why is that? code: r = requests.get(url) soup = BeautifulSoup(r.content,'lxml') soup.find_all('span', class_ = 'BVRRReviewAbbreviatedText') the return value is empty: []
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49950260
has comment: http://stackoverflow.com/comment/86916511
type: Question
answer count: 2

http://stackoverflow.com/a/50060907
accepted answer of: http://stackoverflow.com/q/50060699
upvote count: 4
has comment: http://stackoverflow.com/comment/133420449
has body: Use date2num on the date column Ex: import matplotlib.pyplot as plt from pylab import rcParams import matplotlib.ticker as mtick import matplotlib.dates as mdates from matplotlib.dates import date2num #--&gt;Update import numpy as np import pandas as pd from datetime import datetime, timedelta DF = pd.DataFrame({ 'day': [datetime(2018,1,1).date()+timedelta(x+1) for x in range(100)], 'balance': np.random.normal(100,100,100) }) rcParams['figure.figsize'] = 20, 10 fig, ax = plt.subplots() DF['day'] = DF['day'].apply(date2num) #--&gt;Update ax.bar(DF['day'], DF['balance'], color='lightblue') plt.xlabel('day', fontsize=20) myFmt = mdates.DateFormatter('%Y-%m') ax.xaxis.set_major_formatter(myFmt) plt.show()
answers question: http://stackoverflow.com/q/50060699
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/comment/87034624
type: QuestionComment
comment on: http://stackoverflow.com/q/50009029
has text: sklearn has a fast implementation in [`sklearn.neighbors.DistanceMetric`](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html)
score: 0
type: Comment

http://stackoverflow.com/comment/87081188
has text: First, you almost never want to call dunder methods like `__iter__` and `__next__`. Use `it = iter(items)` and `next(it)`. Also, you should check `spam is None`, or sometimes `not spam`, but never `spam == None` except in very rare cases.
comment on: http://stackoverflow.com/q/50032481
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50056073
tagged with: plot
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50060697
downvote count: 0
accepted answer: http://stackoverflow.com/a/50060697
upvote count: 1
score: 1
tagged with: matplotlib
answer count: 1
has title: Superimpose two seaborn factorplots
has body: I am having difficulties super-imposing (overlaying) two factorplots using the library seaborn. The general problem is that I would like to plot in thin grey lines all the (background data) and then on top in colorful, thicker, lines the data we want to highlight. For one I don't succeed combining the two data-sets in a plot with FacetGrid and secondly I have a problem using zorder. I did a dummy example with the exercise data set: sns.set_style('whitegrid') exercise = sns.load_dataset("exercise") background = exercise.assign(idkind = lambda df: df['id'].astype(str)+df.kind.astype(str)) foreground = exercise.groupby(['kind','time']).mean().reset_index().rename(columns={'id':'idkind'}) Thus far I tried: factorplot + factorplot Plotting two factorplots as if it were sns.pointplot twice analogue to this example. I need to the sns.factorplot due to the experimental setup of the data. This does not work, as simply two independant plots are produced. I basically would want the lower plot on top of the upper plot. g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', legend=False,color='lightgrey',data=background) sns.factorplot(x="time", y="pulse", hue="kind", data=foreground) factorplot + gmap.(factorplot) I thus tried to use sns.factorplot, which I think produces a FacetGrid and g.map a second sns.factorplot on top using a new dataset with the exact same design and categories. The result is, that instead of using the same subplots, it creates a number of rows with a repeated plot. g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', legend=False,color='lightgrey',data=background) g.map(sns.factorplot, x="time", y="pulse",hue='idkind', col='kind', data=foreground) factorplot+ g.map(pointplot) g.map a pointplot, which puts the entire data set in all the subplots, not respecting the design of the FacetGrid. g=sns.factorplot(x="time", y="pulse", hue='idkind', col='kind', legend=False,color='lightgrey',data=background) g.map(sns.pointplot,x="time", y="pu…
favorite count: 0
type: Question
tagged with: facet-grid
linked to: http://stackoverflow.com/q/43799483
tagged with: seaborn
tagged with: python

http://stackoverflow.com/comment/87034686
type: AnswerComment
has text: Thanks, it worked now. I think completely different.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50008988

http://stackoverflow.com/q/50019969
has title: How do I add "args=(...)" into arguments of my own function?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50020104
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: arguments
tagged with: scipy
has body: in scipy there is a function quad(): quad(integrand, 0, 1, args=(a,b)) I have my own function to take integrals using gauss legendgre quadrature, and when I integrate different functions with parameters im kinda tired of adding them. So the question is: is there a way to add an argument args=(...) into arguments of my own function?
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50020104
tagged with: numerical-methods

http://stackoverflow.com/comment/87028899
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50004142
has text: @jasonharper you are right, but I would also like to pass keyword sometimes -- I have edited my question
score: 0

scenekit
tag name: scenekit
tags question: http://stackoverflow.com/q/50070062
type: Tag

http://stackoverflow.com/comment/87028608
score: 0
has text: It might help if you gave the usual FEM statistics - number of elements , nodes, nodes per element, basis functions, dof, size of the stiffness matrix etc. Also are you using just numpy, or scipy sparse? What solver?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49997595

http://stackoverflow.com/comment/87111752
has text: `("params", OrderedDict([..., ("params", OrderedDict([("command", "testing 23")]))]))`
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50047790
type: Comment

http://stackoverflow.com/comment/87133693
has text: Either your `pytesseract` installation is not good or you are not defining the correct path to your image, though I don't think it's the latter since you say the image opens.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50057422

http://stackoverflow.com/q/49949775
type: Question
accepted answer: http://stackoverflow.com/a/50110597
possible better answer: http://stackoverflow.com/a/51199132
has answer: http://stackoverflow.com/a/50110597
has answer: http://stackoverflow.com/a/51199132
tagged with: python
has answer: http://stackoverflow.com/a/56852354
type: AnsweredQuestion
score: 3
upvote count: 3
has title: pybinding cannot import name allow_rasterization
downvote count: 0
has answer: http://stackoverflow.com/a/50540888
has body: I just install pybinding and I'm trying to run the first example that is proposed in the documentation of this library. import pybinding as pb import numpy as np import matplotlib.pyplot as plt import pybinding as pb d = 0.2 # [nm] unit cell length t = 1 # [eV] hopping energy # create a simple 2D lattice with vectors a1 and a2 lattice = pb.Lattice(a1=[d, 0], a2=[0, d]) lattice.add_sublattices( ('A', [0, 0]) # add an atom called 'A' at position [0, 0] ) lattice.add_hoppings( # (relative_index, from_sublattice, to_sublattice, energy) ([0, 1], 'A', 'A', t), ([1, 0], 'A', 'A', t) ) lattice.plot() plt.show() I have already installed what is required in the documentation (for Windows OS) and the sicrpt run pretty well until it has to do the lattice.plot() throwing the following error Traceback (most recent call last): File "prueba.py", line 25, in &lt;module&gt; lattice.plot() File "C:\xampp7\Python\lib\site-packages\pybinding\lattice.py", line 463, in plot axes=axes)) File "C:\xampp7\Python\lib\site-packages\pybinding\results.py", line 598, in plot plot_sites(self.positions, self.sublattices, **props['site']) File "C:\xampp7\Python\lib\site-packages\pybinding\system.py", line 285, in plot_sites from pybinding.support.collections import CircleCollection File "C:\xampp7\Python\lib\site-packages\pybinding\support\collections.py", line 2, in &lt;module&gt; from matplotlib.collections import Collection, allow_rasterization ImportError: cannot import name 'allow_rasterization' I have already check and matplotlib is correctly installed (I try some plots recommended in the documentation of matplotlib and worked pretty well). Also a looked for the file collections.py in the pybinding library and the mistake is in the second line import numpy as np from matplotlib.collections import Collection, allow_rasterization And looking at collections.py of the matplolib and searching for 'allow_rasterization' I found the duplicated 6 time the following function @artist.allow_rasterization d…
tagged with: pybinding
answer count: 4
favorite count: 0

http://stackoverflow.com/q/49941881
has comment: http://stackoverflow.com/comment/86952677
has comment: http://stackoverflow.com/comment/86952897
has comment: http://stackoverflow.com/comment/86908625
tagged with: pygame
tagged with: moviepy
has comment: http://stackoverflow.com/comment/86923959
has comment: http://stackoverflow.com/comment/86945620
has comment: http://stackoverflow.com/comment/86917359
favorite count: 0
has comment: http://stackoverflow.com/comment/86954042
has body: I am making a game using pygame and I wanted to add cut scenes to it. The pygame movie module however doesn’t work anymore so I had to resort to using moviepy. Moviepy isn’t that well documented from what I can see so I’m having some trouble figuring it out. I got it to work using this block of code but all I need now is to full screen it (desired window screen is 640x400). So how would I go about doing so? Thank you in advance. from moviepy.editor import * from pygame import *# Window display WIN_WIDTH = 640 WIN_HEIGHT = 400 HALF_WIDTH = int(WIN_WIDTH / 2) HALF_HEIGHT = int(WIN_HEIGHT / 2) DISPLAY = (WIN_WIDTH, WIN_HEIGHT) DEPTH = 32 FLAGS = FULLSCREEN #display.set_mode(DISPLAY, FLAGS, DEPTH) #define screen values display.set_caption("I'm Working!") Credits = 'Untitled.mp4' def playVid(video): clip = VideoFileClip(video) clip.resize(DISPLAY).preview() return playVid(Credits)
type: Question
has answer: http://stackoverflow.com/a/49969286
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86953570
has comment: http://stackoverflow.com/comment/86953557
has comment: http://stackoverflow.com/comment/86922432
has comment: http://stackoverflow.com/comment/86917753
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/42190332
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86901220
has title: How to resize Moviepy to fullscreen?
has comment: http://stackoverflow.com/comment/86901138
accepted answer: http://stackoverflow.com/a/49969286
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86913198

http://stackoverflow.com/q/50029641
linked to: http://stackoverflow.com/q/46388093
has comment: http://stackoverflow.com/comment/87076288
has title: Libtorrent is downloaded and the Module file exists, pip says it exists, yet I can't import it in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/87169139
type: Question
tagged with: libtorrent
has comment: http://stackoverflow.com/comment/87118454
has body: I am attempting to add libtorrent to my Python. My issue is that even though I have tried many, albeit odd, workarounds (more on this later) to get libtorrent to work with my Python, I cannot for the life of me import the module. I'll walk through what I have tried. I have stumbled upon 'solutions' that have helped me parts of the way, but not all the way through. I even tried to follow the creator's instructions himself provided on Stack Overflow. Let's step a few steps back and observe what I have tried doing. We will start with boost. If you did not know, libtorrent requires boost in order to function. My knowledge is not grand when it comes boost, thus I will leave the explanation out of this. So, much like all instructions I followed, said that boost was required. I promptly installed boost and added its path to the environment table. I subsequently ran the bat file provided in boost and it created two files (possibly more) B2.exe and BJAM . B2 is what I was required to use for the forthcoming steps. I continued by moving into the downloaded boost folder (ver 1.66) > tools > build > example and then editing the user-config.jam file with the additions of these items: using msvc : 14.0 ; using gcc : : : -std=c++11 ; using python : 3.6 : C:\Users\XXXX\AppData\Local\Programs\Python\Python36-32 : C:\Users\XXXX\AppData\Local\Programs\Python\Python36-32\include : C:\Users\XXXX\AppData\Local\Programs\Python\Python36-32\libs ; I then proceeded by opening an elevated x64 Native tool command prompt for VS2017 and executing the following command b2.exe --hash openssl-version=pre1.1 link=shared libtorrent-link=shared stage_module stage_dependencies also provided by Arvid (I believe the creator), in the libtorrent>bindings>python folder This started a 5 minute download period. It gave me the following info: Performing configuration checks - 32-bit : yes (cached) - arm : no (cached) - mips1 : no (cached) - power : no (cached) - sparc : no (cached) - x86 : yes (cached) - symli…
type: UnansweredQuestion
tagged with: pyd
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/87076345
answer count: 0
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87140763

http://stackoverflow.com/comment/87126522
type: Comment
has text: @abarnert I've updated the input and output files :)
comment on: http://stackoverflow.com/q/50054958
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87105279
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50044093
has text: now if you have a better duplicate to suggest, there's still one slot left :)
score: 0

http://stackoverflow.com/comment/87128319
comment on: http://stackoverflow.com/a/50026707
type: AnswerComment
score: 0
has text: This is really great. While the overhead makes it slower compared to the "chunk" answer by @xg.plt.py for small problems, this penalty is minute compared to the massive benefits for large problems. I'm learning so much from this thread, thanks for the insight.
type: Comment

http://stackoverflow.com/q/49942180
linked to: http://stackoverflow.com/q/3100985
has answer: http://stackoverflow.com/a/49942288
accepted answer: http://stackoverflow.com/a/49942288
duplicate of: http://stackoverflow.com/q/3100985
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86900546
tagged with: matplotlib
has title: Python: ValueError: could not convert string to float: 'Service Industries Journal'
has body: I just started to code with Python. I am doing some analysis on a database of papers extracted from the Scopus database. I downloaded the database in .csv and then performed some analyses and filtering on it. After the initial analyses I saved the file in .xlsx which is the current format of the database. I am trying to obtain a graph showing how many times a journal is present in the database. I have extracted the values using the value_counts() command and then I have stored these data into a table with two columns (Journal and Count): journals_count = data['Source_title'].value_counts().reset_index() journals_count.columns = ['Journal', 'Count'] Journal Count 0 IEEE Transactions on Industrial Informatics 40 1 Expert Systems with Applications 37 2 Applied Energy 20 3 International Journal of Production Economics 13 4 Energy and Buildings 11 5 Information Sciences 11 6 International Journal of Information Management 10 7 Decision Support Systems 9 8 International Journal of Advanced Manufacturing 9 9 International Journal of Production Research 8 10 European Journal of Operational Research 7 Now I would like to create a bar chart from this table with the Journal name on the x-axis and the Count value on the y-axis using the following code: import matplotlib.pyplot as plt %matplotlib inline plt.plot(journals_count['Journal'], journals_count['Count']) The problem is that I obtain the following error: ValueError: could not convert string to float: 'Service Industries Journal' 'Service Industries Journal' is the last journal with the Count value equal to 1. How could I plot this into Python?
type: Question

http://stackoverflow.com/q/50040823
favorite count: 0
type: Question
has body: How to use DevTools Capture using Python? There's a code here, but I don't know how to use it for node screenshots. def chrome_takeFullScreenshot(driver): def send(cmd, params): resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id url = driver.command_executor._url + resource body = json.dumps({'cmd': cmd, 'params': params}) response = driver.command_executor._request('POST', url, body) return response.get('value') def evaluate(script): response = send('Runtime.evaluate', {'returnByValue': True, 'expression': script}) return response['result']['value'] metrics = evaluate( \ "({" + \ "width: Math.max(window.innerWidth, document.body.scrollWidth, document.documentElement.scrollWidth)|0," + \ "height: Math.max(innerHeight, document.body.scrollHeight, document.documentElement.scrollHeight)|0," + \ "deviceScaleFactor: window.devicePixelRatio || 1," + \ "mobile: typeof window.orientation !== 'undefined'" + \ "})") print metrics print send('Emulation.setDeviceMetricsOverride', metrics) screenshot = send('Page.captureScreenshot', {'format': 'png', 'fromSurface': True}) send('Emulation.clearDeviceMetricsOverride', {}) return base64.b64decode(screenshot['data'])
tagged with: python
has comment: http://stackoverflow.com/comment/87125240
answer count: 0
has comment: http://stackoverflow.com/comment/87113921
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/87125208
tagged with: devtools
has title: Selenium DevTools Capture node screenshot

http://stackoverflow.com/comment/87089928
type: QuestionComment
comment on: http://stackoverflow.com/q/50036751
has text: @Kasramvd Third code block is pseudocode, I just wanted to write as "substract from first list by comparing its `id` with second lists `user_id`"
score: 0
type: Comment

http://stackoverflow.com/q/50066205
upvote count: 0
has comment: http://stackoverflow.com/comment/87149111
has answer: http://stackoverflow.com/a/50066641
accepted answer: http://stackoverflow.com/a/50066641
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87148926
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29686083
has title: Issues passing arguments to a python script
tagged with: python
score: -1
has body: I have a python script that I want to pass command line arguments. I have taken some guidance from Windows Python Naming Issue and Python Command Line Arguments Tutorial. I don't have any errors that pop up when executing the script, however I don't get the expected error message when no command line arguments are given, nor do I get the print command when the -h command line is given. I have added print commands to the -i and the -s command line arguments as well and have not been able to ever successfully pull through any of the command line arguments (although no errors) I am at a loss why this isn't working, as I am not that experienced with Python. I would be grateful if anyone could point the issue out to me. import re import os import sys import getopt def main(argv): ipaddress = '' scac = '' try: opts, args = getopt.getopt(argv,"hi:s:",["ipaddress=","scac="]) except getopt.GetoptError: print 'test.py -i &lt;ipaddress&gt; -s &lt;scac&gt;' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'FedConnectStatus.py -i &lt;iobipaddress&gt; -s &lt;scac&gt;' sys.exit() elif opt in ("-i", "--ipaddress"): ipaddress = arg elif opt in ("-s", "--scac"): scac = arg
type: AnsweredQuestion

http://stackoverflow.com/comment/86987449
type: QuestionComment
comment on: http://stackoverflow.com/q/49951166
has text: What device model is "Dev1"?
type: Comment
score: 0

http://stackoverflow.com/comment/86892875
type: QuestionComment
type: Comment
score: 0
has text: yes, several subtasks, i want to compare `!= Workspace created` against multiple subtasks names subtask['fields']['summary'].And yes, sometimes it gets None
comment on: http://stackoverflow.com/q/49938446

http://stackoverflow.com/q/50052368
type: Question
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87121259
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/87121268
tagged with: python
has comment: http://stackoverflow.com/comment/87121246
type: AnsweredQuestion
has body: I have a module i've written that contains a function that collects a bunch of inputs, and appends them to a list. This module also contains a bunch of defined turtle functions that need to make use of the list elements. However, I'm getting a syntax error on the turtle functions. This is the exact function that gives me the error (the other turtle functions are similarly written): def draw_circle(turtle, shape_info[5]): turtle.circle(shape_info[5]) List element 5 is the length input the user previously input in the first function. What am I doing wrong? the error is this: Traceback (most recent call last): File "C:\Users\ebarr\OneDrive\Programming\MIS 3300\MIS 3300\hw6.py", line 6, in &lt;module&gt; import hw6util File "C:\Users\ebarr\OneDrive\Programming\MIS 3300\MIS 3300\hw6util.py", line 122 def draw_circle(evan, shape_info[5]): ^ SyntaxError: invalid syntax
has comment: http://stackoverflow.com/comment/87121238
has answer: http://stackoverflow.com/a/50052391
accepted answer: http://stackoverflow.com/a/50052391
possible better answer: http://stackoverflow.com/a/50052393
has comment: http://stackoverflow.com/comment/87121222
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/50052393
has title: Passing list element to function
favorite count: 0

http://stackoverflow.com/comment/87046648
type: AnswerComment
comment on: http://stackoverflow.com/a/50014568
score: 0
has text: Just to verify: you created the model with --python-version="3.5" and get the reported error message even still?
type: Comment

http://stackoverflow.com/a/49943564
score: 0
has body: One solution would be to store your passwords in a DB and hash them. Then, connect to said Database and retrieve the passwords. You can also use environment variables and use them to reference the password without storing the plaintext password in your application. ie, import os print(os.environ['SOMEPASSWORD'])
type: Answer
answers question: http://stackoverflow.com/q/49942003

http://stackoverflow.com/q/49935645
tagged with: java
answer count: 1
type: Question
has title: Import data from mongodb
tagged with: mongodb
has answer: http://stackoverflow.com/a/49938248
tagged with: python
accepted answer: http://stackoverflow.com/a/49938248
type: AnsweredQuestion
score: 0
has body: When I import data from mongodb using jupyter, during the import process, my memory is 35% but my cpu is between 100% to 135%. It takes such a long time to import data. But I am not sure where is the bottleneck in this case. My code is below So according to the other users in SO, this is already indexed. What else can I do to speed up the process of importing data into my pc ? { "_id" : ObjectId("5ad0ade0bef1fc2fba99489d"), "property_a" : 0.0, "property_b" : 0.0, "property_c" : 0.0, "property_d" : 0.0, "property_e" : 0.0, ..... } The code I use to import the data is as follows, and I execute it via the jupyter notebook. Kindly be clear on whether the edits should be on the juypter notebook or in the mongodb, in my case I use robo3t. import pandas as pd from pymongo import MongoClient def _connect_mongo(host, port, username, password, db): """ A util for making a connection to mongo """ if username and password: mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db) conn = MongoClient(mongo_uri) else: conn = MongoClient(host, port) return conn[db] def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True): """ Read from Mongo and Store into DataFrame """ # Connect to MongoDB db = _connect_mongo(host=host, port=port, username=username, password=password, db=db) # Make a query to the specific DB and Collection cursor = db[collection].find(query) # Expand the cursor and construct the DataFrame df = pd.DataFrame(list(cursor)) # Delete the _id if no_id: del df['_id'] return df

http://stackoverflow.com/comment/87149499
type: QuestionComment
has text: That did the trick! The output from cor command was. `C:\Python27\Lib\site-packages\openpyxl\xml\__init__.pyc`. I renamed the whole folder and now pip install works again. Thank you and @Rakesh very much. I am still curious how you resolved my problem from the error message given?
type: Comment
comment on: http://stackoverflow.com/q/50065432
score: 1

http://stackoverflow.com/a/50026398
accepted answer of: http://stackoverflow.com/q/50026206
has body: For your new question, you can use a nested comprehension. lst0 = [[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]] lst = [[t[1] for t in u] for u in lst0] print(lst) output [[2, 3], [5, 7, 1]] I changed the names of the lists since l0 and l aren't very readable in most fonts: the l is too similar to 1. As an alternative, you could do this using map although Guido isn't fond of this construction: from operator import itemgetter lst0 = [[('x0', 2), ('x1', 3)], [('x2', 5), ('x3', 7), ('x4', 1)]] print([list(map(itemgetter(1), u)) for u in lst0]) In Python 2, you can omit the list wrapper: print [map(itemgetter(1), u) for u in lst0]
type: Answer
answers question: http://stackoverflow.com/q/50026206
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86890462
score: 0
has text: Short answer: No!
type: Comment
comment on: http://stackoverflow.com/a/49937116
type: AnswerComment

http://stackoverflow.com/q/49950699
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: function
downvote count: 0
tagged with: variables
has comment: http://stackoverflow.com/comment/86918135
has answer: http://stackoverflow.com/a/49950745
score: 2
has title: Is this a good way to get the average of the input numbers?
has answer: http://stackoverflow.com/a/49950739
answer count: 3
tagged with: python
has body: I'm writing a function to return the mean of the user's comma-separated input. def get_average () : grades = input() grades = grades.split(",") grades = [int(x) for x in grades] average = (sum(grades))/(len(grades)) return round(average, 2) Is this a good way to do so? What about the fact that I redefined the grades variable twice? Is there a more practical way to do it?
has answer: http://stackoverflow.com/a/49950737
favorite count: 0
type: Question

http://stackoverflow.com/comment/86969378
type: AnswerComment
comment on: http://stackoverflow.com/a/49975256
has text: But localhost refused to connect
type: Comment
score: 0

http://stackoverflow.com/q/49918309
tagged with: anaconda
has title: Python package not available from installed Python script in Windows with Anaconda
downvote count: 0
score: 1
upvote count: 1
tagged with: windows
answer count: 1
favorite count: 0
type: Question
has body: I wrote a package 'myname' which is structured as follows /myname __init__.py ----/raster/ ----/__init__.py ----/raster1.py ----/raster2.py ----/config/ ----/__init__.py ----/config.py ----/misc/ ----/__init__.py ----/misc.py ----/bin/ ----/myname.py where myname.py is a command-line script which makes use of all the sub-packages of package myname. The minimal version of my setup.py is as follows: from distutils.core import setup setup( name = 'myname', packages=['myname','myname.config','myname.misc','myname.raster'], scripts = ['myname/bin/myname.py'], ) The package is installed with python setup.py install and works out of the box in Linux. On Windows with Anaconda the script is unable to find the packages. At some point of the script I have written from myname.config import blabla and I get ImportError: no module named config while if I time the same into the python interpreter I get the import done.
tagged with: setup.py
has answer: http://stackoverflow.com/a/49939961
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51569789
upvote count: 49
downvote count: 1
has body: Let's consider how to apply two aggregate functions to the same iterator, which we can only exhaust once. The initial attempt (which hardcodes sum and max for brevity, but is trivially generalizable to an arbitrary number of aggregate functions) might look like this: def max_and_sum_buffer(it): content = list(it) p = sum(content) m = max(content) return p, m This implementation has the downside that it stores all the generated elements in memory at once, despite both functions being perfectly capable of stream processing. The question anticipates this cop-out and explicitly requests the result to be produced without buffering the iterator output. Is it possible to do this? Serial execution: itertools.tee It certainly seems possible. After all, Python iterators are external, so every iterator is already capable of suspending itself. How hard can it be to provide an adapter that splits an iterator into two new iterators that provide the same content? Indeed, this is exactly the description of itertools.tee, which appears perfectly suited to parallel iteration: def max_and_sum_tee(it): it1, it2 = itertools.tee(it) p = sum(it1) # XXX m = max(it2) return p, m The above produces the correct result, but doesn't work the way we'd like it to. The trouble is that we're not iterating in parallel. Aggregate functions like sum and max never suspend - each insists on consuming all of the iterator content before producing the result. So sum will exhaust it1 before max has had a chance to run at all. Exhausting elements of it1 while leaving it2 alone will cause those elements to be accumulated inside an internal FIFO shared between the two iterators. That's unavoidable here - since max(it2) must see the same elements, tee has no choice but to accumulate them. (For more interesting details on tee, refer to this post.) In other words, there is no difference between this implementation and the first one, except that the first one at least makes the buffering explicit. To eliminate buf…
type: Answer
score: 48
has comment: http://stackoverflow.com/comment/90111030
answers question: http://stackoverflow.com/q/50039223
has comment: http://stackoverflow.com/comment/90111084

http://stackoverflow.com/a/50009858
has comment: http://stackoverflow.com/comment/89979572
upvote count: 3
score: 3
has body: For your script to only add the color to the date it would have to be alone in the run. Consider this example: from docx import Document from docx.shared import Inches from docx.enum.text import WD_COLOR_INDEX document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run(' 05-03-2018 ') p.add_run('italic.').italic = True document.save('demo.docx') And then: doc = Document('demo.docx') for p in doc.paragraphs: for run in p.runs: date1 = re.findall(r"[0-9]{2}-[0-9]{2}-(?!0000)[0-9]{4}", run.text) if date1: run.font.highlight_color = WD_COLOR_INDEX.YELLOW doc.save('demo.docx') Update: Maybe this could help you. It will search for the string in the paragraph text. If found it will save the runs to a list, delete the paragraph text and then rebuild the runs. A run with a match inside is rebuilt with a special syntax to color the date. from docx import Document from docx.shared import Inches from docx.enum.text import WD_COLOR_INDEX document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold text. ').bold = True p.add_run('Current date: 05-03-2018 ') p.add_run('italic.').italic = True document.save('demo.docx') doc = Document('demo.docx') pattern = r"[0-9]{2}-[0-9]{2}-(?!0000)[0-9]{4}" for p in doc.paragraphs: if re.findall(pattern, p.text): runs = list(p.runs) p.text = '' for run in runs: match = re.search(pattern, run.text) if not match: newrun = p.add_run(run.text) if run.bold: newrun.bold = True if run.italic: newrun.italic = True else: start, end = match.span() p.add_run(run.text[0:start]) colored = p.add_run(run.text[start:end]) colored.font.highlight_color = WD_COLOR_INDEX.YELLOW p.add_run(run.text[end:len(run.text)+1]) doc.save('demo.docx')
downvote count: 0
has comment: http://stackoverflow.com/comment/89983271
answers question: http://stackoverflow.com/q/50004166
has comment: http://stackoverflow.com/comment/89975128
has comment: http://stackoverflow.com/comment/89975055
type: Answer

http://stackoverflow.com/q/50055457
type: Question
tagged with: pandas
has body: I have 12 dataframes of the same shape for 12 years of data collection. I need to use this as a panel to to plot the various column values across the time series axis (years). Hence, I think I should align these frames as panels. Can someone help me on how to align dataframes as panels? Is this the correct way to do this to prepare for plotting along 3rd dimension? Some sample data: # for 2015 Grave Crimes Cases Recorded Mistake of Law fact Abduction 725 3 Kidnapping 246 6 Arson 466 1 Mischief 436 1 House Breaking 12707 21 Grievous Hurt 1299 3 # for 2016 Grave Crimes Cases Recorded Mistake of Law fact Abduction 738 4 Kidnapping 297 9 Arson 486 4 Mischief 394 1 House Breaking 10287 14 Grievous Hurt 1205 0 # for 2017 Grave Crimes Cases Recorded Mistake of Law fact Abduction 647 2 Kidnapping 251 10 Arson 418 3 Mischief 424 0 House Breaking 8913 12 Grievous Hurt 1075 1
has comment: http://stackoverflow.com/comment/87127536
favorite count: 0
score: 2
has title: Align pandas dataframes as panels
upvote count: 2
has answer: http://stackoverflow.com/a/50056280
answer count: 2
downvote count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87127385
has answer: http://stackoverflow.com/a/50056788

http://stackoverflow.com/comment/86859299
has text: Thanks, but I get an error: Data must be 1 dimensional
score: 0
comment on: http://stackoverflow.com/a/49921656
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50053629
upvote count: 2
type: AnsweredQuestion
score: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/50053877
answer count: 1
has comment: http://stackoverflow.com/comment/87123810
type: Question
has comment: http://stackoverflow.com/comment/87123890
favorite count: 0
has body: While testing the output I found an error in my output. With arr2 and x = 3 as my input, the value mid is 4 during the last recursive call, as it should be. However, instead of returning mid, it instead skips the if statement and returns False at the end. Does anyone [enter image description here][1]see what I did wrong here? Thank you class rotatedArraySearch: #similar to binary search def rotatedAS(self,arr,x,low,high): mid = (low + high)/2 print mid if x == arr[mid]: return mid if low &gt; high: return False #check which side is ordered properly if arr[low] &lt; arr[mid]: #if the left side is ordered properly, check if it is in the left side, if not search right if x &gt;= arr[low] and x &lt; arr[mid]: return self.rotatedAS(arr,x,low,mid-1) else: return self.rotatedAS(arr,x,mid+1,high) elif arr[mid] &lt; arr[low]: #same for right side if x &gt; arr[mid] and arr &lt;= arr[high]: return self.rotatedAS(arr,x,mid+1,high) else: return self.rotatedAS(arr,x,low,mid-1) #if there are duplicate values the order is not known, check both sides elif arr[low] == arr[mid]: if arr[mid] != arr[high]: return self.rotatedAS(arr,mid+1,high,x) else: result = self.rotatedAS(arr,low,mid-1,x) if(result == False): return self.rotatedAS(arr,mid+1,high,x) else: return result return False #test arr = [5,6,7,2,3,4] arr2 = [2,2,2,2,3,4,1] ras = rotatedArraySearch() print ras.rotatedAS(arr2,3,0,len(arr2)-1)
has title: Wrong output when searching in a rotated array with duplicates
has answer: http://stackoverflow.com/a/50053877
tagged with: python
has comment: http://stackoverflow.com/comment/87123959

http://stackoverflow.com/q/50067472
downvote count: 0
has answer: http://stackoverflow.com/a/50067632
answer count: 1
has comment: http://stackoverflow.com/comment/87151410
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50067632
tagged with: python
linked to: http://stackoverflow.com/q/17581332
tagged with: dictionary
has body: In Python 2.7, how does one dynamically access and print out the keys and values of a nested dictionary? Here's a nonsensical example: https://jsoneditoronline.org/?id=da7a486dc2e24bf8b94add9f04c71b4d Normally, I would do something like: import json json_sample = 'sample_dict.json' json_file = open(json_sample, 'r') json_data = json.load(json_file) items = json_data['sample_dict'] for item in items: dict_id = item['dict_id'] person = item['person']['person_id'] family = item['family']['members'] print dict_id print person print family I can hard code it like this and it'll give me desirable results, but how would I access each of the keys and values dynamically so that: The first row just prints the keys (dict_id, person['person_id'], person['name'], family['members']['father']) The second row prints the values respectively (5, 15, "Martin", "Jose") The end result should be in a CSV file.
score: 4
upvote count: 4
tagged with: python-2.7
tagged with: list
has title: Recursively accessing paths and values of a nested dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87151649

http://stackoverflow.com/comment/86887334
score: 0
type: AnswerComment
has text: @NoorAliJafri you would generally want to use `vars` instead of `dir`, but why would you, if you can just us `getattr`?
comment on: http://stackoverflow.com/a/49935471
type: Comment

http://stackoverflow.com/comment/86956864
type: QuestionComment
has text: ...that command wouldn't actually run at all. It would need to be `subprocess.run(['chmod', '+x', 'file.sh'])`, unless `shell=True` is passed (which it shouldn't be).
comment on: http://stackoverflow.com/q/49970453
score: 2
type: Comment

http://stackoverflow.com/comment/87070485
type: Comment
type: QuestionComment
has text: Thanks, I'll change it.
comment on: http://stackoverflow.com/q/50027034
score: 0

http://stackoverflow.com/q/49972498
score: 3
tagged with: python
has body: I have the following (in real life, the C code is much more complex, and I don't want to change it. It uses globals everywhere).: from cffi import FFI ffibuilder = FFI() ffibuilder.set_source( "mymodule", r""" #include &lt;stdio.h&gt; float *x, *y, *z; int n; void some_func(){ int i; for(i==0; i&lt;n; i++) printf("%f %f %f\n", x[i], y[i], z[i]); } """ ) ffibuilder.cdef( """ float *x, *y, *z; int n; void some_func(); """ ) if __name__=="__main__": ffibuilder.compile() from mymodule import ffi, lib import numpy as np n = 4 lib.n = n for i, k in enumerate(['x','y', 'z']): v = i*np.arange(n, dtype=np.float32) v.__repr__() # Need to do this for some reason!! setattr(lib, k, ffi.cast('float*', ffi.from_buffer(v))) lib.some_func() The expected printed output (from some_func) is: 0.000000 0.000000 0.000000 0.000000 1.000000 2.000000 0.000000 2.000000 4.000000 0.000000 3.000000 6.000000 And that is indeed what I get. However, if I take out the line where I call v.__repr__(), I get the following: 0.000000 0.000000 0.000000 1.000000 1.000000 2.000000 2.000000 2.000000 4.000000 3.000000 3.000000 6.000000 i.e. it seems like the memory of x is either being overwritten by y, or is pointing to y. If I have only x and y (no z), then things work as expected. Using double instead of float exhibits the same behaviour. Any ideas on what I'm doing wrong?? Thanks!
tagged with: numpy
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49973110
upvote count: 3
has answer: http://stackoverflow.com/a/49973110
answer count: 1
downvote count: 0
has title: Passing multiple numpy arrays to C using CFFI
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python-cffi

http://stackoverflow.com/q/49957601
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86939179
has title: How can I draw 3D plane using PCA In python?
tagged with: pca
has answer: http://stackoverflow.com/a/60571991
answer count: 2
has comment: http://stackoverflow.com/comment/86934057
score: 1
tagged with: plane
tagged with: matplotlib
downvote count: 0
upvote count: 1
favorite count: 0
has body: X = np.array([[24,13,38],[8,3,17],[21,6,40],[1,14,-9],[9,3,21],[7,1,14],[8,7,11],[10,16,3],[1,3,2], [15,2,30],[4,6,1],[12,10,18],[1,9,-4],[7,3,19],[5,1,13],[1,12,-6],[21,9,34],[8,8,7], [1,18,-18],[15,8,25],[16,10,29],[7,0,17],[14,2,31],[3,7,0],[5,6,7]]) pca = PCA(n_components=1) pca.fit(X) a = pca.components_[0][0] # a b = pca.components_[0][1] # b c = pca.components_[0][2] # c def average(values): if(values) ==0: return None return sum(values, 0.0) / len(values) x_mean = average(x) # For an approximation y_mean = average(y) z_mean = average(z) d = -(a * x_mean + b * y_mean + c * z_mean) so -0.375978766054x + 0.10612154283y -0.920531469111z + 15.1366572005 = 0 Actually, I'm not sure it is right. I want to draw a plane in this situation using matplotlib library. How can I code this?
type: Question
has answer: http://stackoverflow.com/a/49961579

http://stackoverflow.com/q/49966135
has title: Multi-digits bug code
downvote count: 1
linked to: http://stackoverflow.com/q/39981237
favorite count: 0
type: Question
tagged with: python-3.x
has body: Very new to programming and decided to get into Python. Sorry in advance if this question is very simple. Experimenting with functions. Got this to run with no errors, but doesn't always work. I'm pretty sure I'm doing the string replacement wrong? Any explanation or advice would be great. Noticed it wasn't working when I was comparing a single digit number to a multi digit. def bigger(a, b): if a &gt; b: print ("%s is bigger" % a) elif a == b: print ("They are both equal!") else: print ("%s is bigger" % b) a = input("Pick a number: ") b = input("Pick another number: ") bigger(a, b)
answer count: 2
has answer: http://stackoverflow.com/a/49966160
has answer: http://stackoverflow.com/a/49966173
upvote count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/39981237
tagged with: python
has comment: http://stackoverflow.com/comment/86948182
has comment: http://stackoverflow.com/comment/86948008
has comment: http://stackoverflow.com/comment/86948095
has comment: http://stackoverflow.com/comment/86948046
score: -1

http://stackoverflow.com/comment/86965890
has text: Keep in mind that by multiplying the ADC value by 10 you are losing accuracy. You should replace the 100ohm reference resistor with 1000ohm. For switching between multiple sensors you can use relay (I do not recommend it), or use multiple MAX modules and switch between them using the CS (chip select) signal
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49954175
score: 0

http://stackoverflow.com/q/49993719
type: AnsweredQuestion
score: 0
has body: I am learning flask through the book Flask Web Development. I am confused about how web forms be processed by the web server. More concretely, how POSt request be processed in the web server? Here is code snippet for generating response to the main index request: @app.route('/', methods=['GET', 'POST']) def index(): name = None form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html', form=form, name=name) In my opinion, when the client visit the main index for the first time, flask app will receive a GET request. This GET request will be processed by the index view function. form will be constructed from NameForm(), and it will be empty at that time. So form.validate_on_submit() will return false. Then, when user submits the form with data through a POST request, it will also be processed by the index view function. So another form will be constructed from NameFrom(), and I think it will be empty too, which make form.validate_on_submit() still return false. Obviously, my thinking is wrong. My question is: how does form.validate_on_submit() evaluated to be true when user submit the form through a POST? Thanks in advance!
accepted answer: http://stackoverflow.com/a/49993760
type: Question
tagged with: flask-wtforms
has answer: http://stackoverflow.com/a/49993760
has title: How does web forms be processed by the web server?
tagged with: python
tagged with: flask
answer count: 1

http://stackoverflow.com/a/50024794
has body: You asked if Python was a suitable tool for this sort of project. It is, but it is much more suitable if you use it properly. In other words, don't make the problem unnecessarily difficult. I understand your impulse to implement a particular algorithm to get comfortable with programming, but I have to say that this isn't a good choice. Date arithmetic is usually a pain. If you want to use computational shortcuts (and you should), then take a look at the shortcuts that the Python programming environment offers. For example: &gt;&gt;&gt; import datetime &gt;&gt;&gt; from dateutil import parser &gt;&gt;&gt; date = "25/December/1999" &gt;&gt;&gt; datetime.datetime.strftime(parser.parse(date), "%A") 'Saturday' The dateutil module isn't part of the standard library but it is well worth the trouble of installing.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50023794
type: Answer

http://stackoverflow.com/a/50066672
has comment: http://stackoverflow.com/comment/92555534
upvote count: 6
has body: Solution After using filezilla to debug the method, turn out that our FTP returned 0.0.0.0 despite we defined in /etc/vsftpd.conf pasv_adress=IP this post helped us : https://www.centos.org/forums/viewtopic.php?t=52408 You have to comment listen_ipv6=YES and enable listen=YES in /etc/vsftpd.conf Also you can override the ftplib's class FTP if you can't access to vsftpd.conf of the FTP class CustomFTP(ftplib.FTP): def makepasv(self): if self.af == socket.AF_INET: host, port = ftplib.parse227(self.sendcmd('PASV')) else: host, port = ftplib.parse229(self.sendcmd('EPSV'), self.sock.getpeername()) if '0.0.0.0' == host: """ this ip will be unroutable, we copy Filezilla and return the host instead """ host = self.host return host, port to force the previous host if '0.0.0.0' is send
accepted answer of: http://stackoverflow.com/q/50060037
answers question: http://stackoverflow.com/q/50060037
type: AcceptedAnswer
score: 6
has comment: http://stackoverflow.com/comment/118173888
downvote count: 0
type: Answer

http://stackoverflow.com/q/49958098
tagged with: chainer
tagged with: machine-learning
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49961775
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49961775
has body: I am using Chainer for written digit recognition. I have trained a model on the MNIST database. However I cannot for some reason classify a single example. My guess was that I didn't choose the right format for the example but I've tried it many ways and I still cannot resolve this issue. Apologies if this is obvious, I'm unexperienced at Python. This is what the error looks like Code: import chainer import chainer.functions as F import chainer.links as L import os import sys from chainer.training import extensions import numpy as np from tkinter.filedialog import askopenfilename from PIL import Image from chainer import serializers from chainer.dataset import concat_examples from chainer.backends import cuda from chainer import Function, gradient_check, report, training, utils, Variable from chainer import datasets, iterators, optimizers, serializers from chainer import Link, Chain, ChainList CONST_RESUME = '' class Network(chainer.Chain): def __init__(self, n_units, n_out): super(Network, self).__init__() with self.init_scope(): self.l1 = L.Linear(None, n_units) self.l2 = L.Linear(None, n_units) self.l3 = L.Linear(None, n_out) def __call__(self, x): h1 = F.sigmoid(self.l1(x)) h2 = F.sigmoid(self.l2(h1)) return self.l3(h2) def query_yes_no(question, default="no"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits &lt;Enter&gt;. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == …
score: 1
answer count: 1
downvote count: 0
has title: Chainer: Cannot classify, trained model(x) throws error
favorite count: 0
type: Question

http://stackoverflow.com/a/49966160
has body: a = input("Pick a number: ") b = input("Pick another number: ") input() is always represented as a string and not an integer so in order to run comparisons like if a &gt; b you must first convert it to an integer, like this: a = int(input("Pick a number: ")) b = int(input("Pick another number: ")) The reason your program works is because Python is comparing the individual sizes of your strings. So "32" starts with a 3 while "122" starts with a 1 so 32 is larger. &gt;&gt;&gt; '122'&lt;'32' True &gt;&gt;&gt; '44'&gt;'1333333' True
type: Answer
answers question: http://stackoverflow.com/q/49966135
score: 0

http://stackoverflow.com/comment/116839479
score: 0
type: Comment
has text: Probably meant `git log -1`, ie: `git log -1 --format="%h %ad"`
type: AnswerComment
comment on: http://stackoverflow.com/a/49971620

http://stackoverflow.com/comment/87014667
score: 0
type: Comment
type: QuestionComment
has text: Hello, thank you for anwseing. How can I do that ? I just need to know which variables I need to define ?
comment on: http://stackoverflow.com/q/49997600

http://stackoverflow.com/comment/87108354
comment on: http://stackoverflow.com/q/50045537
score: 0
has text: index is not a function, you can try: `stage2.index`
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50003791
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50003960
has answer: http://stackoverflow.com/a/50003960
linked to: http://stackoverflow.com/q/36390406
has title: Removing random rows from a data frame until count is equal some criteria
tagged with: dataframe
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
has body: I have a dataframe with data that I feed to a ML library in python. The data I have is categorized into 5 different tasks, t1,t2,t3,t4,t5. The data I have right now for every task is uneven, to simplify things here is an example. task, someValue t1, XXX t1, XXX t1, XXX t1, XXX t2, XXX t2, XXX In the case above, I want to remove random rows with the task label of "t1" until there is an equal amount of "t1" as there is "t2" So after the code is run, it should look like this: task, someValue t1, XXX t1, XXX t2, XXX t2, XXX What is the most clean way to do this? I could of course just do for loops and if conditions and use random numbers and count the occurances for each iteration, but that solution would not be very elegant. Surely there must be a way using functions of dataframe? So far, this is what I got: def equalize_rows(df): t = df['task'].value_counts() mininmum_occurance = min(t)
downvote count: 0

http://stackoverflow.com/comment/87005035
type: Comment
type: QuestionComment
has text: Possible duplicate of [Merge weights of same model trained on 2 different computers using tensorflow](https://stackoverflow.com/questions/48358874/merge-weights-of-same-model-trained-on-2-different-computers-using-tensorflow)
comment on: http://stackoverflow.com/q/49988009
score: 1

http://stackoverflow.com/a/50079482
type: Answer
answers question: http://stackoverflow.com/q/50073587
has body: scipy.optimize.curve_fit makes it really easy to fit data points to your custom function: import numpy as np from scipy.optimize import curve_fit #definition of the function def myfunc(x, a, b, c): return a + b * np.cos(x - c) #sample data x_data = np.arange(5) y_data = 2.34 + 1.23 * np.cos(x_data + .23) #the actual curve fitting procedure, a, b, c are stored in popt popt, _pcov = curve_fit(myfunc, x_data, y_data) print(popt) #the rest is just a graphic representation of the data points and the fitted curve from matplotlib import pyplot as plt x_fit = np.linspace(-1, 6, 1000) y_fit = myfunc(x_fit, *popt) plt.plot(x_data, y_data, "ro", label = "data points") plt.plot(x_fit, y_fit, "b", label = "fitted curve\na = {}\nb = {}\nc = {}".format(*popt)) plt.legend() plt.show() Output: [ 2.34 1.23 -0.23] Edit: Your question update introduces several problems. First, your x-values are in degree, while np.cos expects values in radians. Therefore, we better convert the values with np.deg2rad. The reverse function would be np.rad2deg. Second, it is a good idea to fit for different frequencies as well, let's introduce an additional parameter for that. Third, fits are usually quite sensitive to initial guesses. You can provide a parameter p0 in scipy for that. Fourth, you changed the resolution of the fitted curve to the low resolution of your data points, hence it looks so undersampled. If we address all these problems: import numpy as np from scipy.optimize import curve_fit #sample data x_data = [0, 60, 120, 180, 240, 300] y_data = [25, 40, 70, 30, 10, 15] #definition of the function with additional frequency value d def myfunc(x, a, b, c, d): return a + b * np.cos(d * np.deg2rad(x) - c) #initial guess of parameters a, b, c, d p_initial = [np.average(y_data), np.average(y_data), 0, 1] #the actual curve fitting procedure, a, b, c, d are stored in popt popt, _pcov = curve_fit(myfunc, x_data, y_data, p0 = p_initial) print(popt) #we have to convert the phase shift back into degrees …
score: 2
has comment: http://stackoverflow.com/comment/87179302
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50073587

http://stackoverflow.com/q/49959111
tagged with: http://stackoverflow.com/tag/svg
accepted answer: http://stackoverflow.com/a/49959191
has answer: http://stackoverflow.com/a/49959191
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: I'm trying to remove element with id "area_3". I used something like: for node in tree.xpath('//ellipse'): node.getparent().remove(node) SVG example: <g> Layer 1 <image id="svg_1" y="0" x="0"/> <image stroke="null" xlink:href="tehplan.jpg" id="svg_5" height="587.777769" width="585.333339" y="0.578137" x="20.083334"/> <ellipse ry="19" rx="18" id="area_2" cy="172" cx="189" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000" fill="#ffffff"/> <ellipse id="area_3" ry="19" rx="18" cy="161" cx="275" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000" fill="#ffffff"/> </g>
tagged with: lxml
tagged with: python
type: AnsweredQuestion
has title: SVG file. remove element

http://stackoverflow.com/q/50058208
type: Question
possible better answer: http://stackoverflow.com/a/50069742
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50069742
has title: How do I scrape a full instagram page in python?
tagged with: python
tagged with: python-requests
answer count: 4
has answer: http://stackoverflow.com/a/71696506
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87132913
tagged with: instagram
has answer: http://stackoverflow.com/a/50058700
has answer: http://stackoverflow.com/a/54208567
has body: Long story short, I'm trying to create an Instagram python scraper, that loads the entire page and grabs all the links to the images. I have it working, only problem is, it only loads the original 12 photos that Instagram shows. Is there anyway I can tell requests to load the entire page? Working code; import json import requests from bs4 import BeautifulSoup import sys r = requests.get('https://www.instagram.com/accountName/') soup = BeautifulSoup(r.text, 'lxml') script = soup.find('script', text=lambda t: t.startswith('window._sharedData')) page_json = script.text.split(' = ', 1)[1].rstrip(';') data = json.loads(page_json) non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd) for post in data['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges']: image_src = post['node']['display_url'] print(image_src)
linked to: http://stackoverflow.com/q/21006940
accepted answer: http://stackoverflow.com/a/50058700

http://stackoverflow.com/comment/86948437
type: Comment
has text: I hope you changed it as well! You still can See it in the edit history
type: QuestionComment
comment on: http://stackoverflow.com/q/49927060
score: 1

http://stackoverflow.com/a/49929076
has body: if you use the elif construct, it will be tested only when the previous condition was false, so in the end only one of the code blocks will run. if some_condition: # code elif another_condition: # code elif yet_another_condition: # code else: # code
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49929025
downvote count: 0
has comment: http://stackoverflow.com/comment/86874380
has comment: http://stackoverflow.com/comment/86874457
has comment: http://stackoverflow.com/comment/86874345

generator
type: Tag
tags question: http://stackoverflow.com/q/49956883
tags question: http://stackoverflow.com/q/49931186
tags question: http://stackoverflow.com/q/49929905
tag name: generator
tags question: http://stackoverflow.com/q/50039451
tags question: http://stackoverflow.com/q/50069361
tags question: http://stackoverflow.com/q/49969006
tags question: http://stackoverflow.com/q/50046477

http://stackoverflow.com/comment/86969071
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49973713
score: 0
has text: you should take a look at https://neo4j-contrib.github.io/neo4j-graph-algorithms/#_betweenness_centrality

http://stackoverflow.com/q/50038514
tagged with: output
has comment: http://stackoverflow.com/comment/87093156
type: Question
has title: How to hide input in python console
tagged with: spyder
tagged with: input
has comment: http://stackoverflow.com/comment/87149530
tagged with: python
has body: I'm using python on spyder and when I run my code the console shows the input as well as the output. I know what the input is, I don't need it taking up space where my results should be. How do I hide it?
score: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/87144926
type: Comment
type: QuestionComment
has text: Ask a sysadmin to check permissions for all directories in the path `/usr/local/lib/python2.7/dist-packages/virtualenv-15.0.1.dist-info`.
comment on: http://stackoverflow.com/q/50061786
score: 0

http://stackoverflow.com/comment/87073336
type: QuestionComment
has text: Ok. But when I do something like that: ` con = sql.connect("example.sqlite3") select = "select ? from data;" cur = con.cursor() t = ('id', ) cur.execute(selec, t) rows = cur.fetchall() con.commit() con.close() for row in rows: for cell in row: print(cell) ` What I get is: id id id id id id id...
score: 0
comment on: http://stackoverflow.com/q/50027426
type: Comment

http://stackoverflow.com/comment/87041077
score: 0
type: AnswerComment
type: Comment
has text: Cheers! If you could click "accept answer" checkmark to the left of the post I'd be great :)
comment on: http://stackoverflow.com/a/49997959

http://stackoverflow.com/comment/87173539
has text: How Atom does it I have no idea. Maybe it bundles some python code that uses introspection to know what to suggest when. That's what Jedi does, AFAIK.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50076430
type: AnswerComment

http://stackoverflow.com/comment/87091747
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50037702
score: 0
has text: Yes, I need the content between the last `/` and the first `_`.

http://stackoverflow.com/a/53546818
answers question: http://stackoverflow.com/q/49941105
type: Answer
score: 0
has body: You need to use '(?i)yes/no'. I ran into this same issue.

http://stackoverflow.com/comment/86998254
comment on: http://stackoverflow.com/a/49987964
has text: Welcome to StackOverflow. When you find an answer acceptable, the best way to show thanks is to accept the answer, which also shows to folks looking for questions to answer that this one has been.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50051160
has body: td is of the type file. you want to convert it to a list of lines. What you should do is: for line in td.readlines() Also for replacing words, try using fileinput. from this post: fileinput already supports inplace editing. It redirects stdout to the file in this case: #!/usr/bin/env python3 import fileinput with fileinput.FileInput(filename, inplace=True, backup='.bak') as file: for line in file: print(line.replace(text_to_search, replacement_text), end='')
answers question: http://stackoverflow.com/q/50050780
type: Answer
score: 0

http://stackoverflow.com/comment/86893444
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49936414
has text: Take a look at these posts: https://stackoverflow.com/a/539024/3287355 and https://stackoverflow.com/a/168435/3287355
score: 0

http://stackoverflow.com/q/49932904
accepted answer: http://stackoverflow.com/a/49933613
tagged with: http-status-code-400
possible better answer: http://stackoverflow.com/a/49991869
type: Question
has answer: http://stackoverflow.com/a/49991869
tagged with: messaging
tagged with: twilio
tagged with: sms
tagged with: python
has answer: http://stackoverflow.com/a/49933613
type: AnsweredQuestion
score: 0
answer count: 2
has title: Twilio SMS Repsonse
has body: I'm playing around with Python and Twilio, attempting to setup an automated response to an SMS. The response comes through when I send a text but none of the other details. My test server also gives a 400 bad request, so it's not understanding what's being requested. I may just be using incorrect syntax since I compiled this code from different examples and text. If anyone know what I'm doing incorrectly or knows the correct syntax I would appreciate the help. from flask import Flask, request from twilio.twiml.messaging_response import * #initialize Flask application app = Flask(__name__) #route for handling request on endpoint @app.route("/sms", methods=['POST', 'GET']) def inbound_sms(): #gets number that text is sent from inbound_num = request.form['From'] #gets message that was sent message_body = request.form['Body'] reply = MessagingResponse() #Sends reply with attached details reply.message("Thank you!".format(inbound_num, message_body)) return str(reply) if __name__ == "__main__": app.run(debug=True)

http://stackoverflow.com/comment/87073680
has text: Yep it does. Just edited my comment before I saw this. Thanks!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50028539
type: Comment

http://stackoverflow.com/q/49949764
tagged with: spyder
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/49960318
has title: python list to dataframe with column headers and removing data types
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: pandas
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49960318
has body: Hoping someone can help me out here to write an efficient code. I am fairly new to python and not the most efficient. I have a ODBC connection to a SQL database and here is the code for that: import pyodbc import pandas as pd import csv cnxn = pyodbc.connect("DSN=acc_DB") cursor = cnxn.cursor() cursor.execute("select top 10 * from Table_XX") rows = cursor.fetchall() Now from here what i get is a this: Then i put that in a dataframe and out to a csv using this code DF = pd.DataFrame(rows) DF.to_csv('out.csv',sep=',') The problem is: DF is not recognizing the column names, there is just a value of 0 for columns The column type is being transferred to the decimal('xxx') is also being captured in the df How do i put this in the Dataframe in a table format with the column headers and no column types?? Like i would in a SQL query i execute on MS SQL management studio?
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49924059
has comment: http://stackoverflow.com/comment/86865021
upvote count: 2
has comment: http://stackoverflow.com/comment/86864528
answers question: http://stackoverflow.com/q/49923299
type: Answer
has comment: http://stackoverflow.com/comment/86864440
has comment: http://stackoverflow.com/comment/86864155
has comment: http://stackoverflow.com/comment/86864080
score: 2
has comment: http://stackoverflow.com/comment/86865239
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86864374
has comment: http://stackoverflow.com/comment/86864264
has body: An O(n) solution (with O(n log(n)) sortings): amounts = [1, 10, 10] left_to_buy = 12 sorted_amounts = list(sorted([amount, index] for index, amount in enumerate(amounts))) for idx, (amount, _) in enumerate(sorted_amounts): buy = min(left_to_buy//(len(amounts)-idx), amount) sorted_amounts[idx][0] -= buy left_to_buy -= buy final_amounts = [a for a, i in sorted(sorted_amounts, key = lambda t: t[1])] bought = [amount - final_amounts[i] for i, amount in enumerate(amounts)] print(final_amounts, bought) #[0, 5, 4] [1, 5, 6] We first sort the list of available items (we keep their indices in a tuple in order to put the list back in original order at the end). Then, we remove from each item its share of what is left to buy, or all of it if we don't have enough. In the end, we put back the list in original order Edit: I had missed the fact that your list is already sorted... In this case, it gets much shorter: amounts = [1, 10, 10] left_to_buy = 12 res = [] for idx, amount in enumerate(amounts): buy = min(left_to_buy//(len(amounts)-idx), amount) left_to_buy -= buy res.append(buy) print(res) # [1, 5, 6]
has comment: http://stackoverflow.com/comment/86865181
accepted answer of: http://stackoverflow.com/q/49923299
has comment: http://stackoverflow.com/comment/86865439

http://stackoverflow.com/a/49993019
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49992516
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49992516
has body: I mopped up a few mistakes in your code to produce this, which works. Note that I inadvertently changed the names of the fields in your test db. import sqlite3 import pandas as pd class ReadSQL: def __init__(self, database): self.database = database self.conn = sqlite3.connect(self.database) self.cur = self.conn.cursor() def query_columns_to_dataframe(self, table, columns): query = 'select ' for i in range(len(columns)): query = query + columns[i] + ', ' query = query[:-2] + ' from ' + table #~ print(query) df = pd.read_sql_query(query, self.conn) return df def close_database(): self.conn.close return test = ReadSQL('test_database.db') df = test.query_columns_to_dataframe('test', ['value_1', 'value_2']) print (df) Output: value_1 value_2 0 2 3

http://stackoverflow.com/comment/86920567
type: Comment
has text: Using a `dict` directly really is the only fast solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/49946181
score: 0

http://stackoverflow.com/q/49965143
has comment: http://stackoverflow.com/comment/86946206
has comment: http://stackoverflow.com/comment/86946170
has comment: http://stackoverflow.com/comment/86946174
type: Question
has comment: http://stackoverflow.com/comment/86946234
has comment: http://stackoverflow.com/comment/86946162
has comment: http://stackoverflow.com/comment/86946258
tagged with: python
accepted answer: http://stackoverflow.com/a/49965238
has comment: http://stackoverflow.com/comment/86946127
has answer: http://stackoverflow.com/a/49965238
upvote count: 2
type: AnsweredQuestion
has body: So I have this textfile, and in that file it goes like this... (just a bit of it) "The truest love that ever heart Felt at its kindled core Did through each vein in quickened start The tide of being pour Her coming was my hope each day Her parting was my pain The chance that did her steps delay Was ice in every vein I dreamed it would be nameless bliss As I loved loved to be And to this object did I press As blind as eagerly But wide as pathless was the space That lay our lives between And dangerous as the foamy race Of ocean surges green And haunted as a robber path Through wilderness or wood For Might and Right and Woe and Wrath Between our spirits stood I dangers dared I hindrance scorned I omens did defy Whatever menaced harassed warned I passed impetuous by On sped my rainbow fast as light I flew as in a dream For glorious rose upon my sight That child of Shower and Gleam" Now, the calculate the length of words without the letter 'e' in each line of text. So in the first line it should have 4, then 5, then 17, etc. My current code is for line in open("textname.txt"): line_strip = line.strip() line_strip_split = line_strip.split() for word in line_strip_split: if "e" not in word: word_e = word print (len(word_e)) My explanation is: Strip each word from each other by removing spaces, so it becomes ['Felt','at','its','kindled','core'], etc. Then we split each word because we can regard it individually when removing words with 'e'?. So we want words without e, then print the length of the string. HOWEVER, this separates each word into a different line by splitting then separating the string? So this doesn't add all the words together in each line but separates it, so the answer becomes "4 / 2 / 3"
score: 0
downvote count: 2
has title: Accumulating Characters in Python
answer count: 1
has comment: http://stackoverflow.com/comment/86946116
has comment: http://stackoverflow.com/comment/86946179
favorite count: 0

http://stackoverflow.com/a/50023746
has comment: http://stackoverflow.com/comment/87065566
type: Answer
has body: Install Homebrew and then install python with brew install python See if you have python installed with brew by ll /usr/local/bin/python* /Library/Frameworks/Python.framework/Versions/3.6/bin part in your path is duplicated. Remove them and keep your path as /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin/python3
score: 0
answers question: http://stackoverflow.com/q/50023434
has comment: http://stackoverflow.com/comment/87079137
has comment: http://stackoverflow.com/comment/87063975
has comment: http://stackoverflow.com/comment/87079037

http://stackoverflow.com/q/50009094
has comment: http://stackoverflow.com/comment/87036004
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87034733
score: 0
answer count: 0
has body: Django Attribute error:'function' object has no attribute 'self' This is my model.py file and I am getting following error: from django.db import models # Create your models here. import uuid from rgbfield.fields import RGBColorField class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) index = models.IntegerField(unique=True, db_index=True) name = models.CharField(unique=True, max_length=100) abbreviation = models.CharField(max_length=4, unique=True) theme_color = RGBColorField(default="#fff") text_color = RGBColorField(default="#000") def __str__(self): return self.name class Tool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, db_index=True, max_length=100, help_text="The name of your tool (must be unique)") byline = models.CharField(max_length=100,help_text="The byline of your tool (can contain HTML)") description = models.TextField(help_text="A description of your tool (can contain HTML)") logo_image = models.ImageField(upload_to='image', blank=True, help_text="Use to upload an (optional) logo image for your tool") logo_link = models.URLField(blank=True, help_text="An (optional) link to be associated with your tool's logo") about_link = models.URLField(blank=True, help_text="An (optional) link to further information about your tool") install_link = models.URLField(blank=True, help_text="An (optional) link to local installation information for your tool") launch_link = models.URLField(blank=True, help_text="An (optional) link to launch your tool. If hosted by EMAC, leave this blank.") categories = models.ManyToManyField(Category, related_name="tools") is_external = models.BooleanField(default=True) def tool_directory_path(instance, filename): # Image file will be uploaded to MEDIA_ROOT/tools/&lt;id&gt;/&lt;filename&gt; return "tools/{0}/{1}".format(instance.id, filename) def __str__(self): return self.name I have checked everything …
has comment: http://stackoverflow.com/comment/87034825
has comment: http://stackoverflow.com/comment/87034844
has comment: http://stackoverflow.com/comment/87035874
has comment: http://stackoverflow.com/comment/87035663
has title: Django Attribute error:'function' object has no attribute '__self__'
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/87107885
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50040348
type: QuestionComment
has text: any comments on why my question was downvoted?

http://stackoverflow.com/comment/86902305
has text: I had already tried the 2nd suggestion of changing the format to '%y %d/%m %H:%M:%S'. It results in ValueError: time data '2018/ 01/01 01:00:00' does not match format '%y %d/%m %H:%M:%S' (match)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49927320

min
type: Tag
tag name: min
tags question: http://stackoverflow.com/q/50070458

http://stackoverflow.com/comment/86983518
has text: try this :- //div[@class='label series smaller' | @class='label series smaller hover']/span[text()="Jul-14"]
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49983508

http://stackoverflow.com/a/51939330
answers question: http://stackoverflow.com/q/50007085
downvote count: 4
upvote count: 1
has comment: http://stackoverflow.com/comment/90907837
has comment: http://stackoverflow.com/comment/90970304
score: -3
type: Answer
has body: That means your model is not a subclass of the torch.nn.Modules class. If you make it a subclass, this should work.

http://stackoverflow.com/a/50069455
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50069340
type: Answer
has body: df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']}) list_=[1,2,3] df['new_col'] = [list_]*len(df) Output: A B new_col 0 1 x [1, 2, 3] 1 2 y [1, 2, 3] 2 3 z [1, 2, 3] Tip: list as a variable name is not advised. list is a built in type like str, int etc.
has comment: http://stackoverflow.com/comment/87155497
answers question: http://stackoverflow.com/q/50069340
score: 2

http://stackoverflow.com/comment/86855880
type: Comment
type: QuestionComment
has text: your `for` loop is wrong, just do `x, y, z = k` then `outputs1.append([int(x), y.strip(), z.strip()])`. Note, this will fix your issue but there is no doubt a better way to code this entire block
score: 0
comment on: http://stackoverflow.com/q/49920150

http://stackoverflow.com/comment/86883654
has text: I was looking for something of the tune of `func(eval(a))` (Which of course, does not work).
comment on: http://stackoverflow.com/a/49934056
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49954014
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49954321
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: When I specify tf.random_normal([1]), it works fine but when I specify tf.random_normal((1)), I get ValueError: Shape must be rank 1 but is rank 0 for 'random_normal_24/RandomStandardNormal' (op: 'RandomStandardNormal') with input shapes: []. This behavior applies to many functions that requires shape to be inputed in Tensorflow. Is this normal? Or is it a bug? Many tutorials and books use round bracket but it seems to be that square bracket should be the right way based on the behavior.
tagged with: tensorflow
has title: Why Tensorflow complains when shape is specified with round bracket but do not when it is specified with square bracket?
has answer: http://stackoverflow.com/a/49955481
score: 1
tagged with: python

http://stackoverflow.com/a/50008873
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50006988
type: AcceptedAnswer
downvote count: 0
score: 4
has body: This will do what you're looking to do. a = list(np.linspace(0,50)) b = list(np.linspace(0,100)) df = pd.DataFrame({'polarity':a, 'subjectivity': b}) df1 = df.describe() df2 = df1.reset_index().melt(id_vars = ['index'], value_vars = ['polarity','subjectivity']) df2['name'] = df2['variable'] + '_' + df2['index'] df2 = df2'name','value'.set_index('name').transpose() For information on melt, you can go here
type: Answer
has comment: http://stackoverflow.com/comment/120244748
answers question: http://stackoverflow.com/q/50006988

http://stackoverflow.com/comment/87123530
has text: First, is `req.txt` using `\r\n` line breaks, and doing so consistently? HTTP/1.1 allows (but doesn't require, or even recommend) servers to accept `\n` line endings, and most of them do—but if you inconsistently mix the two (especially if you use `\r\n` in the headers but then `\n` for the blank line between the headers and the body), many of them will not tolerate that.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50053320

http://stackoverflow.com/comment/86875256
type: Comment
type: QuestionComment
has text: You are right. I found a copy of the file there. I deleted it. But still after restarting the apache2 service. It says it found an error in the file so it cannot restart it. But I already deleted it!! Thanks for the help.
comment on: http://stackoverflow.com/q/49926103
score: 0

http://stackoverflow.com/comment/87311670
has text: http://flask-admin.readthedocs.io/en/latest/api/mod_base/#flask.ext.admin.base.Admin
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50071082
type: AnswerComment

memory
tags question: http://stackoverflow.com/q/49935866
tag name: memory
tags question: http://stackoverflow.com/q/49938020
tags question: http://stackoverflow.com/q/49939860
tags question: http://stackoverflow.com/q/50012376
tags question: http://stackoverflow.com/q/50003851
tags question: http://stackoverflow.com/q/50051210
type: Tag
tags question: http://stackoverflow.com/q/50069730
tags question: http://stackoverflow.com/q/50031691
tags question: http://stackoverflow.com/q/50024378
tags question: http://stackoverflow.com/q/50037654
tags question: http://stackoverflow.com/q/49949224

http://stackoverflow.com/comment/87123810
score: 2
comment on: http://stackoverflow.com/q/50053629
type: Comment
has text: Never post screenshots of code, copy and paste instead.
type: QuestionComment

http://stackoverflow.com/comment/87062876
has text: That's very helpful, thanks. One question Karthikeyan, how come you did not need to assign index = 0 at the beginning of your code? Like the way I did in my original code?
type: Comment
comment on: http://stackoverflow.com/a/50023042
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86916026
comment on: http://stackoverflow.com/q/49949611
type: QuestionComment
score: 1
has text: I'd recommend using something like Keras' `flow_from_directory(directory)` method to help you load these files as needed. I believe it works just fine with binary data too. More documentation on this page: https://keras.io/preprocessing/image/
type: Comment

http://stackoverflow.com/q/50006105
linked to: http://stackoverflow.com/q/291978
has comment: http://stackoverflow.com/comment/87028768
has answer: http://stackoverflow.com/a/50006228
score: 0
has title: variables not defined when used from another function
has body: In the photo, you can see that line 24 shows up as an error - "pile1" is not defined,"pile2" is not defined, "pile3" is not defined import random def create_cards(): deck = [] for i in range(21): suits = ["♥","♦","♠","♣"] numbers = ['1','2','3','4','5','6','7','8','9','10','K','Q','J'] card = (random.choice(numbers) + random.choice(suits)) deck.append(card) return deck def create_piles(): pile1 = [] pile2 = [] pile3 = [] for k in range(7): pile1.append(deck.pop()) pile2.append(deck.pop()) pile3.append(deck.pop()) return piles def user_input(): print (pile1, pile2, pile3) choice = input("Which pile is your card in?") if choice == 1: deck = elif choice == 2: deck = else: deck = def trick(): print(0) deck = create_cards() piles = create_piles() How can I fix this (I have tried putting function create_piles within the user_input brackets, still shows up as undefined.)
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50006224
tagged with: python

http://stackoverflow.com/comment/86890865
score: 0
type: Comment
type: QuestionComment
has text: Have added more detail as suggested!
comment on: http://stackoverflow.com/q/49929583

http://stackoverflow.com/comment/87039368
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50011335
has text: KeyError: '(1094,)'
type: Comment

http://stackoverflow.com/q/49923960
has title: Having problems plotting a partly undefined function
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86863941
has comment: http://stackoverflow.com/comment/86863795
accepted answer: http://stackoverflow.com/a/49924332
type: Question
score: 0
has answer: http://stackoverflow.com/a/49924332
tagged with: algorithm
tagged with: matplotlib
tagged with: python
has body: I have an assignment for my Applied Computer Science class in which we are to test the strength and qualities of an algorithm that tries to find the k:th highest value in a list. This is to be tested both for varying k:s (0, 1, 2, ..., k=N), and varying N:s where I have chosen k=0 and N (1, 2, ..., N). We're supposed to determine whether the algorithm ever makes more than pi*N comparisons as well as log2(N/2 - k)*N comparisons. To find some clarity in this I made two plots, both having number of comparisons as the y-axis, and k and N respectively for the x-axis. Alongside the plots I want the functions y = pi*N and y = log2(N/2 - k)*N. The problem is I get a ValueError for the second function, most definitely when N/2 = k. I would still like to plot it in python and my question is how to get around this. The rest of the code isn't really relevant. My question is: how can I plot this function while circumventing it's undefined parts? I still want to illustrate the undefined part so I don't want to make exceptions in which a simplification is made. def plotHelper(x, yA, yS, title, trials): yPi = list() yLogN = list() for point in x: yPi.append(point*math.pi) yLogN.append((trials*math.log(trials/2 - point, 2) plt.figure() plt.title(title) plt.plot(x, yA) plt.plot(x, yS) plt.plot(x, yPi) plt.plot(x, yLogN) plt.grid(True) plt.legend(["Mean", "Standard Deviation", "y = pi * N"]) plt.ylabel("Comparisons") plt.xlabel("k") plt.show() def plot(): choice = initiate() yA, yS, trials = trialFunc(choice) x = range(0, trials) f_of_k = "Comparisons as a function of desired k (N elements)" f_of_n = "Comparisons as a function of elements (k = 0)" if choice: title = f_of_k else: title = f_of_n plotHelper(x, yA, yS, title, trials)

http://stackoverflow.com/comment/87080817
type: Comment
type: QuestionComment
has text: I think it's not the algorithm, but just a coincidence of the order and selection of cards. Try playing the game manually with the chosen cards, and see if it ends, or continues ad infinitem (be aware of the order in which cards won are appended to the existing deck).
score: 0
comment on: http://stackoverflow.com/q/50032238

http://stackoverflow.com/comment/87136405
score: 0
type: AnswerComment
has text: Can I divide this through by 60 to get minutes?
comment on: http://stackoverflow.com/a/50059928
type: Comment

http://stackoverflow.com/q/49976858
tagged with: string
favorite count: 0
type: AnsweredQuestion
has title: How to remove unwanted letters in strings split by character
has answer: http://stackoverflow.com/a/49977027
tagged with: dataframe
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49977027
has comment: http://stackoverflow.com/comment/86969914
tagged with: pandas
score: 1
answer count: 1
has body: I have a dataframe of nba teams and I want to remove all the unwanted first letter or special characters in front. Teams | W | L | Pct *-Houston Rockets | 65 | 17 | 0.793 y -Golden State | 58 | 24 | 0.707 x -Boston Celtics | 55 | 27 | 0.671 x -Philadelphias | 52 | 30 | 0.634 e -Denver Nuggets | 46 | 36 | 0.561 To become this: Teams | W | L | Pct Houston Rockets | 65 | 17 | 0.793 Golden State | 58 | 24 | 0.707 Boston Celtics | 55 | 27 | 0.671 Philadelphias | 52 | 30 | 0.634 Denver Nuggets | 46 | 36 | 0.561
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50034620
has comment: http://stackoverflow.com/comment/87148646
answers question: http://stackoverflow.com/q/50034590
has comment: http://stackoverflow.com/comment/87114820
has comment: http://stackoverflow.com/comment/87153280
has comment: http://stackoverflow.com/comment/87087602
downvote count: 0
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87157944
has body: To obtain the lagged difference of a series use df['my_column'].diff() You can specify the lag as well, if you wanted to do something different than 1. See the documentation for more info EDIT Here is a possible way to address your formula: df = pd.DataFrame({'A': [20, 22, 25, 43, 23, 45, 67, 50, 70]}) df['result'] = df['A'].diff() df['result'][ df['result'] &lt; 0 ] += 2**32 # you can disregard the pandas warning Based on your logic you can simply take the diff and if the result is less than zero then add the constant 2**32. And it should be a little more efficient than taking the diff a few times (although probably this is not a big concern).

http://stackoverflow.com/q/50060241
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50060301
linked to: http://stackoverflow.com/q/3451111
has comment: http://stackoverflow.com/comment/111744526
has answer: http://stackoverflow.com/a/53227770
downvote count: 0
has answer: http://stackoverflow.com/a/72558214
has answer: http://stackoverflow.com/a/52148109
upvote count: 8
favorite count: 0
score: 8
type: Question
accepted answer: http://stackoverflow.com/a/50060301
tagged with: word-embedding
tagged with: python
has body: I have downloaded the data with wget !wget http://nlp.stanford.edu/data/glove.6B.zip - ‘glove.6B.zip’ saved [862182613/862182613] It is saved as zip and I would like to use glove.6B.300d.txt file from the zip file. What I want to achieve is : embeddings_index = {} with io.open('glove.6B.300d.txt', encoding='utf8') as f: for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:],dtype='float32') embeddings_index[word] = coefs Of course I am having this error: IOErrorTraceback (most recent call last) &lt;ipython-input-47-d07cafc85c1c&gt; in &lt;module&gt;() 1 embeddings_index = {} ----&gt; 2 with io.open('glove.6B.300d.txt', encoding='utf8') as f: 3 for line in f: 4 values = line.split() 5 word = values[0] IOError: [Errno 2] No such file or directory: 'glove.6B.300d.txt' How can I unzip and use that file in my code above on Google colab?
tagged with: google-colaboratory
possible better answer: http://stackoverflow.com/a/52148109
answer count: 4
has title: How to use GloVe word-embeddings file on Google colaboratory

http://stackoverflow.com/comment/87036267
has text: See the addition at the end of the answer.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49990988

http://stackoverflow.com/comment/87091023
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50035578
score: 0
has text: Assuming your polygons are independent features, you could [iterate over features](https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html#iterate-over-features) and then clip the file using each feature in turn.

http://stackoverflow.com/comment/86895999
type: QuestionComment
has text: Just double checked and I think the code is correct. Those inputs should give `[12, 13, 15]`. The final slice in that case will be `4+3+4+2+2` and will cover quite a large time span (21 to 40 seconds) - its over 10, buts its the first available so its OK
score: 0
comment on: http://stackoverflow.com/q/49939762
type: Comment

http://stackoverflow.com/a/49968481
answers question: http://stackoverflow.com/q/49956507
accepted answer of: http://stackoverflow.com/q/49956507
type: Answer
has body: Cancelling f0/sqrt(f0**2) is not legitimate when f0 is 0. To ensure this cancellation is allowed, declare f0 to be positive, not just nonnegative. Also, importing pi from sympy.abc makes pi a generic symbol with no specific meaning; in particular, it's not known to be positive. SymPy already has pi (mathematical constant) built-in, and knows it's a positive number. So removing the import from sympy.abc improves simplification. from sympy import * L0, Csum0, f0 = symbols("L0 C_{{\\Sigma}0} f0", positive=True) equation = sqrt(L0) substitute = solve(Eq(1/(2*pi*sqrt(L0)*sqrt(Csum0)), f0), L0, dict=1)[0] equation = equation.subs(substitute) simplify(equation*f0) returns 1/(2*pi*sqrt(C_{{\Sigma}0}))
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/121970159
type: Comment
comment on: http://stackoverflow.com/a/50060697
type: AnswerComment
score: 0
has text: What does `zorder` do?

http://stackoverflow.com/comment/117703685
type: Comment
comment on: http://stackoverflow.com/a/50072113
score: 0
type: AnswerComment
has text: Is there a way to do a commit WITHOUT supplying the file_list? i.e. have github workout which files need committing.

http://stackoverflow.com/comment/96649805
type: AnswerComment
comment on: http://stackoverflow.com/a/54416505
type: Comment
has text: What is `client` supposed to do?
score: 0

http://stackoverflow.com/comment/87064296
type: Comment
score: 0
type: QuestionComment
has text: Also see [Making object JSON serializable with regular encoder](https://stackoverflow.com/questions/18478287/making-object-json-serializable-with-regular-encoder).
comment on: http://stackoverflow.com/q/50022814

http://stackoverflow.com/q/50026047
has answer: http://stackoverflow.com/a/50163763
has answer: http://stackoverflow.com/a/50101520
has comment: http://stackoverflow.com/comment/87351829
type: UnansweredQuestion
tagged with: database
tagged with: python
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/87069144
score: 0
has body: I'm trying to upload a CSV file to a big query database, however i keep getting the following message. RuntimeError: [{'reason': 'invalid', 'location': 'kid=70943:mkey=customer_encrypt_cns/file-00000000', 'message': 'Error while reading data, error message: CSV table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the error stream for more details.'}, {'reason': 'invalid', 'location': 'kid=70943:mkey=customer_encrypt_cns/file-00000000', 'message': 'Error while reading data, error message: CSV table references column position 1, but line starting at position:0 contains only 1 columns.'}] The data in the csv matches the schema and as a test im only uploading 5 rows of 8columns e.g. 2018-02-02 x 0.1 2.4 0 0 0.88 0.4 2018-02-03 y 0.1 3 0 0 0.87 0.21 2018-02-04 z 0.1 2.8 0 0 0.86 0.21 2018-02-05 a 0.1 2.4 0 0 0.91 0.21 2018-02-06 b 0.1 1.9 0 0 1.00 0.4 Why does it say i only have 1 column?
answer count: 2
has title: Loading csv data into Big Query via API
type: Question

http://stackoverflow.com/comment/87055287
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50019188
has text: u posted a suggestion - sf2 = sf2.apply(lambda x: x.astype(str).str[:10]) - this works perfect however for loop is not working well as it is copying split values into another columns. thanks!

http://stackoverflow.com/comment/127030975
type: AnswerComment
has text: how do you change the `zorder` on this?
type: Comment
comment on: http://stackoverflow.com/a/49933937
score: 0

http://stackoverflow.com/a/50007590
type: Answer
has body: For ID is not continue show up, you want to classify them into two group, then we need create a key(by using cumsum ) in order to help split, first will return the first not null value for each columns s=pd.concat([df'ID','Time',df.pivot(columns='Category', values='Value')],axis=1) s.groupby([s.ID,s.ID.diff().ne(0).cumsum()]).first() Out[540]: ID Time Age Name Sub ID ID 457 1 457 2010-09-0415:00 NaN 'Foo' NaN 3 457 2010-09-0415:40 20 NaN 0.7 542 2 542 2010-09-0415:00 18 'Bar' 0.2
answers question: http://stackoverflow.com/q/50007449
score: 0

http://stackoverflow.com/a/50032741
downvote count: 0
has comment: http://stackoverflow.com/comment/87116324
type: AcceptedAnswer
has body: The solution of diek is the one that worked for me, edited my post because of this. The better code is: import requests import json response = requests.get("") data =response.text parsed=json.loads(data) for product in parsed['products']: print(product['id']) The output will look as follow: 66057248 66057245 66057242 66057239 66057236 66057233 66057230 66057227 66057224
accepted answer of: http://stackoverflow.com/q/50032258
has comment: http://stackoverflow.com/comment/87108950
has comment: http://stackoverflow.com/comment/87114337
has comment: http://stackoverflow.com/comment/87119099
has comment: http://stackoverflow.com/comment/87116470
has comment: http://stackoverflow.com/comment/87097612
type: Answer
has comment: http://stackoverflow.com/comment/87085516
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50032258

http://stackoverflow.com/comment/87108522
score: 0
type: Comment
type: AnswerComment
has text: df['place'] is not a string, it is a dictionary
comment on: http://stackoverflow.com/a/50046029

http://stackoverflow.com/a/50042666
accepted answer of: http://stackoverflow.com/q/50035827
has body: You cannot write a line for each read line, because one single output line can be composed from a number of input line. But if you can assume that input file is sorted according to COUNTRY, EXCHANGE_CODE and TOWN, you can just add the new month at the end of the one of the previous line if COUNTRY, EXCHANGE_CODE and TOWN are the same. Your code could become: ... with open(in_path, 'r') as f_in, open(out_path, 'w', newline='') as f_out: csv_reader = csv.reader(f_in, delimiter=';') writer = csv.writer(f_out) all = [] row = next(csv_reader) row.append('LFU') row.append('EXCHANGE_CODE') row.append('TOWN_CODE') row.append('MONTH_CODE') old = row # just remember it for row in csv_reader: if row[0] in ['FRANCE', 'SWEDEN']: row.append(row[3].split('%')[0]) row.append(row[3].split('%')[1]) row.append(row[3].split('%')[2]) row.append(row[3].split('%')[3]) if row[0] == old[0] and row[5] == old[5] and row[6] == old[6]: old[7] += ';' + row[7] else: all.append(old) # write down previous row old = row all.append(old) # do not forget last row writer.writerows(map(itemgetter(0, 5, 6, 7), all))
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50035827
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87315555

http://stackoverflow.com/comment/87138728
score: 0
type: Comment
type: QuestionComment
has text: There's actually a [Python Quickstart for Admin SDK](https://developers.google.com/admin-sdk/directory/v1/quickstart/python) that you can base your code on. If you're going to modify scopes, delete the previously saved credentials.
comment on: http://stackoverflow.com/q/50044780

http://stackoverflow.com/comment/86863255
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49922911
has text: @shadowdk `new_dict = dict()` (`{}` is a set)

http://stackoverflow.com/q/49932967
answer count: 1
has body: User providing me with search expression, e.g. "^.*/bin/run.sh" Need to scan a file and replace search expression and replace with value also provided by user. search = "^.*/bin/run.sh" replace = "/path/to/bin/new_run.sh" how do I search and replace in python 3?
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86882500
accepted answer: http://stackoverflow.com/a/49933554
has answer: http://stackoverflow.com/a/49933554
has title: python search and replace using variables
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86881739
tagged with: regex
has comment: http://stackoverflow.com/comment/86902727
type: Question
upvote count: 0

http://stackoverflow.com/q/50061883
type: Question
has title: I want to send a file through Gmail and I'm having trouble
tagged with: python
has body: I want to send a file through Gmail and I'm having trouble I want to send a file through Gmail and I'm having trouble I want to send a file through Gmail and I'm having trouble I replaced gmails and passwords, but the problem did not resolve I replaced gmails and passwords, but the problem did not resolve I replaced gmails and passwords, but the problem did not resolve Maybe there's a problem with the addresses. Please help me Maybe there's a problem with the addresses. Please help me Maybe there's a problem with the addresses. Please help me my error : Traceback (most recent call last): File "C:\Users\Michael\Desktop\windows.information.py", line 83, in &lt;module&gt; filenames) File "C:\Users\Michael\Desktop\windows.information.py", line 75, in mail mailServer.sendmail(gmail_user, to, msg.as_string()) File "C:\Program Files 1\Python2\lib\smtplib.py", line 737, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (552, "5.2.3 Your message exceeded Google's message size limits. Please visit\n5.2.3 https://support.google.com/mail/?p=MaxSizeError to view our size\n5.2.3 guidelines. f192sm642881wmg.14 - gsmtp", 'hackdatasender@gmail.com') my script: import os import getpass import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.MIMEBase import MIMEBase from email import Encoders windowsDrive = os.environ['WINDIR'].split(":\\")[0] userName = getpass.getuser() # ===== Set up crap for the attachments files = windowsDrive+':\\Users\\'+userName+'\\windows.information' filenames = [os.path.join(files, f) for f in os.listdir(files)] ## ===== print filenames ## ===== Set up users for email gmail_user = "hackdatasender@gmail.com" gmail_pwd = "******" recipients = ['hackdatareceiver@gmail.com'] # ===== Create Module def mail(to, subject, text, attach): msg = MIMEMultipart() msg['hackdatasender@gmail.com'] = gmail_user msg['hackdatareceiver@gmail.com'] = ", …
tagged with: gmail
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50062055
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50062055
has comment: http://stackoverflow.com/comment/87140383
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87140267
tagged with: python-3.x

http://stackoverflow.com/comment/86948824
type: Comment
score: 1
type: QuestionComment
has text: Your `pip3` seems to be from a different `python3`. Show us `python3 --version` and `pip3 --version`.
comment on: http://stackoverflow.com/q/49966325

http://stackoverflow.com/comment/87133197
score: 0
has text: sure let me add
type: Comment
comment on: http://stackoverflow.com/q/50057208
type: QuestionComment

http://stackoverflow.com/a/58939968
answers question: http://stackoverflow.com/q/50051226
score: 1
type: Answer
has body: I got it to work (on Linux) doing the following: // method to inspect PyObjects static void reprint(PyObject *obj) { PyObject* repr = PyObject_Repr(obj); PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~"); const char *bytes = PyBytes_AS_STRING(str); printf("REPR: %s\n", bytes); Py_XDECREF(repr); Py_XDECREF(str); } . int main() { // for our manually compiled and installed usr-local Python 3.6 //#define PATH L"/usr/local/bin:/usr/local/lib:/usr/local/lib/python3.6/lib-dynload" //#define PREFIX L"/usr/local" //#define EXEC_PREFIX L"/usr/local" //#define FULL_PROG_PATH L"/usr/local/bin/python3.6" // for apt installed Python 3.7 //#define PATH L"/usr/bin:/usr/lib:/usr/lib/python3.7/lib-dynload" //#define PREFIX L"/usr" //#define EXEC_PREFIX L"/usr" //#define FULL_PROG_PATH L"/usr/bin/python3.7" // for venv (which uses the /usr/local/lib python 3.6) #define PATH L"/home/me/venv_dir/bin:/home/me/venv_dir/lib:/usr/local/lib/python3.6:/usr/local/lib/python3.6/lib-dynload" #define PREFIX L"/home/me/venv_dir" #define EXEC_PREFIX L"/usr/local" #define FULL_PROG_PATH L"/usr/local/bin/python3.6" // ------------------------------------------------ #define CHANGE_THE_INTERPRETER #ifdef CHANGE_THE_INTERPRETER // TODO : Look at using this: https://www.python.org/dev/peps/pep-0587/ Py_SetPath(PATH); // change the built-in prefix/exec-prefix, in place. wchar_t* wpPrefix = Py_GetPrefix(); wchar_t* wpExecPrefix = Py_GetExecPrefix(); wchar_t* wpProgramFullPath = Py_GetProgramFullPath(); wcscpy (wpPrefix, PREFIX); wcscpy (wpExecPrefix, EXEC_PREFIX); wcscpy (wpProgramFullPath, FULL_PROG_PATH); #endif //CHANGE_THE_INTERPRETER // inspect the environment variables. With the #define commented out above the "defaults" appear as indicated to the right hand side wchar_t* xx; //defaults xx = Py_GetPrefix(); //&lt;prefix&gt; L"/usr/local" xx = Py_GetExecPrefix(); //&lt;exec_prefix&gt; L"/usr/local" xx = Py_GetPath(); //L"/usr/local/lib/python36.zip:/usr/local/lib/python3.6:/usr/local/li…
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49959424
has answer: http://stackoverflow.com/a/49959618
accepted answer: http://stackoverflow.com/a/49959559
has comment: http://stackoverflow.com/comment/86935288
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49959559
answer count: 2
possible better answer: http://stackoverflow.com/a/49959618
has comment: http://stackoverflow.com/comment/86935291
type: Question
has title: Python fitting model to curve
has comment: http://stackoverflow.com/comment/86935332
has body: I am experimenting with Python to fit curves to a series of data-points, summary below: From the below, it would seem that polynomials of order greater than 2 are the best fit, followed by linear and finally exponential which has the overall worst outcome. While I appreciate this might not be exponential growth, I just wanted to know whether you would expect the exponential function perform so badly (basically the coefficient of x,b, has been set to 0 and an arbitrary point has been picked on the curve to intersect) or if I have somehow done something wrong in my code to fit. The code I'm using to fit is as follows: # Fitting def exponenial_func(x,a,b,c): return a*np.exp(-b*x)+c def linear(x,m,c): return m*x+c def quadratic(x,a,b,c): return a*x**2 + b*x+c def cubic(x,a,b,c,d): return a*x**3 + b*x**2 + c*x + d x = np.array(x) yZero = np.array(cancerSizeMean['levelZero'].values)[start:] print len(x) print len(yZero) popt, pcov = curve_fit(exponenial_func,x, yZero, p0=(1,1,1)) expZeroFit = exponenial_func(x, *popt) plt.plot(x, expZeroFit, label='Control, Exponential Fit') popt, pcov = curve_fit(linear, x, yZero, p0=(1,1)) linearZeroFit = linear(x, *popt) plt.plot(x, linearZeroFit, label = 'Control, Linear') popt, pcov = curve_fit(quadratic, x, yZero, p0=(1,1,1)) quadraticZeroFit = quadratic(x, *popt) plt.plot(x, quadraticZeroFit, label = 'Control, Quadratic') popt, pcov = curve_fit(cubic, x, yZero, p0=(1,1,1,1)) cubicZeroFit = cubic(x, *popt) plt.plot(x, cubicZeroFit, label = 'Control, Cubic') *Edit: curve_fit is imported from the scipy.optimize package from scipy.optimize import curve_fit
tagged with: python

countvectorizer
type: Tag
tag name: countvectorizer
tags question: http://stackoverflow.com/q/49946283

http://stackoverflow.com/a/49948229
has comment: http://stackoverflow.com/comment/86914191
has comment: http://stackoverflow.com/comment/86913266
downvote count: 0
has comment: http://stackoverflow.com/comment/86913351
has body: This: np.cumsum(np.ones((5,), np.int) * 3 + np.random.randint(0, maxn, (5,))) - 3 will give you 5 random numbers spaced by at least 3 points. You have to tweak maxn to get the correct maximum value of the random numbers. Perhaps you may want to have a slightly bigger maxn and the reject samples whose elements exceed your maximum value (20). Note: you didn't say what final distribution you are looking for, e.g. if you want the resulting samples uniformly distributed over the space of the valid samples, or anything else, if that matters.
answers question: http://stackoverflow.com/q/49948065
upvote count: 2
has comment: http://stackoverflow.com/comment/86913601
type: Answer
has comment: http://stackoverflow.com/comment/86913463
has comment: http://stackoverflow.com/comment/86913085
score: 2
has comment: http://stackoverflow.com/comment/86913168

centos7
tags question: http://stackoverflow.com/q/50010108
type: Tag
tag name: centos7

http://stackoverflow.com/comment/87034873
score: 0
type: Comment
type: QuestionComment
has text: Guys I am going to use `zip` Sometimes I get 0 accuracy, sometimes I get 100%. Thank you all.
comment on: http://stackoverflow.com/q/50008833

http://stackoverflow.com/comment/87044373
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50013767
score: 2
has text: You're trying to ask multiple questions in one. That doesn't work well with the format of SO. Edit your question to just focus on the first thing, and then you can write separate questions that focus equally on the other things you need to do.

http://stackoverflow.com/comment/87101716
comment on: http://stackoverflow.com/a/50042680
has text: @TerryA indeed, or 0/1.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87196085
comment on: http://stackoverflow.com/a/50075917
type: Comment
has text: Please indicate what you have changed. I see no obvious differencies.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86915976
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49949611
has text: It sounds like you could write up some sort of input stage that feeds data loaded from these pickles directly to tensorflow, rather than making a CSV. A CSV seems superfluous.
score: 1

http://stackoverflow.com/comment/87142289
has text: @onlyphantom My bad :) .
comment on: http://stackoverflow.com/a/50062448
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87119694
has text: That's honestly up to you. Either way works as long as you keep your data in the form of (samples, timesteps, features), and for each sample you map 128 timesteps to one output. I would test out both stateful and stateless out though.
comment on: http://stackoverflow.com/q/50051281
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49952127
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: Python: reconstruct after pos_tag
has body: I have to following results after using pos_tag: list = [('a',` '1'), ('b', '2'), ('c', '3'), ('d', '4')] Now, I have to reconstruct like the following: a b c d I used: [x[0] for x in list] But, it resulted in ['a', 'b', 'c' , 'd']
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49952142

http://stackoverflow.com/a/49961892
downvote count: 0
answers question: http://stackoverflow.com/q/49961846
has body: If I understand your problem, you can use groupby.mean for this. You can replace with groupby.sum if that's what you need. In general, it's a good idea to avoid lambda functions where possible. df = pd.DataFrame({'upvotes': [1, 1, 1, 67, 1], 'headline': ['Software: Sadly we did adopt from the', 'Google’s Stock Split Means More Control for', 'SSL DOS attack tool released exploiting', 'Immutability and Blocks Lambdas and Closures', 'Comment optimiser la vitesse de Wordpress? ']}) df['wordcount'] = df['headline'].str.split().map(len) df = df.groupby('wordcount', as_index=False)['upvotes'].mean()\ .sort_values('upvotes', ascending=False) print(df) # wordcount upvotes # 0 6 23 # 1 7 1
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49961846
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/49991484
has comment: http://stackoverflow.com/comment/87465246
score: 0
type: AcceptedAnswer
has body: You are printing a pointer to a COM object, which is really meaningless. Loop through the attachments, and save each one using Attachment.SaveAsFile. You can then read the attachment contents from a file.
has comment: http://stackoverflow.com/comment/87465837
accepted answer of: http://stackoverflow.com/q/49991284
answers question: http://stackoverflow.com/q/49991284
type: Answer

http://stackoverflow.com/a/50004754
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/87031797
accepted answer of: http://stackoverflow.com/q/50004649
has body: The problem is because the line x[i+1].SetPrice(x[i]) sets x[i+1] to x[i] which is a Toy, not an int.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50004649
upvote count: 8

http://stackoverflow.com/q/50021368
tagged with: python
tagged with: merge
accepted answer: http://stackoverflow.com/a/50021536
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Addition-merging dataframes
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50023863
type: Question
has answer: http://stackoverflow.com/a/50023863
has answer: http://stackoverflow.com/a/50021536
answer count: 2
has body: What is the best way to add the contents of two dataframes, which have mostly equivalent indices: df1: A B C A 0 3 1 B 3 0 2 C 1 2 0 df2: A B C D A 0 1 1 0 B 1 0 3 2 C 1 3 0 0 D 0 2 0 0 df1 + df2 = A B C D A 0 4 2 0 B 4 0 5 2 C 2 5 0 0 D 0 2 0 0

http://stackoverflow.com/q/50065595
has comment: http://stackoverflow.com/comment/87148322
tagged with: ubuntu
has answer: http://stackoverflow.com/a/50101049
has body: I have a Cython-based package which depends on other C++ SO libraries. Those libraries are binary different between Ubuntu (dev) and RedHat (prod). So the SO file generated by Cython has to be different as well. If I use Wheel to package it the file name is same for both environments: package-version-cp27-cp27mu-linux_x86_64.whl So if I upload it to pypi it will conflict with RedHat based distribution of the same package. I have to upload it to pypi because the project is then PEX-ed (via Pants) and PEX tries to download from pypi and fails if it does not find it with the following exception. Exception caught: 'pex.resolver.Unsatisfiable' Any ideas how to resolve it? Thx.
score: 0
tagged with: python
tagged with: cython
tagged with: redhat
linked to: http://stackoverflow.com/q/49279328
has comment: http://stackoverflow.com/comment/87148848
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87148814
answer count: 1
has title: How to create different Python Wheel distributions for Ubuntu and RedHat

http://stackoverflow.com/q/50000758
answer count: 1
type: Question
tagged with: goose
has answer: http://stackoverflow.com/a/54193899
type: UnansweredQuestion
has title: Python Goose-extractor creats a folder in tmp called goose and is filling it with files
tagged with: python
has comment: http://stackoverflow.com/comment/87018305
has comment: http://stackoverflow.com/comment/87018924
score: 0
has body: I'm using goose-extractor to parse a list of urls from a dictionary key. I'm using python 2.7.6 My code is given below : import json import re import sys from goose import Goose from pymongo import MongoClient mongoobj = MongoClient() coll = mongoobj.db_name.coll_name gobj = Goose() eachkey = sys.argv[1] print "\n "+eachkey all_data = [] total_data = len(json_data[eachkey]) count = 0.0 for each_link in json_data[eachkey]: print "\r",str(round(count/total_data,2)), count += 1 try: data = gobj.extract(each_link) new_data =" ".join( re.findall(r"\b\w+\b",data.cleaned_text)) text = "" if new_data: text = new_data elif data.meta_description: text = " ".join(re.findall(r"\b\w+\b", data.title + " " + data.meta_description)) if text: coll.insert_one({"text":text, "label":eachkey, "title":data.title}) except Exception as e: print e Goose seems to be creating a folder in tmp called goose/ it is filling it with tmp files and it has filled up my system space.. I don't want this to crash my system. Is there something I'm doing wrong that garbage collection is not happening correctly.

http://stackoverflow.com/comment/87052984
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50018315
score: 1
has text: No. The tutorial has a file called views.py. You do not.

http://stackoverflow.com/comment/87079137
has text: I haven't overwritten anything at all since the last save, and confirmed that everything was intact, but now the batch profile is entirely blank, so I'm pretty much lost at this point.
score: 0
comment on: http://stackoverflow.com/a/50023746
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87071275
has text: You probably don’t want to separately compress separate chunks. That would effectively mean restarting the compression dictionary over and over, raising the cost and reducing the compression you get (and also require a bunch of headers, and require some kind of framing to delimit the compressed chunks).
comment on: http://stackoverflow.com/a/50027527
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87097259
has text: upvoted! thanks, i considered a for loop several times but I was quite curious if this can be done in a vectorized manner, I even tried as_strided but still no luck so far
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50040463

http://stackoverflow.com/comment/87152854
type: Comment
score: 0
type: AnswerComment
has text: My bad, I'm using Python version 2.7.10. Logic should still be the same for Python 3 just different syntax.
comment on: http://stackoverflow.com/a/50068069

http://stackoverflow.com/q/49918978
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86864112
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86864199
has title: GraphQL queries in Django returning None
has comment: http://stackoverflow.com/comment/86860458
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49924807
tagged with: graphene-python
accepted answer: http://stackoverflow.com/a/49924807
favorite count: 0
type: Question
has body: I am trying to use graphQL queries in django. Basically I have two apps, my 'api' app which contains everything I need to make the queries and another one called 'frontend' from which I call the api to use these queries. I can use the GraphQL view to type queries in it and it works perfectly, but whenever I try to make the query, I get this: "OrderedDict([('users', None)])" Result of my query in the GraphQl view The code: In 'api' my schema.py: import graphene import graphql_jwt from graphene import relay, ObjectType, AbstractType, List, String, Field,InputObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from datetime import date, datetime from django.contrib.auth.models import User from django.contrib.auth import get_user_model .... class Query(graphene.ObjectType): me = graphene.Field(UserType) users = graphene.List(UserType) profile = relay.Node.Field(ProfileNode) all_profiles = DjangoFilterConnectionField(ProfileNode) def resolve_users(self, info): ### Returns all users ### user = info.context.user if user.is_anonymous: raise Exception('Not logged!') if not user.is_superuser: raise Exception('premission denied') return User.objects.all() def resolve_me(self, info): ### Returns logged user ### user = info.context.user if user.is_anonymous: raise Exception('Not logged!') return user def resolve_all_profiles(self, info, **kwargs): ### Returns all profiles ### return Profile.objects.all() ..... def execute(my_query): schema = graphene.Schema(query=Query) return schema.execute(my_query) And the views.py that calls the app 'api' in my app frontend: from django.shortcuts import render import graphene from api import schema from django.contrib.auth import authenticate def accueil(request): if request.user.is_authenticated: check = "I am logged" else: check = "I am not logged" result = schema.execute("""query { users { id username } }""") return render(request, 'frontend/accueil.html', {'result' : resu…
upvote count: 5
has comment: http://stackoverflow.com/comment/86862803
tagged with: graphql
tagged with: django

http://stackoverflow.com/q/49988566
has comment: http://stackoverflow.com/comment/86993660
tagged with: css
has title: Make 2 Divs side by side Html Django
has answer: http://stackoverflow.com/a/61505961
type: Question
has comment: http://stackoverflow.com/comment/86996513
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86993616
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87026688
tagged with: django
upvote count: 1
favorite count: 0
score: 1
tagged with: http://stackoverflow.com/tag/html
has body: My problem is that I can't place 2+ divs in a single line . I can't use float because I have an unstable number of divs (A div for every post in django ) This is the code I am using : Index.html {% load static %} Temporary {% for post in posts %} {{ post.title}} {% endfor %} indexstyle.css .product { height: 350px; width: 250px; background-color: #E5E5E5; border-radius: 10px; margin-right: 2em; float: left; } img{ height: 200px; width: 250px; border-radius: 10px 10px 0px 0px; } a{ text-decoration : none; color: inherit; }
tagged with: python

http://stackoverflow.com/a/49978922
score: 1
upvote count: 1
has body: Assuming you have to split your string beforehand to extract words, you can count the number of words at an earlier stage: from collections import Counter x = 'this is a test string with this string repeated' words_split = x.split() count, c = len(words_split), Counter(words_split) print(count) # 9 print(c) # Counter({'this': 2, 'string': 2, 'is': 1, 'a': 1, 'test': 1, 'with': 1, 'repeated': 1})
type: Answer
answers question: http://stackoverflow.com/q/49978646
downvote count: 0

http://stackoverflow.com/comment/86961492
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49972657
type: AnswerComment
has text: It is not a copy.

http://stackoverflow.com/comment/86849034
type: Comment
type: QuestionComment
has text: try printing `i` and `nums` within your `while` loop
score: 0
comment on: http://stackoverflow.com/q/49916838

http://stackoverflow.com/comment/87095023
comment on: http://stackoverflow.com/a/50039383
type: Comment
has text: Due to policies, I do not have the luxury to tweak the `Models`, but if I get a sufficient reason to do so, which I believe is beyond my knowledge as of now, I might be able to convince the higher people to allow me to refactor.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87009386
type: Comment
type: AnswerComment
has text: is it like this in admin.py :`from django.contrib import admin` `from .models import UserProfile` `admin.site.register(UserProfile)` how come theres an error `Reverse for 'User profiles' not found. 'User profiles' is not a valid view function or pattern name.` ><
comment on: http://stackoverflow.com/a/49994467
score: 0

http://stackoverflow.com/comment/87053645
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50018657
has text: Getting rid of the circular import would be a good idea as well, but it's not strictly necessary.
score: 1

http://stackoverflow.com/comment/86877501
type: Comment
comment on: http://stackoverflow.com/a/49930123
score: 0
type: AnswerComment
has text: Try using a [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) like `'form[name="simTradePreview"]'` as a single argument for `.select()`. Knowing CSS selectors is important when working with the soup. [The docs contain numerous examples](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors).

http://stackoverflow.com/comment/86901479
type: Comment
comment on: http://stackoverflow.com/a/49941254
score: 0
type: AnswerComment
has text: Thanks for inspiration :This was what I need. number = {} for i in range(2): number.update({i: int(input('Enter number {}:'.format(i)))}) if number[0] < number[1]: print ( 'number[0] ({}) is less number[1] ({})'.format ( number[0]

http://stackoverflow.com/q/49951492
tagged with: machine-learning
tagged with: python
tagged with: conv-neural-network
answer count: 3
has body: I wanted to reproduce: from the paper https://arxiv.org/pdf/1312.6199.pdf. I was wondering, how does one actually implement this in pytorch? My main confusion is that for loss_f I am using a torch.nn.CrossEntropy() criterion for example. Do i just need to change the code that I already have from: loss = criterion(outputs+r, labels) loss.backward() to: loss = criterion(outputs+r, labels) loss = loss + c * r.norm(2) loss.backward() or something along those lines (of course include r in the optimizer!). I know its not quite right cuz I did not explicitly show how I implemented x+r or the hypercube constraint but those are parts that I still need to figure out. I think for the moment I want to focus first without the hypercube constraint. If we assume I am ok with going out of that is the above correct? I just want to know if: loss = loss + c * r.norm(2) works as it should. Now if we do include the hypercube constraint how does my solution change? Is that were the "penalty function method" come into place? https://discuss.pytorch.org/t/how-does-one-implement-adversarial-examples-in-pytorch/15668
score: 7
upvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87304006
has answer: http://stackoverflow.com/a/50175816
has answer: http://stackoverflow.com/a/54914094
tagged with: pytorch
type: UnansweredQuestion
has title: How does one implement adversarial examples in pytorch?
downvote count: 0
tagged with: neural-network
has answer: http://stackoverflow.com/a/49956966

http://stackoverflow.com/comment/87076509
comment on: http://stackoverflow.com/q/49989663
score: 0
type: Comment
has text: How about adding a `/text()` to the xpath? E.g. `response.xpath('//*[contains(@class, "some_class")]/text()')`, or it's not the first child, then `//text()`.
type: QuestionComment

http://stackoverflow.com/comment/126415245
has text: @fferri in my case custom `QLineEdit` still had a hidden left part of text but according to `focusOutEvent` it changed when focus was out. Left part became visible. However I had multiple generated `QLineEdit` and when focus is out cursor still remaind in line. In my case solution was firstly to set text to widget and then `setCursorPosition(0)`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50004613
type: Comment

http://stackoverflow.com/q/49970314
tagged with: python
has answer: http://stackoverflow.com/a/69191446
tagged with: google-cloud-storage
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has body: I am trying to upload a photo, after being cropped by croppie into the GCS. The gcs write(imageToUpload) method fails because imageToUpload isn't currently a file, but rather a BLOB. Does anyone know a way to make this work? Perhaps, a way in python to convert a BLOB to a file? The image types that can be returned from Croppie are: 1) Canvas, 2) HTML, 3) BLOB and 4)Base64 Here is the documentation (Ctrl-F "Result"). Any help would be much appreciated!
has answer: http://stackoverflow.com/a/49987369
has answer: http://stackoverflow.com/a/49973583
answer count: 3
has title: How to Upload Croppie Photo to Google Cloud Storage
tagged with: google-app-engine
tagged with: croppie
linked to: http://stackoverflow.com/q/20879639

http://stackoverflow.com/comment/86953735
comment on: http://stackoverflow.com/q/49968873
type: Comment
has text: This really isn't how you write Python. If you're learning this from a tutorial, stop immediately and find one that is written by someone who actually knows the language. [Here](https://sopython.com/wiki/What_tutorial_should_I_read%3F) are a few suggestions.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87041805
comment on: http://stackoverflow.com/q/50012624
score: 0
has text: @abarnert shelling out to wget? The website I am reaching out to suggests "wget" as the API. "what were you expecting?" I get an output file which looks like a TSV containing bunch of information. Like I said, this works fine in a function. "Also, just putting {href_aw} into your string literal won't cause any kind of substitution?" This allowed me to put the variable string "href_aw" in wget command, which I was not able to do directly. That worked, not sure about your "!" comment since that worked as well.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50054412
downvote count: 0
has body: I am new to azure. I am following starter instructions from https://learn.microsoft.com/en-us/azure/app-service/app-service-web-get-started-python#configure-a-deployment-user. I have closed some gaps in the instructions so far such as incomplete commands (missing &lt;--%> for Bash in &lt; az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name &lt; app_name> --runtime "python|3.4" --deployment-local-git>) or git init (needed before the command git remote add azure &lt; deploymentLocalGitUrl-from-create-step>). Now I am stuck at the step of the push to Azure remote to deploy the app. The command &lt;git push azure master&gt; with the current failure PS Azure:\&gt; git push azure master fatal: Not a git repository (or any of the parent directories): .git I have checked the git status: it showed that there is no commit yet. Any suggestion? I trust the procedure from Azure team and I am following it to the point. Any better resource or updated resource that I could rely to?
tagged with: azure
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87125565
favorite count: 0
type: Question
tagged with: azure-web-app-service
tagged with: web-deployment
has comment: http://stackoverflow.com/comment/87236385
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50055178
tagged with: python
has comment: http://stackoverflow.com/comment/87387886
has comment: http://stackoverflow.com/comment/87273160
has title: git push azure master azure fatal: Not a git repository (or any of the parent directories): .git

http://stackoverflow.com/comment/87014776
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49999407
has text: Update your HTML sample as it's not really readable. Share your current Python code as well
score: 0

http://stackoverflow.com/q/49979749
possible better answer: http://stackoverflow.com/a/49979890
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86975450
answer count: 2
duplicate of: http://stackoverflow.com/q/3627784
has title: Case sensitive conditional string testing in Python
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/49979840
tagged with: string
has comment: http://stackoverflow.com/comment/86975414
has body: Let's say that you wish to check existing usernames in a list using Python, ensuring that we check for case sensitivity, such that we force new users to select a unique username so you write something that looks like this: current_users = ['lana', 'matthew', 'kevin', 'lars', 'louis', 'sarah'] new_users = ['tom', 'tim', 'gus', 'david'] for user in new_users: if user.title().upper().lower() in current_users: print("Sorry, " + user.title() + ", but that username is already taken. Please choose a new username.") else: print("Hello, " + user.title() + ", that username is available. Welcome aboard!") I've tested the code and I know that it works, but I don't pretend to be the world's best coder, and this code doesn't look to be the most efficient. Is there another way to do this in Python without chaining .title().upper().lower() to check for case sensitivity? Also, how would one test for a user who capitalised a character inside the username, such as 'maTThew'?
linked to: http://stackoverflow.com/q/3627784
has answer: http://stackoverflow.com/a/49979890
favorite count: 0
has answer: http://stackoverflow.com/a/49979840
type: Question
has comment: http://stackoverflow.com/comment/86975954
has comment: http://stackoverflow.com/comment/86975431
has comment: http://stackoverflow.com/comment/86975552

http://stackoverflow.com/q/49988617
has answer: http://stackoverflow.com/a/49989163
type: Question
type: UnansweredQuestion
has title: Split integers in string - python
has answer: http://stackoverflow.com/a/49988789
has body: I've got a bunch of numbers in a string. I want to split them into individual digits so I can do more with them later. number = [6, 18, 6, 4, 12, 18, 0, 18] I want to split these like so.... ex: 6, 1, 8, 6, 4, 1, 2, 1, 8, 0, 1, 8 I've tried split(), I've tried list(str(number)), I've tried converting these to strings and integers and I have tried searching stackoverflow. In other searches I keep seeing a list comprehension example like this, which I don't understand and don't get the desired result after trying: [int(i) for i in str(number)] help??
has answer: http://stackoverflow.com/a/49988748
tagged with: python
score: 0
answer count: 3

http://stackoverflow.com/q/49976342
favorite count: 0
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49976560
has answer: http://stackoverflow.com/a/49976494
tagged with: sensors
downvote count: 1
tagged with: python
score: -1
type: Question
has title: Unboundlocalerror: local variable ' pulse_start' is referenced before assignment
has body: It stated that unboundlocalerror: local variable 'pulse_start' referenced before assignment. I run it previously and so sudden error happen. import RPi.GPIO as GPIO, time GPIO.setwarnings(False) def ultrasonicfunction(DistanceOfWaterLevelFromSensor): GPIO.cleanup() GPIO.setmode(GPIO.BCM) TRIG = 23 ECHO = 18 GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) GPIO.output(TRIG, False) time.sleep(1) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO) == 0: pulse_start = time.time() while GPIO.input(ECHO) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17000 if distance &gt; 44: DistanceOfWaterLevelFromSensor = "0" print 'Please place the ultrasonic sensor near the water tank' # Watertank height = 44cm, else: DistanceOfWaterLevelFromSensor = 44 - distance DistanceOfWaterLevelFromSensor = "%.2f" % round(DistanceOfWaterLevelFromSensor, 2) return DistanceOfWaterLevelFromSensor
upvote count: 0
has comment: http://stackoverflow.com/comment/86968716
answer count: 2
type: UnansweredQuestion

robotframework
tags question: http://stackoverflow.com/q/49985035
tags question: http://stackoverflow.com/q/49952139
tags question: http://stackoverflow.com/q/49974379
tag name: robotframework
type: Tag

http://stackoverflow.com/comment/87013834
score: 0
has text: Test on bigger sized arrays?
comment on: http://stackoverflow.com/q/49998879
type: Comment
type: QuestionComment

classification
tags question: http://stackoverflow.com/q/50002654
tags question: http://stackoverflow.com/q/49967190
tags question: http://stackoverflow.com/q/49963138
tags question: http://stackoverflow.com/q/50040352
tag name: classification
tags question: http://stackoverflow.com/q/49929583
tags question: http://stackoverflow.com/q/50004805
tags question: http://stackoverflow.com/q/50011221
tags question: http://stackoverflow.com/q/49969215
tags question: http://stackoverflow.com/q/50004602
tags question: http://stackoverflow.com/q/49987532
type: Tag
tags question: http://stackoverflow.com/q/50010040
tags question: http://stackoverflow.com/q/50042925

http://stackoverflow.com/q/50020949
score: 2
has comment: http://stackoverflow.com/comment/87057784
has comment: http://stackoverflow.com/comment/87057785
has comment: http://stackoverflow.com/comment/87057707
upvote count: 2
has comment: http://stackoverflow.com/comment/87057570
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87057636
linked to: http://stackoverflow.com/q/403421
tagged with: sorting
has comment: http://stackoverflow.com/comment/87058365
has body: I've got an interesting question that I do not understand at all why this is happening. So, I'm trying to sort a list of tuples, where the first element of tuple is an object, based on the attributes within the said objects. So, I have created the following code to test this functionality: class s(object): def __init__(self, name): self._name = name def get_name(self): return self._name def val(x): #This used in place of a lambda return x[0]._name e1 = s("Fred") e2 = s("Bill") print(e2.get_name()) list1 = [(e1, 3), (e2, 4)] for n in list1: print(val(n)) list2 = sorted(list1, key = val) print(list2) print(list2[0] == e2) print(e2.get_name) print(e2._name) With the output of this being: Bill Fred Bill [(&lt;__main__.s object at 0x0000002AC47D6438&gt;, 4), (&lt;__main__.s object at 0x0000002AC47D6240&gt;, 3)] False &lt;bound method s.get_name of &lt;__main__.s object at 0x0000002AC47D6438&gt;&gt; Bill I have absolutely no clue why I'm getting the memory addresses of the attributes as the first elements of my tuples after sorting, and I've scoured through SO and there really shouldn't be any issue with this code since it looks exactly the same as alot of other posts on this. Can ANYONE please help me out here and point out why this is happening? I expect this output: print(list2) #After sorting OUTPUT: [(e2, 4), (e1, 3)]
has comment: http://stackoverflow.com/comment/87057872
favorite count: 0
has title: Sorting list of objects based on attribute, returns memory address instead
tagged with: tuples
tagged with: object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87057733
tagged with: list
has answer: http://stackoverflow.com/a/50021353
accepted answer: http://stackoverflow.com/a/50021353
linked to: http://stackoverflow.com/q/1436703
has comment: http://stackoverflow.com/comment/87057959
tagged with: python
has comment: http://stackoverflow.com/comment/87057683
has comment: http://stackoverflow.com/comment/87058076
type: Question

http://stackoverflow.com/q/50038651
has answer: http://stackoverflow.com/a/56866797
tagged with: python
has comment: http://stackoverflow.com/comment/87095401
accepted answer: http://stackoverflow.com/a/53884012
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53884012
answer count: 3
tagged with: anaconda
tagged with: spyder
downvote count: 0
has comment: http://stackoverflow.com/comment/87094878
has answer: http://stackoverflow.com/a/69357883
has comment: http://stackoverflow.com/comment/87095423
has comment: http://stackoverflow.com/comment/87095345
tagged with: osmnx
tagged with: import
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/87099288
has title: A module is working in Anaconda prompt, but not in Spyder
has comment: http://stackoverflow.com/comment/87099389
has body: I have been fighting with this problem for hours now, and it's a kind of complicated one. I'm on windows 7, Python 2.7, Spyder 3.2.6 I tried to install OSMNX through cygwin, however I faced many issues. Finally managed to install it through windows cmd. Through the anaconda prompt, I could import the osmnx with no error. However, I'm trying to import it in spyder, but I keep receiving: Traceback (most recent call last): File "&lt;ipython-input-2-2b99ab66aebb&gt;", line 1, in &lt;module&gt; import osmnx ImportError: No module named osmnx What is exactly wrong here? and how can I solve it?
upvote count: 8
has comment: http://stackoverflow.com/comment/87099481
has comment: http://stackoverflow.com/comment/87093468
possible better answer: http://stackoverflow.com/a/69357883
has comment: http://stackoverflow.com/comment/87099521

http://stackoverflow.com/q/49919768
answer count: 2
downvote count: 0
score: 7
tagged with: typed-memory-views
upvote count: 7
has title: Cython: size attribute of memoryviews
tagged with: cython
has body: I'm using a lot of 3D memoryviews in Cython, e.g. cython.declare(a='double[:, :, ::1]') a = np.empty((10, 20, 30), dtype='double') I often want to loop over all elements of a. I can do this using a triple loop like for i in range(a.shape[0]): for j in range(a.shape[1]): for k in range(a.shape[2]): a[i, j, k] = ... If I do not care about the indices i, j and k, it is more efficient to do a flat loop, like cython.declare(a_ptr='double*') a_ptr = cython.address(a[0, 0, 0]) for i in range(size): a_ptr[i] = ... Here I need to know the number of elements (size) in the array. This is given by the product of the elements in the shape attribute, i.e. size = a.shape[0]*a.shape[1]*a.shape[2], or more generally size = np.prod(np.asarray(a).shape). I find both of these ugly to write, and the (albeit small) computational overhead bothers me. The nice way to do it is to use the builtin size attribute of memoryviews, size = a.size. However, for reasons I cannot fathom, this leads to unoptimized C code, as evident from the annotations html file generated by Cython. Specifically, the C code generated by size = a.shape[0]*a.shape[1]*a.shape[2] is simply __pyx_v_size = (((__pyx_v_a.shape[0]) * (__pyx_v_a.shape[1])) * (__pyx_v_a.shape[2])); where the C code generated from size = a.size is __pyx_t_10 = __pyx_memoryview_fromslice(__pyx_v_a, 3, (PyObject *(*)(char *)) __pyx_memview_get_double, (int (*)(char *, PyObject *)) __pyx_memview_set_double, 0);; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 2238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __pyx_t_14 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_n_s_size); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 2238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_14); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_7 = __Pyx_PyIndex_AsSsize_t(__pyx_t_14); if (unlikely((__pyx_t_7 == (Py_ssize_t)-1) &amp;&amp; PyErr_Occurred())) __PYX_ERR(0, 2238, __pyx_L1_error) __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; __pyx_v_size = __pyx_t_7; To generate the above code, I have …
tagged with: attributes
favorite count: 0
accepted answer: http://stackoverflow.com/a/49925999
type: Question
has answer: http://stackoverflow.com/a/49922687
possible better answer: http://stackoverflow.com/a/49922687
tagged with: memoryview
tagged with: python
has answer: http://stackoverflow.com/a/49925999
type: AnsweredQuestion

http://stackoverflow.com/comment/86888507
has text: `A=[9,8,7,6]` , `B = [1,10,1,10]` - you do not print the `k` max errors but the first `k` ones.
comment on: http://stackoverflow.com/a/49936355
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50066828
has title: Initialize function variable once & change variable value when function is called
has body: Language: Python I want the value of a variable to be initialized to zero at the start of the execution. This variable is used in a function &amp; its value may also get changed within the function. But I do not want the value of this variable to reset to zero whenever a function call is made. Instead, its value should be equal to the updated value from its previous function call. Example: get_current() is constantly returning a different value when it is called. ctemp is initially zero. In the first function call get_current_difference() will return cdiff &amp; then update the value of ctemp such that ctemp = current. In the second function call, the value of ctemp should not be zero. Instead, it should be equal to the updated value from the first function call. import serial arduino = serial.Serial('/dev/ttyACM1',9600) ctemp = 0 def get_current(): line = arduino.readline() string = line.replace('\r\n','') return string def get_current_difference(): global ctemp current = get_current() cdiff = float(current) - ctemp return cdiff ctemp = current while 1: current = get_current_difference() print(current)
type: Question
tagged with: function
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50066896
has answer: http://stackoverflow.com/a/50066918
tagged with: global-variables
score: 0
answer count: 2

http://stackoverflow.com/a/49978096
answers question: http://stackoverflow.com/q/49977932
type: Answer
has body: You can first create the index using slice and then apply it: &gt;&gt;&gt; index = [slice(None)]*N &gt;&gt;&gt; index[M] = ind &gt;&gt;&gt; x[index] = y
score: 0

http://stackoverflow.com/comment/87108335
type: Comment
score: 1
has text: Do not forget existing tools like the `.dump` command of the [CLI tool](https://www.sqlite.org/cli.html), of the dedicated [sqldiff.exe: Database Difference Utility](https://www.sqlite.org/sqldiff.html)
type: QuestionComment
comment on: http://stackoverflow.com/q/50045714

http://stackoverflow.com/a/50041590
score: 0
has comment: http://stackoverflow.com/comment/87099280
has comment: http://stackoverflow.com/comment/87099095
has body: Maybe the following is a bit too simplistic: # ----------------------------Algorithm 1---------------------------# def main1(): # Algorithm 1 Functions print('Algorithm 1 Functions') # ----------------------------Algorithm 2---------------------------# def main2(): # Algorithm 2 Functions print('Algorithm 2 Functions') if __name__ == "__main__": alg = input("0 for Algorithm 1 / 1 forAlgorithm 2: ") if alg == 0: main1() elif alg == 1: main2() else: print('Incorrect input')
type: Answer
answers question: http://stackoverflow.com/q/50041294

http://stackoverflow.com/a/49950787
has body: There's not a one-liner way to do it. Here's an example of a method for getting the uv bounding boxes of the shells in Python. It uses the API to get bounding boxes for all the uv shells in an object (note -- it should be a mesh shape object , I didn't add any checks). import maya.api.OpenMaya as api from math import floor def get_shells(obj, uvset = ''): selected = api.MGlobal.getSelectionListByName(obj) node = selected.getDependNode(0) mesh = api.MFnMesh(node) howmany, shell_ids = mesh.getUvShellsIds(uvset) u_list, v_list = mesh.getUVs() shells = [] for shell_num in range(howmany): umin = vmin = 9999999999999 umax= vmax = -9999999999999 for idx, value in enumerate(shell_ids): if value == shell_num: umin = min(umin, u_list[idx]) umax = max(umax, u_list[idx]) vmin = min(vmin, v_list[idx]) vmax = max(vmax, v_list[idx]) shells.append ( (umin, vmin, umax, vmax) ) return shells print get_shells('pCylinderShape1') # [(0.3437499701976776, -7.450580596923828e-08, 0.65625, 0.3125), (0.375, 0.3125, 0.6249997615814209, 0.6884398460388184), (0.3437499701976776, 0.6874999403953552, 0.65625, 1.0)] The result is a list of 4-item tuples which are the bounding boxes of the uv shells in the object stored as ( u min, v min, u max, v max ) . To catch a tile boundary just check that the minimum and maximum corners of the are the same integer values: for shell in get_shells('pCylinderShape1'): mintile = int(shell[0]), int(shell[1]) maxtile = int(shell[2]), int(shell[3]) if mintile != maxtile: print "shell crosses UV boundary", shell
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49932107
answers question: http://stackoverflow.com/q/49932107
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/q/49969087
score: -2
has title: Alternative to GridSearchCV for finding the parameters for SVM model
tagged with: grid-search
tagged with: python
has comment: http://stackoverflow.com/comment/86964042
tagged with: svm
has answer: http://stackoverflow.com/a/49970026
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
has body: I am working on a transactional dataset where I am trying to create a churn prediction model using SVM. I have manually defined my training and testing dataset and have not used CrossValidation. However, to find the best hyperparameters for my SVM(svc) model, is there any alternative way to do it without Grid Search CV, my objective here is to try and prevent any data leakage happening as I understand that using CV wouldn't solve that problem.
favorite count: 0
type: Question

http://stackoverflow.com/comment/87123727
type: QuestionComment
comment on: http://stackoverflow.com/q/50053576
type: Comment
score: 0
has text: It is good that you put a minimum code, but at the same time that code must be complete in the sense that it can be executed, and yours is not, please take the time and improve your example. :D

http://stackoverflow.com/q/49988624
has body: Suppose you have the following list of lists: list1 = [[1,2,3], [9, 0], [5], [-4,-5,-2,-3,-1]]; Using only basic operations and loops, how to interleave the lists, so the result is the following: result = [1,9,5,-4,2,0,-5,3,-2,-3,-1] All the solutions I found here use some sort of libraries, but I'm interested in the solution only using loops. My current solution is: result = [] def interleave(myList): for i in range(len(myList)): if len(myList[i]) == 0: continue result.append( myList[i][0] ) del myList[i][0] print result list1 = [[1,2,3], [9, 0], [5], [-4,-5,-2,-3,-1]] print list1 interleave(list1) interleave(list1) interleave(list1) interleave(list1) interleave(list1) What tricks me right now, is how to put these 5 calls to my interleave function inside the function, so I call interleave() only once.
has comment: http://stackoverflow.com/comment/86993749
tagged with: python
accepted answer: http://stackoverflow.com/a/49988809
downvote count: 4
has answer: http://stackoverflow.com/a/49988887
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86993866
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/49988872
has comment: http://stackoverflow.com/comment/86993805
score: -1
has answer: http://stackoverflow.com/a/49988809
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49988872
has comment: http://stackoverflow.com/comment/86993893
has comment: http://stackoverflow.com/comment/86993677
has title: Interleave list of list without modules
has comment: http://stackoverflow.com/comment/86993793

http://stackoverflow.com/a/49951096
has body: You could use. separator = ' ' parameters = input("parameters:").split(separator) e.g. Python 3.6.5 (default, Mar 30 2018, 06:42:10) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; separator = '-' &gt;&gt;&gt; parameters = input("parameters:").split(separator) parameters:5-6 &gt;&gt;&gt; parameters ['5', '6'] &gt;&gt;&gt;
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/49951072
accepted answer of: http://stackoverflow.com/q/49951072
upvote count: 4
has comment: http://stackoverflow.com/comment/86918762

http://stackoverflow.com/q/49958000
has comment: http://stackoverflow.com/comment/86933087
tagged with: django
tagged with: django-urls
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: django-views
linked to: http://stackoverflow.com/q/49960589
has comment: http://stackoverflow.com/comment/86932883
has body: My proof App's CreateView takes 2 arguments "user" and "post". The user requirement is fulfilled by self.object.user = self.request.user How do I satisfy the self.object.post requirement. I am new to Django. I apologize if I am violating any Django rules models.py User = get_user_model() class Proof(models.Model): user = models.ForeignKey(User, related_name='proofmade') post = models.ForeignKey(Post, related_name='proofmade') made_at = models.DateTimeField(auto_now=True) image_of_task= models.ImageField() proof_you_made_it = models.ImageField() suggestions = models.TextField(max_length=1000) def __str__(self): return self.post.title views.py User = get_user_model() class ProofCreate(LoginRequiredMixin, CreateView): model = Proof fields = ('image_of_task', 'proof_you_made_it', 'suggestions') def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.user = self.request.user ###### I think the following line may be wrong ########## slug = self.kwargs.get('slug') print(slug) self.object.post = get_object_or_404(Post, slug=slug) self.object.save() return super().form_valid(form) urls.py app_name = 'proof' urlpatterns = [ url(r'^new_proof/$', views.ProofCreate.as_view(), name='new_proof'),
answer count: 1
has comment: http://stackoverflow.com/comment/86933677
has answer: http://stackoverflow.com/a/49958931
accepted answer: http://stackoverflow.com/a/49958931
has title: 404 error on CreateView form_valid with more than 1 arguement
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86932267
has comment: http://stackoverflow.com/comment/86932408

http://stackoverflow.com/comment/87016795
type: QuestionComment
type: Comment
has text: Is it an issue with case? I think it should still open it though.
score: 0
comment on: http://stackoverflow.com/q/50000399

http://stackoverflow.com/comment/87095456
type: Comment
has text: `if selected_pizza in range(len(pizzas_with_prices)):`
score: 0
comment on: http://stackoverflow.com/q/50039694
type: QuestionComment

http://stackoverflow.com/comment/86994136
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49988774
has text: And that will be very nice. Until 3.6 becomes the norm, we have to warn users about this order issue (note that OP is using python 2.7 as the tag says, and `map` which returns a list is another giveaway :)
type: Comment

http://stackoverflow.com/comment/87044597
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50014176
has text: Hi @Bert, can you provide me the link to the source? please!

http://stackoverflow.com/comment/86947307
comment on: http://stackoverflow.com/q/49965288
score: 0
has text: If you do not input `'good'` you will skip the age and cover things ... they _are_ only executed fot `'good'` books.I do not get you
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50025314
has body: You can do this with just a str.replace() full_string = 'H12-H121' sub_string = 'H12' output_string = full_string.replace(sub_string,"G12",1) print(output_string) outputs: G12-H121
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50025151
score: 2

segmentation-fault
tags question: http://stackoverflow.com/q/50015737
tag name: segmentation-fault
tags question: http://stackoverflow.com/q/50002896
type: Tag

http://stackoverflow.com/comment/86964116
score: 0
has text: Any reason to trim the `tagName` from the HTML provided within the question?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49972237

http://stackoverflow.com/a/52213917
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50069730
downvote count: 0
has body: In Python, objects are passed as reference. That means even though a LazyFrame object might be a list of extremely big numpy arrays, the size of that LazyFrame object itself is small, since it only stores the reference to the np.ndarrays. In other words, you can think of LazyFrame just pointing to the np.ndarray data, and not actually storing each copy of the individual array within itself. import numpy as np a = np.ones((2,3)) b = np.ones((2,3)) X = [a, b] print(X) &gt;&gt;&gt; [array([[1., 1., 1.], [1., 1., 1.]]), array([[1., 1., 1.], [1., 1., 1.]])] X_stacked = np.stack(X) print(X_stacked) &gt;&gt;&gt; array([[[1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.]]]) a[0] = 2 print(X) &gt;&gt;&gt; [array([[2., 2., 2.], [1., 1., 1.]]), array([[1., 1., 1.], [1., 1., 1.]])] print(X_stacked) &gt;&gt;&gt; array([[[1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.]]]) As you can see here, X (which is a list of arrays) stores only the reference to a and b, thus when we do a[0] = 2, the change can be seen by printing X. But once you stack the arrays, you actually create a new array with that much memory. To address your "how does it save memory" question a bit more directly, here's an example. import sys a = np.random.randn(210, 160, 3) b = np.random.randn(210, 160, 3) X = [a,b] X_stacked = np.stack(X) print(sys.getsizeof(X)) &gt;&gt;&gt; 80 print(sys.getsizeof(X_stacked)) &gt;&gt;&gt; 1612944
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50069730
has comment: http://stackoverflow.com/comment/96399799
type: Answer

http://stackoverflow.com/q/49927619
has comment: http://stackoverflow.com/comment/86871964
tagged with: deep-learning
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86871748
downvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51915786
has comment: http://stackoverflow.com/comment/86871646
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86896454
upvote count: 2
has body: I am trying to build a simple neural network to recognize 14 words from the voice of 2 people. I created a train dataset containing 2471 files with a length of 0.5 s (8000 Hz) and a test dataset containing 612 files. I used "Short-time Fourier transform" like this: _, _, d = signal.stft(d, 8000, nperseg=400) d = numpy.abs(d) The spectrogram of example file: And this is my network: net = tflearn.input_data(shape=[None, 201, 21]) net = tflearn.max_pool_1d(net, 8) net = tflearn.conv_1d(net, 128, 6, activation='relu') net = tflearn.avg_pool_1d(net, 4) net = tflearn.fully_connected(net, 128, activation='relu') net = tflearn.dropout(net, 0.6) net = tflearn.fully_connected(net, 14, activation='softmax') net = tflearn.regression(net, optimizer='adam', loss='categorical_crossentropy', learning_rate=0.02) # Train model model = tflearn.DNN(net) model.fit(X, Y, n_epoch=12, validation_set=(X_test, Y_test), show_metric=True) I tried to change many parameters, but the accuracy of the network is still around 90% | Adam | epoch: 011 | loss: 0.34011 - acc: 0.9428 | val_loss: 0.23105 - val_acc: 0.9003 | Adam | epoch: 012 | loss: 0.37237 - acc: 0.9253 | val_loss: 0.22360 - val_acc: 0.9118 After 100 epochs: | Adam | epoch: 088 | loss: 0.21640 - acc: 0.9753 | val_loss: 0.24923 - val_acc: 0.9297 | Adam | epoch: 099 | loss: 0.48295 - acc: 0.9469 | val_loss: 0.28505 - val_acc: 0.9346 | Adam | epoch: 100 | loss: 0.56168 - acc: 0.9489 | val_loss: 0.24747 - val_acc: 0.9395 After 500 epochs: | Adam | epoch: 485 | loss: 0.20620 - acc: 0.9795 | val_loss: 0.41541 - val_acc: 0.9265 | Adam | epoch: 493 | loss: 0.48699 - acc: 0.9559 | val_loss: 0.23821 - val_acc: 0.9248 -- iter: 4942/4942 | Adam | epoch: 499 | loss: 0.69429 - acc: 0.9501 | val_loss: 0.39483 - val_acc: 0.8987 | Adam | epoch: 500 | loss: 0.87411 - acc: 0.9394 | val_loss: 0.36144 - val_acc: 0.9248 Can anyone tell me what I can change to get better results? What am I doing wrong ? Increasing the number of neurons or epochs does not impro…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86871270
has title: How can I improve the accuracy of my neural network?
has comment: http://stackoverflow.com/comment/86872852
tagged with: tflearn
tagged with: python
has comment: http://stackoverflow.com/comment/86875410
tagged with: voice-recognition

http://stackoverflow.com/q/49954262
type: Question
has comment: http://stackoverflow.com/comment/86926028
has answer: http://stackoverflow.com/a/49954963
possible better answer: http://stackoverflow.com/a/49954963
has answer: http://stackoverflow.com/a/49954971
tagged with: python
has body: I have problems operating with the exiting database in mysql using a sqlalchemy as I need it for building Flask RESTful api. I get funny errors about circular dependencies here: from flask import Flask, request, jsonify, make_response from flaskext.mysql import MySQL from flask_sqlalchemy import SQLAlchemy #from webapi import models # mysql = MySQL() app = Flask(__name__) app.config['SECRET_KEY'] = 'secretkey' #for use later app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@127.0.0.1/mydb' db = SQLAlchemy(app) class Extensions(db.Model): __tablename__ = "Extensions" extnbr = db.Column(db.Integer, primary_key=True, default="NULL") authname = db.Column(db.String(256), nullable=True, default="@nobody") extpriority = db.Column(db.Integer, nullable=True, default=0) callaccess = db.Column(db.Integer, nullable=True, default=0) extlocation = db.Column(db.String, nullable=True, default="NULL") display = db.Column(db.String, nullable=True, default="NULL") @app.route("/") def hello(): return "Welcome to Python Flask App!" @app.route("/extensions", methods=["GET"]) def get_all_extensions(): users = Extensions.query.all() output = [] for user in users: user_data = {} user_data['extnbr'] = user.extnbr user_data['authname'] = user.authname user_data['extpriority'] = user.extpriority user_data['callaccess'] = user.callaccess user_data['extlocation'] = user.extlocation user_data['display'] = user.display output.append({'extensions' : output}) return jsonify({'users' : output}) if __name__ == "__main__": app.run(debug=True) I get error about circular dependence: Debug and trace: https://dpaste.de/F3uX
tagged with: flask
has comment: http://stackoverflow.com/comment/86926135
has comment: http://stackoverflow.com/comment/86925722
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49954971
has title: How to get SQLAlchemy working with mysql with existing database
tagged with: http://stackoverflow.com/tag/json
tagged with: mysql
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/87069022
score: 1
has text: Possible duplicate of [Not able to install python packages \[SSL: TLSV1\_ALERT\_PROTOCOL\_VERSION\]](https://stackoverflow.com/questions/49768770/not-able-to-install-python-packages-ssl-tlsv1-alert-protocol-version)
type: QuestionComment
comment on: http://stackoverflow.com/q/50024617
type: Comment

http://stackoverflow.com/q/49960195
upvote count: 2
has body: I need to read in data which is stored in many files of the same format, but varying length, i.e. identical columns, but varying number of rows. Furthermore, I need each column of the data to be stored in one array (preferrably one numpy array, but a list is also acceptable). For now, I read in every file in a loop with numpy.loadtxt() and then concatenate the resulting arrays. Say the data consists of 3 columns and is stored in the two files "foo" and "bar": import numpy as np filenames = ["foo", "bar"] col1_all = 0 #data will be stored in these 3 arrays col2_all = 0 col3_all = 0 for f in filename: col1, col2, col3 = np.loadtxt(f, unpack=True) if col1.shape[0] &gt; 0: # I can't guarantee file won't be empty if type(col1_all) == int: # if there is no data read in yet, just copy arrays col1_all = col1[:] col2_all = col2[:] col3_all = col3[:] else: col1_all = np.concatenate((col1_all, col1)) col2_all = np.concatenate((col2_all, col2)) col3_all = np.concatenate((col3_all, col3)) My question is: Is there a better/faster way to do this? I need this to be as quick as possible, as I need to read in hundreds of files. I could imagine, for example, that first finding out how many rows in total I will have and "allocating" an array of big enough size to fit all the data first, then copying the read-in data in that array might perform better, as I circumvent the concatenations. I don't know the total number of rows, so this will have to be done in python too. Another idea would be first read in all the data, store each read-in separately, and concatenate them in the end. (Or, as this essentialy gives me the total number of rows, allocate a row that fits all the data, and then copy the data in there). Does anyone have experience on what works best?
tagged with: arrays
answer count: 1
downvote count: 0
has title: Python fast way to get data from multiple files in single numpy array
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49960255
score: 2
tagged with: numpy
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86937182
has answer: http://stackoverflow.com/a/49960255

http://stackoverflow.com/comment/86935105
type: Comment
has text: maybe just use `df = df.assign(...)`, this will overwrite `df`with the correct values. Assign just append a column without modifying the underlying data frame. Concerning the nan's, look that I am applying them after assign. In your solution, the pd.Series stuff does not cause nan's (check it, the series is nan free), the assignment to 'dns' will cause nans since there are for some index values of df no value is passed.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49919654

http://stackoverflow.com/comment/86890583
score: 0
has text: Thank you @Jean-François Fabre. This is what I wanted to do :)
comment on: http://stackoverflow.com/a/49937458
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49951066
has body: You can use remove Example: list=['A','B','C'] list.remove('A')
downvote count: 1
has comment: http://stackoverflow.com/comment/86918788
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49951041
upvote count: 0

http://stackoverflow.com/comment/86946206
has text: @Mehrdad-pedramfar i just edited it
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49965143
type: QuestionComment

http://stackoverflow.com/comment/87084195
type: Comment
type: QuestionComment
has text: Unfortunately, I have to use Python for this. I tried some ways but I hit the wall.
comment on: http://stackoverflow.com/q/50021611
score: 0

http://stackoverflow.com/q/50032647
has answer: http://stackoverflow.com/a/50033099
duplicate of: http://stackoverflow.com/q/23296282
type: UnansweredQuestion
has body: import numpy as np import pandas as pd df = pd.DataFrame([[np.nan, 2, 1, 0], [3, 4, np.nan, 1], [np.nan, np.nan, 8, 5], [np.nan, 3, np.nan, 4]], columns=list('ABCD')) df2 = df df.fillna(value = df.mean(), inplace=True) Now df2 and df are identical. How do I avoid changing df2?
tagged with: python
has answer: http://stackoverflow.com/a/50032664
linked to: http://stackoverflow.com/q/23296282
has comment: http://stackoverflow.com/comment/87081482
score: 0
answer count: 3
tagged with: pandas
has title: Pandas fillna with inplace=True changes all dataframes that are equal to the one that it is supposed to operate on
linked to: http://stackoverflow.com/q/21537078
type: Question
has answer: http://stackoverflow.com/a/50032708

http://stackoverflow.com/comment/87129421
comment on: http://stackoverflow.com/q/50056461
type: Comment
score: 1
has text: Is there a _reason_ this has to be a one-liner all crammed into a single `print`? You can do it, but that doesn't mean you _should_ do it.
type: QuestionComment

http://stackoverflow.com/comment/86977332
type: QuestionComment
comment on: http://stackoverflow.com/q/49979054
score: 0
has text: @Inian code added.
type: Comment

http://stackoverflow.com/comment/87020381
score: 0
type: QuestionComment
type: Comment
has text: @Dark Here it is: 0 [{'outlets': [{'connector': 7, 'id': 340304, '... 1 [{'network_id': 8, 'outlets': [{'connector': 6... 10 [{'outlets': [{'connector': 10, 'id': 364859, ... 100 [{'outlets': [{'connector': 10, 'id': 329118, ... 101 [{'outlets': [{'connector': 14, 'id': 462278, ... Name: stations, dtype: object
comment on: http://stackoverflow.com/q/50002021

http://stackoverflow.com/q/49947820
downvote count: 0
accepted answer: http://stackoverflow.com/a/49956651
tagged with: databricks
has answer: http://stackoverflow.com/a/49956651
favorite count: 0
type: Question
tagged with: apache-spark-sql
score: 8
upvote count: 8
has title: Saving a dataframe result value to a string variable?
possible better answer: http://stackoverflow.com/a/49948259
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49948259
has body: I created a dataframe in spark when find the max date I want to save it to the variable. Just trying to figure out how to get the result, which is a string, and save it to a variable. code so far: sqlDF = spark.sql("SELECT MAX(date) FROM account") sqlDF.show() what results look likes: +--------------------+ | max(date)| +--------------------+ |2018-04-19T14:11:...| +--------------------+ thanks
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49948069
answer count: 3

http://stackoverflow.com/comment/86860093
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49921626
has text: did you use robo 3T ?

http://stackoverflow.com/q/49957509
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/49957888
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86931269
tagged with: random
has body: I was watching SentDex, youtuber , about pygame tutorial makinga a "simple" game... So I decided to renovate it, to make my own , but with same flat as his. when you play apples are falling from trees and you have to catch them with the cart, however, when i want to catch it apple go trough , but it doesn't go trough when apple hits the edge. Here is code: import pygame import time import random pygame.init() width = 800 height = 600 gameDisplay = pygame.display.set_mode((width,height)) pygame.display.set_caption("Catching apples") clock = pygame.time.Clock() apple = pygame.image.load("jabuka.png") cartImg = pygame.image.load("gajba.png") black = (0,0,0) white = (255,255,255) red = (255,0,0) def apples(x,y): gameDisplay.blit(apple,(x,y)) def text_objects(text,font): textSurface = font.render(text,True,black) return textSurface,textSurface.get_rect() def message_dispaly(text): largeText = pygame.font.Font("freesansbold.ttf",90) TextSurf, TextRect = text_objects(text,largeText) TextRect.center = ((sirina/2),(visina/2)) gameDisplay.blit(TextSurf,TextRect) pygame.display.update() time.sleep(2) game_loop() def n_uhvatili(): message_dispaly("You did no catch the apple!") def gajba(x,y): gameDisplay.blit(cartImg,(x,y)) def game_loop(): #About apple. width_apple = 50 height_apple = 82 apple_startx = random.randrange(0,width-apple_width) apple_starty = -600 apple_speed = 8 x_cart = (width * 0.45) y_cart = (height * 0.8) x_change = 0 cart_width = 193 car_height = 105 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameEXit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -8 elif event.key == pygame.K_RIGHT: x_change = 8 elif event.tyoe == pygame.K_q: pygame.quit() quit() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x_cart += x_change gameDisplay.fill(white) jabuke(apple_startx,apple_starty) apple_starty += apple_speed if apple_start…
answer count: 1
has comment: http://stackoverflow.com/comment/86931413
accepted answer: http://stackoverflow.com/a/49957888
has comment: http://stackoverflow.com/comment/86931188
type: Question
has title: python pygame game - My apple go trough the cart

http://stackoverflow.com/comment/87131447
comment on: http://stackoverflow.com/a/50056604
score: 0
type: Comment
type: AnswerComment
has text: @user2970608 - Not sure if understand, last `explanation` is not enough?

http://stackoverflow.com/q/50049320
tagged with: python
has title: Correct way to pass data from one view to another in django?
has body: Currently Im trying to build an app using Django that pull data from fitbit. Im in the process of getting the Oauth2.0 connection to work. So I generated a authorization url from a bunch of user inputs: fitbit url, fitbit api, fitbit client id, fitbit client secret and redirect url. Once the link is generated and visited, fitbit returns with an access code in the URL like: https://localhost:8000/?code=#= Im able to extract the access code, but Im not sure what is the correct way to obtain the previous user input data in the newly redirected view. One way I can think of is saving the first user inputs into a DB and then pulling it out when redirected with the new access code. But Im not sure what other options are available and what the standard way of doing this is. Im still new to django, so any help is appreciated. Thanks!
has comment: http://stackoverflow.com/comment/87115135
score: 0
has comment: http://stackoverflow.com/comment/87115767
answer count: 1
has comment: http://stackoverflow.com/comment/87127524
type: Question
has comment: http://stackoverflow.com/comment/87115018
has answer: http://stackoverflow.com/a/50049542
type: UnansweredQuestion
tagged with: fitbit
tagged with: django

http://stackoverflow.com/q/49950172
accepted answer: http://stackoverflow.com/a/49950244
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86917242
tagged with: pandas
has comment: http://stackoverflow.com/comment/86917091
has title: Changing column value by finding substring in string values
has body: I'm trying to change the values in a single column using pandas apply(). My function partially worked, but I'm stuck on how to fix this other half. Data Column: County Name Riverside County San Diego County SanFrancisco County/city I'm trying to get rid of " County" so I'm left with just the name of the county. I successfully got rid of the " County" with the function but I'm having trouble removing the " County/city" from San Francisco. Code: def modify_county(countyname): if "/city" in countyname: return countyname.replace(" County/city","") return countyname.replace(" County","") lfd["CountyName"] = lfd["CountyName"].apply(modify_county) Output: CountyName Riverside San Diego San Francisco County/city Is something wrong with the conditional in the function?
has answer: http://stackoverflow.com/a/49960677
tagged with: substring
tagged with: pandas-apply
type: Question
has answer: http://stackoverflow.com/a/49950340
possible better answer: http://stackoverflow.com/a/49950340
tagged with: python
has answer: http://stackoverflow.com/a/49950244
type: AnsweredQuestion

http://stackoverflow.com/comment/87170501
has text: Thanks! I had to do some googling to understand the map function but it is a well written and helpful answer.
comment on: http://stackoverflow.com/a/50067976
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87189661
type: Comment
type: QuestionComment
score: 1
has text: Uninstalling Teradata's ODBC driver version 16.20 and installing 16.10 did the trick. Link to downloads for both drivers: http://downloads.teradata.com/download/connectivity/teradata-odbc-driver-for-mac-os-x
comment on: http://stackoverflow.com/q/50024626

http://stackoverflow.com/a/49971485
has body: This is a OpenCV version compatibility issue. Just use cv2.ORB_create() instead of cv2.ORB(). The code should look like: import cv2 img = cv2.imread('box.png',0) # queryImage orb = cv2.ORB_create() # Initiate SIFT detector # find the keypoints and descriptors with SIFT kp1, des1 = orb.detectAndCompute(img, None)
type: Answer
score: 61
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49971484
accepted answer of: http://stackoverflow.com/q/49971484
upvote count: 61

http://stackoverflow.com/comment/86862070
type: Comment
type: QuestionComment
has text: I have tried what you said and the problem is solved but now there is another problem :Traceback (most recent call last): File "/media/yavuzhan/DATA/2017-2018/Otonom Araç Projesi/Dosya/Otonom Araç Yazılım/renkalgilama.py", line 34, in <module> cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) IndexError: invalid index to scalar variable.
comment on: http://stackoverflow.com/q/49918828
score: 0

http://stackoverflow.com/comment/86998787
comment on: http://stackoverflow.com/q/49990974
score: 0
type: Comment
type: QuestionComment
has text: Yes, That works for me. Thanks.

http://stackoverflow.com/q/49939123
has comment: http://stackoverflow.com/comment/115753630
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/49946205
downvote count: 0
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49946205
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86893888
has body: I want to scrap DIV content created by javascript function by using python script. I have tried with BS4 and by doing with that i'm not able to get dynamic data. instead it shows only the source code. Sample code: import requests from bs4 import BeautifulSoup URL = "https://rawgit.com/skysoft999/tableauJS/master/example.html" r = requests.get(URL) soup = BeautifulSoup(r.content, 'html5lib') for row in soup.findAll('div', attrs = {'class':'quote'}): print(row) print(soup.prettify()) Sample HTML source code is in Pastebin Sample data to be extracted:
type: Question
has title: Scrape Dynamic contents created by Javascript using Python
tagged with: arrays
tagged with: python
linked to: http://stackoverflow.com/q/8049520

http://stackoverflow.com/comment/86949852
has text: This is one of the many screwy things that happen when you call `Tk()` more than once (once implicitly in `Myapp`, once explicitly in `tutorial`). You have to use `Toplevel()` instead to create additional windows.
comment on: http://stackoverflow.com/q/49966750
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49929663
upvote count: 0
answer count: 1
has body: I have here a function for a counter. My question is how to set the counter to 0 again after a button click. import tkinter import sys root=tkinter.Tk() root.geometry("200x200") root.title("His Button Increaser") counter=tkinter.IntVar() def OnClick(event=None): counter.set(counter.get() + 1) tkinter.Label(root, textvariable=counter).pack() tkinter.Button(root, text="One up", command=onClick).pack() root.mainloop()
has comment: http://stackoverflow.com/comment/86875377
downvote count: 1
has title: How to set the counter to 0 again after button click?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: counter
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49929785
has comment: http://stackoverflow.com/comment/86875435
tagged with: tkinter

http://stackoverflow.com/comment/86880516
has text: I'd say it depends on whether or not using exceptions provide more readable code than heavily nested `if` statements.
type: Comment
comment on: http://stackoverflow.com/a/49932343
type: AnswerComment
score: 0

http://stackoverflow.com/q/49962913
downvote count: 4
has body: I have an original list of sites: original_list = ["http://www.firstSite.com", "http://secondSite.com", "http://thirdSite.com", "http://www.fourthSite.com"] I want to allow user to choose some sites and arrange the new array like this: new_list = ["http://secondSite.com", "http://www.fourthSite.com"] The filling of the new array depends on user's choice
upvote count: 0
answer count: 1
has title: How to choose some items from array in Python
favorite count: 0
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49962982
score: -4
tagged with: python
has answer: http://stackoverflow.com/a/49962982
type: AnsweredQuestion

http://stackoverflow.com/comment/87154399
has text: @depperm will do my best, one minute
comment on: http://stackoverflow.com/q/50068976
score: 0
type: Comment
type: QuestionComment

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/49943850
tags question: http://stackoverflow.com/q/50072510
type: Tag

http://stackoverflow.com/a/50299752
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49944582
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87623577
has comment: http://stackoverflow.com/comment/87714406
answers question: http://stackoverflow.com/q/49944582
has body: In that case you can't take advantage of parallel downloads, but since you want to simulate the same thing in Scrapy this can be achieved in different ways Approach 1 - Yield page using page numbers class PaginationTestSpider(scrapy.Spider): name = 'pagination' # Start with page #1 start_urls = ['http://esencjablog.pl/page/1/'] def parse(self, response): # we commnicate the page numbers using request meta # this is not mandatory as we can extract the same data from # the response.url also. But I prefer using meta here page_no = response.meta.get('page', 1) + 1 items = response.css('.post_more a.qbutton') for link in items: yield{"link":link.css('::attr(href)').extract_first()} if items: # if items were found we move to the next page yield Request("http://esencjablog.pl/page/{}".format(page_no), meta={"page": page_no}, callback=self.parse) The ideal way would usually be that if you can find the last page count from the first request then you will extract that number and fire all the request in one in first parse call. But that would only work if it is possible to know the last page number Approach 2 - Yield next page using object class PaginationTestSpider(scrapy.Spider): name = 'pagination' # Start with page #1 start_urls = ['http://esencjablog.pl/page/1/'] def parse(self, response): items = response.css('.post_more a.qbutton') for link in items: yield{"link":link.css('::attr(href)').extract_first()} next_page = response.xpath('//li[contains(@class, "next_last")]/a/@href') if next_page: yield response.follow(next_page) # follow to next page, and parse again This is nothing but a blunt copy of what @Konstantin mentioned. Sorry but want to make this a more complete answer Approach 3 - Yield all page on first response class PaginationTestSpider(scrapy.Spider): name = 'pagination' # Start with page #1 start_urls = ['http://esencjablog.pl/page/1/'] first_request = True def parse(self, response): if self.first_request: self.first_request = False last_page_num = response.c…
type: Answer
has comment: http://stackoverflow.com/comment/87706549
score: 4

http://stackoverflow.com/q/50045719
has body: from tkinter import * from tkinter import ttk from tkinter import Tk def Finddif(): numb= 0 for i, j in zip(t1.get('1.0', 'end-1c'), t2.get('1.0', 'end-1c')): if (i != j): numb = numb + 1 lab2.config(text=numb) root = Tk() root.title("AJC") root.resizable(width=FALSE, height=FALSE) root.geometry("500x500+30+10") lab2 = ttk.Label(root, text = "") lab2.place(x = 100, y = 100, width = 180, height = 50) t1 = Text(root) scr1 = Scrollbar(root, command = t1.yview) t1.config(yscrollcommand = scr1.set) scr1.place(x = 585, y = 65, width = 50, height = 50) t2 = Text(root) scr2 = Scrollbar(root, command = t2.yview) t2.config(yscrollcommand = scr2.set) scr2.place(x = 585, y = 300, width = 50, height = 50) t1.place(x = 20, y = 65, width = 100, height = 100) t2.place(x = 20, y = 300, width = 100, height = 100) b1 = ttk.Button(root, text = "Finddif", command = Finddif) b1.place(x = 20, y = 30, width = 80, height = 25) root.mainloop() Here is a little programm of mine. There are 2 texts and code have to search the difference and color the character. tag is not working in this situation because dont know where will be the wrong character.
score: 0
tagged with: text-widget
linked to: http://stackoverflow.com/q/14786507
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87107978
has title: Changing background color of character text widget python tkinter
type: Question
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/50058671
has comment: http://stackoverflow.com/comment/87107896
type: UnansweredQuestion

http://stackoverflow.com/q/49927030
has answer: http://stackoverflow.com/a/49927766
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49927123
possible better answer: http://stackoverflow.com/a/49927151
has answer: http://stackoverflow.com/a/49927079
has title: What's the elegant way to get filename that contains more than one dot in python
downvote count: 1
answer count: 7
tagged with: string
has answer: http://stackoverflow.com/a/79335118
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/49927123
has answer: http://stackoverflow.com/a/49927151
tagged with: python
upvote count: 4
has body: I need to process linux file with multiple parts in the name like: abc.def.gh.bz2 bz2 is the real extension, I need to get abc.def.gh Can anyone tell me an elegant way to do this in python? Thank you very much.
has answer: http://stackoverflow.com/a/49927085
has answer: http://stackoverflow.com/a/72268473

http://stackoverflow.com/comment/86995334
type: Comment
type: AnswerComment
has text: hehe nice, you addressed my [comment](https://stackoverflow.com/questions/49989288/printing-odd-numbers-in-python-using-iterators#comment86995101_49989288) asking exactly this.
comment on: http://stackoverflow.com/a/49989428
score: 0

http://stackoverflow.com/q/49956533
has body: I have an interactive matplotlib window which is driven both by the command line and keyboard input when focus is on the window. The problem is that the key events while focus is on the window do not get triggered until the mouse is moved anywhere on the screen. To run the example code below: Run the script, then on the command line that opens, type plot. This plots a window with random coloured dots. Every time you issue plot, it repaints random dots in the next colour. The keyboard event when pressing 'c' while focus is on the matplotlib window does the same, but it doesn't get triggered until you move the mouse. If this works for you, please report which backend you're using (it plots this on startup). So here's the minimal working example. Unless you're on a mac using the macports python, you'll need to delete the first line so /usr/bin/python is run: #!/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 #!/usr/bin/python import time, os, sys import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation import random import cmd colors = [ 'red', 'green', 'blue' ] colorindex = 0 def key_handler(event): global colors global colorindex print('Key pressed:', event.key) sys.stdout.flush() if event.key == 'x': print "Exiting..." sys.exit(0) elif event.key == 'c': print "changing color" colorindex += 1 if colorindex &gt;= len(colors): colorindex = 0 plotfig() def plotfig(): global fig global ax1 global colors global colorindex ax1.clear() someX = range(1,1000) someY = [] for i in someX: someY.append(random.randrange(0, 1000)) ax1.plot(someX, someY, '.', color=colors[colorindex], markersize=8, label="Some Values") plt.show() class someShell(cmd.Cmd): intro = 'some shell. Type help or ? to list commands.\n' prompt = 'ss&gt; ' def do_plot(self, arg): global colorindex colorindex += 1 if colorindex &gt;= len(colors): colorindex = 0 plotfig() def do_exit(self, arg): 'Exits SomeShell' return True fig = plt.figure(figsize=(12…
has comment: http://stackoverflow.com/comment/86951507
type: Question
has comment: http://stackoverflow.com/comment/86938440
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86960936
has comment: http://stackoverflow.com/comment/86947660
has comment: http://stackoverflow.com/comment/86961023
score: 0
has title: matplotlib plot with key handler only updates when mouse moves
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86951555
tagged with: python
tagged with: macos

http://stackoverflow.com/q/49934932
answer count: 3
has title: Regarding GIL in python
score: 10
tagged with: python
favorite count: 0
upvote count: 11
type: Question
linked to: http://stackoverflow.com/q/10938360
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49938239
tagged with: django
tagged with: gil
tagged with: web-services
has body: I know GIL blocks python from running its threads across cores. If it does so, why python is being used in webservers, how are the companies like youtube, instagram handling it. PS: I know alternatives like multiprocessing can solve it. But it would be great if anyone can post it with a scenario that was handled by them.
downvote count: 1
has answer: http://stackoverflow.com/a/63434738
has answer: http://stackoverflow.com/a/49936201

http://stackoverflow.com/comment/87071225
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50027007
has text: Works for me. I'm actually using a User model that just defines the user type and then extending that model to get BusinessUser (which is where I add details like city and state). So, I had to do something like: `user_info = BusinessUser.objects.get(pk=self.request.user.pk)` and then access the city and state fields from `user_info` with `initial['location'] = user_info.city + ", " + user_info.state`. I wouldn't think the standard use case needs this quibble so I'll leave the question as is if you agree.

http://stackoverflow.com/q/49920150
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: Here I'm trying to make a sub-list from list, and I'm getting "Not enough values to unpack error. If I use k=s.split(',') it shows the error, whereas if I use k1=[s.split(',')], it doesn't show any error while unpacking. Both have the same type, same size and same-content My code: inputs = ["1, foo, bar", "2, tom, jerry"] outputs1=[] for s in inputs: print(s) k=s.split(',') print(k,type(k),len(k)) k1=[s.split(',')] print(k1,type(k1),len(k1)) for (x, y, z) in k: outputs1.append([int(x), y.strip(), z.strip()]) print(outputs1)
has comment: http://stackoverflow.com/comment/86855880
tagged with: python
answer count: 4
has title: Not enough values to unpack when using split function
has answer: http://stackoverflow.com/a/49920280
score: 0
has answer: http://stackoverflow.com/a/49920248
has answer: http://stackoverflow.com/a/49920320
has answer: http://stackoverflow.com/a/49920389
has comment: http://stackoverflow.com/comment/86856089
upvote count: 1

http://stackoverflow.com/a/49972928
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/49968274
type: Answer
answers question: http://stackoverflow.com/q/49968274
upvote count: 4
has comment: http://stackoverflow.com/comment/86995635
has body: Short solution: Store the QLine in a list and redraw: class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(300, 300)) pybutton = QPushButton('button', self) pybutton.clicked.connect(self.draw_line) pybutton.resize(100,100) pybutton.move(0, 0) pybutton2 = QPushButton('button2', self) pybutton2.clicked.connect(self.draw_line) pybutton2.resize(100,100) pybutton2.move(200, 0) self.lines = [] def draw_line(self): button = self.sender() r = button.geometry() p1 = QPoint(r.left() + r.width()/2, r.height()) p2 = p1+QPoint(0, 100) line = QLine(p1, p2) if line not in self.lines: self.lines.append(line) self.update() def paintEvent(self,event): QMainWindow.paintEvent(self, event) painter = QPainter(self) pen = QPen(Qt.red, 3) painter.setPen(pen) for line in self.lines: painter.drawLine(line) Long solution: These kinds of questions have been asked countless times so I'm going to take the time to expand and give a general perspective of the problem so that I do not answer this type of question every time, so this question It will be improved and updated. paintEvent() is a method that handles Qt to perform the repainting of the GUI, this method redraws everything, therefore the drawing does not save memory, so you must store the instructions and make the drawing with those instructions. The paintEvent() method I recommend using to create custom widgets, not to make a GUI that performs the painting task as a main function, for this Qt offers class QGraphicsView, QGraphicsScene and QGraphicsItems. The task of redrawing using the instructions of QPainter as drawLine(), fillRect(), etc consume resources, if you want to make a more efficient implementation it is appropriate to create a QPixmap that you must update whenever necessary, and repaint in the paintEvent() using the mentioned QPixmap: class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(300, 300)) pybutton = QPushButton('butt…

http://stackoverflow.com/q/49965079
accepted answer: http://stackoverflow.com/a/49965714
has body: ...and that reference comes from a separate matrix. This question is an extension of an earlier answered question where the reference element came directly from the same column it was being compared against. Some clever sorting and referencing the index of the sort seemed to solve that one. Broadcasting has been suggested in both the original and this new question. I run out of memory at around n ~ 3000 and need another order of magnitude larger yet. The Target ( Production-grade ) Scaling Definitions: So as to let proposed solutions' approaches fair and mutually comparable, both in the [SPACE]- and the [TIME]-domains, let's assume n = 50000; m = 20; k = 50; a = np.random.rand( n, m ); ... I'm now interested in a more general form where the reference value comes from another matrix of reference values. Original question: Vectorized pythonic way to get count of elements greater than current element New question: Can we write a vectorized form to perform the following role. Function receives as input 2 2-d arrays. A = n x m B = k x m and returns C = k x m. C[i,j] is the proportion of observations in A[:,j] ( just the j-th column ) that are larger than B[i,j] Here is my embarrasingly slow double for loop implementation. import numpy as np n = 100 m = 20 k = 50 a = np.random.rand(n,m) b = np.random.rand(k,m) c = np.zeros((k,m)) for j in range(0,m): #cols for i in range(0,k): # rows r = b[i,j] c[i,j] = ( ( a[:,j] &gt; r).sum() ) / (n)
tagged with: python
possible better answer: http://stackoverflow.com/a/49965730
tagged with: vectorization
has comment: http://stackoverflow.com/comment/86947552
linked to: http://stackoverflow.com/q/49880927
has title: Vectorized form to get count of elements greater than a reference
type: AnsweredQuestion
score: 3
answer count: 2
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49965730
has comment: http://stackoverflow.com/comment/86949109
has comment: http://stackoverflow.com/comment/86947364
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49965714
tagged with: numpy

http://stackoverflow.com/q/49983070
answer count: 1
has title: multiprocessing: TypeError: 'numpy.ndarray' object is not callable
type: Question
linked to: http://stackoverflow.com/q/49197916
score: 0
has body: I'm trying to use multiprocessing to create a process that performs an inference operation using Keras, so I can monitor the resource usage of that operation (as suggested in response to my previous question here). For some reason the start method is causing a TypeError that I can't figure out. worker_process = mp.Process(target=small_model.predict(x_test[0:1])) worker_process.start() Process Process-13: Traceback (most recent call last): File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) TypeError: 'numpy.ndarray' object is not callable
accepted answer: http://stackoverflow.com/a/49983359
tagged with: python
has answer: http://stackoverflow.com/a/49983359
tagged with: python-multiprocessing
type: AnsweredQuestion

http://stackoverflow.com/q/50030414
score: 0
upvote count: 2
has body: Let's say I have an exception that is triggered by another one. I have a set of actions meant for that inner exception. Apparently first I have to catch the outmost exception, I do this and then how do I except the one that follows?
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87076906
has comment: http://stackoverflow.com/comment/87077055
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50030566
has title: How to catch inner exception in python?
has answer: http://stackoverflow.com/a/50030566
has comment: http://stackoverflow.com/comment/87077051
tagged with: python
has comment: http://stackoverflow.com/comment/87077125
type: Question

http://stackoverflow.com/comment/87108849
comment on: http://stackoverflow.com/a/50046244
type: Comment
type: AnswerComment
has text: This did it. The big thing I was getting wrong was attaching the `.find()` to the wrong place. Thank you!
score: 0

http://stackoverflow.com/a/50021346
answers question: http://stackoverflow.com/q/50021282
has comment: http://stackoverflow.com/comment/87058622
has body: There are multiple ways in which you can add a description to your command. The recommended way is to add a module documentation at the top of your source code file as in: """ This is the description, it will be accessible within the variable __doc__ """ And then: parser = argparse.ArgumentParser(description=__doc__) To add text below the parameter description, use epilog, as shown in the following example taken from the documentation: &gt;&gt;&gt; parser = argparse.ArgumentParser(description='A foo that bars', epilog="And that's how you'd foo a bar") &gt;&gt;&gt; parser.print_help() usage: argparse.py [-h] A foo that bars optional arguments: -h, --help show this help message and exit And that's how you'd foo a bar Refer to the documentation (linked above) for more information.
has comment: http://stackoverflow.com/comment/130614740
upvote count: 32
score: 32
type: Answer
has comment: http://stackoverflow.com/comment/87058706
has comment: http://stackoverflow.com/comment/130610599
downvote count: 0

http://stackoverflow.com/comment/87105409
has text: Great, I am glad to have helped you.
score: 0
comment on: http://stackoverflow.com/a/49977348
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86954850
type: Comment
score: 0
type: AnswerComment
has text: Worked!! Thanks so much :)
comment on: http://stackoverflow.com/a/49961282

http://stackoverflow.com/q/50022591
type: Question
score: 2
upvote count: 2
answer count: 8
has comment: http://stackoverflow.com/comment/87481893
downvote count: 0
type: UnansweredQuestion
has body: I am trying to make a string alternate between upper and lower case letters. My current code is this: def skyline (str1): result = '' index = 0 for i in str1: result += str1[index].upper() + str1[index + 1].lower() index += 2 return result When I run the above code I get an error saying String index out of range. How can I fix this?
has answer: http://stackoverflow.com/a/50022877
has answer: http://stackoverflow.com/a/63136923
has answer: http://stackoverflow.com/a/50023042
has answer: http://stackoverflow.com/a/50023048
has answer: http://stackoverflow.com/a/57151765
has title: Alternate letters in a string - code not working
has answer: http://stackoverflow.com/a/50022792
tagged with: python
has answer: http://stackoverflow.com/a/50022870
has comment: http://stackoverflow.com/comment/87061150
has answer: http://stackoverflow.com/a/50022823
favorite count: 0

http://stackoverflow.com/a/59369715
score: 24
has comment: http://stackoverflow.com/comment/118500262
type: Answer
answers question: http://stackoverflow.com/q/50065731
has comment: http://stackoverflow.com/comment/119530229
upvote count: 25
has comment: http://stackoverflow.com/comment/118525224
has body: New kid on the block https://devblogs.microsoft.com/dotnet/an-introduction-to-dataframe/ Announced today, still in preview, Microsoft's own take on a DataFrame :)
downvote count: 1

http://stackoverflow.com/q/50003803
type: Question
tagged with: python-3.x
has body: My program does the following: take folder of txt files for each file: read the file do POST request to an API in localhost using file content parse XML response (not in the example below) I was concerned with performance of synchronous version of the program so tried to use aiohttp to make it asynchronous (it's my first attempt of async programming in Python besides Scrapy). It turned out that the async code took 2 times longer and I don't understand why. SYNCHRONOUS CODE (152 seconds) url = "http://localhost:6090/api/analyzexml" package = #name of the package I send in each requests with open("template.txt", "r", encoding="utf-8") as f: template = f.read() articles_path = #location of my text files def fetch(session, url, article_text): data = {"package": package, "data": template.format(article_text)} response = session.post(url, data=json.dumps(data)) print(response.text) files = glob(os.path.join(articles_path, "*.txt")) with requests.Session() as s: for file in files: with open(file, "r", encoding="utf-8") as f: article_text = f.read() fetch(s, url, article_text) Profiling results: +--------+---------+----------+---------+----------+-------------------------------------------------------+ | ncalls | tottime | percall | cumtime | percall | filename:lineno(function) | +--------+---------+----------+---------+----------+-------------------------------------------------------+ | 849 | 145.6 | 0.1715 | 145.6 | 0.1715 | ~:0(&lt;method 'recv_into' of '_socket.socket' objects&gt;) | | 2 | 1.001 | 0.5007 | 1.001 | 0.5007 | ~:0(&lt;method 'connect' of '_socket.socket' objects&gt;) | | 365 | 0.772 | 0.002115 | 1.001 | 0.002742 | ~:0(&lt;built-in method builtins.print&gt;) | +--------+---------+----------+---------+----------+-------------------------------------------------------+ (WANNABE) ASYNCHRONOUS CODE (327 seconds) async def fetch(session, url, article_text): data = {"package": package, "data": template.format(article_text)} async with session.post(url, data=json.…
has answer: http://stackoverflow.com/a/50004557
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50004557
score: 2
type: AnsweredQuestion
tagged with: aiohttp
tagged with: python-asyncio
answer count: 1
downvote count: 0
has title: asynchronous slower than synchronous
tagged with: python-requests
favorite count: 0

http://stackoverflow.com/q/50055316
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87134323
tagged with: pip
tagged with: python
has title: Flask upgrade - Lots of "Exception ignored in..." messages in console
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/50516050
answer count: 1
has comment: http://stackoverflow.com/comment/87127004
has body: After upgrading to Flask 1.0 and potentially a few other libraries (running > pip3 install -r requirements.txt --upgrade) , I'm getting a lot of Exceptions in my console when running the local server environment which I didn't get before. Any idea why? Config: Mac OS X latest, PyCharm, Python 3.6.4, Flask 1.0 Exception ignored in: . at 0x117574e60> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/werkzeug/urls.py", line 428, in if not rest or any(c not in s('0123456789') for c in rest): SystemError: error return without exception set Exception ignored in: . at 0x1176d00f8> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/werkzeug/urls.py", line 428, in if not rest or any(c not in s('0123456789') for c in rest): SystemError: error return without exception set Exception ignored in: . at 0x117574af0> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/werkzeug/urls.py", line 428, in if not rest or any(c not in s('0123456789') for c in rest): SystemError: error return without exception set Exception ignored in: . at 0x11489dc50> Traceback (most recent call last): File "/Development &amp; Product/Project/googleapiclient/discovery.py", line 1171, in if tokenName in fields), None) SystemError: error return without exception set Exception ignored in: . at 0x11489dc50> Traceback (most recent call last): File "/Development &amp; Product/Project/googleapiclient/discovery.py", line 1171, in if tokenName in fields), None) SystemError: error return without exception set Exception ignored in: . at 0x11489dc50> Traceback (most recent call last): File "/Development &amp; Product/Project/googleapiclient/discovery.py", line 1171, in if tokenName in fields), None) SystemError: error return without exception set Exception ignored in: . at 0x11489dc50> Traceback (most recent call last): File "/Development &amp; Product/Project/googleapiclient/discovery.py", line 1171, in if tokenName in fields), Non…

http://stackoverflow.com/comment/87111620
score: 0
type: Comment
type: QuestionComment
has text: Show the table definitions.
comment on: http://stackoverflow.com/q/50038805

http://stackoverflow.com/comment/87026446
type: QuestionComment
has text: `print(row['content'].encode('utf-8', errors='backslashreplace')` (or `'ignore'`)
score: 0
comment on: http://stackoverflow.com/q/50001268
type: Comment

http://stackoverflow.com/comment/86989854
type: Comment
score: 0
type: QuestionComment
has text: Just fixed it- turns out I could solve the problem by compressing the file using gzip compression :) Thanks anyway!!
comment on: http://stackoverflow.com/q/49950725

http://stackoverflow.com/a/50001320
has comment: http://stackoverflow.com/comment/87022068
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49999636
has body: This should get you pretty close if I understand correctly. import numpy as np import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame(columns=['Name', 'Cat_1', 'Cat_2']) df['Name'] = ['foo', 'bar', 'bla', 'blu', 'boo', 'faa'] df['Cat_1'] = ['P', 'R, M', 'E', 'F', 'G', 'P, E'] df['Cat_2'] = ['Apples, Pears, Cats', 'Apples', 'Pears', 'Cats, Pears', 'Apples, Pears', 'Apples, Cats'] # arrange data simply prepopulate with zero df_pl = pd.DataFrame(columns=df["Cat_1"].str.split(", ", expand=True).stack().unique().tolist(), index=df["Cat_2"].str.split(", ", expand=True).stack().unique().tolist(), data=0) # get chunk size for each combination for x in df_pl.columns: ind = df.Cat_1.str.contains(x) for name in df_pl.index: df_pl.set_value(name, x, df.loc[ind, 'Cat_2'].str.contains(name).sum()) N = len(df_pl.columns) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence plotted = [] p = {} for name in df_pl.index: bottoms = df_pl.index.isin(plotted).sum() p[name] = plt.bar(ind, df_pl.loc[name].values.tolist(), bottom=bottoms) plotted.append(name) plt.ylabel('y_label') plt.title('some plot') plt.xticks(ind, df_pl.columns.tolist()) plt.legend(p.values(), p.keys()) plt.show()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49999636

http://stackoverflow.com/q/50028452
answer count: 1
has body: I am trying to merge two similar xml files using python. file1.xml: <c>value1</c> <d>value2</d> <e> <f>value3</f> <g>value4</g> </e> file2.xml <c>value5</c> <d>value6</d> <e> <f>value7</f> <g>value8</g> </e> Desired Output (file3.xml). Combine all the child for repeated b element but not combine the repeated e element. <c>value1</c> <d>value2</d> <c>value5</c> <d>value6</d> <e> <f>value3</f> <g>value4</g> </e> <e> <f>value7</f> <g>value8</g> </e>
type: Question
has title: Merging similar xml files using python
tagged with: python
has answer: http://stackoverflow.com/a/50029281
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/87073338
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/87116195
type: Comment
comment on: http://stackoverflow.com/a/50049858
score: 0
type: AnswerComment
has text: @PetPan Glad to help!

http://stackoverflow.com/a/49953922
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49952847
type: Answer
has body: The pandas way to do is to pass the data to DataFrame and then groupby operation: df = pd.DataFrame(data) df.groupby(0).apply(lambda x: x.values).values Output: [array([[ 0, 1994], [ 0, 1965], [ 0, 1943]]), array([[ 1, 1994], [ 1, 1965]]), array([[ 2, 1948]])]

http://stackoverflow.com/a/49924916
score: 0
type: AcceptedAnswer
has body: UPDATE: from you update to your question it looks like you may be trying to import the file as a class. Instead of doing: variable = desiredclass() Try this: variable = desiredclass.ClassNameInFile() There are several ways you might wish to import your own files. For example if your file structure looks like this: --Workfolder --Main.py --other.py You may want to import something like this. import other Or if you want only something specific from that file do: from other import func_name However if it is part of a package you sometimes need to specify the package name first. So if your file structure is like this: --Workfolder --MY_PACKAGE --Main.py --other.py You may want to import like this: import MY_PACKAGE.other or for a specific function: from MY_PACKAGE.other import func_name Let me know if you have any questions.
type: Answer
accepted answer of: http://stackoverflow.com/q/49924607
answers question: http://stackoverflow.com/q/49924607

http://stackoverflow.com/comment/87008682
type: Comment
has text: @jahan. That would mean a totally different requirement and regex.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49994479

http://stackoverflow.com/comment/87105097
has text: Could your softmax function be def softmax(x): return np.exp(x) / np.sum(np.exp(x), axis=0)
comment on: http://stackoverflow.com/q/50042925
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/a/49981064
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49974379
has body: The simplest method is to get a reference to the selenium library that has been imported by your suite, and then call the keyword on that instance. You can get a reference to the library with the built-in keyword get library instance from robot.libraries.BuiltIn import BuiltIn def screenshot(): se2lib = BuiltIn().get_library_instance("SeleniumLibrary") se2lib.capture_page_screenshot()
score: 1

http://stackoverflow.com/comment/87007211
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49995015
has text: Also, technically, `method="POST"` is not valid in HTML5; it needs to be `method="post"`. However, that one, I doubt any actual browser would care about.

http://stackoverflow.com/q/49992174
linked to: http://stackoverflow.com/q/18854425
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/118018617
downvote count: 0
has answer: http://stackoverflow.com/a/50054939
tagged with: python
upvote count: 3
score: 3
tagged with: array-broadcasting
has title: Compute trace of matrix product using numpy/pytorch broadcasting
tagged with: pytorch
answer count: 1
has body: Let A be an (nxm)-matrix and M an (mxm)-matrix. Writing tr() for the trace of a matrix, I need to compute tr(AM(A^T)). However, the final trace operation throws away most of the computation. Can I use numpy's or pytorch's broadcasting rules to compute only the necessary diagonal of AM(A^T)? Update: Here is my solution to compute the diagonal in PyTorch: torch.sum(torch.sum(A.t()[:,None,:]*M[:,:,None],0)*A.t(),0)
favorite count: 0
type: Question

http://stackoverflow.com/comment/87139597
has text: Hey ! Thanks for your answer..Unfortunately this is not working in my case caus the variable x ist not static. This means if i use import A.py in B.py by writing import A and afterwards: A.main() it only runs the A code but i cannot further process or even access the variable x within B.py... Is there a way to execute script A.py as a long as the variable is empy (by starting it from B.py) and if the value is not None keep running A.main() ? Thanks a lot
comment on: http://stackoverflow.com/a/50055877
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50045758
has answer: http://stackoverflow.com/a/52482106
tagged with: matplotlib
tagged with: python
score: 1
has title: ModuleNotFoundError: No module named 'matplotlib._path'
possible better answer: http://stackoverflow.com/a/50046198
has body: While I installed properly the matplotlib and seaborn. I was able to import matplotlib but when I was trying to import the seaborn I got the following error message. ModuleNotFoundError: No module named 'matplotlib._path' . Same if I was trying to import matplotlib.pyplot. After spending a lot of time googling and trying this and that, installing and unistaling, finally, I first checked out the import sys sys.path to see what are the folders that it searches for the installed packages. my result was something like this. ['', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\python36.zip', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\DLLs', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\lib', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36', 'C:\\Users\\gsotiropoulos\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\lib\\site-packages', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\lib\\site-packages\\win32', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\lib\\site-packages\\win32\\lib', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\lib\\site-packages\\Pythonwin', 'C:\\Users\\gsotiropoulos\\AppData\\Local\\conda\\conda\\envs\\py36\\lib\\site-packages\\IPython\\extensions', 'C:\\Users\\gsotiropoulos\\.ipython'] then as suggested I import matplotlib as mpl and mpl.__path__ seeing that I import matplotlib from the folder 'C:\\Users\\gsotiropoulos\\AppData\\Roaming\\Python\\Python36\\site-packages' Which is not the one from anaconda and it is older. I am not sure if it would be better to just remove this folder completely. However, as I understand, python first searched there and found a matplotlib package which was outdated. I simply changed the name of the `matplotlib' to something like 'matplotlib_test' and then the library is installed from one o…
accepted answer: http://stackoverflow.com/a/52482106
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50046198
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: anaconda

enumeration
tag name: enumeration
type: Tag
tags question: http://stackoverflow.com/q/50011031

http://stackoverflow.com/a/49926506
accepted answer of: http://stackoverflow.com/q/49925168
upvote count: 1
has comment: http://stackoverflow.com/comment/86872740
answers question: http://stackoverflow.com/q/49925168
has comment: http://stackoverflow.com/comment/86873022
score: 1
type: Answer
has body: I believe it was correct that your y signal has its peak values near x=0 and x=400, however, I'm not entirely clear what you're trying to achieve. It seems like your Y vector represents a frequency spectrum which is a top-hat function. By passing this to numpy.fft.irfft you are effectively treating your frequency spectrum as consisting of equal amplitudes of positive and negative frequencies, of which you only supply the positive (and zero) frequencies. If you had a continuous frequency spectrum of this form, then the inverse Fourier transform would be a sinc() function centred on t=0. For a discrete Fourier transform, this isn't strictly true, but is a good approximation, except for the wrap-around that occurs at t=0. That means that the negative-time parts of the inverse Fourier transform are put at the end of the time-window, as you've observed in your middle (y) plot. If you wanted to shift this time-domain function, what you could do is introduce a linear phase variation in your Y vector (making it a sequence of complex numbers). However, if what you're trying to do is generate a sinc() function that is centred on a give time-value, this must be much easier to do directly in the time-domain, using numpy.sinc(), and without the need for any Fourier transforms. Perhaps in your application you want a known bandwidth in the frequency domain, but that should be straightforward to convert into the width of the sinc() function (with the width in the time-domain being inversely proportional to the width in the frequency domain).
has comment: http://stackoverflow.com/comment/86872619
has comment: http://stackoverflow.com/comment/86872135
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49977544
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: In a CSV file, I have three columns z,x,y where 'z' column is used to groupby x and y columns and will be plotted w.r.t 'z'. Below is the table for z,x,y. z x y 23 1,75181E-07 6,949512 23 8,88901E-07 6,963877 23 1,61279E-05 7,293052 23 5,35262E-05 8,135064 23 8,56942E-05 8,903738 23 0,000114883 9,579907 23 0,01068653 211,0798 23 0,01070811 211,3568 23 0,0107263 211,5871 23 0,01074606 211,8401 23 0,01076813 212,1311 23 0,01078525 212,3436 40 1,75181E-07 6,949513217 40 8,889E-07 6,96388319 40 1,61277E-05 7,293169621 40 5,35248E-05 8,135499439 40 0,00029527 13,63721607 40 0,000319049 14,1825142 40 0,000340228 14,69608917 40 0,014110191 252,3893548 40 0,014132366 252,5804547 40 0,014155023 252,8030254 40 0,014180293 253,0374241 40 0,014202693 253,1983821 40 0,014226167 253,4140887 40 0,014251631 253,6566835 40 0,014272699 253,8120535 Now I need to replace the 'x' and 'y' columns with new values say 'x1' and 'y1' by an equation: x1 = ln(1 + x) and y1 = y*(1+x) and w.r.t. same 'z' column I should plot x1 and y1. I have tried the below code and I am able to see my new values but not able to plot with new values. import csv import os import tkinter as tk import sys from tkinter import filedialog import pandas as pd import matplotlib.pyplot as plt import math from tkinter import ttk import numpy as np def readCSV(self): x=[] # Initializing empty lists to store the 3 columns in csv y=[] z=[] global df self.filename = filedialog.askopenfilename() df = pd.read_csv(self.filename, error_bad_lines=False) #Reading CSV file using pandas read = csv.reader(df, delimiter = ",") fig = plt.figure() ax= fig.add_subplot(111) df.set_index('x', inplace=True) #Setting index line = df.groupby('z')['y'].plot(legend=True,ax=ax) #grouping and plotting cursor = datacursor(line) gdf= df[df['z'] == 23] x=np.asarray(gdf.index.values) y=np.asarray(gdf['y'].values) x1 = np.log(1+x) y1 = y * (1 + x) df.set_index('x1', inplace=True) #Setting new index line = df.groupby('z')['y1'].plot(legend=True,ax=ax) …
type: Question
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
favorite count: 0
has title: Pandas : Replace old column values and plot new column values with respect to equations
has answer: http://stackoverflow.com/a/49977670
tagged with: pandas

http://stackoverflow.com/comment/87030556
type: QuestionComment
has text: Exactly my comment then, and the answer below.
type: Comment
comment on: http://stackoverflow.com/q/50005092
score: 1

filenotfoundexception
type: Tag
tag name: filenotfoundexception
tags question: http://stackoverflow.com/q/50014421

http://stackoverflow.com/comment/87079907
type: Comment
type: QuestionComment
has text: Errors: Imports are missing, probably "import copy" + "import pandas as pd"; class name has a typo; line 17 and 19 are butchered; there is no sample dataframe to be written to the file; and save() is also never called; Jesus.
comment on: http://stackoverflow.com/q/49941005
score: 0

http://stackoverflow.com/comment/87071730
type: QuestionComment
has text: `set_explicit_value` seems to work for me, as long as you don't actually *need* the single-quote/apostrophe in the cell. If you expect to "see" the value without the leading quote, do you actually need the leading quote mark?
comment on: http://stackoverflow.com/q/50027429
score: 0
type: Comment

http://stackoverflow.com/q/50045805
has comment: http://stackoverflow.com/comment/87110752
score: -2
tagged with: datetime
has comment: http://stackoverflow.com/comment/87108493
tagged with: dataframe
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/87109680
has answer: http://stackoverflow.com/a/50048895
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87108010
downvote count: 2
tagged with: pandas
has title: Merging Date columns in Pandas dataframes with filtering conditions in Python
has body: Have a tricky problem. I got two Pandas dataframes with datetime data in both of them, first one: Date Number 2018-02-28 23:59:00 20 2018-03-01 00:37:00 35 2018-03-01 00:58:00 46 2018-03-01 02:14:00 11 2018-03-01 02:32:00 15 second one: Date Value 2018-02-28 23:50:00 20 2018-02-28 23:51:00 35 2018-02-28 23:52:00 46 2018-02-28 23:53:00 11 2018-02-28 23:54:00 15 2018-02-28 23:55:00 20 2018-02-28 23:56:00 35 2018-02-28 23:57:00 46 2018-02-28 23:58:00 11 2018-02-28 23:59:00 15 2018-03-01 00:00:00 15 As you can already notice, the dates in first dataframe are just random dates and in the second dataframe they stored in order increasing on +1 minute each row. What I try to achieve is to join the first dataframe on the second on date column but not like inner join style one-to-one but with a rule looking like this: you take the date from first dataframe (for example, '2018-02-28 23:59:00' and join twenty one rows from second dataframe -10 minutes from the date and +10 from the date (for this example, will be from '2018-02-28 23:49:00' to '2018-03-01 00:09:00'). I'm kind of confused-is there any Pandas filtering features that can help in achieving this kind of merging? Or maybe there is some pure pythonic solution. Desired result will be the following: Date1 Date2 Value 2018-02-28 23:59:00 2018-02-28 23:49:00 20 2018-02-28 23:59:00 2018-02-28 23:50:00 35 2018-02-28 23:59:00 2018-02-28 23:51:00 46 2018-02-28 23:59:00 2018-02-28 23:52:00 15 2018-02-28 23:59:00 2018-02-28 23:53:00 20 2018-02-28 23:59:00 2018-02-28 23:54:00 35 2018-02-28 23:59:00 2018-02-28 23:55:00 46 2018-02-28 23:59:00 2018-02-28 23:56:00 11 2018-02-28 23:59:00 2018-02-28 23:57:00 15 2018-02-28 23:59:00 2018-02-28 23:58:00 20 2018-02-28 23:59:00 2018-02-28 23:59:00 35 2018-02-28 23:59:00 2018-03-01 00:00:00 46 2018-02-28 23:59:00 2018-03-01 00:01:00 11 2018-02-28 23:59:00 2018-03-01 00:02:00 15 2018-02-28 23:59:00 2018-03-01 00:03:00 20 2018-02-28 23:59:00 2018-03-01 00:04:00 35 2018-02-28 23:59:00 2018-03-0…
answer count: 1
has comment: http://stackoverflow.com/comment/87109607
accepted answer: http://stackoverflow.com/a/50048895
favorite count: 0
type: Question

http://stackoverflow.com/q/50033953
score: -1
has body: Consider the following class: from abc import abstractmethod class K: @staticmethod def sm(*args): pass @classmethod def cm(*args): pass @abstractmethod def am(*args): pass # instance method def im(*args): pass Why do methods not decorated with @abstractmethod have an __isabstractmethod__ attribute which is set to True? To reproduce this, you can run the following code: # DON'T LET DESCRIPTORS' `__get__` methods be called! # USE THE DICT! K_dct = object.__getattribute__(K, '__dict__') sm = K_dct['sm'] cm = K_dct['cm'] am = K_dct['am'] im = K_dct['im'] ms = [sm, cm, am, im] def go_soul_searching(obj): """ :param obj: :return: string containing all global labels pointing to `obj` """ g = globals() ns = [n for n in g.keys() if g[n] is obj] return '{' + ', '.join(ns[0:-1]) + ', ' + ns[-1] + '}' print_nicely = lambda m, attrname: ''.join([str(x).ljust(25) for x in [ attrname, str(hasattr(m, attrname)) ]]) def inspect_method(m): header = '\n' + go_soul_searching(m) + '\n' print(header, end='') for attrname in inspect_method.attrs: print(print_nicely(m, attrname)) inspect_method.attrs = ['__call__', '__get__', '__set__', '__isabstractmethod__'] for m in ms: inspect_method(m) The Output Is: {sm, m} # STATIC METHOD __call__ False __get__ True __set__ False __isabstractmethod__ True {cm, m} # CLASS METHOD __call__ False __get__ True __set__ False __isabstractmethod__ True {am, m} # ABSTRACT METHOD __call__ True __get__ True __set__ False __isabstractmethod__ True {im, m} # INSTANCE METHOD __call__ True __get__ True __set__ False __isabstractmethod__ False
has answer: http://stackoverflow.com/a/50034097
tagged with: python-decorators
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87085099
has comment: http://stackoverflow.com/comment/87084353
downvote count: 2
answer count: 1
upvote count: 1
tagged with: descriptor
has title: Why do methods **NOT** decorated with `@abstractmethod` have an `__isabstractmethod__` attribute which is True?
tagged with: decorator
favorite count: 0
has comment: http://stackoverflow.com/comment/87084984
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50034097
tagged with: python

http://stackoverflow.com/comment/87145100
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50062211
has text: Can you provide some sample data?

http://stackoverflow.com/comment/87120286
type: QuestionComment
has text: and the question is?
comment on: http://stackoverflow.com/q/50051916
score: 1
type: Comment

http://stackoverflow.com/comment/86851580
type: AnswerComment
comment on: http://stackoverflow.com/a/49917891
has text: @AjItHHeGdE That could only be if your variable `a` is a list. Is it? Declared as above it sure works.
score: 0
type: Comment

http://stackoverflow.com/q/49959177
tagged with: python
score: -2
has title: How can I merge 2 lists and between them stays number 1 by creating lists of lists of 3-tuples?
type: Question
has comment: http://stackoverflow.com/comment/86934823
has answer: http://stackoverflow.com/a/49959470
has comment: http://stackoverflow.com/comment/86934783
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/86934844
has body: I want to merge two lists and place a 1 between them and create a lists of lists 3-tuples (inner list size is varying) .And l2 and the flattened version of l1 have the same size. Example lists: l1=[[a1,b1,c1],[a2,b2]] l2=[x,y,z,t,u] I want to produce the following list: l3=[[(a1,1,x),(b1,1,y),(c1,1,z)],[(a2,1,t),(b2,1,u)]] Thank you very much.
favorite count: 0
tagged with: tuples
tagged with: list
answer count: 1

user-defined-functions
tags question: http://stackoverflow.com/q/50040232
tag name: user-defined-functions
type: Tag
tags question: http://stackoverflow.com/q/50038842

http://stackoverflow.com/comment/86948085
type: Comment
has text: @Symphony - use `d = df.to_dict('r')`
comment on: http://stackoverflow.com/a/49962887
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87030499
score: 3
has text: Here is the pseudo algorithm to not breast feed you the answer: you need to find a character which delimits your columns, then for each line, split this line using this delimiter. Then you get a list of strings, which you can work with to create your dictionary.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50007028

http://stackoverflow.com/comment/87122936
type: QuestionComment
comment on: http://stackoverflow.com/q/50053107
has text: oops there ya go, line 3 and 6. Forgot to change userNum to magicNum
score: 0
type: Comment

http://stackoverflow.com/a/49950586
has body: It turns out that querying for python statistics with BigQuery doesn't work unless you are 1) logged in and 2) have given your billing information. Its free - for the first terabyte of data - but you will not be billed.
type: Answer
upvote count: 2
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49929675
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49929675

http://stackoverflow.com/comment/86947419
comment on: http://stackoverflow.com/q/49965774
type: QuestionComment
has text: Any difference if instead of a lambda, you use a ‘def’?
score: 0
type: Comment

http://stackoverflow.com/q/49964181
tagged with: python
score: 4
type: AnsweredQuestion
tagged with: scapy
has body: I've recently started using scapy and this doc. https://scapy.readthedocs.io/en/latest/ But a lot of stuff isn't written there for ex. all methods, what fields do sniffed packets have, what layers I can get etc. Where can I learn about scapy without loosing my sanity and googling for hours?
answer count: 1
favorite count: 0
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50164781
has title: Where to find pythons scapy module full documentation?
has answer: http://stackoverflow.com/a/50164781
downvote count: 0

http://stackoverflow.com/comment/87092679
type: QuestionComment
comment on: http://stackoverflow.com/q/50032639
has text: @DevOps Thank you! That was indeed the issue. Did a bit of research and found that I needed to update from mac os 10.8.5 to something much newer. In my case, I went to High sierra and everything worked.
score: 1
type: Comment

http://stackoverflow.com/a/49956903
has comment: http://stackoverflow.com/comment/86944206
has body: The problem is that the sleep function and possibly any other blocking function you call in your bar function blocks the GUI. A solution could be pushing the actions to a worker thread. A very quick solution I can come up with is this: from random import randint from threading import Thread from tkinter import Tk, DoubleVar, HORIZONTAL from tkinter.ttk import Frame, Button, Progressbar from time import sleep class Worker(Thread): def __init__(self, reference): super().__init__() self.reference = reference def run(self): print("running...") # replace this dummy loop with actual processing tasks while self.reference.get_progress() &lt; 100: duration = randint(1, 3) sleep(duration) self.reference.add_progress(10 * duration) print("finished.") class Example(Frame): def __init__(self, root): super().__init__(master=root) self.progress = DoubleVar(value=0.0) self.worker = Worker(reference=self) self.startbutton = Button(master=self, text="Start", command=self.start) self.startbutton.pack() self.progressbar = Progressbar(master=self, orient=HORIZONTAL, length=100, mode='determinate', variable=self.progress) self.progressbar.pack() self.infobutton = Button(master=self, text="Info", command=self.info) self.infobutton.pack() self.pack() def get_progress(self): return self.progress.get() def set_progress(self, value): self.progress.set(value) def add_progress(self, value): self.progress.set(self.progress.get() + value) def start(self): # print("sleeping...") # sleep(10) # uncomment this to block the GUI print("starting...") self.worker.start() def info(self): print(self.worker.is_alive()) def main(): root = Tk() app = Example(root) app.mainloop() if __name__ == '__main__': main() Note that the info button works before, while and after the thread runs. One problem with this quick solution is that the thread can only be run once. To run it multiple times, some kind of resetting needs to be implemented.
has comment: http://stackoverflow.com/comment/86934796
has comment: http://stackoverflow.com/comment/86935867
has comment: http://stackoverflow.com/comment/86931462
score: 0
answers question: http://stackoverflow.com/q/49956375
type: Answer
has comment: http://stackoverflow.com/comment/86954732
has comment: http://stackoverflow.com/comment/86931394

http://stackoverflow.com/comment/87127057
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50055307
type: QuestionComment
has text: you do not need append in list comprehension

http://stackoverflow.com/q/49976741
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15614927
downvote count: 0
has answer: http://stackoverflow.com/a/49977393
favorite count: 0
tagged with: qt
has answer: http://stackoverflow.com/a/49979592
has title: Get Output in Qt: 'QProcess::start()' and 'QProcess:readAllStandardOutPut()'
has answer: http://stackoverflow.com/a/49977218
tagged with: python
has body: Platform：Windows10 I use QProcess::start execute the Python file(in same diretory)，but i can't get results from readAllStandardOutput function. Python file code ： test.py print “hello,world” Qt： #include &lt;QProcess&gt; #include &lt;QStringList&gt; #include &lt;QByteArray&gt; #include &lt;QDebug&gt; void fun1(){ QProcess process; process.start("python test.py"); process.waitForFinished(); QByteArray a = process.readAllStandardOutput(); qDebug()&lt;&lt;a; } int main(){ fun1(); } I can get output when I execute test.py, but when I use readAllStandardOutput I can't get it. It a just print "" without data. #include &lt;QProcess&gt; #include &lt;QStringList&gt; #include &lt;QByteArray&gt; #include &lt;iostream&gt; #include &lt;QDebug&gt; void fun2(){ QStringList args("F:/test.py"); QProcess process; process.execute(QString("Python.exe"), args); QByteArray a = process.readAllStandardOutput(); process.waitForFinished(); qDebug()&lt;&lt;a; } int main(){ fun1(); qDebug&lt;&lt;"--------"; fun2(); } In fun2 function, the function execute() can print "hello,world" at Qt terminal, but I can't get the standard output with readAllStandardOutput function. The a also print "" without data i don't know why? Because I want to use the python module "requests" to visit a url directly, so I want my C++ code can execute this python file. So, if you have a better way, tell me please.
tagged with: qprocess
type: Question
tagged with: c++
score: 2
answer count: 3

http://stackoverflow.com/comment/86881552
type: Comment
type: QuestionComment
has text: The first purpose for this task is to decode without importing any module
comment on: http://stackoverflow.com/q/49932871
score: 0

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/50033311
type: Tag

http://stackoverflow.com/comment/86865143
type: QuestionComment
comment on: http://stackoverflow.com/q/49924561
score: 0
has text: Take a look at this for the 2nd part of your question https://stackoverflow.com/questions/49281459/np-dot-product-between-two-3d-matrices-along-specified-axis
type: Comment

http://stackoverflow.com/q/49957840
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86932500
favorite count: 0
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/86932608
has title: plot bool-int scatter in different colors in python
tagged with: python
has body: I have a dataframe as show below: df = index boolvalue 2014-05-21 10:00:00 1 2014-05-21 11:00:00 1 2014-05-21 12:00:00 0 2014-05-21 13:00:00 1 2014-05-21 14:00:00 0 2014-05-21 15:00:00 1 .... The column just has two values, "1" and "0". This are origin code and figure I have done: plt.scatter(df.index, df.boolvalue, s = 5,c='b' ) plt.ylim([-2, 2]) l would like to plot it as a scatter plot, with value "1" in color blue and "0" in color red . Because the index (time series) is long, I think it is better not to use a for-loop. Does anyone have an idea to do it? Thanks in advance!
accepted answer: http://stackoverflow.com/a/49958233
has answer: http://stackoverflow.com/a/49958233
tagged with: pandas

http://stackoverflow.com/comment/87003953
comment on: http://stackoverflow.com/a/49953095
score: 0
type: Comment
has text: BTW It is interesting to have an accepted answer with -1 score, I must have stepped on someone's toes recently...
type: AnswerComment

http://stackoverflow.com/q/50035053
tagged with: python
has comment: http://stackoverflow.com/comment/87129071
accepted answer: http://stackoverflow.com/a/50148020
type: AnsweredQuestion
score: 3
has body: I use save_model() method in ModelAdmin. I want to do sth when specific field changed (i.e. staus). So I want to know initial data before save admin so I could check it in save_model. I knew that there's __init__ and __save__ method in Model itself, but I want to activate code only in ModelAdmin. Here's sample code below def save_model(self, request, obj, form, change): if obj.status != xxx (intial data?) and obj.status == 7: # do sth super(CustomAdmin, self).save_model(request, obj, form, change) Summary Can I know initial data from obj after save in admin? Is there any way to do sth when only saving in admin site? Thanks in advance.
has answer: http://stackoverflow.com/a/50148020
upvote count: 3
answer count: 1
downvote count: 0
tagged with: admin
has comment: http://stackoverflow.com/comment/87129205
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87087081
has title: How to check initial data when save model in ModelAdmin?
tagged with: django

http://stackoverflow.com/a/50061123
accepted answer of: http://stackoverflow.com/q/50057591
type: Answer
score: 11
type: AcceptedAnswer
downvote count: 1
has body: You want your subplots to be squared. The function plt.axis accepts 'square' as a parameter and it really means it: it will make the current axes squared, both in pixels and in data units. x = np.arange(2) y = x / 3 u = v = [0, 1] plt.subplot(121) plt.plot(x, y) plt.axis('square') plt.subplot(122) plt.plot(u, v) plt.axis('square') Unfortunately this will expand the Y axis limits way beyond the Y data range, which is not what you want. What you need is the subplot's aspect ratio to be the inverse of the data ranges ratio. AFAIK there isn't any convenience function or method for this but you can write your own. def make_square_axes(ax): """Make an axes square in screen units. Should be called after plotting. """ ax.set_aspect(1 / ax.get_data_ratio()) plt.subplot(121) plt.plot(x, y) make_square_axes(plt.gca()) plt.subplot(122) plt.plot(u, v) make_square_axes(plt.gca())
answers question: http://stackoverflow.com/q/50057591
upvote count: 12

http://stackoverflow.com/q/50060981
upvote count: 6
type: AnsweredQuestion
has body: I have a huge code base before me, and I have a place where a file with name "foobar" gets written. I have no clue where this file gets read. My idea how to solve this: do monkey patching or mocking. An exceptions should get raised if a file with this name gets opened. run all tests and see where the exception gets raised. How to let the interpreter raise an exception if a file with given name gets opened? I am sure that the place I search is pure python, not a c-extension. I use Python 2.7
accepted answer: http://stackoverflow.com/a/50061469
has comment: http://stackoverflow.com/comment/87138893
answer count: 1
has comment: http://stackoverflow.com/comment/87138454
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/50061469
favorite count: 0
type: Question
tagged with: debugging
tagged with: python
has title: Python: raise Exception if file with name "foobar" gets opened

http://stackoverflow.com/comment/87035690
score: 0
comment on: http://stackoverflow.com/q/50008337
type: Comment
type: QuestionComment
has text: You can use regroup in your template. See https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#regroup (dont forget to order_by on the regroup field in your view or it wont work)

http://stackoverflow.com/comment/118257307
comment on: http://stackoverflow.com/a/66899406
score: 0
type: Comment
type: AnswerComment
has text: Is `eval` the right thing to use here? I feel like either `float` or `int` should be used as clearly a number is expected from user input.

http://stackoverflow.com/q/49947850
has title: Python pickle for Machine Learning
tagged with: python
has body: I have built a predictive model in Windows to train the dataset using python 3.6.1. I have used pickle to save the train model as a Pickle file Now I have written a another python script to read and load the train pickle file to predict the test data. I have got results successful in Windows. Now I want to move the Train pickle file and the Python script (that used the Train pickle file to predict the model using test data) to Linux environment which has the similar version of python installation as that of windows.But the python installation in Linux doesn't include machine learning libraries. In such a case will the Train pickle file of windows behave as a exe file having all the machine learning libraries? Will the python script that loads and read the train pickle file to predict the data fail in Linux as it does not any machine learning libraries installed.
has comment: http://stackoverflow.com/comment/87104394
favorite count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49947979
has comment: http://stackoverflow.com/comment/86913678
score: 1

http://stackoverflow.com/comment/87133454
comment on: http://stackoverflow.com/q/50058414
score: 0
has text: Yes, numbers in start list can get skipped. But numbers in end list can not, and raise an error.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50019840
answers question: http://stackoverflow.com/q/50019825
downvote count: 0
has body: Use list of list: dataExample = [1,2] columnNames = ['a','b'] df = pd.DataFrame( [dataExample] , columns = columnNames ) print (df) a b 0 1 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50019825
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/86882789
type: Comment
comment on: http://stackoverflow.com/a/49933620
type: AnswerComment
score: 0
has text: Your indentation is a little off, just saying.

http://stackoverflow.com/comment/87077398
comment on: http://stackoverflow.com/q/50030460
type: Comment
has text: @Jean-FrançoisFabre missing a `[` in the beginning: `array=[[[""] for _ in range(2)] for _ in range(2)]`
type: QuestionComment
score: 1

http://stackoverflow.com/comment/87127353
type: QuestionComment
comment on: http://stackoverflow.com/q/50035082
has text: @lenz. When I query the database and print the result to console, I do get ação back. The ODBC trace seems to show the same bytes for the insert and select. `SELECT 43 6C 61 73 73 69 66 69 63 61 C3 83 C2 A7 C3 83 Classifica C2 A3 6F 20 42 72 61 73 69 6C 65 69 72 61 20 64 o Brasileira d` `INSERT 00 43 6C 61 73 73 69 66 69 63 61 C3 83 C2 A7 C3 Classifica 83 C2 A3 6F 20 42 72 61 73 69 6C 65 69 72 61 20 o Brasileira`
score: 0
type: Comment

file
tags question: http://stackoverflow.com/q/50034202
type: Tag
tags question: http://stackoverflow.com/q/49987325
tags question: http://stackoverflow.com/q/49918701
tags question: http://stackoverflow.com/q/50016320
tags question: http://stackoverflow.com/q/50032946
tags question: http://stackoverflow.com/q/50035562
tags question: http://stackoverflow.com/q/49931615
tags question: http://stackoverflow.com/q/50017534
tags question: http://stackoverflow.com/q/50057457
tags question: http://stackoverflow.com/q/49983047
tags question: http://stackoverflow.com/q/50042255
tags question: http://stackoverflow.com/q/50028067
tags question: http://stackoverflow.com/q/49950606
tags question: http://stackoverflow.com/q/50017003
tag name: file
tags question: http://stackoverflow.com/q/49946165
tags question: http://stackoverflow.com/q/49956405
tags question: http://stackoverflow.com/q/49955556
tags question: http://stackoverflow.com/q/50032810
tags question: http://stackoverflow.com/q/49930650
tags question: http://stackoverflow.com/q/49959094
tags question: http://stackoverflow.com/q/50012991
tags question: http://stackoverflow.com/q/50035986
tags question: http://stackoverflow.com/q/50011733
tags question: http://stackoverflow.com/q/50004310
tags question: http://stackoverflow.com/q/50012481
tags question: http://stackoverflow.com/q/50033072
tags question: http://stackoverflow.com/q/50040697

http://stackoverflow.com/comment/86875604
type: Comment
comment on: http://stackoverflow.com/q/49929676
type: QuestionComment
has text: Ah I see, thanks for clearing that up!
score: 0

http://stackoverflow.com/q/50059102
type: AnsweredQuestion
score: 2
has body: I have a working chat app on localhost, but it does not work on heroku (Question from yesterday). After some research I think the problem is how I start the app. Procfile currently: web: gunicorn adult_main:app I need to use gevent in combination with gunicorn. This way I should be able to have max. 1000 socket.io connections, which is enough for me for the moment. I already installed and added gevent to the requirements.txt. Here an extract of the file: Flask-SocketIO==2.9.6 gunicorn==19.7.1 gevent==1.2.2 gevent-socketio==0.3.6 gevent-websocket==0.10.1 But I do not understand how to start the app correctly. On a sidenote, I am using heroku's free tier to test everything. I tried a few solutions, which I found online, but I do not fully understand them and I have not found a documentation on that yet. Here are some of my attempts: web: gunicorn -k gevent-socketio adult_main:app web: gunicorn -k gevent adult_main:app I also tried to start without gunicorn, but I think that was completely wrong. Am I on the correct path here? EDIT I managed to make some progress with: web: gunicorn -k gevent -w 1 adult_main:app The app does not crash on start now, but in the web console I see an error: socket.io.js:7 WebSocket connection to 'wss://my- project.herokuapp.com/socket.io/? EIO=3&amp;transport=websocket&amp;sid=0022c1937df648bbab836bfcb4c35' failed: Error during WebSocket handshake: Unexpected response code: 500 In the heroku logs: RuntimeError: You need to use the gevent-websocket server. EDIT Eventhough I see these errors, the chat works now on heroku. That is really weird. Probably I can establish now only 1 connection, how to continue now?
downvote count: 0
answer count: 1
tagged with: websocket
tagged with: socket.io
has title: Python heroku configure procfile gunicorn + gevent for socket.io chat app | RuntimeError: You need to use the gevent-websocket server
favorite count: 0
type: Question
tagged with: heroku
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/50079510
accepted answer: http://stackoverflow.com/a/50079510
upvote count: 2

http://stackoverflow.com/comment/87161738
comment on: http://stackoverflow.com/q/50072403
has text: It would be so much easier to answer this question if you show us your current result and an example of you are trying to accomplish. Certainly you've seen this visual representation somewhere else. Anyway, you can use `candlestick2_ohlc` from `matplotlib.finance` if you need to plot something quick.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49969413
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49927060
has body: Instagram has built-in limits to prevent abuse of their APIs. There's nothing you can do to "fix" this as the problem isn't with your code. You can set a delay in-between requests to prevent getting 429'd. In case you get 429'd you should probably not attempt to do anything for a while (except checking if the block is gone every few minutes).

http://stackoverflow.com/q/49956272
has body: I'm trying to use Django + Haystack + Elasticsearch. So I installed Elasticsearch 2.4 with pip becouse Django gave me errors about that it can't import Elasticsearch. Now it can and I can run ./manage.py rebuild_index in my Django project and it gives this output: Indexing 23 journal entrys GET /haystack/_mapping [status:404 request:0.006s] but only if I somehove run elasticsearch. So I installed elsasticsearch2 from AUR packages as well and run that. But as I suspected when I try to get all documents by running: curl -X GET "localhost:9200/_cat/indices?v" which returns: health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open haystack 5 1 0 0 795b 795b If I understand correctly it is empty. I went where pip installs packages(/usr/lib/python3.6/site-packages) and found two folders related to Elasticsearch: elasticsearch ├── client │ ├── cat.py │ ├── cluster.py │ ├── indices.py │ ├── ingest.py │ ├── __init__.py │ ├── nodes.py │ ├── __pycache__ │ │ ├── cat.cpython-36.pyc │ │ ├── cluster.cpython-36.pyc │ │ ├── indices.cpython-36.pyc │ │ ├── ingest.cpython-36.pyc │ │ ├── __init__.cpython-36.pyc │ │ ├── nodes.cpython-36.pyc │ │ ├── snapshot.cpython-36.pyc │ │ ├── tasks.cpython-36.pyc │ │ └── utils.cpython-36.pyc │ ├── snapshot.py │ ├── tasks.py │ └── utils.py ├── compat.py ├── connection │ ├── base.py │ ├── http_requests.py │ ├── http_urllib3.py │ ├── __init__.py │ ├── pooling.py │ └── __pycache__ │ ├── base.cpython-36.pyc │ ├── http_requests.cpython-36.pyc │ ├── http_urllib3.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ └── pooling.cpython-36.pyc ├── connection_pool.py ├── exceptions.py ├── helpers │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── test.cpython-36.pyc │ └── test.py ├── __init__.py ├── __pycache__ │ ├── compat.cpython-36.pyc │ ├── connection_pool.cpython-36.pyc │ ├── exceptions.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ ├── serializer.cpython-36.pyc │ └── transport.cpython-36.pyc ├── serializ…
has title: How to run pip installed elasticsearch?
tagged with: elasticsearch
tagged with: python
type: Question
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: django-haystack
downvote count: 0
tagged with: django
favorite count: 0
has comment: http://stackoverflow.com/comment/86940408
score: 3
tagged with: linux
has comment: http://stackoverflow.com/comment/86942281

http://stackoverflow.com/comment/87025568
type: Comment
type: AnswerComment
has text: agree with you on his problem, to be more clear : instanceObj = MC.instance(thing, name=thing[0] + '_instance#')
score: 0
comment on: http://stackoverflow.com/a/50001477

http://stackoverflow.com/q/50049769
has comment: http://stackoverflow.com/comment/87116489
has comment: http://stackoverflow.com/comment/87116046
tagged with: flask
tagged with: uwsgi
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87117955
has title: uWSGI max requests vs Flask (Python) Garbage Collection
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87115981
tagged with: python
has comment: http://stackoverflow.com/comment/87116383
has body: I am facing conceptual issue where I cannot find a valid explanation. I have a product where I am using Flask and uWSGI configuration. In uWSGI documentation, there is a parameter called max-requests . The purpose of this flag is to respawn workers if the request count exceeds the limit specified for max-requests in INI file. The document says that it is used to prevent memory leak. The confusion is that Python-Flask have their own memory management and garbage collection implemented and it works significantly well. My confusion is if frameworks have their own memory management, why uWSGI is trying to do memory management to prevent data leak? Second part of problem is that if the respawn happens, for that few milliseconds, the API which is already accepted by that worker takes few seconds to respond. It looks something like this. Response Time: 32ms API: /api/v1.0/ping Date: 2018-04-26 12:00:10 # respawn happens Response Time: 7s API: /api/v1.0/ping Date: 2018-04-26 12:00:20 Response Time: 10ms API: /api/v1.0/ping Date: 2018-04-26 12:00:30 Is there a better way to handle this so that I do now respawn workers and rely completely on Python's garbage collector? This may sound like a stupid questions but it extremely helpful if someone can explain me how and why of uWSGI? Thanks a lot.
score: 2
upvote count: 2
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/87098305
type: QuestionComment
has text: do you mean `x**(3/(sp.exp(x)-1))` or `(x**3) / (sp.exp(x)-1)` ? what doesn't work? error? wrong value? 42 ?
comment on: http://stackoverflow.com/q/50041121
score: 2
type: Comment

http://stackoverflow.com/comment/87005212
has text: I want my final data to be in similar format to the code i shared on how i read the .txt, list of dictionaries, kindly refer to `label1` in my question which is a list of dictionaries(json).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49994443
type: AnswerComment

http://stackoverflow.com/comment/86981213
has text: add the `fieldnames`. Updated snippet.
comment on: http://stackoverflow.com/a/49982084
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89231478
comment on: http://stackoverflow.com/a/49999624
score: 0
type: Comment
has text: @walksignison, just as I said, it works when I install it from `requirements.txt` with the command `pip install -r requirements.txt`. I don't need to use `pip3` because I'm using a virtualenv where the defaults are `python3` and `pip3`.
type: AnswerComment

http://stackoverflow.com/comment/86879998
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49931918
type: AnswerComment
has text: @tdelaney Ask any seasoned developer during code review which one they would prefer. 99/100 developers would say to use an `if` statement and not an unconventional dictionary approach.

http://stackoverflow.com/q/49942464
tagged with: indexing
type: AnsweredQuestion
has body: I have the following Dataframe below: Rec Channel Value1 Value2 Pre 10 20 Pre 35 42 Event A 23 39 FF 50 75 Post A 79 11 Post B 88 69 I am trying to determine the appropriate syntax for this Pandas Dataframe on how to index for all instances where the column 'Channel' is either equal to either A or B. Once all instances are found, I would like to print those out. Additionally, I would like to be able to call upon each index for further applications within the script. I want the display to be: Rec Channel Value1 Value2 Event A 23 39 Post A 79 11 Post B 88 69 And then I want to have a 'for loop' that goes through and prints out each indexed instance separately so that it is easy to identify and call upon them individually for further uses in the script. Can someone please advise?
has answer: http://stackoverflow.com/a/49942512
accepted answer: http://stackoverflow.com/a/49942512
tagged with: dataframe
tagged with: python
upvote count: 4
score: 4
linked to: http://stackoverflow.com/q/12096252
type: Question
has answer: http://stackoverflow.com/a/49942708
answer count: 2
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/16476924
duplicate of: http://stackoverflow.com/q/12096252
has title: Python Pandas: Getting the Index of All Rows that Match a Column Value
favorite count: 0
possible better answer: http://stackoverflow.com/a/49942708

http://stackoverflow.com/comment/86902815
score: 0
comment on: http://stackoverflow.com/q/49943195
type: QuestionComment
has text: < This script IS naming the files created. > I don't see that. `if not os.path.exists(fname)` is checking if the file exists.
type: Comment

http://stackoverflow.com/comment/87146301
has text: If you're interested, I have code I can license to you which handles this completely client-side. That is, it demuxes the ICY-style metadata without making separate connections to the server. Contact me at brad@audiopump.co if you're interested.
comment on: http://stackoverflow.com/q/50040481
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49973005
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49971915
accepted answer of: http://stackoverflow.com/q/49971915
type: Answer
has body: sympy has a plotting module, pretty much just the example code from sympy import symbols from sympy.plotting import plot3d x, y = symbols('x y') plot3d((x**2 - y**2))

http://stackoverflow.com/comment/86990206
has text: awesome ! its so clear now... By the way, do you know, how can i remove the margin? Be free to post as an answer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49983806
score: 0

http://stackoverflow.com/q/49990900
has body: I need to run a function send_user_survey to every 100 users who hit a certain endpoint. I can't simple increment a counter locally because I have multiple machines, so 50 hits on one machine and 50 on another should trigger one run of send_user_survey. I could store the count on the database but using a SQL database to lock and increment on every API call doesn't seem like the right solution, especially since this API gets hit pretty hard.
accepted answer: http://stackoverflow.com/a/49990901
type: Question
type: AnsweredQuestion
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/49990901
answer count: 1
has title: Run a function every N calls to an API in a distributed environment
tagged with: django

http://stackoverflow.com/q/50023807
has body: I'm using pandas.io.json.json_normalize() to convert some json into a dataframe, which is then pushed to an SQLite database via df.to_sql(). However, I'm getting sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. when progressing with this, I think due to one of my json fields being an empty array. I understand I can pass additional path arguments to json_normalize to have it pull out array values and augment the rows with the parent data: json_normalize(json_data, 'field_name_of_empty_array_value') However I can't use this for this instance, as the array is empty and so it returns no values. Is there a way to set the empty list value to None, or to serialize the empty list via the json_serialize function? Or do I need to do this on the returned dataFrame? The reason I want to understand whether this is possible is to limit the complexity when dealing with more difficult json which may have empty array values nested deep within its structure. I've search for this specific question but can't seem to find an example dealing with this specific case, and not sure the docs covers it. Thanks
tagged with: python
type: AnsweredQuestion
has title: Using pandas.io.json.json_normalize() with empty list attributes
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50041879
score: 3
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/50041879
downvote count: 0
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49916921
type: Question
type: AnsweredQuestion
has body: If I run this code twice: tf.flags.DEFINE_integer("batch_size", "2", "batch size for training") I will get this error: DuplicateFlagError: The flag 'batch_size' is defined twice. First from D:/Python/workspace/FCN_dataset/FCN.tensorflow-master/FCN.py, Second from D:/Python/workspace/FCN_dataset/FCN.tensorflow-master/FCN.py. Description from first occurrence: batch size for training I know that it's because of I redefine the default value of flag. So how can I clear flags or allow to redefine the flag's default value?
score: 7
tagged with: python
has title: How to clear tf.flags?
accepted answer: http://stackoverflow.com/a/49932628
has answer: http://stackoverflow.com/a/49932628
answer count: 1
downvote count: 0
upvote count: 7
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/86999741
has text: Another possibility that's sometimes simpler is to just wrap the function in a global function that takes some extra arguments, instead of binding them into the closure, and then pass the global function and the extra arguments, or pass a `partial` that binds them in. It's not as clean-looking as passing a local closure, but it's actually cleaner under the covers (when it's appropriate).
comment on: http://stackoverflow.com/q/49991266
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86898244
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49941181
type: QuestionComment
has text: The models for the Product or models for the 'item' fk? Or both?

http://stackoverflow.com/comment/86889308
type: Comment
score: 0
type: AnswerComment
has text: That is a different question. The syntax error in `SELECT` that you reported is now fixed. What you now have is a runtime error caused by the failure of the `INSERT`. We can't possibly tell why that is failing without knowing the structure of the table `formI` and whatever table is named in `nameGroup`.
comment on: http://stackoverflow.com/a/49936543

http://stackoverflow.com/q/49994975
upvote count: 1
has comment: http://stackoverflow.com/comment/87007769
tagged with: python
has comment: http://stackoverflow.com/comment/87006556
has title: kivy app freezes when using threading
has comment: http://stackoverflow.com/comment/87007884
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87006629
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49996059
accepted answer: http://stackoverflow.com/a/49996059
answer count: 1
tagged with: kivy
has body: I had this code which uses threading but at some point, the GUI freezes (after I pressed the button). import threading import Queue from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.clock import Clock main_kv = """ &lt;CustomLabel&gt;: size_hint: (None, None) size: self.texture_size &lt;Main&gt;: orientation: "vertical" Button: size_hint: (1, None) height: dp(70) on_press: root.spawn_threads() """ class CustomLabel(Label): pass class Main(BoxLayout): def spawn_threads(self, *args): Clock.schedule_once(self.do_something, 1) def job(self): task = self.q.get() self.add_widget(CustomLabel(text=str(task))) self.q.task_done() def do_something(self, *args): data = [i for i in xrange(20)] self.q = Queue.Queue() for i in data: self.q.put(i) for _ in xrange(20): t = threading.Thread(target=self.job) t.daemon = 1 t.start() self.q.join() class TestApp(App): def build(self): Builder.load_string(main_kv) return Main() TestApp().run() I've read somewhere that I must not block the GUI or else it will freeze... Maybe the "self.q.join()" is blocking the GUI. Is there another way to implement queue join() method so that I'm not blocking the GUI?
has comment: http://stackoverflow.com/comment/87006292
has comment: http://stackoverflow.com/comment/87006406
type: Question
has comment: http://stackoverflow.com/comment/87006468

http://stackoverflow.com/a/50031855
type: AcceptedAnswer
has body: In for key,value in data, there are two problems: data is the list of dictionaries. You probably meant for key,value in row. Iterating over a dictionary only iterates over its keys. To iterate over both keys and values, do for key,value in row.items(). My question is: what is meant by too many values? for key,value in data means that data should be an iterable of pairs that get unpacked into key and value. But the first thing you get when iterating over data is the big dictionary it contains. To try to unpack the dictionary into key, value, Python iterates over the dictionary and gets all 52 keys, which is too many values. Think of it this way: you wouldn't do: for row in data: key, value = row because the row has many keys and values. Nor would you do: for k in row: key, value = k because k is a key of row, which is a string. Hence we need .items().
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/87310005
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50031627
answers question: http://stackoverflow.com/q/50031627

hadoop-yarn
tags question: http://stackoverflow.com/q/50071304
type: Tag
tag name: hadoop-yarn

http://stackoverflow.com/comment/86968119
type: QuestionComment
comment on: http://stackoverflow.com/q/49975783
score: 0
has text: install manually https://centos.pkgs.org/7/ius-archive-x86_64/python35u-mod_wsgi-4.5.7-1.ius.centos7.x86_64.rpm.html
type: Comment

http://stackoverflow.com/q/49944545
answer count: 0
upvote count: 1
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
score: 1
has body: I just moved from Matlab to Python. So I am looking hopefully to re-build my GUI in Matlab Guide with Page Python (only hopeful for better performance for big data) I designed several Push Buttons and inside the code I try to write the below code just beneath Button1.configure. I can not take out seop value from this clicked () function although I even define it as global variable. I need seop for whole the program. self.Button1.configure(text='''Data''') def clicked(): global seop from tkinter import filedialog, messagebox fname = filedialog.askopenfilename (initialdir="C:\Sgty") import numpy as np seop = np.loadtxt (fname) messagebox.showinfo ('Data Import', 'Int') s1 = self.Button1.configure (command=clicked, text="Import Data")
tagged with: python
has title: How to modify Page Py output
tagged with: tkinter

http://stackoverflow.com/comment/87057851
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50006314
has text: @nekomatic No, I installed it into a Python 2.7 env I had from before. I'll try a new env, thanks.
score: 0

http://stackoverflow.com/a/49952270
type: Answer
has comment: http://stackoverflow.com/comment/86921152
answers question: http://stackoverflow.com/q/49952108
has body: This can achieve what you need , create a new key by using cumsum, then we groupby the key we created , using cumsum again df.groupby(df.A.eq(1).cumsum()).B.apply(lambda x : x.astype(str).cumsum()) Out[838]: 0 4 1 43 2 431 3 4312 4 5 5 54 6 2 7 22 8 224 Name: B, dtype: object
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49952108
has comment: http://stackoverflow.com/comment/86921145
score: 1

http://stackoverflow.com/comment/86862820
type: QuestionComment
score: 0
has text: You need to use '\n' if you write to a file.
comment on: http://stackoverflow.com/q/49923488
type: Comment

http://stackoverflow.com/q/49930064
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has title: Get sample size for boxplots in seaborn factorplot
tagged with: seaborn
tagged with: boxplot
tagged with: python
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/49948522
upvote count: 2
has answer: http://stackoverflow.com/a/49948522
answer count: 1
has body: I'm looking to get the sample number to appear on each boxplot as I see here: https://python-graph-gallery.com/38-show-number-of-observation-on-boxplot/ I'm able to get the median and counts in lists as the link above presents. However, I have a factorplot with hue, such that the positions of the x-ticks don't seem to be captured on the x-axis. Using the seaborn tips data set, I have the following: import seaborn as sns import matplotlib.pyplot as plt import numpy as np sns.set_style("whitegrid") tips = sns.load_dataset("tips") g = sns.factorplot(x="sex", y="total_bill",hue="smoker", col="time",data=tips, kind="box",size=4, aspect=.7) # Calculate number of obs per group &amp; median to position labels medians = tips.groupby(['time','sex','smoker'])['total_bill'].median().values nobs = tips.groupby(['time','sex','smoker']).size() nobs = [str(x) for x in nobs.tolist()] nobs = ["n: " + i for i in nobs] plt.show() Here is the plot I'd like to get the "n: [# of observations]" right above the median, and I'm wondering if there's a way to get that x-tick. Also, assume some groups don't always have both male and female so it can't just be hard coded.

http://stackoverflow.com/q/49940511
has title: Why does pd.concat change the resulting datatype from int to float?
has answer: http://stackoverflow.com/a/60802429
possible better answer: http://stackoverflow.com/a/60802429
favorite count: 0
has answer: http://stackoverflow.com/a/49940609
accepted answer: http://stackoverflow.com/a/49940609
type: Question
score: 31
upvote count: 31
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I have three dataframes: timestamp (with timestamps), dataSun (with timestamps of sunrise and sunset), dataData (with different climate data). Dataframe timestamp has datatype "int64". timestamp.head() timestamp 0 1521681600000 1 1521681900000 2 1521682200000 3 1521682500000 4 1521682800000 Dataframe dataSun has also datatype "int64". dataSun.head() sunrise sunset 0 1521696105000 1521740761000 1 1521696105000 1521740761000 2 1521696105000 1521740761000 3 1521696105000 1521740761000 4 1521696105000 1521740761000 Dataframe with climate data dataData has datatype "float64". dataData.head() temperature pressure humidity 0 2.490000 1018.000000 99.0 1 2.408333 1017.833333 99.0 2 2.326667 1017.666667 99.0 3 2.245000 1017.500000 99.0 4 2.163333 1017.333333 99.0 5 2.081667 1017.166667 99.0 I want to concatenate these three dataframes in one. dataResult = pd.concat((timestamp, dataSun, dataData), axis = 1) dataResult.head() timestamp sunrise sunset temperature pressure 0 1521681600000 1.521696e+12 1.521741e+12 2.490000 1018.000000 1 1521681900000 1.521696e+12 1.521741e+12 2.408333 1017.833333 2 1521682200000 1.521696e+12 1.521741e+12 2.326667 1017.666667 3 1521682500000 1.521696e+12 1.521741e+12 2.245000 1017.500000 4 1521682800000 1.521696e+12 1.521741e+12 2.163333 1017.333333 5 1521683100000 1.521696e+12 1.521741e+12 2.081667 1017.166667 weatherMeasurements.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 7188 entries, 0 to 7187 Data columns (total 6 columns): timestamp 7188 non-null int64 sunrise 7176 non-null float64 sunset 7176 non-null float64 temperature 7176 non-null float64 pressure 7176 non-null float64 humidity 7176 non-null float64 dtypes: float64(5), int64(1) Why pd.concat has changes the datatype of the values DataSun? I have tried different ways to concatenate the dataframes. For example, I concatenated only timestamp and dataSun in one dataframe, then I concatenated resulted dataframe with dataData. But it was the same result. How can I concatena…
tagged with: concatenation
answer count: 3
has answer: http://stackoverflow.com/a/78772020
downvote count: 0

http://stackoverflow.com/q/50013318
upvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50013367
answer count: 2
has body: very new to python and have a "python block" I'm trying to solve. I want to query a specific linux directory for its files (could be any number of files in directory), then display (print) the files list for user input selection; like the following: Please choose your option: 1 - somecode.py 2 - somefile.txt 3 - someotherfile.j2 Where the above filenames were pulled from the directory and the option number is prefixed and displayed for the user to select. So far I can pull the directory list and print it, but getting stuck pulling the list into a user input function for proper display and user selection. if I just pull a print the files in the directory it looks good, but having trouble with the part about prefixing a option varibale to the list and displaying for user input. for filename in os.listdir('./templates'): print(filename) it looks like this: cisco_tmpl.j2 juniper_tmpl.j2 nxos_tmpl.j2 Many hours trying various ways to pretty this up and any help will be greatly appreciated. Thanks
accepted answer: http://stackoverflow.com/a/50013488
has answer: http://stackoverflow.com/a/50013488
has title: Using directory list, assign input option and print
downvote count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50013367
score: 1

http://stackoverflow.com/a/68087486
score: 0
answers question: http://stackoverflow.com/q/50050343
type: Answer
has body: To search only using Google News you need to add tbm=nws to your url. https://www.google.com/search?q=coca+cola --> https://www.google.com/search?q=coca+cola&tbm=nws Here's how you can do it using beautifulsoup, requests, urllib libraries to scrape with actual pagination. Code and example in the online IDE: from bs4 import BeautifulSoup import requests, urllib.parse def paginate(url, previous_url=None): # Break from infinite recursion if url == previous_url: return headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582" } response = requests.get(url, headers=headers).text soup = BeautifulSoup(response, 'lxml') # First page yield soup next_page_node = soup.select_one('a#pnnext') # Stop when there is no next page if next_page_node is None: return next_page_url = urllib.parse.urljoin('https://www.google.com/', next_page_node['href']) # Pages after the first one yield from paginate(next_page_url, url) def scrape(): pages = paginate( "https://www.google.com/search?hl=en-US&q=coca+cola&tbm=nws") for soup in pages: print(f'Current page: {int(soup.select_one(".YyVfkd").text)}') print() for data in soup.findAll('div', class_='dbsr'): title = data.find('div', class_='JheGif nDgy9d').text link = data.a['href'] print(f'Title: {title}') print(f'Link: {link}') print() # part of the output: ''' Results via beautifulsoup Current page: 1 Title: A Post-Truth World: Why Ronaldo Did Not Move Coca-Cola Share Price Link: https://www.forbes.com/sites/iese/2021/06/19/a-post-truth-world-why-ronaldo-did-not-move-coca-cola-share-price/ ... Current page: 22 Title: The Coca-Cola Co. unveils oat milk line Link: https://www.foodbusinessnews.net/articles/18356-the-coca-cola-co-unveils-oat-milk-line ''' Alternatively, you can do the same thing using Google Search Engine Results API from SerpApi. It's a paid API with a free trial of 5,000 searches. Check out the playground. Code to integrate: # http…

http://stackoverflow.com/comment/87151795
comment on: http://stackoverflow.com/q/50067583
type: Comment
has text: If you're trying to avoid needing to have numpy installed on the remote machine, that's not possible. If you have values or functions that fail to unpickle on the remote machine, you may be able to just use `cloudpickle` (if you expect your two setups to be identical) or `dill` (if you don't) instead of plain `pickle`. You also might want to consider using a distributed computing library that wraps up the pickling, dispatching, etc. rather than trying to build one from scratch.
score: 1
type: QuestionComment

http://stackoverflow.com/q/49972553
has body: Hi can someone please explain to me why this function isn't working as I intended it to? I know I can do it by using the index of the list to check if the element is equal to a variable but why can't this method work? Expectations- I wanted this function to change the element in list (stored) if it matches a particular value. IE chance letter c to the # symbol in this example. Results - The list (stored) that is printed will have no difference and end up print [a,b,c,d,e] Code stored = ["a", "b", "c", "d", "e"] def if_match(): for letters in stored: if letters == "c": letters = "#" print stored
has title: Changing of stored list value
has comment: http://stackoverflow.com/comment/86961155
has comment: http://stackoverflow.com/comment/86961750
favorite count: 0
has answer: http://stackoverflow.com/a/49972657
type: Question
linked to: http://stackoverflow.com/q/4081217
type: UnansweredQuestion
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/4081217
downvote count: 2
has comment: http://stackoverflow.com/comment/86961186
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50055401
has comment: http://stackoverflow.com/comment/87129462
has answer: http://stackoverflow.com/a/51811293
tagged with: selenium-webdriver
score: 1
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/50057160
has title: What are the arguments of webdriver.Firefox() and their significance
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: firefox
tagged with: geckodriver
upvote count: 1
tagged with: python
has body: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities cap = DesiredCapabilities().FIREFOX cap["marionette"] = False webdriver.Firefox(capabilities=cap, executable_path='D:/nchaurasia/Python-Architect/connect2tech.in-Selenium-Python/FF/geckodriver.exe') The above code works perfectly fine. Now i am trying to understand the selenium.webdriver.Firefox i.e. find the documentation for Firefox which comes from webdriver. I have checked the following links: https://seleniumhq.github.io/selenium/docs/api/py/api.html http://selenium-python.readthedocs.io/api.html http://selenium-python.readthedocs.io/py-modindex.html I have googled a lot but cannot find the documentation for selenium.webdriver.Firefox Actually I am looking for something similar to https://seleniumhq.github.io/selenium/docs/api/java/ where i can access package, classes and methods in classes. Thanks.
has comment: http://stackoverflow.com/comment/87128987

http://stackoverflow.com/q/50055085
has answer: http://stackoverflow.com/a/50055159
upvote count: 2
has comment: http://stackoverflow.com/comment/87126631
possible better answer: http://stackoverflow.com/a/50056332
downvote count: 0
has title: How to seperate date, month and year from the following data frame.its a data of 8.4 Million users
favorite count: 0
type: Question
has body: I have tried using DatetimeIndex method. The column with values is as follows reg_date 2013-06-10T00:00:00.000Z 2014-09-30T00:00:00.000Z 2014-09-30T00:00:00.000Z 2014-09-30T00:00:00.000Z 2014-10-01T00:00:00.000Z type(df.reg_date) yields pandas.core.series.Series and have used the following df['reg_month'] = pd.DatetimeIndex(df['reg_date']).month I got this for earlier data, but DatetimeIndex doesn't work here and getting the Below error TypeError Traceback (most recent call last) C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike(arg, box, format, name, tz) 302 try: --&gt; 303 values, tz = tslib.datetime_to_datetime64(arg) 304 return DatetimeIndex._simple_new(values, name=name, tz=tz) pandas/_libs/tslib.pyx in pandas._libs.tslib.datetime_to_datetime64() TypeError: Unrecognized value type: &lt;class 'str'&gt; During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) &lt;ipython-input-22-4e7ef5ca2997&gt; in &lt;module&gt;() ----&gt; 1 df['reg_month'] = pd.DatetimeIndex(df['reg_date']).month C:\ProgramData\Anaconda3\lib\site-packages\pandas\util\_decorators.py in wrapper(*args, **kwargs) 116 else: 117 kwargs[new_arg_name] = new_arg_value --&gt; 118 return func(*args, **kwargs) 119 return wrapper 120 return _deprecate_kwarg C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\datetimes.py in __new__(cls, data, freq, start, end, periods, copy, name, tz, verify_integrity, normalize, closed, ambiguous, dtype, **kwargs) 340 is_integer_dtype(data)): 341 data = tools.to_datetime(data, dayfirst=dayfirst, --&gt; 342 yearfirst=yearfirst) 343 344 if issubclass(data.dtype.type, np.datetime64) or is_datetimetz(data): C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\tools\datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin) 378 result = _convert_listlike(arg, box, format, name=arg.name) 379 elif is_l…
tagged with: datetime
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50056332
accepted answer: http://stackoverflow.com/a/50055159
type: AnsweredQuestion
score: 2
tagged with: datetimeindex
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/87038091
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49989909
has text: My fault: the max-method in `data.groupby().max()` returns all Maximum values, i.e. in each group you receive the Maximum value of every individual column - which of course doesn't preserve the row-structure. What you Need is a Maximum-calculation which is better described as a filter, so it has to be informed about which column should be checked for max, so that the row with this Maximum value only in this column can be returned. You find the according code in the middle of the post in the latest edit, it is `data_grpd = data.groupby('cluster_name')` `data.loc[data_grpd['pident'].idxmax()]`

http://stackoverflow.com/comment/86978438
type: Comment
has text: I use the offline mode, this is why
score: 0
comment on: http://stackoverflow.com/a/49980108
type: AnswerComment

http://stackoverflow.com/comment/87157993
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50070571
has text: As a side note, why are you using `findAll` instead of `find_all`? That happens to work, despite the documentation saying it was removed, but you really shouldn't rely on that. More to the point, if you're learning from a tutorial for BS3 instead of BS4, you really want to find a newer and better tutorial (and likewise if you're copying and pasting BS3 code, etc.).
score: 3

http://stackoverflow.com/comment/88004556
has text: Hi, sorry for bothering again. I think I found a solution using `stripe(a[..., ::-1, :])[..., ::-1, :]`, can you explain why you have to flip it the second time after applying stripe?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49982967

http://stackoverflow.com/comment/87155461
type: AnswerComment
comment on: http://stackoverflow.com/a/50069208
score: 0
type: Comment
has text: `df.rank.sum(level=0)` you can add this

http://stackoverflow.com/comment/87158703
has text: Yes, the max and for that matter any normal pandas functions work across all partitions, you don't have to worry about it. As for groupby does not really require any computation to happen after it (you could for example manually loop through the groups in a groupby object in pandas) and groupby is much faster if your dataset fits in memory. But I would just try it the way I had it in my answer and add a progressbar to keep track of how long you need to wait.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50051329

http://stackoverflow.com/q/49969085
downvote count: 0
tagged with: pip
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86954292
has comment: http://stackoverflow.com/comment/86954289
has answer: http://stackoverflow.com/a/49970573
has comment: http://stackoverflow.com/comment/86954297
has comment: http://stackoverflow.com/comment/86954286
has comment: http://stackoverflow.com/comment/86954158
has title: I have installed beautifulsoup4, but when I try to import bs4 in python shell, I get ModuleNotFound Error
has answer: http://stackoverflow.com/a/49969489
favorite count: 0
tagged with: beautifulsoup
type: Question
upvote count: 2
score: 2
answer count: 2
has body: I have repeatedly installed and uninstalled beautifulsoup4, but no matter what I try to do, when I try to import bs4 in shell, I get ModuleNotFoundError. I'm on Windows 10 and using Python 3.6.4. I'm new to programming, but am on my third Python book and this is the first time I've run into a big problem trying to import a module, including those I've installed using pip.

http://stackoverflow.com/a/77710745
score: 0
answers question: http://stackoverflow.com/q/50004745
has body: I'm a bit late but you could play around with Kivy (and integrate the OpenCV webcam), but it would require you to make most of the game from scratch.
type: Answer

http://stackoverflow.com/q/49944571
has body: I have a class(call it ClassC) where one of the attributes is another class(call it ClassB). ClassB actually needs data from ClassC to initialize itself, so I pass ClassC to ClassB using the following syntax: class ClassC(object): def __init__(self): self.val = 8 self.derived_class = ClassB(self) I'm seeing an error that complains about init() not taking any parameters, but I'm just not seeing where the issue could be arising from. Am I not using super() in the correct way so that ClassB initializes its base class,ClassA, as well? Traceback (most recent call last): File "python", line 18, in File "python", line 15, in init File "python", line 9, in init TypeError: object.init() takes no parameters I have reproduced the code below, or you can run it here. class ClassA(object): def __init__(self, initial_class): self.val = None self.initial_class = initial_class class ClassB(ClassA): def __init__(self, initial_class): super(ClassA, self).__init__(initial_class) self.val = 7 class ClassC(object): def __init__(self): self.val = 8 self.derived_class = ClassB(self) c = ClassC()
answer count: 0
has comment: http://stackoverflow.com/comment/86905418
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14086782
type: Question
score: 0
tagged with: oop
duplicate of: http://stackoverflow.com/q/14086782
has title: Passing a class to Python's super()
tagged with: python
has comment: http://stackoverflow.com/comment/86906244

http://stackoverflow.com/a/49931068
answers question: http://stackoverflow.com/q/49928609
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49928609
has body: I do not think there is a faster than O(N) solution to this problem, unless you remove the repetitions. That being said, this is the fastest implementation that I could come up with: def is_part_of_sequence(a, d, x): return (x%d) == a def get_length(a, d, l): # going to be using this a few times in this function ips = is_part_of_sequence # get the length of the list n = len(l) # get the first value in the sequence min_seq_ind, min_seq_value = next( (i, v) for i, v in enumerate(l) if v == a ) # get the last value in the sequence max_seq_ind, max_seq_value = next( (n-i-1, v) for i, v in enumerate(reversed(l)) if ips(a, d, v) ) min_length = ((max_seq_value - a)//d) + 1 # this is the minimum length # check to see if min_length is the correct answer- if so, short circuit if min_length == (max_seq_ind - min_seq_ind + 1): return min_length count = 2 count += sum(1 if ips(a, d, l[i]) else 0 for i in range(min_seq_ind+1, max_seq_ind)) return count The only optimization here is that in the case that the sequence contains no duplicates, this algorithm is constant time because it can short circuit.
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86963067
type: AnswerComment
comment on: http://stackoverflow.com/a/49968935
has text: Thank you for your solution but can you suggest me an alternative solution without using SQL-Alchemy?
score: 0
type: Comment

http://stackoverflow.com/comment/86960232
comment on: http://stackoverflow.com/q/49969398
type: Comment
type: QuestionComment
score: 0
has text: It is still unclear... The provided data example is for target? What is your network input? Some time series feature?

http://stackoverflow.com/a/50069928
has body: More specific answer considering python 3 would be: import requests from urllib.parse import urljoin from bs4 import BeautifulSoup search_item = 'orange timberland' #make sure the search terms are in small letters (a portion of text will suffice) URL = 'https://www.off---white.com/en/GB/section/new-arrivals.js' res = requests.get(URL) soup = BeautifulSoup(res.text, 'html.parser') for link in soup.find_all(class_="brand-name"): if search_item in link.text.lower(): item_name = link.get_text(strip=True) item_link = urljoin(URL,link.find_parents()[2].get('href')) print("Name: {}\nLink: {}".format(item_name,item_link)) Output: Name: ORANGE TIMBERLAND BOOTS Link: https://www.off---white.com/en/GB/men/products/omia073s184780161900
score: 0
answers question: http://stackoverflow.com/q/50067941
type: Answer

http://stackoverflow.com/q/50068976
has comment: http://stackoverflow.com/comment/87156086
has comment: http://stackoverflow.com/comment/87156215
has body: First off, I have researched this topic on stackoverflow beforehand, but I would like more information about it so I'm asking a new question. So basically, I've been working in Pygame 1.9.3 and I've succeeded in making a simple 2D game with graphics. I am using the Sprite class, and thus I use Group() methods often. I draw my graphics to the screen using groupName.draw(screen). A component of my game is the ability to interact with the terrain, such as removing tiles and placing tiles. Each tile is a part of my block Sprite Group that is drawn to the screen. However, my program begins to visibly lag as the number of block tiles increases. Here's what I have done to try to counteract the problem: Used .convert_alpha() for all of my loaded images Load images only once Change the target FPS (using 60 atm) Change my program such that the blockGroup.draw() command is ONLY called when the environment changes. Basically, if the environment changes, I redraw the blocks, screenshot my window, then blit this image until the environment changes again (this, as expected, causes lag when screenshots are taken) However, my game continues to lag. Naturally, if I increase the size of my block sprites (meaning how I resize them when loading their respective images), I can end up placing more blocks without lag occurring until later, since there are less sprites total, but this is not ideal for what I want to accomplish. Furthermore, I have implemented 2 teams of NPCs who interact with this terrain. Thus, it is understandable that my program needs to check a lot of collisions in my main game loop, but nonetheless, I wasn't expecting my program to lag unless I added in a team of ~30 NPCs (I am currently working with only 10 NPCs, 5 on each team). When my program begins to lag, I calculated the number of sprites total (adding up all the sprites in each group) to be 170. So, finally, my question: if I plan to have a program that uses multiple sprites (multiple being ~170) at the same ti…
tagged with: python
has comment: http://stackoverflow.com/comment/87154599
has title: Pygame Program Lagging With Multiple Sprites (~170)
has answer: http://stackoverflow.com/a/62781189
has comment: http://stackoverflow.com/comment/87155353
tagged with: performance
has comment: http://stackoverflow.com/comment/87155094
has comment: http://stackoverflow.com/comment/87154957
score: 0
has comment: http://stackoverflow.com/comment/87154717
answer count: 1
has comment: http://stackoverflow.com/comment/87154399
tagged with: pygame
has comment: http://stackoverflow.com/comment/87154927
type: Question
has comment: http://stackoverflow.com/comment/87154332
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87157794

pyinstaller
tags question: http://stackoverflow.com/q/49944462
tags question: http://stackoverflow.com/q/49981485
tags question: http://stackoverflow.com/q/50050776
tags question: http://stackoverflow.com/q/49949336
tags question: http://stackoverflow.com/q/50011932
type: Tag
tags question: http://stackoverflow.com/q/50028886
tags question: http://stackoverflow.com/q/50058673
tags question: http://stackoverflow.com/q/50050951
tags question: http://stackoverflow.com/q/49948484
tags question: http://stackoverflow.com/q/49984180
tags question: http://stackoverflow.com/q/50018264
tag name: pyinstaller
tags question: http://stackoverflow.com/q/50044607
tags question: http://stackoverflow.com/q/50048117
tags question: http://stackoverflow.com/q/50051672

http://stackoverflow.com/a/49992954
type: Answer
score: 4
upvote count: 4
has body: The Python method for java static method is @classmethod.
downvote count: 0
answers question: http://stackoverflow.com/q/49992880
has comment: http://stackoverflow.com/comment/87002311

deep-learning
tags question: http://stackoverflow.com/q/49973639
tags question: http://stackoverflow.com/q/49935491
tags question: http://stackoverflow.com/q/50007085
tags question: http://stackoverflow.com/q/50070398
tags question: http://stackoverflow.com/q/50060424
tags question: http://stackoverflow.com/q/49946942
tags question: http://stackoverflow.com/q/50002526
tags question: http://stackoverflow.com/q/50028940
tags question: http://stackoverflow.com/q/49992069
tags question: http://stackoverflow.com/q/50050021
tags question: http://stackoverflow.com/q/49991300
tags question: http://stackoverflow.com/q/50058439
tags question: http://stackoverflow.com/q/49942873
tags question: http://stackoverflow.com/q/49944822
tags question: http://stackoverflow.com/q/50063514
tags question: http://stackoverflow.com/q/50047653
type: Tag
tags question: http://stackoverflow.com/q/49959545
tags question: http://stackoverflow.com/q/50065484
tags question: http://stackoverflow.com/q/49929070
tags question: http://stackoverflow.com/q/49945838
tags question: http://stackoverflow.com/q/50053292
tags question: http://stackoverflow.com/q/49945462
tags question: http://stackoverflow.com/q/49973379
tags question: http://stackoverflow.com/q/50032197
tags question: http://stackoverflow.com/q/49975649
tags question: http://stackoverflow.com/q/49927354
tags question: http://stackoverflow.com/q/50055149
tags question: http://stackoverflow.com/q/49929841
tags question: http://stackoverflow.com/q/49932293
tags question: http://stackoverflow.com/q/49977839
tags question: http://stackoverflow.com/q/50053151
tags question: http://stackoverflow.com/q/49941426
tags question: http://stackoverflow.com/q/50036892
tags question: http://stackoverflow.com/q/50015475
tags question: http://stackoverflow.com/q/50011969
tags question: http://stackoverflow.com/q/50047909
tags question: http://stackoverflow.com/q/49970594
tags question: http://stackoverflow.com/q/49936431
tags question: http://stackoverflow.com/q/50067558
tags question: http://stackoverflow.com/q/50005092
tags question: http://stackoverflow.com/q/49941265
tags question: http://stackoverflow.com/q/50054419
tags question: http://stackoverflow.com/q/50063237
tags question: http://stackoverflow.com/q/49922674
tags question: http://stackoverflow.com/q/49986992
tags question: http://stackoverflow.com/q/49952714
tag name: deep-learning
tags question: http://stackoverflow.com/q/49940110
tags question: http://stackoverflow.com/q/49973504
tags question: http://stackoverflow.com/q/50041558
tags question: http://stackoverflow.com/q/49959727
tags question: http://stackoverflow.com/q/49925374
tags question: http://stackoverflow.com/q/49969006
tags question: http://stackoverflow.com/q/49927619

http://stackoverflow.com/comment/87000853
comment on: http://stackoverflow.com/q/49991870
score: 1
type: QuestionComment
type: Comment
has text: Do you really need to know about both Python 2.x and 3.x? Because the answers are very different—and a lot simpler, for 3.x, and even simpler for 3.7+.

http://stackoverflow.com/comment/87163464
comment on: http://stackoverflow.com/q/50073397
score: 0
type: QuestionComment
type: Comment
has text: `array.append(object)` appends a reference to the object the name `object` refers to.

http://stackoverflow.com/comment/87155294
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50069389
has text: I suspect that it's because of the `_weakref.finalize`... Once your variable goes out of scope (which is immediately in the second case), your directory cleans itself up.
type: Comment

http://stackoverflow.com/comment/87051219
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50017055
type: Comment
has text: Correct i have had the same output but what i was thinking of is keeping them as lists of dictionaries like i showed an example of in my question, without adding ordereddict in the output or make them tuples shape,.

http://stackoverflow.com/q/50010021
has answer: http://stackoverflow.com/a/50010106
upvote count: 4
type: AnsweredQuestion
has title: Find minimum value above a certain threshold in a Python list
answer count: 2
has comment: http://stackoverflow.com/comment/87036717
downvote count: 0
has answer: http://stackoverflow.com/a/50010128
score: 4
linked to: http://stackoverflow.com/q/2580136
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50010128
accepted answer: http://stackoverflow.com/a/50010106
tagged with: python
has body: I'm trying to find the minimum in a list, above a certain threshold without using the min() function (I'm doing things the hard way for practice). I've managed by first creating a list of values above the threshold and then looping through the list, saving a value to a variable if it is smaller than the previously seen values: def minpass(mymarks, mypass): passed= [x for x in mymarks if x &gt;= mypass] min_value = passed[0] for x in passed: if x &lt; min_value: min_value = x return min_value x = [2, 53, 90] y = 50 minpass(x, y) This correctly returns 53. Is it possible to do it without creating a second list (passed)? Why doesn't it work to add a second condition? e.g. def minpass(mymarks, mypass): min_value = mymarks[0] for x in mymarks: if x &lt; min_value and x &gt;= mypass: min_value = x return min_value x = [2, 53, 90] y = 50 minpass(x, y) This incorrectly returns 2 rather than 53.

http://stackoverflow.com/q/49971092
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49972021
has title: Tensorflow - Model Only Predicting 2 Classes Out of 6
tagged with: neural-network
tagged with: machine-learning
upvote count: 1
tagged with: python
has body: I am building a CNN to classify 6 classes with 50x50 pixel grayscale images (1400 per class).. After training the model and evaluating the loss and accuracy everything seems to working fine with a training accuracy of around 98% and loss down to 3.0, but when evaluating the model on test data for each class the model is way off. The classes i have are images of facial expressions: 1) anger 2) fear 3) happy 4) neutral 5) sad 6) suprise Here is the Jupyter Notebook: https://www.floydhub.com/arse123/projects/cnn-1/20/code/train_edge.ipynb For example, when i feed 350 test images for each classes only the anger and suprise classes are ever predicted. TEST IMAGES RESULTS Angry - it classified 76 angry, and 273 surprise Fear - it classified 8 angry and 342 surprise Happy - 12 angry and 338 surprise Neutral - 350 surprise Sad - 22 angry and 328 surprise Surprise - a full 350/350 classified for this one.. Its clear that there is some bias towards angry and surprise as not one of the other images were classified once. When i ran acc.eval({x: test_images, y: test_labels, is_training : False}) (which is 2100 images for each class and the corresponding) after training i got an accuracy of 82%, so i dont know how this is happening. Is it possible that the model some how could have been training on these two classes the whole time? @NOTE: images and labels are one hot encoded, also randomly shuffled, batch normalization implemented UPDATE I retrained the model and it is having the same affect, but with different classes. This time it favours sad and suprise, rather than angry and suprise. Here are the results: Angry - Sad 259 and surprise 75 Fear - Sad 118 and surprise 218 (some classifications missing here for some reason) Happy - Sad 167 times and suprise 160 times (same again, missing some classifications) Neutral - sad 94 and surprise 249 Sad - sad 211 and surprise 122 Surprise - Sad 284 and surprise 52
has answer: http://stackoverflow.com/a/49972021
has comment: http://stackoverflow.com/comment/86958571
type: AnsweredQuestion
tagged with: conv-neural-network
score: 1
has comment: http://stackoverflow.com/comment/86958113
downvote count: 0
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/a/50034287
answers question: http://stackoverflow.com/q/50034202
has body: The key is the inner error: exceptions.ValueError Mixing iteration and read methods would lose data According to this SO response, the error comes from using both next and readlineon the same file handle. If you use readline to skip the header line you I think should be ok.
type: Answer
score: 0

http://stackoverflow.com/comment/87078839
score: 2
comment on: http://stackoverflow.com/q/50031385
type: QuestionComment
type: Comment
has text: try using the operator * between parentheses.

http://stackoverflow.com/q/49955964
score: 1
answer count: 1
tagged with: timeout
downvote count: 0
upvote count: 1
tagged with: client
has body: I have a python script, which already sends messages from time to time to peer using socket. I want to add a feature, that socket listens asynchronously for inbound messages and then reacts, for ex. processes content and resends a reply. Is it possible to do it using only one socket? I have to use one socket because my peer creates its socket on localhost:30000. EDIT: Here is some code of my tries I have done so far. Run() method from the listening thread: def run(self): print("Started listening to messages from peer...") while True: socketLock.acquire() try: self.listenToInboundMessages() finally: socketFlag.set() socketLock.notify() socketLock.release() def listenToInboundMessages(self): clientsocket.settimeout(1) received = clientsocket.recv(BUFF) print(received) Run() method for the thread which sends messages: def run(self): print("Ready to send messages.") while True: print("Attempting to acquire lock...") socketLock.acquire() while not socketFlag.isAvailable(): socketLock.wait print("Attempting to send message...") clientsocket.send("Message for per") socketLock.release() time.sleep(1) I use socketLock condition variable and socketFlag class to coordinate both threads.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87038236
has title: Using one socket to both receiving and sending messages in Python
tagged with: server
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/49982002
has comment: http://stackoverflow.com/comment/86928330

http://stackoverflow.com/comment/117165856
comment on: http://stackoverflow.com/a/66270059
score: 0
type: AnswerComment
has text: Note that this will require first installing [Anaconda Python](https://www.anaconda.com/).
type: Comment

http://stackoverflow.com/q/49961120
tagged with: django-rest-framework
favorite count: 0
type: Question
has title: Django 2.0, First Level Class View, AttributeError: 'str' object has no attribute 'values'
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49966686
tagged with: django-views
has body: I have created a generic view and serializer in Django 2.0, so that I don't have to repeat my self, creating CRUD views or serializers. My views.py file of my API app from rest_framework import generics, mixins from rest_framework.serializers import ModelSerializer class StandardListMixinCreateApiView(mixins.CreateModelMixin, generics.ListAPIView): def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class StandardRudApiView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' This function sets The serializer.Meta.model of each enabled model. The `cls parameter is one of the StandardApiViews. def get_adapted_class(cls, model_class, serializer_fields='__all__'): class AdaptedSerializer(ModelSerializer): class Meta: model = model_class fields = serializer_fields class AdaptedView(cls): model = model_class.__name__ queryset = model_class.objects.all() serializer_class = AdaptedSerializer return AdaptedView My urls.py from django.urls import re_path from .views import * from django.contrib.auth.models import Group, Permission from .models import * app_name = "api" The models for which CRUD views get generated. ENABLEDMODELS = [ Address, Group, Permission, Customer, Employee, Commission, BugReport, FeatureRequest, ] APILISTVIEWS = [get_adapted_class( StandardListMixinCreateApiView, model) for model in ENABLEDMODELS] APIRUDVIEWS = [get_adapted_class( StandardRudApiView, model) for model in ENABLEDMODELS] Adds an url route for each created ListView to the urlpatterns # List, create views urlpatterns = [re_path( f'^(?i){class_view.model}/', class_view.as_view(), name=f'{class_view.model}-list') for class_view in APILISTVIEWS] # Retrive, update, delete views urlpatterns += [re_path( f'^(?i){class_view.model}/' + r'(?P&lt;pk&gt;\d+)', class_view.as_view(), name=f'{class_view.model}-rud') for class_view in APIRUDVIEWS] Error Messages Environment: Request Method: GET Request URL: http://localhost:8000/api/address/ Django Version: 2.0.4 …
has comment: http://stackoverflow.com/comment/86938670
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49949354
score: 0
has title: Trying to get a script to read a CSV file that is in the same subdirectory
has comment: http://stackoverflow.com/comment/86915544
has comment: http://stackoverflow.com/comment/86915378
type: Question
has comment: http://stackoverflow.com/comment/86915920
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86915539
has comment: http://stackoverflow.com/comment/86917493
has body: I have a CSV file saved in my downloads folder. It is the folder I use for any code that needs to be downloaded to Python from somewhere else. I have a CSV file there, and can even open the file in Python, however when I run my script to read it I get an error that the file does not exist. The code looks like this. Just to get the numbers into a list. data = [] with open('file','r') as fout: for line in fout: data.append(line.split(",")) If I replace my csv file with a text file from the same folder, it works, but when I try using this csv file, it's like Python does not know the file is there. What is going on? I have absolutely no clue what to do or why this is happening.
answer count: 0

http://stackoverflow.com/comment/87097971
has text: @Yobmod I can't reproduce that. `b'%PDF-1.4\n%\x93\x8c\x8b\x9e'.decode('unicode_escape')` returns `'%PDF-1.4\n%\x93\x8c\x8b\x9e'`.
score: 0
comment on: http://stackoverflow.com/a/50040812
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49966846
accepted answer of: http://stackoverflow.com/q/49963845
answers question: http://stackoverflow.com/q/49963845
has body: Define a Slack app Your app (Python script) needs to run on a public webserver that can be reached by Slack (can also by your local machine if you use tools like ngrok) Put the URL for your app as "request URL" in your Slack app configuration under "Interactive messages" Once the user clicks one of the button, Slack will call your app with a POST request which will contain the action that the use chose Check out the documentation you linked for details like how the data structure of the Slack request looks like.
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/131853984
comment on: http://stackoverflow.com/a/50002176
score: 0
has text: adding to this, installing Anaconda can lead to conflicts with the `conda-forge` channel. Instead, I would recommend installing [`miniforge`](https://github.com/conda-forge/miniforge) or [`mambaforge`](https://github.com/conda-forge/miniforge#mambaforge). See e.g. [Can't install cartopy](https://stackoverflow.com/questions/74293754/cant-install-cartopy)
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50057604
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87131678
has comment: http://stackoverflow.com/comment/87132055
type: Answer
has body: Use eval function. a = "[(u'Dan', u'Alon', u'Carla',),(u'Carla', u'Stockton', u'Munich', u'Memoir',)]" list_a = eval(a) print list_a # [(u'Dan', u'Alon', u'Carla',),(u'Carla', u'Stockton', u'Munich', u'Memoir',)]
answers question: http://stackoverflow.com/q/50057457

http://stackoverflow.com/comment/86964239
comment on: http://stackoverflow.com/a/49974152
score: 3
type: AnswerComment
has text: Python.. sqlalchemy..?
type: Comment

http://stackoverflow.com/comment/86914539
score: 0
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49945857

http://stackoverflow.com/comment/87094938
comment on: http://stackoverflow.com/a/50039381
type: AnswerComment
has text: Didnt't think it was this simple! :)
score: 1
type: Comment

http://stackoverflow.com/comment/116245613
score: 0
comment on: http://stackoverflow.com/q/50052065
type: Comment
type: QuestionComment
has text: @andilabs We ended up implementing a test DAG for every production DAG. It runs the DAG itself as a subDAG (on a test data) and then it runs a test task, which compares the results between the actual and the expected datasets.

gmail
type: Tag
tags question: http://stackoverflow.com/q/50061883
tag name: gmail

http://stackoverflow.com/a/49967111
has comment: http://stackoverflow.com/comment/86949900
accepted answer of: http://stackoverflow.com/q/49967097
type: Answer
has comment: http://stackoverflow.com/comment/86949880
upvote count: 2
type: AcceptedAnswer
has body: def my_update_function(obj): obj.x, obj.y = obj.x * obj.x, obj.y * obj.y then in your class: class my_class(object): def __init__(self): self.x = 2 self.y = 3 def simulate(self): my_update_function(self)
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/86950089
answers question: http://stackoverflow.com/q/49967097

http://stackoverflow.com/comment/86987741
type: Comment
comment on: http://stackoverflow.com/a/49985152
type: AnswerComment
has text: @Sadegh - That's quite ok. Thank you for accepting my answer. Welcome to Stack Overflow!
score: 0

http://stackoverflow.com/comment/87126179
type: QuestionComment
comment on: http://stackoverflow.com/q/50054842
score: 0
has text: Is your `pred_fl` equal your `blahblahblah`?
type: Comment

http://stackoverflow.com/q/49984765
has comment: http://stackoverflow.com/comment/86986169
tagged with: http://stackoverflow.com/tag/zip
has comment: http://stackoverflow.com/comment/86987014
has comment: http://stackoverflow.com/comment/86986230
accepted answer: http://stackoverflow.com/a/49985551
has answer: http://stackoverflow.com/a/49985194
tagged with: python
has comment: http://stackoverflow.com/comment/86986057
has answer: http://stackoverflow.com/a/49985551
has comment: http://stackoverflow.com/comment/86986322
has title: Extract a list of tarfile using python
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49985194
score: 1
downvote count: 0
tagged with: http://stackoverflow.com/tag/tar
upvote count: 1
has comment: http://stackoverflow.com/comment/86986473
favorite count: 0
type: Question
has body: I have a folder (dataset_folder) that contains 10 *.tar files. Here is my code to extract them in a specific path. listtar=glob.glob(dataset_folder+'/*.tar') for file in listtar: tar=tarfile.open(file) tar.extractall(path=dataset_folder) tar.close() Note that dataset_folder is under the current directory. I get an error ReadError: unexpected end of data Note also that I can untar files manually without problems.

http://stackoverflow.com/comment/87132798
type: Comment
has text: For now this server only.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50057929

http://stackoverflow.com/comment/87108251
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50045537
has text: It should be `stage2.index`

http://stackoverflow.com/comment/87022893
type: QuestionComment
comment on: http://stackoverflow.com/q/50002804
score: 1
has text: Which is to say -- you could certainly cause your program to stop itself from the child end after the fork and before the exec (so after there's a new PID allocated, but before the program running associated with it becomes your `binary` and not a copy of the Python interpreter), but I doubt that that's actually helpful towards your intended goal.
type: Comment

http://stackoverflow.com/comment/87051866
score: 0
comment on: http://stackoverflow.com/a/49993974
type: Comment
type: AnswerComment
has text: @NingyuanChen Please accept the answer if it helped.

http://stackoverflow.com/q/49977810
tagged with: pandas-groupby
has title: Count how many rows satisfy a certain filter
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49978243
favorite count: 0
has body: I am working with 2 different dataframes (general and last) which are something like this: general=pandas.DataFrame(columns=["code","grade","year","quarter","subject"],data=[[01,4.5,2011,1,1],[01,5.0,2012,2,1],[23,5.0,2013,1,2],[01,7.5,2011,1,2]) last=pandas.DataFrame(columns=["code","grade","subject"],data=[[01,5.0,1],[01,7.5,2],[23,5.0,2]) I want to add in "last" a column named "attempts" in which I get the number of attempts that a student has taken to pass the subject.(Basically, add a column with the number of rows that satisfy certain criteria). I have tried using this: last["ATTEMPTS"]=None for ind in general.index: st=general.loc[ind]["code"] subject=general.loc[ind]["subject"] fil1=grades["code"]==st fil2=grades["subject"]==subject attempts=len(general[fil1&amp;fil2]) last.at[ind, "ATTEMPTS"] = attempts But it takes too long... Any easier ideas? Thanks!
has answer: http://stackoverflow.com/a/49978243
type: Question
has comment: http://stackoverflow.com/comment/86972103
tagged with: dataframe
tagged with: python
tagged with: merge
type: AnsweredQuestion

http://stackoverflow.com/q/50063834
accepted answer: http://stackoverflow.com/a/50065646
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87144407
type: AnsweredQuestion
score: 0
has title: Best way to get around the unique-constraint for many-to-many relationships in Django?
tagged with: sql
has comment: http://stackoverflow.com/comment/87144334
answer count: 1
has answer: http://stackoverflow.com/a/50065646
type: Question
has body: I have a situation where I need to be able to add multiple copies of the same object to a many-to-many relationship. Let's say that the problem is recording the types of furniture someone has. Here are my base models: class Person(models.Model): name = models.CharField(max_length=100) class Furniture(models.Model): furniture_name = models.CharField(max_length=100) #e.g. Chair, Sofa. Lets say I want to record that Sam owns 3 chairs and 2 sofas. But I don't want to make more than one sofa object in the DB. How can I do this with a many-to-many relationship? The traditional many-to-many has a unique-constraint that prevents this. I'm thinking of using a through table, with another field in the unique-constraint (date-purchased, or just a random string). Will that work? Does anyone have a better way of doing this?

http://stackoverflow.com/comment/87057872
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50020949
has text: Right, but surely I can do this without one; the methods work outside of the sorted(<...>), something is going wrong when I try to sort if using my function val(x) as the key and I'm wondering what exactly is causing the objects themselves to be replaced by the memory addresses of the attribute I'm sorting by. Right, but shouldn't sorted just organise the objects based on their value? I've seen similiar code in other questions work fine, but I'm not sure why mine doesn't work: https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects

http://stackoverflow.com/q/49997503
has comment: http://stackoverflow.com/comment/87012144
has title: Pandas dataframe. Lose a part of text data when save with encoding='utf-8'
tagged with: pandas
has comment: http://stackoverflow.com/comment/87011855
answer count: 1
has comment: http://stackoverflow.com/comment/87011972
tagged with: unicode
type: Question
has answer: http://stackoverflow.com/a/49997591
tagged with: encoding
type: UnansweredQuestion
tagged with: python
has body: I'm trying to put a large list of words (in russian, unicoded) to a dataframe column and save resulting dataframe into a .csv file. I need to save encoded text, but whenever I manually set encoding='utf-8', it cuts a part of my data and saves only first 100 words or something. I'm using Python 2.7. (lists are quite large, so here I write only the first and the last elements) a = [u'совмещать', ... , u'энергии'] s = [u'совмещать', ... , u'личной'] d = {'col1': [0, 1], 'col2': [a, s]} df = pd.DataFrame(data=d) df.to_csv('test.csv', encoding='utf-8') Appriciate any suggestions.
has comment: http://stackoverflow.com/comment/87011633
score: 0

http://stackoverflow.com/comment/87134154
type: Comment
type: QuestionComment
score: 0
has text: I guess you only have the tesseract python wrapper and not the tesseract backend. Install from here https://github.com/UB-Mannheim/tesseract/wiki
comment on: http://stackoverflow.com/q/50057422

http://stackoverflow.com/comment/87021491
has text: i edit my question and explain it again and more transparent. if is necessary i ask a new question about it?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50000174

http://stackoverflow.com/q/50073421
has comment: http://stackoverflow.com/comment/87164328
score: 1
has body: I have the following indices as you would get them from np.where(...): coords = ( np.asarray([0 0 0 1 1 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 5 5 5 6 6 6]), np.asarray([2 2 8 2 2 4 4 6 2 2 6 2 2 4 6 2 2 6 2 2 4 4 6 2 2 6]), np.asarray([0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]), np.asarray([0 1 0 0 1 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 1 0 1 1]) ) Another tuple with indices is meant to select those that are in coords: index = tuple( np.asarray([0 0 1 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 5 5 5 6 6 6]), np.asarray([2 8 2 4 4 6 2 2 6 2 2 4 6 2 2 6 2 2 4 4 6 2 2 6]), np.asarray([0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]), np.asarray([0 0 1 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 1 0 1 1]) ) So for instance, coords[0] is selected because it's in index (at position 0), but coords[1] isn't selected because it's not available in index. I can calculate the mask easily with [x in zip(*index) for x in zip(*coords)] (converted from bool to int for better readability): [1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] but this wouldn't be very efficient for larger arrays. Is there a more "numpy-based" way that could calculate the mask?
has title: Efficient way to get a subset of indices in numpy
linked to: http://stackoverflow.com/q/48411962
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8317022
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50076048
has answer: http://stackoverflow.com/a/50073867

http://stackoverflow.com/a/50005220
has body: from copy import deepcopy def myfunct(arg): new_arg = deepcopy(arg) new_arg.x += 1 return new_arg I would recommend deepcopy over copy since you want to make sure that all references to the original object are cut.
answers question: http://stackoverflow.com/q/50005048
type: Answer
score: 0

http://stackoverflow.com/a/50053689
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50053292
has body: Got it!!! https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/18_TFRecords_Dataset_API.ipynb This guy Magnus Erik Hvass Pedersen has an awsome tutorial on how to write and read from TFRecords. His script takes in images but it can easily converted to np arrays by replacing images for a slice of your numpy array.

http://stackoverflow.com/comment/87031034
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49957768
type: AnswerComment
has text: Thank you very much for your answer. However, an error appears: "ValueError: Index contains duplicate entries, cannot reshape". Maybe because my .txt file can contain some symbols actually not present in the symbol column.

http://stackoverflow.com/comment/87128472
type: Comment
comment on: http://stackoverflow.com/q/50043499
score: 0
has text: No, it is a string.
type: QuestionComment

http://stackoverflow.com/a/50071681
has body: You can use a combination of the fileinput module for in-place file editing and the re regex module for doing search-and-replace on that specific h1 tag. Here's the code first: (Note that I used "config.txt" for the config file and "output.css" for the CSS file) # read the color from the config file color_config = "" with open("config.txt", "r") as config_file: for line in config_file: if line.startswith("color"): color_config = "h1 {" + line.strip() + "}" break # update the css file in-place with fileinput.input(files=("output.css"), inplace=True) as css_file: for line in css_file: # the h1 tag could be on its own line or could be part of # a line with other styles, so we capture them in groups matches = re.match(r"(.*)(h1\s*\{color:.*\})(.*)", line) if matches: # group(0): entire matching line # group(1): everything before the h1 tag # group(2): the h1 tag # group(3): everything after the h1 tag print(line.replace(matches.group(2), color_config), end="") else: print(line, end="") For some explanation: The first with block is where we read the config file to get the color: #ffffff; value. I am assuming here that it's placed on its own line (that's why I used startswith). I don't know what your config file looks like, so just tweak it based on what you need. Then, we store color: #ffffff; into color_config, formatted as an h1 { .. } string. We format it now to make it easy to search and replace later. The second with block does the in-place file search-and-replace. It uses fileinput.input with the inplace parameter set to True. From the docs: Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typicall…
has comment: http://stackoverflow.com/comment/87180784
has comment: http://stackoverflow.com/comment/87171994
type: Answer
answers question: http://stackoverflow.com/q/50065151
has comment: http://stackoverflow.com/comment/87171373
has comment: http://stackoverflow.com/comment/87180957
score: 0

http://stackoverflow.com/comment/87039174
type: QuestionComment
has text: You've got it right. But see also the official documentation for [ord](https://docs.python.org/3/library/functions.html#ord) and [chr](https://docs.python.org/3/library/functions.html#chr).
type: Comment
comment on: http://stackoverflow.com/q/50011314
score: 1

http://stackoverflow.com/comment/86936569
score: 1
type: Comment
has text: Interestingly enough, other types like `Union` work fine (ie. `Union[Type[BaseException]]`). It seems to be that `Optional[Type[...]]` is the issue.
type: QuestionComment
comment on: http://stackoverflow.com/q/49959656

http://stackoverflow.com/comment/86958829
comment on: http://stackoverflow.com/q/49971487
has text: 1e-11 is basically 0 so I would argue that the data you are checking this on makes little sense (if all "true" gradients are below the interesting precision, equally acceptable code would be "return 0")
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/97455949
comment on: http://stackoverflow.com/a/50052897
type: Comment
score: 0
type: AnswerComment
has text: I believe that the answer id the formatting of DataFrame, the whole column has not to be an object, see `pd.DataFrame().info()` details and use conversion by `pd.to_numeric(...)` https://stackoverflow.com/a/28648923/4521646

http://stackoverflow.com/q/49943001
tagged with: terminal
tagged with: list
has comment: http://stackoverflow.com/comment/86902374
score: -3
has answer: http://stackoverflow.com/a/49943187
has comment: http://stackoverflow.com/comment/86902264
type: Question
has title: Extra characters and order changes in terminal output? Is this a terminal problem (CoCalc)?
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 3
tagged with: python
favorite count: 0
has body: Why am I seeing extra ] characters in output of a list construction that should have just a list of lists? Is this a terminal problem (using CoCalc's terminal)? Particularly, the output should have just two levels of lists, the global list and each of the sublists inside it. But when I read through the output of data in a Python interpreter in CoCalc's terminal. Then I see this kind of thing: Notice the extra ] as if there was inner lists that should not exist. Also notice the numbering which seems to not be in order, even though in the data it is ordered. What's happening here? To reconstruct the problem: Download the dorothea_valid.data file from here: https://archive.ics.uci.edu/ml/machine-learning-databases/dorothea/DOROTHEA/ Then create a project in CoCalc (https://cocalc.com/). Upload dorothea_valid.data to that project. Start a Linux terminal in CoCalc, and make sure you know the path/working directory so that you can find dorothea_valid.data from Python. In the Linux terminal start the Python interpreter by writing python. Paste the following function meant for reading a file with sequences of integer values separated by "\n" to the interpreter: def read_datafile(fname): data = list() with open(fname, 'r') as file: for line in file: data.append([int(i) for i in line.split()]) return data # and then call print(read_datafile(fname)) to get the output. Then call read_datafile() on dorothea_valid.data, and then print the resulting object as suggested in the above comment. The screen captured lines are seen when scrolling right to the bottom, however problems may be seen from other parts of the output as well. EDIT: It's now 10/08/2022 and I'm unable to see the problem. Maybe it has been fixed in CoCalc.
has comment: http://stackoverflow.com/comment/86902272

http://stackoverflow.com/comment/86862062
type: Comment
type: QuestionComment
has text: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the other links found on that page. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.
score: 0
comment on: http://stackoverflow.com/q/49923103

http://stackoverflow.com/a/49950905
has comment: http://stackoverflow.com/comment/86919938
answers question: http://stackoverflow.com/q/49949849
has comment: http://stackoverflow.com/comment/86924656
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49949849
type: AcceptedAnswer
has body: I used js2py, since materials object contains several keys (BVRRRatingSummarySourceID, BVRRSecondaryRatingSummarySourceID and BVRRSourceID) and getting the HTML from its values with regex would be much harder in case you need it all. from bs4 import BeautifulSoup import js2py import requests r = requests.get('https://bedbathandbeyond.ugc.bazaarvoice.com/2009-en_us/1061083288/reviews.djs?format=embeddedhtml') pattern = (r'var' r'\s+' r'materials' r'\s*=\s*' r'{"BVRRRatingSummarySourceID".*}') js_materials = re.search(pattern, r.text).group() obj = js2py.eval_js(js_materials).to_dict() html = obj['BVRRSourceID'] soup = BeautifulSoup(html, 'lxml') spans = soup.select('span.BVRRReviewAbbreviatedText') &gt;&gt;&gt; len(spans) 5 In the example below I only used the HTML under the BVRRSourceID key, but you can use the entire HTML by join the values together: html = ''.join(obj.values()) Don't forget to install js2py: pip install js2py and pip install lxml if you want to use lxml parser.

http://stackoverflow.com/comment/86949767
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49959825
score: 0
has text: How can I replace JS_BLOCK with my webpage? Neither soup nor page / page.content are working!

http://stackoverflow.com/q/49940584
answer count: 1
downvote count: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49940838
has answer: http://stackoverflow.com/a/49940838
score: 2
type: AnsweredQuestion
tagged with: django-views
has title: Django delete&update view only for owner
has body: I'm writing some task for my university in Django.In my update&amp;delete view I want to make sure that only an owner of object can update/delete it. Now everyone can do it. Here are views: class UpdateCar(SuccessMessageMixin, UpdateView): model = Car form_class = AddNewCarForm template_name = 'c2crental/car/update_car.html' success_url = reverse_lazy('c2crental:list_user_cars') success_message = _("Car has been updated.") def get_queryset(self): owner = self.request.user return self.model.objects.filter(owner=owner) class DeleteCar(DeleteView): model = Car success_url = reverse_lazy('c2crental:list_user_cars') template_name = 'c2crental/car/delete_confirm_car.html' success_message = _("Car has been deleted.") def delete(self, request, *args, **kwargs): messages.success(self.request, self.success_message) return super(DeleteCar, self).delete(request, *args, **kwargs) def get_queryset(self): owner = self.request.user return self.model.objects.filter(owner=owner) I found some solutions with querysets as shown above. They won't let other Users update/delete an object and raise Http404 error which is fine, but I want to use Django messages framework to print error message on page and dont redirect to Http404 page. How can I do that?
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/87119526
type: Comment
has text: What if there are multiple rows in dict_2 corresponding to time_key in dict_1 ?
comment on: http://stackoverflow.com/a/50050579
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87111338
has text: `np.float64(3.1415927) > np.float32(np.pi) # False` is consistent because once you round up the number increasing precision doesn't decrease back the value
comment on: http://stackoverflow.com/a/50047327
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50024737
has comment: http://stackoverflow.com/comment/87065638
linked to: http://stackoverflow.com/q/17922056
upvote count: 0
answer count: 2
downvote count: 1
has title: Modifying xml attributes through python
has comment: http://stackoverflow.com/comment/87065535
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: attributes
type: Question
has answer: http://stackoverflow.com/a/50024845
has answer: http://stackoverflow.com/a/50024837
has comment: http://stackoverflow.com/comment/87065690
type: UnansweredQuestion
has body: I have the following XML file in which the following information is present. &lt;PHYSICAL_TLINE&gt; &lt;Traces general_diff="0" z_array="0" s_array="0" w_array="0" etch_factor="0.35" TS_track2track="0" TS_DQS="0" TW_DQS="0" TS_byte2dqs="0" TS_byte2byte="0" TS_DQ="0" TW_DQ="0" dsl_offset="0" D="20" TS="7" TW="5"/&gt; &lt;PHYSICAL_TLINE&gt; Is there a way to set the values of these elements through python? For example, if I want to change the value of s_array to 5 instead of 0?. I know that there is the xml.etree set command but I'm not too sure on how to set the values of these attributes in the child through python.
tagged with: python
score: -1

http://stackoverflow.com/comment/87035634
comment on: http://stackoverflow.com/q/50009514
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [Call Python from Java](https://stackoverflow.com/questions/31674122/call-python-from-java)

http://stackoverflow.com/comment/87042209
type: QuestionComment
score: 1
has text: Yes, Python 3 doesn't handle imports the same way Python 2 does. You have a few options: 1/ Use Python 2, 2/ ask the author to fix the imports, 3/ fix the imports yourself, and re-install the package. Given the last update is from 2014, I'm doubtful point 2/ will work though.
comment on: http://stackoverflow.com/q/50012848
type: Comment

http://stackoverflow.com/q/49923857
has comment: http://stackoverflow.com/comment/86865211
has comment: http://stackoverflow.com/comment/86863761
type: Question
has comment: http://stackoverflow.com/comment/86863661
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86863796
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49924669
answer count: 1
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86865635
has title: My Python shells and terminal in macOS don't allow me to ask the version type as 'python --version'?
has comment: http://stackoverflow.com/comment/86863781
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/16857105
has comment: http://stackoverflow.com/comment/86863573
has body: This is the resulting notice of entering "python --version" Traceback (most recent call last): File "", line 1, in NameError: name 'python' is not defined I have tried Python 2.7 and 3.6 shell as well as my terminal but cannot seem to figure out whats wrong. Eventually, I am trying to get pip.
has comment: http://stackoverflow.com/comment/86863592
tagged with: macos

http://stackoverflow.com/q/49962411
has body: I trained a cnn in mathematica using the network lenet und exported it as MXnet. How can I use the exported JSON and PARAMS in python to predict? How to load the model? I could not find useful examples or documentation for this. I am using python 3.6 with anaconda.
answer count: 1
has title: how to use mxnet in python
score: 0
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/86965775
tagged with: mxnet
tagged with: python
has answer: http://stackoverflow.com/a/50012362
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/79363287
type: Answer
has body: This is now possible with numpy.lib.recfunctions.structured_to_unstructured With your example: import numpy as np from numpy.lib import recfunctions as rfn arr = np.array([(105.0, 34.0, 145.0, 217.0)], dtype=[('a', 'f4'), ('b', 'f4'), ('c', 'f4'), ('d', 'f4')]) out = rfn.structured_to_unstructured(arr'a', 'b') print(repr(out)) # array([[105., 34.]], dtype=float32)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50028309
score: 1

http://stackoverflow.com/comment/87146339
score: 1
type: QuestionComment
has text: Possible duplicate of [Splitting elements within a list and separate strings, then counting the length](https://stackoverflow.com/questions/50063078/splitting-elements-within-a-list-and-separate-strings-then-counting-the-length)
comment on: http://stackoverflow.com/q/50064750
type: Comment

http://stackoverflow.com/comment/86995822
score: 0
type: Comment
type: QuestionComment
has text: Thanks @miradulo for providing this, I'll most definitely try it.
comment on: http://stackoverflow.com/q/49988118

http://stackoverflow.com/comment/86894124
type: Comment
comment on: http://stackoverflow.com/a/49939040
score: 0
type: AnswerComment
has text: No, `Category` is the column name in the df provided. I converted it using `astype('category')`, this is the working code.

http://stackoverflow.com/comment/87012029
type: QuestionComment
comment on: http://stackoverflow.com/q/49996737
has text: I could post my whole code if that helps?
score: 0
type: Comment

http://stackoverflow.com/q/49957069
has answer: http://stackoverflow.com/a/52645351
tagged with: tfidfvectorizer
type: UnansweredQuestion
has body: I am recently processing a quiet big dataset, and I intend to use Tfidfvectorizer to analyze it. There were previous posts regarding MemoryError when implementing Tfidfvectorizer, However, in my case, the MemoryError occurs before I feed data into the Tfidfvectorizer. Here is my code. read data data = pd.read_csv(...) data['description'] is the text content process data from sklearn.feature_extraction.text import TfidfVectorizer description_vectorizer = TfidfVectorizer(max_features=500, min_df=0.2, ngram_range=(2, 3), preprocessor=preprocessor, stop_words='english') description_vectorizer.fit(data.description.values.astype('U')) Many posts here talked about MemoryError when fitting Tfidfvectorizer, but I found that when I transform the data into unicode, i.e. IN THIS STEP: data.description.values.astype('U'), the MemoryError occurs. So, strategies regarding how to tune parameters in Tfidfvectorizer is NOT useful in my case. Anyone encountered this before and know how to fix it? many thanks.
tagged with: python
has answer: http://stackoverflow.com/a/50808564
answer count: 3
has answer: http://stackoverflow.com/a/49992319
score: 1
downvote count: 0
upvote count: 1
tagged with: unicode
favorite count: 0
type: Question
has title: Python: how to avoid MemoryError when transform text data into Unicode using astype('U')

http://stackoverflow.com/q/49974855
score: 1
tagged with: supervised-learning
has body: I'm able to draw a 3D animation of Firefly algorithm using SwarmPackagePy library. I want to use this algorithm to optimize the hyperparameter in Gaussian Process Regression(GPR). For this, I defined the optimizer of GPR as: alh = SwarmPackagePy.fa(50, tf.easom_function, 0, 16, 2, 10, 1, 1, 1, 0.1, 0, 0.1) animation3D(alh.get_agents(),tf.easom_function, 10,-10) Then I used this optimizer (alh) in GPR as follows: gp = GaussianProcessRegressor(kernel=kernel, alpha=1.5, optimizer=alh, n_restarts_optimizer=5) However, after running the python code, I get an error as follows: ValueError: Unknown optimizer &lt;SwarmPackagePy.fa.fa object at 0x0982A3B0&gt;. Am I doing the wrong way? What could be the cause of the error? Thank you!
answer count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: regression
has title: How to use SwarmPackagePy in regression in python code of sklearn?
tagged with: scikit-learn
tagged with: python
accepted answer: http://stackoverflow.com/a/49976751
downvote count: 1
has answer: http://stackoverflow.com/a/49976751
type: AnsweredQuestion
tagged with: particle-swarm

http://stackoverflow.com/q/49980337
has comment: http://stackoverflow.com/comment/86976711
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86976952
tagged with: python
tagged with: twitter
has comment: http://stackoverflow.com/comment/86976733
score: 0
has comment: http://stackoverflow.com/comment/86978885
answer count: 0
has body: Trying to extract Extended_Tweet from within a JSON. This is the code I am using. It keeps giving me errors. How do I make it better? def process(inputfn, outputfn): report = [] for line in open(inputfn): ob = json.loads(line) try: data = tweet['extended_tweet']['full_text'] "").replace("\n", " ").replace(" ", " ").strip() except KeyError as e: print(e) data = tweet['stuff'] user = ob.get("user") username = "unknown" if user: username = user.get("screen_name", "") msg = u"%s: %s" % (username, text) report.append(msg) with codecs.open(outputfn, "w", "utf8") as f: f.write("\n".join(report)) if __name__ == "__main__": process("data/test.json", "data/stream_test-part-tweets.txt") Edit: Link to pastebin: https://pastebin.com/KTHwD5E5 New Edit: Added updated code: Link: https://pastebin.com/Uf0Nb3bg
type: UnansweredQuestion
has title: Unable to extract data from a Twitter Dataset
type: Question

http://stackoverflow.com/a/49986916
has comment: http://stackoverflow.com/comment/86990173
accepted answer of: http://stackoverflow.com/q/49986865
upvote count: 8
answers question: http://stackoverflow.com/q/49986865
has comment: http://stackoverflow.com/comment/87080928
type: Answer
has comment: http://stackoverflow.com/comment/86990255
has comment: http://stackoverflow.com/comment/86990252
type: AcceptedAnswer
downvote count: 0
has body: All these slicing/indexing operations create views/copies of the original dataframe and you then reassign df to these views/copies, meaning the originals are not touched at all. Option 1 dropna(...inplace=True) Try an in-place dropna call, this should modify the original object in-place df_list = [test_1, test_2] for df in df_list: df.dropna(subset=['A'], inplace=True) Note, this is one of the few times that I will ever recommend an in-place modification, because of this use case in particular. Option 2 enumerate with reassignment Alternatively, you may re-assign to the list - for i, df in enumerate(df_list): df_list[i] = df.dropna(subset=['A']) # df_list[i] = df[df.A.notnull()]
score: 8

http://stackoverflow.com/comment/99818633
comment on: http://stackoverflow.com/a/49984997
score: 0
type: Comment
has text: but why not just `df['totalwords'] = df['col'].str.split().len()`?
type: AnswerComment

google-calendar-api
tags question: http://stackoverflow.com/q/49972507
type: Tag
tag name: google-calendar-api

http://stackoverflow.com/a/56929466
score: 8
upvote count: 8
downvote count: 0
answers question: http://stackoverflow.com/q/49968377
type: Answer
has body: You can use Consumer.get_watermark_offsets (see docs) Example: cfg = { # ... ... "group.id": str(uuid4()) } consumer = AvroConsumer(cfg) topic_partition = TopicPartition("topic-name", partition=123) low, high = consumer.get_watermark_offsets(topic_partition) print("the latest offset is {}".format(high))

http://stackoverflow.com/q/50062211
type: AnsweredQuestion
tagged with: fillna
accepted answer: http://stackoverflow.com/a/50062343
score: 0
tagged with: pandas
has title: Filling null values with mean
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87142585
has body: I am given a data set with many NaN values and I wanted to fill the null value with the mean of each column. So I tried the following code: def fill_mean(): m = [df.columns.get_loc(c) for c in df.columns if c in missing] for i in m: df[df.columns[i]] =df[df.columns[i]].fillna(value=df[df.columns[i]].mean()) return df but I get this error: TypeError: must be str, not int The columns I'm trying to fill are all composed by the same type: which is either 'float64' or 'O'. I suspect the problem derives from this fact, but how can I solve it? Edit: I created a dictionary containing the column which contains the index of the columns where some data are missing and each column's type. di = dict(zip(missing, m2)) def fill_mean(): m = [df.columns.get_loc(c) for c in df.columns if c in missing] for i in m: if di[m] == "dtype('float64')": df[df.columns[i]] = df[df.columns[i]].fillna(value=df[df.columns[i]].mean()) return df If I run fill_mean(), now I get a different error: if di[m] == "dtype('float64')": TypeError: unhashable type: 'list'
tagged with: missing-data
tagged with: python
has comment: http://stackoverflow.com/comment/87145100
has answer: http://stackoverflow.com/a/50062343

http://stackoverflow.com/q/50060356
tagged with: matplotlib
answer count: 1
tagged with: lookup-tables
tagged with: image-processing
has answer: http://stackoverflow.com/a/50060495
has body: For the sake of simplicity, let us assume that the image has two rows and four columns, and pixel colors are represented by a triplet of intensity levels (intensity is quantized to five different integer values). I want to transform such color image into a single-channel image through a 3D look up table by using the intensity levels of each pixel as indices. This toy example can be implemented as follows: import numpy as np levels = 5 rows, columns, channels = 2, 4, 3 lut = np.arange(levels**channels).reshape([levels for n in range(channels)]) np.random.seed(0) img = np.random.randint(low=0, high=levels, size=(rows, columns, channels)) I'm aware that I can hardcode the indexing like this: red = img[:, :, 0] green = img[:, :, 1] blue = img[:, :, 2] indexed = lut[red, green, blue] The code above can be generalized to work with multi spectral images: indexed = lut[[img[:, :, i] for i in range(channels)]] Both approaches yield the same result: In [931]: indexed Out[931]: array([[103, 91, 89, 4], [ 55, 30, 48, 15]]) My question: Is there a more elegant way to obtain the same result? More concretely, I'm looking for a NumPy function that splits a color image (3D array) into a list of its chromatic channels (2D arrays). Alternatively I've thought that the transformation could be carried out through matplotlib using lut as a colormap.
type: Question
tagged with: numpy
tagged with: python
accepted answer: http://stackoverflow.com/a/50060495
has title: How to apply a multidimensional look up table to a color image?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50040416
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50040238
has body: Workflow Load the data (see How do I read and write CSV files with Python? ) Preprocess the data (e.g. filtering / creating new features) Make the train-test (validation and dev-set) split Code Sklearns sklearn.model_selection.train_test_split is what you are looking for: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=0)
answers question: http://stackoverflow.com/q/50040238
has comment: http://stackoverflow.com/comment/87096839
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/87062008
has text: Why not have `names` be `[classA, classB]`, with the actual classes, so you don't need to use `getattr` or `locals`.
comment on: http://stackoverflow.com/q/50022954
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/comment/86884231
comment on: http://stackoverflow.com/q/49934343
type: QuestionComment
has text: If you're talking about the model, I fixed that though it's only one indent.
type: Comment
score: 0

http://stackoverflow.com/comment/86852932
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49918734
has text: You do not have a class `result__info u-show-phablet` in the mentioned html

http://stackoverflow.com/comment/86864528
comment on: http://stackoverflow.com/a/49924059
score: 1
type: Comment
has text: @jalanga For lots of such problems, working on sorted data makes things much easier. What makes it a bit ugly here is the need to restore the order of the original list.
type: AnswerComment

http://stackoverflow.com/q/49980524
has comment: http://stackoverflow.com/comment/86987190
has comment: http://stackoverflow.com/comment/86979429
has comment: http://stackoverflow.com/comment/86979585
has answer: http://stackoverflow.com/a/49980759
has title: Unifying floats in Python
has comment: http://stackoverflow.com/comment/86977376
tagged with: python
has comment: http://stackoverflow.com/comment/86977790
tagged with: python-2.7
score: 0
answer count: 2
type: UnansweredQuestion
has body: How can i have rounded floating point numbers to be of equal values (so that == returns True) no matter what operations get applied on them (i want the end rounded results to be the same float). I have the following function: def _round(f, n): x = f * pow(10, n) return truediv(int(x), pow(10, n)) but it still doesn't give me the same floating number. Is there a way to make a float (no matter how it has been calculated) to look always strictly the same, since they are being used in a dictionary as keys and any small change results in a KeyError.
has answer: http://stackoverflow.com/a/49984361
linked to: http://stackoverflow.com/q/23721230
has comment: http://stackoverflow.com/comment/86979654
tagged with: floating-point
has comment: http://stackoverflow.com/comment/86979398
type: Question

http://stackoverflow.com/a/49981690
type: Answer
has body: will list the files in the folder folder script is running from main folder files ... main.py will list only files, not . and .. import os dir = os.path.dirname(__file__) or '.' dir_path = os.path.join(dir, '../folder/') onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
answers question: http://stackoverflow.com/q/49981603
has comment: http://stackoverflow.com/comment/86979908
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/49981603
upvote count: 3

http://stackoverflow.com/q/49962987
has comment: http://stackoverflow.com/comment/86942057
linked to: http://stackoverflow.com/q/26157456
tagged with: pyspark
has comment: http://stackoverflow.com/comment/86942351
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86942207
has title: pyspark: TypeError: 'float' object is not iterable
has comment: http://stackoverflow.com/comment/86942211
has comment: http://stackoverflow.com/comment/86942270
has comment: http://stackoverflow.com/comment/86942398
tagged with: apache-spark
answer count: 1
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86942375
has comment: http://stackoverflow.com/comment/86942167
has answer: http://stackoverflow.com/a/49963324
favorite count: 0
has comment: http://stackoverflow.com/comment/86942269
accepted answer: http://stackoverflow.com/a/49963324
type: Question
has comment: http://stackoverflow.com/comment/86942506
has comment: http://stackoverflow.com/comment/86942206
has comment: http://stackoverflow.com/comment/86942536
upvote count: 0
has comment: http://stackoverflow.com/comment/86942152
has comment: http://stackoverflow.com/comment/86942237
has body: I'm working on a spark code, I always got error: TypeError: 'float' object is not iterable on the line of reduceByKey() function. Can someone help me? This is the stacktrace of the error: d[k] = comb(d[k], v) if k in d else creator(v) File "/home/hw/SC/SC_spark.py", line 535, in &lt;lambda&gt; TypeError: 'float' object is not iterable Here is code: def field_valid(m): dis=m[1] TxP=m[2] ef=m[3] pl=m[4] if TxP != 'NaN' and disl != 'NaN' and ef !='NaN' and pl != 'NaN': return True else: return False def parse_input(d): #d=data.split(',') s_name='S'+d[6] # serving cell name if d[2] =='NaN' or d[2] == '': ef='NaN' else: ef=float(d[2].strip().rstrip()) if d[7] =='NaN' or d[7] == '' or d[7] == '0': TxP='NaN' else: TxP=float(d[7].strip().rstrip()) if d[9] =='NaN' or d[9] == '': dis='NaN' else: dis=float(d[9].strip().rstrip()) if d[10] =='NaN' or d[10] == '': pl='NaN' else: pl=float(d[10].strip().rstrip()) return s_name,dis, TxP, ef, pl sc=SparkContext(appName="SC_spark") lines=sc.textFile(ip_file) lines=lines.map(lambda m: (m.split(","))) lines=lines.filter(lambda m: (m[6] != 'cell_name')) my_rdd=lines.map(parse_input).filter(lambda m: (field_valid(m)==True)) my_rdd=my_rdd.map(lambda x: (x[0],(x[1],x[2]))) my_rdd=my_rdd.reduceByKey(lambda x,y:(max(x[0],y[0]),sum(x[1],y[1]))) #this line got error Here is some sample data: Class,PB,EF,RP,RQ,ID,cell_name,TxP,BW,DIS,PL,geom NaN,10,5110,-78.0,-7.0,134381669,S417|134381669|5110,62.78151250383644,10,2578.5795095469166,113.0,NaN NaN,10,5110,-71.0,-6.599999904632568,134381669,S417|134381669|5110,62.78151250383644,10,2689.630258510342,106.0,NaN NaN,10,5110,-77.0,-7.300000190734863,134381669,S417|134381669|5110,62.78151250383644,10,2907.8184899249713,112.0,19.299999999999983 NaN,10,5110,-91.0,-11.0,134381669,S417|134381669|5110,62.78151250383644,10,2779.96762695867,126.0,5.799999999999997 NaN,10,5110,-90.0,-12.69999980926514,134381669,S417|134381669|5110,62.78151250383644,10,2749.8351648579583,125.0,9.599999999999994 NaN,10,5110,-95.0…

http://stackoverflow.com/a/50025969
type: Answer
accepted answer of: http://stackoverflow.com/q/50025786
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: IIUC, to divide only columns C and D up to (and including) index 2, you can do: a.iloc[:3]"C", "D" /= 5 Which results in: A B C D 0 40.10 41.00 165.2 177.80 1 40.10 43.60 167.0 167.40 2 40.10 41.65 163.0 172.66 3 45.45 47.70 169.5 178.80 4 41.60 46.00 170.0 172.90 5 39.60 42.95 165.5 170.00 The above method is faster than using apply, but here is how to modify your existing code to get the same result: a.iloc[:3] = a.iloc[:3].apply(lambda x: x/5 if x.name in {"C", "D"} else x) The difference is that this runs the apply only on a slice of the DataFrame, and assigns the output back to the same slice. Notice that we slice [:3] because the end index is not included in the slice. More on understanding python's slice notation. Also, you don't have to check both conditions individually- you can use x.name in {..} to check if x.name is contained in a set. Using a set to test membership is faster than using a list: Python Sets vs Lists .
score: 1
answers question: http://stackoverflow.com/q/50025786

http://stackoverflow.com/q/50044629
linked to: http://stackoverflow.com/q/35252397
has comment: http://stackoverflow.com/comment/87105917
upvote count: 0
answer count: 1
downvote count: 3
has title: why [] and [[]] make difference in numpy operations
has comment: http://stackoverflow.com/comment/87105596
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/87105621
tagged with: python
has body: Why I am getting different answers to the following l = np.array([1,-2.6]) s = np.array([[1,-2.6]]) l = np.dot(l.T,l) s = np.dot(s.T,s) print l,s output 7.76 [[ 1. -2.6 ] [-2.6 6.76]] Also in the following case s = np.array([[ 1., -2.6], [-1., 0.4], [-1., -0.6], [ 0., 2.4], [ 1., 0.4]] ) print an element gives the result without [[]] print s[0,:] [1. -2.6]
has comment: http://stackoverflow.com/comment/87105768
has answer: http://stackoverflow.com/a/50044998

http://stackoverflow.com/q/49935601
downvote count: 0
has body: I am new to python and django.I am having a list obtained dynamically containing database table fieldnames. How do I use this list within values_list() in django queryset while fetching results from database? fieldList=['field1','field2'] #list containing table fields obj=sampletable.objects.filter(somecondition).values_list(fieldlist) #---&gt;want like this I came to know that we can't use lists simply as it is inside values_list().So I converted it into a string like this and then tried it but in vain. fieldListstr=','.join(repr(e) for e in fieldList) This is the error which I got Cannot resolve keyword "'field1','field2'" into field. Choices are: field1, field2 Please help me with your solutions. And thanks in advance
has title: How to use a list inside values_list() in django?
possible better answer: http://stackoverflow.com/a/49935611
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49935611
has answer: http://stackoverflow.com/a/49935670
accepted answer: http://stackoverflow.com/a/49935670
upvote count: 5
score: 5
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
tagged with: django-views
answer count: 2

http://stackoverflow.com/comment/86863341
has text: @Divakar [Hah, so does method 1!](https://stackoverflow.com/a/48805093/4909087)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49923729
score: 1

resolution
tag name: resolution
tags question: http://stackoverflow.com/q/50003297
type: Tag

http://stackoverflow.com/q/50049111
has title: python csv subcombinations columns
type: UnansweredQuestion
tagged with: python
score: 0
has body: I have csv file like this: F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,label a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,L1 b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,L2 I want to have the combination of columns into the file as follows: -For a column combination with the label and write the expected results to: file1: F1,label a1,L1 b1,L2 file2: F2,label a2,L1 b2,L2 until file10: F10,label a10,L1 b10,L2 -For 2 column combinations with the label and write the expected results to: 2C_file1: F1,F2,label a1,a2,L1 b1,b2,L2 2C_file2: F1,F3,label a1,a3,L1 b1,b3,L2 until 45C_file45: F9,F10,label a9,a10,L1 b9,b10,L2 -For 3 columns combinations with the label and write to 120 files: .....until..... -For 9 columns combinations with the label and write to 10 files: -For 10 columns combinations with the label and write to 1 files: I have searched and I found a python code for string combination with itertool. How could I archive above tasks with python code? import itertools as iters text='ABCDEFGHIJ' C1= iters.combinations(text,1) print list(C1) C2= iters.combinations(text,2) print list(C2) ..... C9= iters.combinations(text,9) print list(C9) C10=iters.combinations(text,10) print list(10)
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50050216

http://stackoverflow.com/comment/86946425
comment on: http://stackoverflow.com/a/49965208
type: Comment
has text: Don't encourage using the name `list` as a variable. Also you have a small indentation error and it would be nice if you explain your answer at least a little bit.
score: 2
type: AnswerComment

ffmpeg
tags question: http://stackoverflow.com/q/50009034
type: Tag
tags question: http://stackoverflow.com/q/50052269
tags question: http://stackoverflow.com/q/50004065
tag name: ffmpeg

python-decorators
tags question: http://stackoverflow.com/q/50030408
type: Tag
tags question: http://stackoverflow.com/q/49987640
tag name: python-decorators
tags question: http://stackoverflow.com/q/49973804
tags question: http://stackoverflow.com/q/49954170
tags question: http://stackoverflow.com/q/50033953

http://stackoverflow.com/a/49953712
has body: What do you mean by putting the range for year? You could consider putting your dates to a dictionary or nested lists.
score: -1
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49953624
downvote count: 1

http://stackoverflow.com/q/50024431
has body: I've a problem regarding reconstructing sentences with in a large Pandas DataFrame (1 500 000 rows). My aim is to reconstruct sentences out of words into a new dataframe so that there's one sentence per row. I have two Series in my DataFrame: words &amp; tags. Each sentence is separated by an exclamation mark. On top of this I want to create two separate Series into the new DataFrame for adjectives and nouns/verbs using the tags in the original DataFrame. So here is what I have: &gt;df word tag bike NOUN winner NOUN ! PUNCTUATION red ADJECTIVE car NOUN is VERB fast ADJECTIVE ! PUNCTUATION ... ... and here is what I'd like to have &gt;df2 sent nounverb adj bike winner bike winner None red car is fast car is red fast ... I've been unable to find a solution for this and as I'm a beginner in Python, I haven't been able to come up with a for loop that would do this for me. EDIT: Thank you Andy &amp; Jesús for your quick answers. Andy's answer worked neatly, although when creating the new DataFrame a slight modification was needed on my end. It was needed to call the words as strings. df2 = pd.DataFrame({ "sent": g.apply(lambda sdf: " ".join(sdf.word.astype(str))), "nounverb": g.apply(lambda sdf: " ".join(sdf[sdf.is_nounverb].word.astype(str))), "adj": g.apply(lambda sdf: " ".join(sdf[sdf.tag == "ADJECTIVE"].word.astype(str))) })
tagged with: dataframe
tagged with: nlp
type: Question
upvote count: 2
score: 2
has title: Pandas: How to reconstruct strings from a word per row
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50025623
accepted answer: http://stackoverflow.com/a/50025623
tagged with: python
possible better answer: http://stackoverflow.com/a/50025279
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/50025279
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/q/50053968
linked to: http://stackoverflow.com/q/35475082
tagged with: google-cloud-pubsub
has title: Is it possible to perform real-time communication with a Google Compute Engine instance?
tagged with: tensorflow
has body: I would like to run a program on my laptop (Gazebo simulator) and send a stream of image data to a GCE instance, where it will be run through an object-detection network and sent back to my laptop in near real-time. Is such a set-up possible? My best idea right now is, for each image: Save the image as a JPEG on my personal machine Stream the JPEG to a Cloud Storage bucket Access the storage bucket from my GCE instance and transfer the file to the instance In my python script, convert the JPEG image to numpy array and run through the object detection network Save the detection results in a text file and transfer to the Cloud Storage bucket Access the storage bucket from my laptop and download the detection results file Convert the detection results file to a numpy array for further processing This seems like a lot of steps, and I am curious if there are ways to speed it up, such as reducing the number of save and load operations or transporting the image in a better format.
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/46896828
score: 0
answer count: 1
tagged with: google-compute-engine
tagged with: python
accepted answer: http://stackoverflow.com/a/50057983
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50057983

http://stackoverflow.com/a/49948191
answers question: http://stackoverflow.com/q/49948152
upvote count: 2
type: Answer
has body: It's nothing about informing about type, as python is dynamically typed language, but also python is strongly typed, which means that strings can't be easily coerced to integers. You had to cast them explicitly to integers to use pow function.
score: 1
downvote count: 1

http://stackoverflow.com/comment/86993780
has text: change to `events.views.send_alert` in this file `class SomeView` where that tasks is called, Updated code , same eeror
comment on: http://stackoverflow.com/a/49982659
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50069625
has answer: http://stackoverflow.com/a/50100343
has answer: http://stackoverflow.com/a/50100795
tagged with: python
has title: Selenium-Python - How to reduce time for NoSuchElementException
tagged with: webdriver
tagged with: selenium-webdriver
answer count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
has body: I have a test case where I need to check that on clicking an element, a popup is NOT displayed. This code works fine, but it takes too long, 60 seconds for NoSuchElementException, print the PASS condition and move to next test case. How can I reduce the wait time in this case? driver.find_element_by_xpath( ".//*[@id='assetIdDIV']/div/myaots-input/div/div/div[1]/span/i[2]" ).click() try: DUP_popup = driver.find_element_by_xpath( ".//*[@id='DuplicateTicketsPopup']/div/div/div/div[1]/span[2]/img" ) if (DUP_popup): print ("Duplicate tkts popup is displayed - Fail") except NoSuchElementException: print ("Duplicate popup not displayed - PASS")
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50071509
has comment: http://stackoverflow.com/comment/87156341
type: Question
has comment: http://stackoverflow.com/comment/87155928
tagged with: nosuchelementexception
score: 1

http://stackoverflow.com/a/49991554
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49991435
score: 2
has body: Do not use subprocess, and you don't have to worry about shell escaping. Use the high-level file operation APIs provided in stdlib's shutil: import shutil shutil.rmtree('/home/user/Desktop/directory(2018)')
has comment: http://stackoverflow.com/comment/87000414
upvote count: 2

http://stackoverflow.com/a/49960355
has body: Change Default Loading Image To change the default loading image to your loading image use Loader.loading_image = 'loading.png'. Please refer to the example below for details. Example main.py from kivy.app import App from kivy.loader import Loader from kivy.lang import Builder kv = """ BoxLayout: AsyncImage: source: "http://wallpaper-gallery.net/images/wallpaper-for-android/wallpaper-for-android-24.jpg" keep_ratio: True allow_stretch: True """ class gif_deneme(App): def build(self): Loader.loading_image = 'loading.gif' a = Builder.load_string(kv) return a gif_deneme().run() Output
type: Answer
has comment: http://stackoverflow.com/comment/86985087
has comment: http://stackoverflow.com/comment/86941410
has comment: http://stackoverflow.com/comment/87176601
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49960057
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49960057

http://stackoverflow.com/a/49956390
score: 1
upvote count: 1
type: Answer
has body: Change check(ips, "80) for for ip in ips: check(ip, "80) link.connect expected a unique ip and you're passing a list of ips.
answers question: http://stackoverflow.com/q/49956156
accepted answer of: http://stackoverflow.com/q/49956156
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50034420
downvote count: 0
has answer: http://stackoverflow.com/a/50034701
favorite count: 0
type: Question
has body: I'm trying to retrieve all items from a specific key in a dictionary. The code works, but I keep receiving a None statement in the output from my function general_info. The other function specific_info works normally. Any suggestion? Thanks a lot. countries = { "canada": { 'name': "Canada", 'location': "North America", 'currency': "Canadian Dollar", 'capital city': "Ottawa", 'population': "32.268.240", 'area': "9.970.610 km2" }, "brazil": { 'name': "Brazil", 'location': "South America", 'currency': "Brazilian Real", 'capital city': "Brasilia", 'population': "186.404.900", 'area': "8.514.877 km2" }, "ukraine": { 'name': "Ukraine", 'location': "Europe", 'currency': "Ukrainian Hryvnia", 'capital city': "Kyiv", 'population': "46.480.700", 'area': "603.700 km2" }, "haiti": { 'name': "Haiti", 'location': "North America", 'currency': "Haitian Gourde", 'capital city': "Port-au-Prince", 'population': "8.527.777", 'area': "27.750 km2" }, "albania": { 'name': "Albania", 'location': "Europe", 'currency': "Albanian Lek", 'capital city': "Tirana", 'population': "3.129.678", 'area': "28.748 km2" }, "india": { 'name': "India", 'location': "Asia", 'currency': "Indian Rupee", 'capital city': "New Delhi", 'population': "1.103.371.000", 'area': "3.287.263 km2" } } def general_info(c_name): for key, val in countries[c_name].items(): info = print(c_name.title() + " " + key + " is " + val) return info def specific_info(c_name, info): if c_name in countries and info in countries[c_name].keys(): return (info.title() + " from " + c_name.title() + " is " + countries[c_name][info]) ask_country = input("Country name: ") ask_info = input("Information requested: ") c_name = ask_country.lower() info = ask_info.lower() print(general_info(c_name)) print() print(specific_info(c_name, info))
has comment: http://stackoverflow.com/comment/87084977
answer count: 2
tagged with: for-loop
tagged with: function
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50034701
has title: python function for loop in dictonary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50034483
has comment: http://stackoverflow.com/comment/87085025
possible better answer: http://stackoverflow.com/a/50034483
score: 1
upvote count: 1

http://stackoverflow.com/comment/86995149
has text: sorry I forgot... it's correct now
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49989125
score: 0

http://stackoverflow.com/q/50060161
tagged with: python
tagged with: matlab-engine
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87143884
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87136910
tagged with: anaconda
has comment: http://stackoverflow.com/comment/87136817
has body: I'm using Mac OSX High Sierra anaconda3 python (virtual environment with python=3.6) Matlab R2018a. Steps to reproduce: Create a new python 3.6 environment. Activate the environment Go to Matlab/extern/engines/python and run python setup.py install. Run the following script. import matlab.engine matlab.engine.start_matlab() Segmentation fault happen at the start_matlab() line (not the import line). I had no trouble before using matlab engine this way. How could I debug this? (mostly is just linking problem). ====================== I uninstalled Anaconda3, and used Python 2.7 system. I met with the same problem, and the problem is with libwmvm.dylib of Matlab. Process: Python [5124] Path: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 2.7.10 (2.7.10) Code Type: X86-64 (Native) Parent Process: bash [2183] Responsible: Python [5124] User ID: 501 PlugIn Path: /Applications/MATLAB_R2018a.app/bin/maci64/libmwmvm.dylib PlugIn Identifier: libmwmvm.dylib PlugIn Version: ??? (0) Date/Time: 2018-04-27 23:27:03.250 +0700 OS Version: Mac OS X 10.13.4 (17E199) Report Version: 12 Anonymous UUID: 885790DC-B32C-0363-903C-837A7C285AF3 Sleep/Wake UUID: 14FBD560-D2B9-4A59-89F1-DABA878FCA70 Time Awake Since Boot: 10000 seconds Time Since Wake: 3700 seconds System Integrity Protection: enabled Crashed Thread: 3 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000090 Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [0] VM Regions Near 0x90: --&gt; __TEXT 000000010e1c6000-000000010e1c8000 [ 8K] r-x/rwx SM=COW p [/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python] Thread 0:: Dispatch queue: com.apple.main-thread
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52200196
has title: Segmentation fault when running start_matlab in matlab engine

http://stackoverflow.com/a/50065403
has body: It is due to the indentation when looping through the text file. It is only reading one line that's why its failing. I've fixed it in the code below. However storing usernames and password like this probably isn't the best idea, I would advise using a database for this. Whenever dealing with passwords as well they should be hashed using a strong hashing function. Also validation on the username is quite important, for example the username could have a space in so it won't read the password properly. import time def register(): username = input("Please enter a username: ") print('') password = input("Please enter your desired password: ") print('') file = open("accountfile3.txt","a") file.write(username) file.write(" ") file.write(password) file.write("\n") file.close() if login(): print("You are now logged in...") else: print("You aren't logged in!") def login(): x = False while x == False: username = input("Please enter your username: ") print('') password = input("Please enter your password: ") print('') for line in open("accountfile3.txt","r").readlines(): # Read the lines login_info = line.split() # Split on the space, and store the results in a list of two strings if username == login_info[0] and password == login_info[1]: print("Correct credentials!") return True break print("Incorrect credentials.") print('') print('Hello') print('') time.sleep(1) print('This is python_workspace') print('') time.sleep(1) print('These are the choices available: ') print('') print('|' + '-'*24 + '|') print('| 1. Register |') print('| |') print('| 2. Login |') print('| |') print('| 3. Exit |') print('|' + '-'*24 + '|') y = True while y == True: choice1 = input('Please enter the number: ') print('') if choice1 == '1': register() break elif choice1 == '2': login() break elif choice1 == '3': break else: print('Incorrect input, please enter either: 1, 2, 3') print('')
answers question: http://stackoverflow.com/q/50065320
has comment: http://stackoverflow.com/comment/87152556
upvote count: 2
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/a/49943275
upvote count: 1
has body: You can use __hour to filter by the hour: MyModel.objects.filter( emp_id=1, time__hour__gt=6 ).count()
accepted answer of: http://stackoverflow.com/q/49942997
score: 1
answers question: http://stackoverflow.com/q/49942997
type: Answer
has comment: http://stackoverflow.com/comment/86906960
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87054462
has text: If possible, try to set up an exact example that we can run to reproduce your error.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50016231
type: Comment

http://stackoverflow.com/q/50064596
tagged with: python
has comment: http://stackoverflow.com/comment/87146278
upvote count: 2
score: 2
answer count: 0
downvote count: 0
tagged with: mysql
tagged with: string
favorite count: 0
type: Question
has title: Python pymysql placeholder breaking using WHILE column IN (set) query
has comment: http://stackoverflow.com/comment/87146487
type: UnansweredQuestion
tagged with: pymysql
has body: I am using pymysql to query a MySQL database using placeholders. It works well. I have a query which raises a warning because of the way that the string is handled when the parameters are loaded into the query : My sample code: thing_ids = "1, 2, 3, 4" list_notes = db_get_list("SELECT n.note_id, n.note_info, ... FROM note n, contact c WHERE n.note_created_by=c.contact_id AND n.note_on_thing_id IN (%s)", (thing_ids, )) and db_get_list is: def db_get_list(self, sql, args=None): with self.connection.cursor() as cursor: cursor.execute(sql, args) return cursor.fetchall() The warning raised is: /Library/Python/2.7/site-packages/pymysql/cursors.py:323: Warning: (1292, u"Truncated incorrect DOUBLE value: '1, 2, 3, 4'") I have done some debugging with MySQL on the console. When I run the query ending: WHERE .... AND n.note_on_thing_id IN ('1, 2, 3, 4') I get the warning. When I run the query ending: WHERE .... AND n.note_on_thing_id IN (1, 2, 3, 4) (no quotes) there is no warning. How can I pass the argument to cursor.execute() and ask it in this case NOT to wrap the query with 'quotes' (every other time I want to pass it the same as it does today!). I have seen the other % options in the documentation, e.g. %d, %g - but these only seem to work when the variable is an integer type not a string type. The string will always be a string with comma separated integer numbers in it (they represent primary key IDs of a column).

http://stackoverflow.com/q/49998709
favorite count: 0
accepted answer: http://stackoverflow.com/a/49999060
has answer: http://stackoverflow.com/a/49999060
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: numpy
has body: Assuming I create the following data frame: df = pd.DataFrame({'A':np.random.random(20), 'B':np.random.random(20)}) df Out[162]: A B 0 0.888651 0.380360 1 0.513343 0.605991 2 0.560978 0.076174 3 0.209426 0.498564 4 0.121748 0.771653 5 0.843299 0.279264 6 0.644060 0.725061 7 0.200187 0.349093 8 0.807808 0.657373 9 0.212760 0.384311 10 0.000725 0.023815 11 0.614540 0.534569 12 0.083690 0.228761 13 0.202334 0.266114 14 0.104520 0.757514 15 0.039944 0.014512 16 0.465300 0.164657 17 0.247370 0.894628 18 0.980589 0.833938 19 0.734673 0.745574 I then, want to: Know the frequency of the 'B' columns which falls in the bins: np.arange(0, 1.05, 0.05) Add that information as column 'freq'. So, for example, row[0] where 'B' is 0.38 and is between [0.35, 0.40) is happening 2 times in the data frame. Therefor we will have df['freq'][0] = 2 Then, I want to have a new column called 'weights' which will be, for each row, max(freq)/freq I can solve 1 with something like: df.groupby(pd.cut(df['B'], np.arange(0, 1.05, 0.05))).count() though there might be a more elegant way to do so I fail to solve 2 And 3 is pretty straight forward. Eventually, I only need the 'weights' column that is created by 1, 2 and 3.
type: AnsweredQuestion
has title: Pandas DF - Measure frequency, attached to appropriate rows and normalize by max(freq)
downvote count: 0
upvote count: 1
score: 1
answer count: 1

http://stackoverflow.com/comment/87019318
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50001562
has text: I'm sorry, I don't think your question is clear at the moment. Is it possible that you can [edit] your question and better explain what you are asking?
score: 0

http://stackoverflow.com/a/49929417
has comment: http://stackoverflow.com/comment/86878677
has comment: http://stackoverflow.com/comment/86878655
has comment: http://stackoverflow.com/comment/86878601
type: Answer
has body: Firstly, you need to rename your methods, it can cause problems using the same name on multiple methods. Adding a number to them should suffice for this purpose. Secondly, What do you want to happen when you enter a different username? If you want to print the schedule for that student you should look at creating some usernames for those students. Thirdly, there's actually a newer version of PyQt named PyQt5, while you don't have to upgrade it I highly recommend it :)
score: 0
has comment: http://stackoverflow.com/comment/86875089
answers question: http://stackoverflow.com/q/49927064

selenium
tags question: http://stackoverflow.com/q/49935754
tags question: http://stackoverflow.com/q/50027548
tags question: http://stackoverflow.com/q/49968965
tags question: http://stackoverflow.com/q/49999407
tags question: http://stackoverflow.com/q/50069625
tags question: http://stackoverflow.com/q/50013902
tags question: http://stackoverflow.com/q/50040823
tags question: http://stackoverflow.com/q/50048640
tags question: http://stackoverflow.com/q/49923497
tags question: http://stackoverflow.com/q/49985726
tags question: http://stackoverflow.com/q/49983002
tags question: http://stackoverflow.com/q/50052053
tags question: http://stackoverflow.com/q/49929940
tags question: http://stackoverflow.com/q/49922385
tags question: http://stackoverflow.com/q/50030448
tags question: http://stackoverflow.com/q/49919214
tags question: http://stackoverflow.com/q/49974265
tags question: http://stackoverflow.com/q/49930667
tags question: http://stackoverflow.com/q/50047392
tags question: http://stackoverflow.com/q/49992340
tags question: http://stackoverflow.com/q/49972306
tags question: http://stackoverflow.com/q/50023175
tags question: http://stackoverflow.com/q/50060755
tags question: http://stackoverflow.com/q/50027278
tags question: http://stackoverflow.com/q/50000321
tags question: http://stackoverflow.com/q/49974708
tags question: http://stackoverflow.com/q/49937997
tags question: http://stackoverflow.com/q/50057427
tags question: http://stackoverflow.com/q/49991505
tags question: http://stackoverflow.com/q/49957418
tags question: http://stackoverflow.com/q/50047349
tags question: http://stackoverflow.com/q/49994941
tags question: http://stackoverflow.com/q/49967652
tags question: http://stackoverflow.com/q/49953271
tags question: http://stackoverflow.com/q/49990501
tags question: http://stackoverflow.com/q/49924876
tags question: http://stackoverflow.com/q/50071983
tags question: http://stackoverflow.com/q/49965592
tags question: http://stackoverflow.com/q/50031290
tags question: http://stackoverflow.com/q/50045590
tags question: http://stackoverflow.com/q/49952697
tags question: http://stackoverflow.com/q/50036796
tags question: http://stackoverflow.com/q/50016011
tags question: http://stackoverflow.com/q/49984257
tags question: http://stackoverflow.com/q/49978486
tags question: http://stackoverflow.com/q/49982941
tags question: http://stackoverflow.com/q/49956239
tags question: http://stackoverflow.com/q/50002322
tags question: http://stackoverflow.com/q/49988171
tags question: http://stackoverflow.com/q/49955629
type: Tag
tags question: http://stackoverflow.com/q/50016048
tags question: http://stackoverflow.com/q/50026910
tags question: http://stackoverflow.com/q/49938766
tags question: http://stackoverflow.com/q/49945427
tags question: http://stackoverflow.com/q/50053647
tags question: http://stackoverflow.com/q/49986071
tags question: http://stackoverflow.com/q/50055401
tags question: http://stackoverflow.com/q/50011134
tags question: http://stackoverflow.com/q/49953047
tags question: http://stackoverflow.com/q/49929374
tags question: http://stackoverflow.com/q/49974379
tag name: selenium
tags question: http://stackoverflow.com/q/49939449
tags question: http://stackoverflow.com/q/49946614
tags question: http://stackoverflow.com/q/50013127
tags question: http://stackoverflow.com/q/50006810
tags question: http://stackoverflow.com/q/49948709
tags question: http://stackoverflow.com/q/49942003
tags question: http://stackoverflow.com/q/49971785
tags question: http://stackoverflow.com/q/49947704
tags question: http://stackoverflow.com/q/49946717
tags question: http://stackoverflow.com/q/49953188
tags question: http://stackoverflow.com/q/49988239
tags question: http://stackoverflow.com/q/49972237
tags question: http://stackoverflow.com/q/49931373
tags question: http://stackoverflow.com/q/49921128

http://stackoverflow.com/q/49978646
has title: Summing values in Counter dictionary
has answer: http://stackoverflow.com/a/49978788
has comment: http://stackoverflow.com/comment/86973399
tagged with: counter
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/49978922
has answer: http://stackoverflow.com/a/49978922
answer count: 2
has body: I've got a dictionary, what shows how many words 'WOMAN' had spoken in a movie script. Now I want t add up the value of the dictionary so I get a total count of the words spoken by 'WOMAN'. Is there a way to achieve this? 'WOMAN': Counter({'Mia': 4, 'a': 4, 'the': 4, 'and': 3, 'is': 3, 'on': 3, '--': 3, 'it': 2, 'Then': 2, 'STUDIO': 2, 'Cappuccino,': 1, 'from': 1, 'her.': 1, 'No,': 1, 'I': 1, 'insist.': 1, 'She': 1, 'pays.': 1, 'smiles': 1, 'at': 1, 'drops': 1, 'bill': 1, 'in': 1, 'tip': 1, 'jar.': 1, 'watches': 1, 'as': 1, 'Woman': 1, 'walks': 1, 'off,': 1, 'joined': 1, 'screen:': 1, '4:07.': 1})})
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49978788

http://stackoverflow.com/comment/87031544
type: AnswerComment
has text: When I do that I see "Found 0 images belonging to 2 classes." in the console. test_path = 'dataset/test_set' : this path consists of only 1 directory mixed with 200 pictures of 'bird' and 'no_bird'
comment on: http://stackoverflow.com/a/50007513
score: 0
type: Comment

http://stackoverflow.com/a/49970987
upvote count: 1
has comment: http://stackoverflow.com/comment/86957898
answers question: http://stackoverflow.com/q/49970816
score: 1
has body: You can just add your input to the variable. You didn't provide any code so I'll just have to improvise: data = open('output.txt', 'w') a = input('&gt;&gt;') data.write(a + '\n') data.close() But the better solution would be, like the comment below me mentioned, to use sys.stdin.readline() import sys data.write(sys.stdin.readline())
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87115706
score: 0
has text: See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), as the code you have provided still does not allow us to replicate the problem you are having. You should also edit the post tags to specify which language you are using with Selenium (Python in this case).
type: Comment
comment on: http://stackoverflow.com/q/50047668
type: QuestionComment

http://stackoverflow.com/comment/87115981
has text: Flask does not have any such thing. What makes you think it does?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50049769
type: Comment

http://stackoverflow.com/a/50025668
has comment: http://stackoverflow.com/comment/87070614
has comment: http://stackoverflow.com/comment/87068237
has comment: http://stackoverflow.com/comment/87070719
has comment: http://stackoverflow.com/comment/87070747
type: Answer
has comment: http://stackoverflow.com/comment/87067472
has comment: http://stackoverflow.com/comment/87067774
score: 6
has comment: http://stackoverflow.com/comment/87067819
has comment: http://stackoverflow.com/comment/87067986
has comment: http://stackoverflow.com/comment/87067882
has body: You can use space as a seperator. Ex: import pandas as pd df = pd.read_csv(filename, sep="\s+", names = ["A", "B"]) print(df["A"][0]) print(df["B"][0]) Output: 49907 87063 for i in df.values: print(i) Output: [49907 87063] [42003 51519] [21301 46100] [97578 26010] [52364 86618] [25783 71775] [ 1617 29096] [ 2662 47428] [74888 54550] [17182 35976] [86973 5323]
downvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87068138
has comment: http://stackoverflow.com/comment/87070777
accepted answer of: http://stackoverflow.com/q/50025612
has comment: http://stackoverflow.com/comment/87067951
has comment: http://stackoverflow.com/comment/87068153
has comment: http://stackoverflow.com/comment/87068336
answers question: http://stackoverflow.com/q/50025612
has comment: http://stackoverflow.com/comment/87068031
upvote count: 8

http://stackoverflow.com/comment/86961603
score: 0
comment on: http://stackoverflow.com/a/49972653
type: AnswerComment
has text: Just create a map of each real output to one of the classes from 0 to 20. You can do that inside the dataloader.
type: Comment

http://stackoverflow.com/comment/87020260
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50001840
score: 0
has text: @Sarah.d I believe Jean-Francois is correct, please try the edit I suggested in the answer below.

http://stackoverflow.com/comment/87361424
comment on: http://stackoverflow.com/a/50093990
has text: Thank you for your kind information.and now i have a doubt how can i make two way communication via call using twilio for example i need to call any number that verified by Twilio account and i make call from my verified number to another verified number if i greet like hello and the human response also i can able to here via call like call center.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50055848
type: Question
possible better answer: http://stackoverflow.com/a/50076073
has title: Algorithmic complexity of this algorithm to find all ordered permutations of length X
has answer: http://stackoverflow.com/a/50076073
tagged with: algorithm
tagged with: python
has comment: http://stackoverflow.com/comment/87136518
has comment: http://stackoverflow.com/comment/87131692
has comment: http://stackoverflow.com/comment/87131578
has body: I have written a recursive function to generate the list of all ordered permutations of length X for a list of chars. For instance: ['a', 'b', 'c', 'd'] with X=2 will give [['a', 'a'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'a'], ['b', 'b'], ..., ['d', 'd']] I'm not sure about its algorithmic complexity though (at least I know it's pretty horrible). I would say it's something around: O(X * N^(L + X)) (where L is the number of different chars, 4 here because we have 'A', 'B', 'C', 'D', and X the length of the permutations we want to generate). Because I have 2 nested loops, which will be run X times (well, X-1 because of the special case when X = 1). Is it correct? def generate_permutations(symbols, permutations_length): if permutations_length == 1: return [[symbol] for symbol in symbols] tails = generate_permutations(symbols, permutations_length-1) permutations = [] for symbol in symbols: for tail in tails: permutation = [symbol] + tail permutations.append(permutation) return permutations print(generate_permutations(['a', 'b', 'c', 'd'], 2)) By the way: I know this is not idiomatic Python and I apologize if it's ugly but it's just some prototyping I'm doing before writing this code in a different, less expressive language. And I also know that I could use itertools.permutations to do this task. By the way, I'd be interested if someone happens to know the algorithmic complexity of itertool's permutations function, and if there is some way to improve the complexity of my own algorithm. Thanks!
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87132378
tagged with: time-complexity
has comment: http://stackoverflow.com/comment/87133151
accepted answer: http://stackoverflow.com/a/50056102
tagged with: permutation
has answer: http://stackoverflow.com/a/50056102
has comment: http://stackoverflow.com/comment/87128397

http://stackoverflow.com/q/50020659
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50020967
has body: import pandas as pd import numpy as np df = pd.read_excel(r"C:\Users\venkagop\Subbu\promo validation testing\P 02. Promotions-UK C1.xls") df = df'Promotions', 'Promotions: AE', 'Promotions: Anaplan ID', 'Promotions: Is Optima Scenario?', 'Promotions: SIDs', 'Set Inactive?', 'Start Date', 'End Date', 'Promo Period', 'Promo Optima Status', 'Change Promo Status' df = df[(df['Promo Period'] == 'FY1819')] df = df[(df['Set Inactive?'] == 0 ) &amp; (df['Promotions: Is Optima Scenario?'] == 1)] df.dropna(subset=['Promotions: SIDs'], inplace=True) df['Optima vs Anaplan Promo Status Validation'] = "" df['Optima vs Anaplan Promo Status Validation'] = np.where(df['Promo Optima Status'] == df['Change Promo Status'], 'True', 'False') df.to_excel(r"C:\Users\venkagop\Subbu\mytest.xls", index = False) #after this i want to change sheeet1 name to some other name#
has answer: http://stackoverflow.com/a/50020967
tagged with: dataframe
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 3
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
has title: Change the name of excel worksheet with pandas

http://stackoverflow.com/comment/87153780
has text: Good edit, thanks.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50068431

http://stackoverflow.com/comment/87068741
comment on: http://stackoverflow.com/q/50020112
has text: In general, it looks right, but the structure definitions could be wrong and the C definitions weren't provided.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49950347
has title: Spacy Doc not parsing and processing text
answer count: 0
tagged with: spacy
score: 1
has comment: http://stackoverflow.com/comment/93578673
downvote count: 0
upvote count: 1
tagged with: flask
favorite count: 0
type: Question
tagged with: heroku
type: UnansweredQuestion
tagged with: python
tagged with: nlp
has body: I'm creating a Flask endpoint so I can do some text processing, and in order to get the spacy english model to load I'm downloading the model file through my Pipfile when I push to Heroku. Whereas before when working locally I was loading the model with: nlp = spacy.load('en') doc = nlp(text) Now I download the en_core_web_sm during the build on heroku (or even when running heroku local web and do: import en_core_web_sm nlp = en_core_web_sm.load() doc = nlp(text) Weirdly the spacy Doc object is still created, the model is loaded, but...nothing happens. It doesn't tokenize, it doesn't run the entity extractor, nada. What am I missing?

http://stackoverflow.com/q/49948956
has title: Python: using indices and str
linked to: http://stackoverflow.com/q/49820806
has body: I am attempting to learn Python and am working on an assignment for fun that involves translating "encrypted" messages (it's just the alphabet in reverse). My function is supposed to be able to read in an encoded string and then print out its decoded string equivalent. However, as I am new to Python, I find myself continually running into a type error with trying to use the indices of my lists to give the values. If anyone has any pointers on a better approach or if there is something that I just plain missed, that would be awesome. def answer(s): ''' All lowercase letters [a-z] have been swapped with their corresponding values (e.g. a=z, b=y, c=x, etc.) Uppercase and punctuation characters are unchanged. Write a program that can take in encrypted input and give the decrypted output correctly. ''' word = "" capsETC = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\ ' ', '?', '\'', '\"', '@', '!', '#', '$', '%', '&amp;', '*', '(', \ ') ', '-', '_', '+', '=', '&lt;', '&gt;', '/', '\\' alphF = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' alphB = 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm',\ 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a' for i in s: if i in capsETC: # if letter is uppercase or punctuation word = word + i # do nothing elif i in alphB: # else, do check for x in alphB: # for each index in alphB if i == alphB[x]: # if i and index are equal (same letter) if alphB[x] == alphF[x]: # if indices are equal newLetter = alphF[x] # new letter equals alpf at index x str(newLetter) # convert to str? word = word + newLetter # add to word print(word) s = "Yvzs!" answer(s)
tagged with: python
accepted answer: http://stackoverflow.com/a/49949163
possible better answer: http://stackoverflow.com/a/49949067
tagged with: alphabet
has answer: http://stackoverflow.com/a/49949163
has answer: http://stackoverflow.com/a/49949067
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86914501
tagged with: loops
type: Question
tagged with: python-3.x
answer count: 2

javascript
tags question: http://stackoverflow.com/q/49929833
tags question: http://stackoverflow.com/q/50004657
tags question: http://stackoverflow.com/q/49946180
tags question: http://stackoverflow.com/q/50074064
tags question: http://stackoverflow.com/q/49953785
tags question: http://stackoverflow.com/q/50039036
tags question: http://stackoverflow.com/q/50004209
tag name: javascript
tags question: http://stackoverflow.com/q/50011251
tags question: http://stackoverflow.com/q/50042492
tags question: http://stackoverflow.com/q/50023175
tags question: http://stackoverflow.com/q/49987780
tags question: http://stackoverflow.com/q/49957822
tags question: http://stackoverflow.com/q/50032122
tags question: http://stackoverflow.com/q/50017962
tags question: http://stackoverflow.com/q/49994941
tags question: http://stackoverflow.com/q/50045880
tags question: http://stackoverflow.com/q/49925322
tags question: http://stackoverflow.com/q/49934730
tags question: http://stackoverflow.com/q/49957034
tags question: http://stackoverflow.com/q/49972237
tags question: http://stackoverflow.com/q/49939907
tags question: http://stackoverflow.com/q/49970116
tags question: http://stackoverflow.com/q/49981093
tags question: http://stackoverflow.com/q/50045203
tags question: http://stackoverflow.com/q/49976003
tags question: http://stackoverflow.com/q/49949020
tags question: http://stackoverflow.com/q/49994136
type: Tag
tags question: http://stackoverflow.com/q/49997050
tags question: http://stackoverflow.com/q/49954033
tags question: http://stackoverflow.com/q/49946213

http://stackoverflow.com/comment/86880461
score: 0
type: Comment
type: QuestionComment
has text: Seems like the particles should also cause a failure even if the button doesn't change color.
comment on: http://stackoverflow.com/q/49932344

http://stackoverflow.com/q/50031613
has answer: http://stackoverflow.com/a/50031712
type: AnsweredQuestion
tagged with: pipe
has title: Python multiprocess non-blocking intercommunication using Pipes
accepted answer: http://stackoverflow.com/a/50031717
favorite count: 0
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/50031717
upvote count: 4
answer count: 2
has body: Is it possible to receive process intercommunications using Pipes in a non-blocking fashion? Consider the following code: from multiprocessing import Process, Pipe import time def f(conn): time.sleep(3) conn.send('Done') conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=f, args=(child_conn,)) p.start() while True: print('Test') msg = parent_conn.recv() if msg == 'Done': break print('The End') p.join() The parent_conn.recv() will block the while-loop until a message is received. Is there a way to listen for messages in a non-blocking way?
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50031712
score: 4
type: Question

http://stackoverflow.com/q/49999115
has answer: http://stackoverflow.com/a/49999291
has body: I have the following code that breaks: l = [] tup = ('a', 'b') l = l + tup which gives the below error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can only concatenate list (not "tuple") to list but the below code runs l = [] tup = ('a','b') l += tup without any error. I always thought l+= is the same as l = l + What is going on over here?
tagged with: python
has comment: http://stackoverflow.com/comment/87014349
linked to: http://stackoverflow.com/q/13904493
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/13904493
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49999291
has title: What is the difference between these two ways of appending tuples to a list

http://stackoverflow.com/comment/132551113
type: AnswerComment
has text: Look at this final dp[] value {1: 1, 2: 1, 3: 2, 4: 2, 5: 1, 6: 2, 7: 2, 8: 3, 9: 3, 10: 2, 11: 3}, here the key is amount and value is minimum coins required for that amount. Here we are using for loop and inside we are using recursion if (amount- coin value) >=0 just to check for each coins combination whether we are able to make that amount or not , and saving the minimum coins required for that amount in dp.
comment on: http://stackoverflow.com/a/75074833
score: 0
type: Comment

http://stackoverflow.com/comment/87126505
comment on: http://stackoverflow.com/a/50054920
score: 1
has text: `In [10]: %timeit [re.findall('#\w+', i) for i in tweets] 3.4 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87119787
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50050796
type: Comment
has text: How to exit main() in B.py after it received a value and how to assign it to a new variable...

http://stackoverflow.com/comment/86947321
has text: provide a [mcve]
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49965770

http://stackoverflow.com/comment/87065889
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50022491
has text: @ whoever downvoted, please cite the reason. I shall be more than happy to try and clear the confusion.
score: 0

http://stackoverflow.com/comment/86981510
has text: Can you have a look now?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49980664

http://stackoverflow.com/comment/86976733
comment on: http://stackoverflow.com/q/49980337
type: Comment
has text: @etene Yeah and please provide a JSON example (i.e. just print the json and post it here)
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86960636
type: AnswerComment
has text: every now and again you get someone that comes in and just sticks a DV on all the answers. Can't do much about it.
score: 0
comment on: http://stackoverflow.com/a/49972270
type: Comment

http://stackoverflow.com/q/50006669
type: Question
linked to: http://stackoverflow.com/q/13605646
has comment: http://stackoverflow.com/comment/90671371
tagged with: package
tagged with: python
has comment: http://stackoverflow.com/comment/87030398
has title: unexplained entry appears when i run 'ls' command in one of my Git repositories
has comment: http://stackoverflow.com/comment/87029925
has comment: http://stackoverflow.com/comment/90671430
type: AnsweredQuestion
has body: When i 'cd' into one of my GIT repositories from terminal and run the ls command i can see two entries. One of them i expect to see as it is the python file i created but i also see an entry '=3.4.0' as well. What is this entry? Is appears to be a version number of somesort. Can someone shed light on this?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87042102
accepted answer: http://stackoverflow.com/a/51859763
has comment: http://stackoverflow.com/comment/87030112
has comment: http://stackoverflow.com/comment/90671488
has answer: http://stackoverflow.com/a/51859763

http://stackoverflow.com/q/50002449
has answer: http://stackoverflow.com/a/50032622
tagged with: python
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50129258
has body: I have the pos_order_total field in the contact tree view. It is calculated perfecly if store=False, but if store=True it is not calculated if I make some POS order. So how can I make this work with store=True from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' pos_order_total = fields.Monetary( string='POS Order Total', compute='_compute_pos_order_total', store=True) def _compute_pos_order_total(self): Order = self.env['pos.order'] for partner in self: total = 0.0 domain = [('partner_id', '=', partner.id)] for o in Order.search(domain): total += o.amount_total partner.pos_order_total = total
has title: How to make work a computed field with "store=True" when I am using fields from other model?
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/50129258
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87080869
tagged with: python-2.7
tagged with: odoo-10
accepted answer: http://stackoverflow.com/a/50032622
tagged with: odoo
score: 1
tagged with: odoo-8

http://stackoverflow.com/comment/86985515
has text: @GrantWilliams your answer only adds the digits up, but does not produce the desired single digit outcome the OP was asking for (i.e. returns 11 for 38 instead of 2)
score: 0
comment on: http://stackoverflow.com/a/49984285
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50326101
answers question: http://stackoverflow.com/q/50040023
upvote count: 7
has comment: http://stackoverflow.com/comment/114149677
type: Answer
has comment: http://stackoverflow.com/comment/138917371
accepted answer of: http://stackoverflow.com/q/50040023
has body: Solved : It was a proxy problem. I'm using session without env var : session = requests.Session() session.trust_env = False ret = session.get(url, json=my_json)
score: 7
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49991998
tagged with: opencv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87000706
has title: Real-time face_recognition can't indentify the right face
tagged with: python
has body: I want to build an attendance system by face_recognition with real-time. Therefore, I created a folder that have 20 pictures of some famous people to test the code. However, the result is bad, since the program can't really identify the right face. What should I do to improve the code such that I can identify the right faces? I hope to get some advice from you. Thanks a lot. # -*- coding: utf-8 -*- #I have installed these package successfully import face_recognition import cv2 import datetime import glob2 as gb import numpy as np video_capture = cv2.VideoCapture(0) #There are 20 pictures in my local folder img_path=gb.glob(r'F:\liuzhenya\photo\\*.jpg') #Store the name of picture known_face_names=[] #Store the matrix from these pictures known_face_encodings=[] for i in img_path: picture_name=i.replace('F:\liuzhenya\photo\\','') picture_newname=picture_name.replace('.jpg','') obama_img = face_recognition.load_image_file(i) obama_face_encoding = face_recognition.face_encodings(obama_img)[0] known_face_names.append(picture_newname) known_face_encodings.append(obama_face_encoding) face_locations = [] face_encodings = [] face_names = [] process_this_frame = True while True: ret, frame = video_capture.read() small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame=small_frame[:,:,::-1] if process_this_frame: face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: match = face_recognition.compare_faces(known_face_encodings, face_encoding) if True in match: match_index=match.index(True) name = "match" #To print name and time cute_clock = datetime.datetime.now() print (known_face_names[match_index]+':'+str(cute_clock)) else: name = "unknown" face_names.append(name) process_this_frame = not process_this_frame for (top, right, bottom, left), name in zip(face_locations, face_names): top *= 4 right *= 4 bottom *= 4 left …
answer count: 0
has comment: http://stackoverflow.com/comment/87348136
upvote count: 2
score: 1
downvote count: 1
tagged with: face-recognition
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87160479
comment on: http://stackoverflow.com/q/50071752
has text: @DavidParks will upvote too. Sorry I did not mention you, I posted my comment apparently at the same time as you wrote.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87101359
type: Comment
has text: Thanks ! It helped .. Updated Regex : ifpattern = "\bif\b\s*\(.*?{0}=.*?\)".format(itemFieldList[i]);
type: AnswerComment
comment on: http://stackoverflow.com/a/49981074
score: 0

http://stackoverflow.com/comment/87042144
type: Comment
has text: Are you using Python 3? This may be an absolute versus relative import issue that would only work in Python 2.
type: QuestionComment
comment on: http://stackoverflow.com/q/50012848
score: 0

http://stackoverflow.com/comment/86902081
has text: I've updated my post
type: Comment
comment on: http://stackoverflow.com/a/49942708
score: 0
type: AnswerComment

http://stackoverflow.com/q/50011476
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: Python- How to open two excel files with each in its own excel application
has comment: http://stackoverflow.com/comment/87236337
has comment: http://stackoverflow.com/comment/87042341
tagged with: excel
has comment: http://stackoverflow.com/comment/87041984
tagged with: win32com
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87041992
has body: How can you open an xlsx file in a separate excel application then a second xls file, so that during a condition, I just want to close one of them and not both. The current code below, opens both files in the same excel application even though I am opening specifying two separate excel objects. And when call the close() function on one of the files, it closes both. My requirement is that I have to do his with dispatch from win32com. Thanks. import time, os.path, os from win32com.client import Dispatch path1 = 'C:\\Todolist.xlsx' path2 = 'C:\\Todolist2.xlsx' xla = Dispatch("Excel.Application") xla.DisplayAlerts = False xla.Visible = True xl = Dispatch("Excel.Application") xl.DisplayAlerts = False xl.Visible = True wb1=xla.Workbooks.Open(Filename=path1) wb2= xl.Workbooks.Open(Filename=path2) time.sleep(3) wbCloseA = xla.Workbooks.Close()
has comment: http://stackoverflow.com/comment/87039500
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87040032
answer count: 0

http://stackoverflow.com/comment/86943097
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49963298
has text: @abccd Err what makes you think that? Because they are both formatted like Leetcode solutions?
type: Comment

http://stackoverflow.com/a/49919394
type: Answer
has comment: http://stackoverflow.com/comment/86855801
has body: Try a left merge. To maintain index, you will need use reset_index before and set_index after the marge. res = df2.reset_index()\ .merge(df1, how='left')\ .set_index('index')\ .loc[:, ['a', 'b', 'c', 'd']] print(res) # a b c d # index # A 1 21 1.135899 5.5 # A 1 21 1.135899 3.3 # A 1 21 1.135899 2.1 # B 2 22 1.093204 0.8 # B 2 22 1.093204 0.5 # C 3 23 2.035373 1.3 # C 3 23 2.035373 6.5 # C 3 23 2.035373 7.1
has comment: http://stackoverflow.com/comment/86855073
score: 2
has comment: http://stackoverflow.com/comment/86855762
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49919217
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49919217

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/50015082
type: Tag
tags question: http://stackoverflow.com/q/49970453
tags question: http://stackoverflow.com/q/49933747

http://stackoverflow.com/a/50110600
has comment: http://stackoverflow.com/comment/87276874
has comment: http://stackoverflow.com/comment/87277811
has body: You can chose to search for only retweets or exclude all retweets from your search query. For searching for no retweets "-filter:retweets" for tweet in tweepy.Cursor(api.search, q='github -filter:retweets',tweet_mode='extended').items(5): For searching for only retweets "filter:retweets" for tweet in tweepy.Cursor(api.search, q='github filter:retweets',tweet_mode='extended').items(5): Extra Information: Whilst you can exclude retweets straight in the search query, it is also very easy to find if a tweet is a retweet because all retweets begin with "rt @UsernameOfAuthor". You can find if a tweet is a retweet by doing a basic if statement to see if the tweet begins with the rt. first make a basic query and save the information into variables. for tweet in tweepy.Cursor(api.search, q='github',tweet_mode='extended').items(5): # Defining Tweets Creators Name tweettext = str( tweet.full_text.lower().encode('ascii',errors='ignore')) #encoding to get rid of characters that may not be able to be displayed # Defining Tweets Id tweetid = tweet.id Then print the info for demonstration purposes # printing the text of the tweet print('tweet text: '+str(tweettext)) # printing the id of the tweet print('tweet id: '+str(tweetid)) Then there is the if statement to find if it is a retweet or not # checking if the tweet is a retweet (this method is basic but it will work) if tweettext.startswith("rt @") == True: print('This tweet is a retweet') else: print('This tweet is not retweet')
has comment: http://stackoverflow.com/comment/87348974
type: Answer
score: 11
upvote count: 11
accepted answer of: http://stackoverflow.com/q/50052330
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50052330
has comment: http://stackoverflow.com/comment/87288423

http://stackoverflow.com/q/49965263
has comment: http://stackoverflow.com/comment/86946942
has answer: http://stackoverflow.com/a/49965686
answer count: 1
favorite count: 0
has body: I am working on a assignment of detect hidden message in a PDF documents useing word-space shift method. In order to do that I need a python package that can help me to get the exactly space value between any word but I have not found any package. Anyone know any package can do that ? Thanks you. Example: Input: This_is__a_simple_sentence_with__no_meaning" Output: [1, 2, 1, 1, 1, 2, 1] For visual view, I assume each underscore present a space and each space equal 1. As you can see the total number of space between each word are not equal, some have more than one space between. What I try to archive here is output an array content only the total value of space between each words.
type: Question
has comment: http://stackoverflow.com/comment/86946521
tagged with: http://stackoverflow.com/tag/pdf
score: -2
has comment: http://stackoverflow.com/comment/86948722
has comment: http://stackoverflow.com/comment/86949911
has comment: http://stackoverflow.com/comment/86946898
has comment: http://stackoverflow.com/comment/86946487
has comment: http://stackoverflow.com/comment/86946390
upvote count: 0
downvote count: 2
tagged with: python
type: UnansweredQuestion
has title: Extract word-space from PDF documents

http://stackoverflow.com/q/50048877
has comment: http://stackoverflow.com/comment/87114077
has comment: http://stackoverflow.com/comment/87113920
tagged with: raku
has body: comb in Perl 6 is like a complement of split. Instead of choosing what to exclude from the results, you are choosing what to include. Is there a Python equivalent, and if so, what is it? So far, all of my searching for "Python comb" gives me results related to "combinations", not "the complement of split". Here is an example of it in Perl 6: #!/bin/env perl6 my $text = "5 foos, 16 bars, 7 bazes"; my @result = $text.comb(/\d+/); # \d matches numbers say @result.join(" "); # 5 16 7 Update based on feedback: comb is more like a complement of split than its "opposite".
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87155203
has comment: http://stackoverflow.com/comment/87146886
upvote count: 3
has answer: http://stackoverflow.com/a/50048924
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87113955
score: 3
accepted answer: http://stackoverflow.com/a/50048924
linked to: http://stackoverflow.com/q/21664367
has title: What is the Python equivalent of Perl 6's comb method?
has comment: http://stackoverflow.com/comment/87113939
tagged with: python
has comment: http://stackoverflow.com/comment/87155171

flat
tag name: flat
tags question: http://stackoverflow.com/q/49930650
type: Tag

deployment
tags question: http://stackoverflow.com/q/49953699
tag name: deployment
tags question: http://stackoverflow.com/q/50036298
type: Tag
tags question: http://stackoverflow.com/q/49967860

http://stackoverflow.com/comment/87034798
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50008894
has text: Any change your `loc` is 2-dimensional?

http://stackoverflow.com/comment/87031615
score: 0
type: AnswerComment
has text: @RashidAziz: ah, my apologies. I was using Python 3.7 and it contains a fix to handle the `:` in the `+00:00` timezone offset. In Python 3.6, only `+0000` is supported. I've updated the solution to avoid this problem altogether..
comment on: http://stackoverflow.com/a/49996177
type: Comment

http://stackoverflow.com/q/49970141
tagged with: image-processing
tagged with: linear-algebra
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
score: 5
possible better answer: http://stackoverflow.com/a/49980480
tagged with: tensor
downvote count: 0
tagged with: python
has body: I am trying to use the reshape command in numpy python to perform the unfold operation on a 3rd-rank/mode tensor. I'm not sure whether what I'm doing is correct. I found this paper online Tensor Decomposition. Also found this code: SVD Image Compression in which the author writes: Color images are represented in python as 3 dimensional numpy arrays — the third dimension to represent the color values (red,green blue). However, svd method is applicable to two dimensional matrices. So we have to find a way to convert the 3 dimensional array to 2 dimensional arrays, apply svd and reconstruct it back as a 3 dimensional array. There are two ways to do it. We will show both these methods below. reshape method Layer method Reshape method to compress a color image: This method involves flattening the third dimension of the image array into the second dimension using numpy’s reshape method . image_reshaped = image.reshape((original_shape[0],original_shape[1]*3)) I am trying to understand the reshape method. This looks to me like an unfold operation on a 3-rank/mode tensor. Lets say I have an array that is of size NxMxP, which mode would I be unfolding along if I used the following python command: reshape(N, M*P)? Here is the way I test the unfold operation: import cv2 import numpy as np def m_unfold(thrd_order_tensor,m): matrix = [] if m == 1: matrix = thrd_order_tensor.reshape((thrd_order_tensor.shape[0], thrd_order_tensor.shape[1]*3)) #matrix = np.hstack([thrd_order_tensor[:, :, i] for i in range(thrd_order_tensor.shape[2])]) if m == 2: matrix = thrd_order_tensor.reshape((thrd_order_tensor.shape[1], thrd_order_tensor.shape[0]*3)) #matrix = np.hstack([thrd_order_tensor[:, :, i].T for i in range(thrd_order_tensor.shape[2])]) if m == 3: matrix = thrd_order_tensor.reshape((3, thrd_order_tensor.shape[0]*thrd_order_tensor.shape[1])) #matrix = np.vstack([thrd_order_tensor[:, :, i].ravel() for i in range(thrd_order_tensor.shape[2])]) return matrix def fold(matrix, os): #os is the o…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50086319
has title: Using numpy reshape to perform 3rd rank tensor unfold operation
has answer: http://stackoverflow.com/a/50086319
upvote count: 5
has answer: http://stackoverflow.com/a/49980480

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/49976342

http://stackoverflow.com/comment/87152474
has text: http://matthiaseisen.com/pp/patterns/p0203/ have you looked at this? Try starting from these examples and modify them to your needs
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50067977
type: QuestionComment

http://stackoverflow.com/comment/87155550
comment on: http://stackoverflow.com/a/50069462
score: 1
type: Comment
has text: Worked a treat - thank you very much :) Will mark as answer when I can.
type: AnswerComment

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50048689
tags question: http://stackoverflow.com/q/49988412
tags question: http://stackoverflow.com/q/50026341
tags question: http://stackoverflow.com/q/49966396
tags question: http://stackoverflow.com/q/49943627
tags question: http://stackoverflow.com/q/49940522
tags question: http://stackoverflow.com/q/49990758
tags question: http://stackoverflow.com/q/50002754
tags question: http://stackoverflow.com/q/50040534
tags question: http://stackoverflow.com/q/50030000
type: Tag

http://stackoverflow.com/q/49968432
has body: Image of ull error I am trying to run LabelEncoder on all columns that are of type object. This is the code I wrote but it throws this error: TypeError: '&lt;' not supported between instances of 'int' and 'str' Does anybody know how to fix this? le=LabelEncoder() for col in X_test.columns.values: if X_test[col].dtypes=='object': data=X_train[col].append(X_test[col]) le.fit(data.values) X_train[col]=le.transform(X_train[col]) X_test[col]=le.transform(X_test[col])
answer count: 2
upvote count: 2
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49968574
tagged with: pandas
has comment: http://stackoverflow.com/comment/86952889
has title: Running sklearns label encoder on all columns at once
has answer: http://stackoverflow.com/a/49968573
tagged with: python
possible better answer: http://stackoverflow.com/a/49968573
has comment: http://stackoverflow.com/comment/86952791
accepted answer: http://stackoverflow.com/a/49968574
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/86952700

http://stackoverflow.com/comment/86982324
type: Comment
has text: Can you compare the execution plan of this method vs. the one proposed by OP? I suspect that, while this looks neater, it's actually doing the same thing under the hood.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49983088

http://stackoverflow.com/q/49949017
downvote count: 0
has title: Reverse bit in python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86914675
has comment: http://stackoverflow.com/comment/86914593
answer count: 2
possible better answer: http://stackoverflow.com/a/49949060
has body: Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). This does not work def reverseBits(self, n): return int(bin(n)[:1:-1], 2)
has answer: http://stackoverflow.com/a/49949152
accepted answer: http://stackoverflow.com/a/49949152
has answer: http://stackoverflow.com/a/49949060
tagged with: python
has comment: http://stackoverflow.com/comment/86914577
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86914605

http://stackoverflow.com/q/49927610
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86875367
answer count: 1
tagged with: arrays
has body: In my text files, every "\n\n" row seperates different simulation results, and I need them seperated. Is there a way to add another dimension to the matrix table in pandas? Or to pull numpy arrays in sections of every N rows (8 in my case)? Panda reading the data in: xPos yPos range otherData ... 0 -800.0 711.2 6100 73.56 1 -700.0 751.2 6100 73.56 2 -600.0 701.2 6100 73.56 3 -500.0 741.2 6100 73.56 4 -400.0 700.2 6100 73.56 5 -300.0 677.2 6100 73.56 6 -200.0 789.2 6100 73.56 7 -100.0 200.2 6100 73.56 # pandas cobines \n\n sections 8 -800.0 711.2 6100 73.56 9 -700.0 751.2 6100 73.56 10 -600.0 701.2 6100 73.56 11 -500.0 741.2 6100 73.56 12 -400.0 97.0 6100 73.56 13 -300.0 677.2 6100 73.56 14 -200.0 789.2 6100 73.56 15 -100.0 200.2 6100 73.56 16 -800.0 711.2 6100 73.56 17 -700.0 751.2 6100 73.56 18 -600.0 701.2 6100 73.56 19 -500.0 741.2 6100 73.56 20 -400.0 700.2 6100 73.56 21 -300.0 677.2 6100 73.56 22 -200.0 789.2 6100 73.56 23 -100.0 200.2 6100 73.56 If there is no easy read solution to what I am asking, then I what is the easiest way to make matrix arrays of each section? I need the easy access of pd_data['xPos'] for each simulation. I would like to access data like: # [sim run #] [row] [col] print(simRun[1][4][1]) # prints 97.0 in the example above run2 = 1 print(simRun[run2][len(run2)-1]['yPos'] # prints 200.2 in the example above Keep in mind, these text files can be huge with thousands of simulation results. Tyler, your code works well, but... (so close!) Here is the old "brute force" way I was doing it: fd = pd.read_csv(sys.argv[1],sep='\s{2,}',comment='#',engine='python') nSim = int(len(fd)/8) xRange = [] for x in range(nSim): xRange.append(fd['xPos'][x*8]) print(xRange) # This works for the time being. xPlot = np.array(xRange) The purpose is to grab the starting x &amp; y positions in each individual simulation runs so I can use it for plotting and other analysis. The first row of the chunks are the initial starting positions of each sim. Here is how I appl…
has title: Python Pandas File Parsing: Another matrix dimension for "\n\n" delimiter
has answer: http://stackoverflow.com/a/49929088
score: 0
tagged with: pandas
tagged with: python
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/86871489

http://stackoverflow.com/comment/86967834
type: Comment
comment on: http://stackoverflow.com/q/49963710
type: QuestionComment
score: 1
has text: @FrancescoB. I have not tried it yet! I am meeting soon to try and get the original dataset... see if they can look how they retrieved it and eliminate the space problem altogether. If not, I will proceed with the solution and let you know how it goes!

http://stackoverflow.com/a/55251027
has body: Well, i have a same problem as you. My solution was add the following commands in .bashrc: export IPOPT_HOME="/opt/CoinIpopt" export PATH="${PATH}:${IPOPT_HOME}/bin" export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${IPOPT_HOME}/lib" /opt/CoinIpopt is the path which the IpOpt was installed.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49988987
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49988987
upvote count: 1

stripe-payments
tags question: http://stackoverflow.com/q/49938029
tag name: stripe-payments
tags question: http://stackoverflow.com/q/49962296
type: Tag

http://stackoverflow.com/comment/88046436
comment on: http://stackoverflow.com/a/50493747
score: 0
type: AnswerComment
has text: The handler should also fire when the check goes from warning/critical/unknown back to ok right?
type: Comment

http://stackoverflow.com/a/50044449
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87108020
downvote count: 0
has comment: http://stackoverflow.com/comment/87108415
upvote count: 1
has body: Have you considered using composition instead of inheritance? It seems like it is much more suitable for this use case. See the bottom of the answer for details. Anyway, class C(A): ......... class C(B): ..... is not even valid, and will result with only class C(B) getting defined. I'm not sure a metaclass will be able to help you here. I believe the best way would be to use type but I'd love to be corrected. A solution using type (and probably misusing locals() but that's not the point here) class A: def __init__(self): print('Inherited from A') class B: def __init__(self): print('Inherited from B') class_to_inherit = input() # 'A' or 'B" C = type('C', (locals()[class_to_inherit],), {}) C() 'A' or 'B' &gt;&gt; A Inherited from A 'A' or 'B' &gt;&gt; B Inherited from B Composition Tracking back to the question in the beginning of my answer, you state yourself that the implementation of both "C(A)" and "C(B)" is identical and they don't actually care about A or B. It seems more correct to me to use composition. Then you can do something along the lines of: class A: pass class B: pass class C: def __init__(self, obj): # obj is either A or B instance, or A or B themselves self.obj = obj # or self.obj = obj() if obj is A or B themselves c = C(A()) # or c = C(A) In case C should expose the same API as A or B, C can overwrite __getattr__: class A: def foo(self): print('foo') class C: def __init__(self, obj): self.obj = obj def __getattr__(self, item): return getattr(self.obj, item) C(A()).foo() # foo
has comment: http://stackoverflow.com/comment/87107938
answers question: http://stackoverflow.com/q/50044254

http://stackoverflow.com/comment/87064184
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49976331
has text: You should pass a python counterpart of your `std::vector<int>`, the `VectorOfInt`. Something like `a = VectorOfInt([1,2]); b = VectorOfInt([1,2]); somefunction(a, b)` I believe.

http://stackoverflow.com/a/49936133
has body: You are almost at your goal, you just need to play around a bit: The enumerate method works as intended. When we enumerate an iterable python object, we get a 1-1 correlation between the object's elements and a "pointer" which ranges from 0 to len(iterable_object)-1. Have a look at this example from the documentations: &gt;&gt;&gt; seasons = ['Spring', 'Summer', 'Fall', 'Winter'] &gt;&gt;&gt; list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] Now one way to achieve what you are showing us here, would be to use the pointer generated from enumerate 2 times and split the contents of each test elements accordingly: np.random.seed(131) test1 = np.random.randint(50, size=(5, 2, 2)) contour_lst = [] row_lst = [] column_lst = [] for n, t_elem in enumerate(test1): # First square coordinates for this contour. contour_lst.append(n) row_lst.append(t_elem[0][0]) column_lst.append(t_elem[0][1]) # Second square coordinates for this contour. contour_lst.append(n) row_lst.append(t_elem[1][0]) column_lst.append(t_elem[1][1]) contours_df1 = pd.DataFrame({ 'contour': contour_lst, 'row': row_lst, 'column': column_lst, })
has comment: http://stackoverflow.com/comment/86903753
score: 1
answers question: http://stackoverflow.com/q/49930616
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86859757
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49921998
type: QuestionComment
has text: what is the problem with the code you posted?

http://stackoverflow.com/q/50072620
type: Question
has answer: http://stackoverflow.com/a/50072704
has comment: http://stackoverflow.com/comment/87161941
has body: class Weightcheck: def bag_products(self,product_list): bag_list = [] non_bag_items = [] MAX_BAG_WEIGHT = 5.0 for product in product_list: if float(product['weight']) &gt; MAX_BAG_WEIGHT: product_list.remove(product) non_bag_items.append(product) and argument product_list is like product_list = {'barcode': [123, 456], 'Name': ['Milk, 2 Litres', 'Bread'], 'Price': ['2', '3.5'], 'weight': ['2', '0.6']} if the passed arugument is like product_list = [{'name': 'Milk', 'price': 2.0, 'weight': 2.0}, {'name': 'LowfatMilk', 'price': 2.0, 'weight': 2.0}, {'name': 'HighfatMilk', 'price': 2.0, 'weight': 2.0}, {'name': 'Bread', 'price': 2.0, 'weight': 7.0}] then it works properly. i mean list of dictionary. please help how can i solve this
type: UnansweredQuestion
has title: Python dictionary value conversion to dictionary list
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50072673
downvote count: 2
answer count: 2
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50018595
type: AnsweredQuestion
score: 0
tagged with: matplotlib
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50018793
type: Question
tagged with: numpy
has title: python code for mathematics graph
has comment: http://stackoverflow.com/comment/87053539
has body: wrote some Python code to plot the coordinates of simple one dimensional linear mapping using matplotlib. There is no warnings and errors, but no coordinates are entered in graph. Can someone tell me what's wrong with my code? import matplotlib.pyplot as plt import numpy as np result = [10] result[0] = 1 a = 1.1 x = np.linspace(0, 10, 10) for i in range(len(result)-1): result[i+1] = a*(result[i] - 1/2) + 1/2 plt.plot(x, result[i], 'ro') plt.xlim(0, 10) plt.ylim(0, 10) plt.axhline(0, color='b', ls='-', lw=0.5) plt.axvline(0, color='b', ls='-', lw=0.5) plt.xlabel(r'$x$', fontsize=18) plt.ylabel(r'$x_{n+1}$', fontsize=18) plt.title(r'Graphs of $x_{n+1} = a(x_{n}-\frac{1}{2}) + \frac{1}{2}$', fontsize=20) plt.show()
accepted answer: http://stackoverflow.com/a/50018793

http://stackoverflow.com/comment/86915672
score: 0
comment on: http://stackoverflow.com/a/49949533
type: AnswerComment
has text: Right, but I am trying to do this for a generic response (I am scraping a web dictionary), so the method of inserting a static string won't work for me. Maybe I should clarify that in my post
type: Comment

http://stackoverflow.com/q/50002322
accepted answer: http://stackoverflow.com/a/50002783
tagged with: selenium
has comment: http://stackoverflow.com/comment/87021716
has body: I have a list of URLs that I need to iterate over. The process I am working on is that selenium opens each of the URLs in the list, clicks a button to open the form, and pass some strings into the form. I have gotten to the point of clicking the button to open the form. I can not pass in any strings into the form however using any of the elements. I get error 'Unable to locate element' This is my code so far, easily_apply is list of the URLs: for i in easily_apply: driver.get(i) test = driver.find_element_by_class_name('button') test.click() test.find_element_by_name("applicant.name") test.send_keys("John Smith") This is the HTML in question: &lt;input type="text" aria-describedby="label-input-applicant.name-error" aria-labelledby="label-input-applicant.name" id="input-applicant.name" name="applicant.name" class="icl-TextInput-control icl-TextInput-control--sm"&gt; Thank you in advance. edit: Code with xpath, not working, getting error 'Unable to locate elements': for i in easily_apply: driver.get(i) test = driver.find_element_by_class_name('indeed-apply-button') test.click() test.find_element_by_xpath('//input[@type="text"]') test.send_keys("John Smith") edit2: code with wait in it, still getting same error 'Unable to locate elements': for i in easily_apply: driver.get(i) test = driver.find_element_by_class_name('indeed-apply-button') test.click() wait = ui.WebDriverWait(driver,60) test.find_element_by_name('applicant.name') test.send_keys("John Smith")
has comment: http://stackoverflow.com/comment/87035528
type: Question
linked to: http://stackoverflow.com/q/7781792
has title: Selenium not identifying any element in particular HTML, why?
has answer: http://stackoverflow.com/a/50002783
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87021356
has answer: http://stackoverflow.com/a/50002453
possible better answer: http://stackoverflow.com/a/50002453
answer count: 3
has answer: http://stackoverflow.com/a/50004217

http://stackoverflow.com/comment/87170469
type: QuestionComment
has text: What are your imports?
comment on: http://stackoverflow.com/q/50072289
score: 0
type: Comment

http://stackoverflow.com/comment/87152819
score: 0
comment on: http://stackoverflow.com/q/50067957
type: Comment
type: QuestionComment
has text: @mathisfun You are a genius. I loved how simple and efficient this command is. Thank you so much!

http://stackoverflow.com/comment/89743356
type: AnswerComment
has text: When I press ctrl -> shift -> p and select 'MicroPython: Run', it says ampy isn't installed. When I tell it to install, it says it can't and I should 'check my internet connection'. When I type 'pip list' in terminal window, Windows says ampy is installed.
comment on: http://stackoverflow.com/a/51079224
type: Comment
score: 0

http://stackoverflow.com/a/49966000
score: 0
has body: To answer this question as rightly pointed out by cricket_007, I had to add in a host and port in my code. this was the cause of my issue
type: Answer
answers question: http://stackoverflow.com/q/49963872

http://stackoverflow.com/comment/86914575
comment on: http://stackoverflow.com/a/49947858
type: Comment
type: AnswerComment
has text: Please see [How should duplicate questions be handled?](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled)
score: 0

http://stackoverflow.com/comment/86995661
comment on: http://stackoverflow.com/q/49988950
has text: @ldavid I am getting the error above. I changed the loss function as suggested. Thank you!
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87153729
score: 0
has text: Yes, there was a subtle difference in the column names. Thanks.
type: QuestionComment
comment on: http://stackoverflow.com/q/50066510
type: Comment

http://stackoverflow.com/a/49943548
has comment: http://stackoverflow.com/comment/86907904
has comment: http://stackoverflow.com/comment/86907782
has body: Threads are suitable for this. Nothing runs exactly simultaneously on a multi user system anyway. import threading from time import sleep class Game: def __init__(self): self.loading_screen() def loading_screen(self): t = threading.Thread(target=self.load_assets) t.daemon = True t.start() while t.isAlive(): sleep(0.1) print("loading screen") print ("assets done, ready to proceed now") def load_assets(self): i = 0 while i &lt; 10: print("loading assets") i += 1 sleep(1) g = Game() print("done") This puts your asset loading to a thread and then enters loading_screen() in the main thread. This just prints messages to demonstrate they both run in parallel.
has comment: http://stackoverflow.com/comment/86905633
score: 0
has comment: http://stackoverflow.com/comment/86907852
answers question: http://stackoverflow.com/q/49943309
has comment: http://stackoverflow.com/comment/86907885
has comment: http://stackoverflow.com/comment/86906876
has comment: http://stackoverflow.com/comment/86906606
has comment: http://stackoverflow.com/comment/86903940
has comment: http://stackoverflow.com/comment/86907020
type: Answer

http://stackoverflow.com/comment/87102941
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50043393
has text: so why not `return num1 + sum(args)` ?

http://stackoverflow.com/comment/86937159
score: 1
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/3750118/sqlalchemy-0-5-8-max-function, https://stackoverflow.com/questions/11830980/sqlalchemy-simple-example-of-sum-average-min-max
comment on: http://stackoverflow.com/q/49958396

http://stackoverflow.com/q/49960582
tagged with: python
has title: What is the best way to write large xml file from mongodb document?
downvote count: 0
upvote count: 1
score: 1
tagged with: mako
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: python-3.x
has body: My task is basically simple. I want to make a query (which returns about 50k document) and with those results I want to write an xml document. I have a desired template on which I want my fields to put. I have used Mako already, which is pretty pretty slow. So basically I am here for a fast alternative/approach. My attempt is below: from pymongo import MongoClient from mako.template import Template from mako.runtime import Context temp = '''&lt;jobs&gt; % for i in data: &lt;job&gt; &lt;city&gt;${i['city']}&lt;/city&gt; &lt;created_at&gt;${i['created_at']}&lt;/created_at&gt; &lt;description&gt; ${i['description']} &lt;/description&gt; &lt;/job&gt; % endfor &lt;/jobs&gt;''' client = MongoClient("") result = client.db.col.find({'field': 'value'}) tpl = Template(temp) with open('output.xml', 'w') as f: ctx = Context(f, data=result) tpl.render_context(ctx)
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/87184413
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50020768
has text: @GrahamDumpleton, I tried using "attempt 2" (with the `python-home` directive), and adding `WSGIApplicationGroup %{GLOBAL}`. The result is still "Script timed out before returning headers: wsgi.py"... Any other ideas? Is there a way to troubleshoot/debug these settings in a controlled manner, so I can see exactly what fails?

http://stackoverflow.com/comment/86993448
has text: No I want to store the actual file in mongodb
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49988186

http://stackoverflow.com/a/50045057
type: Answer
has comment: http://stackoverflow.com/comment/87471402
has body: (Disclaimer: I am the author of calmjs) After mulling over this particular issue for another few days, this question actually encapsulates multiple problems which may or may not be orthogonal to each other depending on one's given point of view, given some of the following (the list is not exhaustive) How can a developer ensure that they have all the information required to install the package when given one. How does a project ensure that the ground they are standing on is solid (i.e. has all the dependencies required). How easy is it for the user to install the given project. How easy is it to reproduce a given build. For a single language, single platform project, the first question posed is trivially answered - just use whatever package management solution implemented for that language (i.e. Python - PyPI, Node.js - npm). The other questions generally fall into place. For a multi-language, multi-platform, this is where it completely falls apart. Long story short, this is why projects generally have multiple sets of instructions for whatever version of Windows, Mac or Linux (of various mainstream distros) for the installation of their software, especially in binary form, to address the third question so that it's easy for the end user (which usually end up being doable, but not necessarily easy). For developers and system integrators, who are definitely more interested in questions 2 and 4, they likely want an automation script for whatever platform they are on. This is kind of what you already got, except it only works on Linux, or wherever Bash is available. Now this also begs the question: How does one ensure Bash is available on the system? Some system administrators may prefer some other form of shell, so we are again back to the same problem, but instead of asking if Node.js is there, we have to ask if Bash is there. So this problem is basically unsolvable unless a line is drawn. The first question hasn't really been mentioned yet, and I am going to make th…
has comment: http://stackoverflow.com/comment/87166668
downvote count: 0
score: 9
answers question: http://stackoverflow.com/q/49953785
has comment: http://stackoverflow.com/comment/87168899
upvote count: 9

http://stackoverflow.com/comment/86997916
has text: Trace it with debug or add `print(type(___)) `you will find the solution
comment on: http://stackoverflow.com/q/49988568
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/67925151
has body: Why not successively take the Square of the candidate, after initially extracting the exponent component? When the square results in a number greater than 2, divide by two, and set the bit in the mantissa of your result that corresponds to the iteration. This is a much quicker and simpler way of determining log base 2, which can then in a single multiplication, be transformed to the e or 10 base.
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49994216
type: Answer

http://stackoverflow.com/q/49991416
has comment: http://stackoverflow.com/comment/87031489
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87012778
tagged with: python
has comment: http://stackoverflow.com/comment/87032256
has comment: http://stackoverflow.com/comment/87022693
has comment: http://stackoverflow.com/comment/87021698
has comment: http://stackoverflow.com/comment/87034860
score: 2
has body: I think this got foobarred when I was doing some brew update stuff. Everytime my system python3 is called, it emits: Error in sitecustomize; set PYTHONVERBOSE for traceback: KeyError: 'PYTHONPATH' This is particularly annoying because I use powerline in my terminal and powerline makes several calls to python each time I execute a command. Calling Python3 with a the Verbose flag I get: $ PYTHONVERBOSE=True python3 &lt;multiple pages of python startup info...&gt; # possible namespace for /usr/local/lib/python2.7/site-packages/backports # bytecode is stale for 'sitecustomize' # code object from /usr/local/lib/python2.7/site-packages/sitecustomize.py Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 481, in execsitecustomize import sitecustomize File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 950, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 655, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 205, in _call_with_frames_removed File "/usr/local/lib/python2.7/site-packages/sitecustomize.py", line 15, in &lt;module&gt; str(sys.version_info[0]) + '.x!\n PYTHONPATH is currently: "' + str(os.environ['PYTHONPATH']) + '"\n' + File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'PYTHONPATH' # destroy sitecustomize import 'site' # &lt;_frozen_importlib_external.SourceFileLoader object at 0x101e3a630&gt; &lt;more python startup info...&gt; So the system Python3 is trying to load the Python2 version of sitecustomize? I suspect that's the problem. If so, what are my options for fixing this? brew unlink python3 &amp;&amp; brew link python3 didn't help. I'm not sure what the bytecode is stale for 'sitecustomize' comment python is…
has comment: http://stackoverflow.com/comment/87023385
answer count: 0
has title: "KeyError: 'PYTHONPATH'". Sites.py broken in python3?
downvote count: 0
has comment: http://stackoverflow.com/comment/87002137
tagged with: site-packages
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87033720
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87034890
has comment: http://stackoverflow.com/comment/87021623
upvote count: 2
has comment: http://stackoverflow.com/comment/86999587

http://stackoverflow.com/q/50008833
has body: I have an array with elements, and I want to sum up the accuracy. I want to sum the arrays that have the elements in the same order. I rather not be writing a for loop going through each element with zip and summing them up, is there an easier way to do this? The two arrays are as follows, and currently my code is below for calculating the sum. yp = [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] y = [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]] sums = np.sum(yp == y) I am getting an accuracy of zero.
answer count: 1
has comment: http://stackoverflow.com/comment/87034300
has comment: http://stackoverflow.com/comment/87034762
has comment: http://stackoverflow.com/comment/87034298
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87034414
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87034258
has comment: http://stackoverflow.com/comment/87034377
has answer: http://stackoverflow.com/a/50010049
has comment: http://stackoverflow.com/comment/87034364
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87034691
has comment: http://stackoverflow.com/comment/87034309
has comment: http://stackoverflow.com/comment/87034786
has comment: http://stackoverflow.com/comment/87034502
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87034873
has comment: http://stackoverflow.com/comment/87034767
upvote count: 0
has comment: http://stackoverflow.com/comment/87034442
has title: Sum up indentical list elements
linked to: http://stackoverflow.com/q/25490641

http://stackoverflow.com/comment/86915293
has text: Sorry - just now I saw you have the "python 2.7" tag there. The only thng that should change above however is how to make use of the metaclass, (and te metaclass "kw" attributes will be useless, I'd guess) ; Anyway, it makes little sense to research advanced Python features in python 2 these day's, I'd suggest you to update to 3.6 .
type: AnswerComment
comment on: http://stackoverflow.com/a/49948873
score: 1
type: Comment

http://stackoverflow.com/comment/86859997
comment on: http://stackoverflow.com/q/49922004
type: Comment
type: QuestionComment
has text: python is cpython ... Do you mean cython?
score: 1

http://stackoverflow.com/comment/87096802
type: Comment
type: AnswerComment
has text: I now have: 'logits, out_layer = multilayer_perceptron(x, weights, biases)' and `cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y))` But I am still getting zero loss
comment on: http://stackoverflow.com/a/50039953
score: 0

tflearn
tags question: http://stackoverflow.com/q/49927619
tags question: http://stackoverflow.com/q/50028940
tags question: http://stackoverflow.com/q/50040428
type: Tag
tag name: tflearn

traitsui
tag name: traitsui
type: Tag
tags question: http://stackoverflow.com/q/49964466

http://stackoverflow.com/comment/87047310
type: Comment
type: AnswerComment
has text: if i remove it i wont be able to add a new student information then
comment on: http://stackoverflow.com/a/50014969
score: 0

http://stackoverflow.com/q/50027047
has body: I have a data frame of provinces and average finish times in a race for people from each province. I would like to query the dataset for the name of the province with the lowest average time. My data frame looks like this:
has answer: http://stackoverflow.com/a/50027184
has answer: http://stackoverflow.com/a/50027292
tagged with: dataframe
tagged with: python
has title: How to query a pandas dataframe for a specific attribute
answer count: 3
upvote count: 2
tagged with: pandas
score: 2
possible better answer: http://stackoverflow.com/a/50027238
downvote count: 0
has answer: http://stackoverflow.com/a/50027238
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50027184
has comment: http://stackoverflow.com/comment/87481876

http://stackoverflow.com/comment/87104005
has text: It is recommended to use cffi instead of ctypes. cffi is much more convenient.https://cffi.readthedocs.io/en/latest/overview.html A while ago I was also using ctypes, but people recommended to switch. And they were right, I would never tough ctypes again. :)
comment on: http://stackoverflow.com/q/50043861
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50030845
type: Answer
has comment: http://stackoverflow.com/comment/87081626
has body: If by "more efficient", you mean "might be correct", then yes. Your current code doesn't work for all inputs. With that SQR "wild-card", you cannot trivially know whether the operation you're looking at is beneficial. For instance LDI 1 ADD -8 LDI 2 ADD -1 ADD 3 SQR The maximum value comes from (-8 + -1)^2. You should use dynamic programming (see the link provided in the first comment) to keep track of all "best possible" results at each step. You classically program this with a recursive routine that tries two branches as it considers each instruction: use / don't use that instruction in the final answer. Then you recur with the current value of X and the remaining instruction list. If you want to do data-flow analysis, you can apply various short-cuts. For instance, in any stream of ADD instructions, you can combine all negative and all positive values into a single ADD. When you have a LDI, you consider whether the new value is greater in both true and absolute value -- the latter being what drives an improvement through SQR. Frankly, I recommend doing the bisect-recur-dynamic_programming route. UPDATE I gave this more thought. Although DP is the way to go for large problems, this is not what you'll want to attack first (in my opinion). Rather, attack the problem of whether or not to include each particular command. You will need to do both, until further refinement. You can't even guarantee that you want to include the SQR command: a subsequent subtraction can make it undesirable. The logic of the recursion is something like this: def optimize(x_reg, command_list): # x_reg current value of the X register # command_list remaining list of commands # base case if len(command_list) == 0 return x_reg # recursion case op = command_list[0][0] if op == "ADD": new_x = x_reg + command_list[0][1] elif op == "LDI": new_x = command_list[0][1] else: # op == "SQR": new_x = x_reg * x_reg with_op = optimize(new_x, command_list[1:]) # Use the command sans_op = optimize(x_reg, com…
upvote count: 1
has comment: http://stackoverflow.com/comment/87081347
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/50030521
answers question: http://stackoverflow.com/q/50030521
has comment: http://stackoverflow.com/comment/87081574
has comment: http://stackoverflow.com/comment/87081437

http://stackoverflow.com/comment/87111009
type: QuestionComment
type: Comment
has text: Sorry, @Josh I'm on MacOS 10.11. I'll update my post
score: 0
comment on: http://stackoverflow.com/q/50047105

http://stackoverflow.com/q/49966065
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86952950
has answer: http://stackoverflow.com/a/50096235
has comment: http://stackoverflow.com/comment/87138224
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87138196
has comment: http://stackoverflow.com/comment/87138051
score: 2
has comment: http://stackoverflow.com/comment/87186211
linked to: http://stackoverflow.com/q/37972778
tagged with: many-to-many
has title: SQLAlchemy Self-Referential Many to Many Symmetric Relationship
tagged with: sql
answer count: 1
tagged with: python
has body: I am using python 2.7 with SQLAlchemy, and trying to model a friendship relation with a many to many relationship. I need the table to be completely symmetric; if A is B's friend, then it must be the other way around also. I've tried to model the relationship with secondary friendship table, and connect it to the model using primary- and secondaryjoin, but I'm starting to get the feeling that I'm going in the wrong direction. I found this post where someone tried to model the same thing using a one to many relationship, but this does not work for me, because my friendship relationship is not a one to many. I have managed to achieve a working model using many to many table, if I am kipping a "duplicate": when I want to add B as A's friend, I add A as B's friend too. But I feel that the proposed solution should be more neat. The end game here is similar to Facebook's friendship modeling. A can only be B's friend if B is A's friend.
tagged with: sqlalchemy

http://stackoverflow.com/comment/87164414
has text: @Delgan I wonder when Debian will move to Python3. I doubt Python 2 will disappear soon.
type: QuestionComment
comment on: http://stackoverflow.com/q/50074014
score: 0
type: Comment

http://stackoverflow.com/a/49964816
has body: Like C: cdef float z[100][100] For more detail please refer to this link.
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86945758
type: Answer
answers question: http://stackoverflow.com/q/49964757
score: 2
has comment: http://stackoverflow.com/comment/86945839

http://stackoverflow.com/comment/86946053
score: 2
comment on: http://stackoverflow.com/q/49964093
has text: Possible duplicate of [Python pip3 - cannot import name 'main'](https://stackoverflow.com/questions/49836676/python-pip3-cannot-import-name-main)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87136764
comment on: http://stackoverflow.com/a/50059676
score: 1
type: Comment
type: AnswerComment
has text: It didn't work, because the cursor object is not iterable in the jayDeBeeApi implementation

http://stackoverflow.com/q/50009978
downvote count: 0
linked to: http://stackoverflow.com/q/4484167
answer count: 1
has title: Numpy: garbage collection after slicing
has comment: http://stackoverflow.com/comment/87036972
favorite count: 0
type: Question
tagged with: numpy
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/50010239
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/87036721
tagged with: memory-leaks
tagged with: garbage-collection
tagged with: python
has comment: http://stackoverflow.com/comment/87036634
has comment: http://stackoverflow.com/comment/87036663
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50010239
has body: def foo(): x = np.ones((10,10)) return x[:5,:5] If I call y = foo() I'll get a 5x5 array (1/4 of the values in x). But what happens to the other values in x, do they persist in memory or get garbage collected in some way? I'd like to understand this.

http://stackoverflow.com/a/51086120
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49989579
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89162649
has body: this worked for me: import dataset import pandas db = dataset.connect('sqlite:///db.sqlite3') data = list(db['my_table'].all()) dataframe = pandas.DataFrame(data=data)
type: Answer
accepted answer of: http://stackoverflow.com/q/49989579

http://stackoverflow.com/comment/87107669
has text: Did you try the other solutions without super user?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50042715
score: 0

http://stackoverflow.com/comment/87270442
has text: I have posted a new question as in: https://stackoverflow.com/questions/50126232/fastest-way-of-counting-all-possibilities-of-going-through-a-dependency-graph , I have never referenced a previous post on this site and couldn't reference your name correctly, please suggest modifications to the new post! Thank you
comment on: http://stackoverflow.com/a/49957216
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50068826
has title: summarize the previous rows with conditions, python
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50071107
tagged with: summarize
has body: I am new in python. I have a question about how to summarize the previous rows. The dataset is: df=pd.DataFrame({'ID':[1,1,1,1,2,2,2,2],'reason':['B','A','B','A','A','A','B','A'],'result':['W','W','Z','X','X','W','Z','W']}) ID reason result 0 1 B W 1 1 A W 2 1 B Z 3 1 A X 4 2 A X 5 2 A W 6 2 B Z 7 2 A W I want to summarize the history data (previous rows) of reason with the same ID. And I also want to summarize the history data of result with reason A. The results should look like: ID reason result Previous_reason Previous_result_reasonA 0 1 B W 1 1 A W B 2 1 B Z B|A W 3 1 A X B|A|B W 4 2 A X 5 2 A W A X 6 2 B Z A|A X|W 7 2 A W A|A|B X|W Thank you in advance.
tagged with: conditional-statements
score: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49944795
type: Answer
has body: You have to use scrapy.Request for that: class PaginationTestSpider(scrapy.Spider): name = 'pagination' start_urls = ['http://esencjablog.pl/page/58'] def parse(self, response): # Find href from next page link link = response.css('.post_more a.qbutton::attr(href)') if link: # Extract href, in this case we can use first because you only need 1 href = link.extract_first() # just in case the website use relative hrefs url = response.urljoin(href) # You may change the callback if you want to use a different method yield scrapy.Request(url, callback=self.parse) You can find more details in the scrapy documentation
score: 0
answers question: http://stackoverflow.com/q/49944582

http://stackoverflow.com/comment/87022040
has text: This is exactly what I was looking for thank you so much Satish!
comment on: http://stackoverflow.com/a/50002783
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/50006876
score: 1
type: AcceptedAnswer
has body: Whole idea of futures is that you can await for it just like for coroutines, tasks, etc. class class_B: async def co_B(self): # execute time consuming code # wait for result from co_A result = await class_A_instance.fut # execute more time consuming code See section "Things a coroutine can do" here.
has comment: http://stackoverflow.com/comment/87072250
has comment: http://stackoverflow.com/comment/87030855
accepted answer of: http://stackoverflow.com/q/50005974
type: Answer
answers question: http://stackoverflow.com/q/50005974
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87159447
score: 0
comment on: http://stackoverflow.com/q/50068957
type: Comment
type: QuestionComment
has text: I have removed the multiprocessing bit and tried the loop without it. I am half way through the second loop, and still generating new results.

http://stackoverflow.com/a/50021660
has comment: http://stackoverflow.com/comment/87059760
has body: from flask import Flask from flask_db2 import DB2 app = Flask(__name__) app.config['DB2_DATABASE'] = 'sample' app.config['DB2_HOSTNAME'] = 'localhost' app.config['DB2_PORT'] = 50000 app.config['DB2_PROTOCOL'] = 'TCPIP' app.config['DB2_USER'] = 'db2inst1' app.config['DB2_PASSWORD'] = 'db2inst1' db = DB2(app) #You forgot that @app.route('/') def index(): cur = db.connection.cursor() cur.execute(...) First: You forgot to have an object to use the flask db2 module. The DB2(app) is a constructor for your Flask extension and will bind your application to this module. where as db = DB2(app) Initialises your db object with help of your extension's constructor which you can further use for your Database operations. Secondly: use app configs to play with DB2 credentials. (This step should be done before you bind the app) Third: You can execute your query like this cur.execute("SELECT id FROM users") #something like that I hope I have clarified :D just drop message. Ill try helping more.
has comment: http://stackoverflow.com/comment/87060749
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87430261
has comment: http://stackoverflow.com/comment/87091539
answers question: http://stackoverflow.com/q/50021538
score: 1
accepted answer of: http://stackoverflow.com/q/50021538
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87433824
has comment: http://stackoverflow.com/comment/87063691

http://stackoverflow.com/q/50011561
score: -2
has comment: http://stackoverflow.com/comment/87039924
tagged with: python
tagged with: protected
tagged with: class
tagged with: c++
has answer: http://stackoverflow.com/a/50011714
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87039629
tagged with: inheritance
has body: Before doing a C++ class, I decided to first do it in Python. There were good sources to do the Python class but I couldn't find useful sources for C++. Python code: class Human: def __init__(self, first, last, age, sex): self.firstname = first self.lastname = last self.age = age self.sex = sex ... class Student(Human): def __init__(self, first, last, age, sex, school, semester): super().__init__(first, last, age, sex) self.school = school self.semester = semester ... C++ code: class Human { protected: string name; string lastname; int age; string sex; public: Human(string name, string lastname, int age, string sex): name(name), lastname(lastname), age(age), sex(sex){ } ~Human(); }; class Student: protected Human{ public: string school; int semester; //Student(string school, int semester); ~Student(); }; how can I do the same thing in my C++ code?
favorite count: 0
accepted answer: http://stackoverflow.com/a/50011714
type: Question
has comment: http://stackoverflow.com/comment/87041473
has title: Python class inheritance to c++

http://stackoverflow.com/q/50010717
type: UnansweredQuestion
tagged with: ndimage
tagged with: python
score: 4
upvote count: 4
has body: I think I understand the working of ndimage.generic_filter but I don't understand what happens when you throw in an array with more than 2 dimensions (like [[R],[G],[B]] values from an image) Given the following code: import numpy as np from scipy.ndimage import generic_filter a = np.arange(36).reshape(3,3,4) def fnc(buffer): return np.min(buffer) footprint = [ [[1, 1], [1, 1]], [[1, 1], [1, 1]], [[1, 1], [1, 1]] ] generic_filter(a, fnc, footprint = footprint) The output is: array([[ [ 0, 0, 1, 2], [ 0, 0, 1, 2], [ 4, 4, 5, 6] ],[ [ 0, 0, 1, 2], [ 0, 0, 1, 2], [ 4, 4, 5, 6] ],[ [12, 12, 13, 14], [12, 12, 13, 14], [16, 16, 17, 18] ]]) It seems to me here that the first array is duplicated at the cost of the last entered array which I can't see the logic of. Would this be intentional behaviour or am I not supposed to use generic_filter like this?
has title: How does ndimage.generic_filter() work with multidimensional arrays
answer count: 0
downvote count: 0
tagged with: scipy
favorite count: 0
type: Question

http://stackoverflow.com/comment/87045003
type: Comment
type: QuestionComment
has text: If I presume correctly that your code is producing a results that are close to the expected one, you do not have a programming issue, but a numerics one. This is something that is more fitting for [scicomp.se]. However, if you ask there, please elaborate: What do you expect and why? What actual values do you obtain?
comment on: http://stackoverflow.com/q/50013988
score: 2

http://stackoverflow.com/q/50040717
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/69950045
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69950045
score: 3
has answer: http://stackoverflow.com/a/71846605
answer count: 3
tagged with: google-cloud-platform
upvote count: 3
favorite count: 0
type: Question
tagged with: command-line
accepted answer: http://stackoverflow.com/a/50040718
has body: Airflow allows us to add connection information via command-line airflow connections. This can help with automated deployment of airflow installations via ansible or other dev-ops tools. It is unclear how connections to google cloud platform (service accounts) can be added to ariflow via command line.
has title: Add GCP credentials to airflow via command line
has answer: http://stackoverflow.com/a/50040718
tagged with: airflow

http://stackoverflow.com/a/49951897
has body: How about this regex? [^\w\s]|(.)(?=\1(?&lt;![^o]oo|[^e]ee)) Demo
type: Answer
answers question: http://stackoverflow.com/q/49951850
score: 0
accepted answer of: http://stackoverflow.com/q/49951850
type: AcceptedAnswer

http://stackoverflow.com/a/50055736
has body: You can check the requirement of groups param at the documentation of GroupShuffleSplit: groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. The length of groups should be equal to the number of samples, with each value indicating the group label its a part of. The output of this line: groups = df_train.groupby(df_train['date_posted'].dt.year).groups is a dict where key is the group label and value is the indices of rows belonging to that column. But this is not what scikit-learn expects. For example, for this data: Index A B #Columns 0 0 2 1 3 1 2 0 0 3 0 0 4 0 2 If you want the first three rows to belong to group1 and last two columns to belong to group2, then you need to pass the groups as: groups=['group1','group1','group1','group2','group2'] or groups=[0, 0, 0, 1, 1] Observe that here, total values are 5, corresponding to the rows in my data, and each value represent the group the row at that index belongs to. So in your case, you can convert the returned dict to a list by using the below code: import numpy as np groups_proper = np.zeros(len(df_train)) for val in groups.iteritems(): for index in val[1].tolist(): groups_proper[index]=val[0] And then pass it: cv = GroupShuffleSplit().split(X, y, groups=groups_proper)
type: Answer
answers question: http://stackoverflow.com/q/50045558
score: 0
accepted answer of: http://stackoverflow.com/q/50045558
type: AcceptedAnswer

http://stackoverflow.com/comment/86970368
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49974393
type: AnswerComment
has text: I can't reproduce the error with the updated code. The error `\'year like \'*\'select * from image where " + " and day like \'*\'select * from image\'` means you concatenate `select * from image` multiple times. Try to print the sql before execute it.

http://stackoverflow.com/a/49988484
has body: This line seems wrong: super(UpdateProfile, self).__init__(commit) You're calling __init__ from the parent class, but the method being called is save()... Also you're refering to a user variable which is (hopefully) not defined in this scope.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49988421

http://stackoverflow.com/q/50028127
tagged with: keras
has body: I looked into different cases but could not understand what I have to choose. My code is also working but my prediction looks strange only having 2 parallel lines. I have an LSTM Autoencoder for regression of time series. Autoencoder because I need to reduce the dimensions. Mydata looks like: 400 samples with each of them containing 5.000 rows.I concatenated them into an array. (Between the samples in real I have 5 minutes). How do I have to choose time steps for the model ? is it like (400,10,5000) ?can anyone please give me an advise with an example also in regarding to the batchsize?
type: Question
has title: lstm autoencoder time series data input shape
tagged with: python
accepted answer: http://stackoverflow.com/a/50028462
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50028462
answer count: 1

http://stackoverflow.com/q/50042242
tagged with: typeerror
has answer: http://stackoverflow.com/a/50042393
possible better answer: http://stackoverflow.com/a/50042393
accepted answer: http://stackoverflow.com/a/50042327
linked to: http://stackoverflow.com/q/47045669
score: 7
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/137251397
has answer: http://stackoverflow.com/a/50042410
type: AnsweredQuestion
has body: I'm trying to map a function that takes 2 arguments to a list: my_func = lambda index, value: value.upper() if index % 2 else value.lower() import string alphabet = string.ascii_lowercase n = map(my_func, enumerate(alphabet)) for element in n: print(element) This gives me a TypeError: &lt;lambda&gt;() missing 1 required positional argument: 'value'. What is the correct way to map my lambda onto this input?
answer count: 3
has comment: http://stackoverflow.com/comment/87100349
has answer: http://stackoverflow.com/a/50042327
downvote count: 0
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/87100596
type: Question
tagged with: python-3.x
has title: Using a function with multiple parameters with `map`
has comment: http://stackoverflow.com/comment/87481739

http://stackoverflow.com/comment/104706707
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50059693
has text: Did you find a way to fix this
type: Comment

http://stackoverflow.com/a/49982002
answers question: http://stackoverflow.com/q/49955964
score: 1
downvote count: 0
upvote count: 1
has body: For windows you can use the select class to filter a list of socket connections into 3 lists, sockets that are ready to ready, sockets that are ready to write, and sockets that have errors. Here is a basic implementation for a p2p socket connection (not class based). import socket, select, time s = socket.socket() s.bind(("10.48.72.71", 8080)) s.listen(10) connections = [s] while True: time.sleep(.1) recv,write,err = select.select(connections,connections,connections) for socket in recv: if socket == s: client,address = socket.accept() connections.append(client) else: msg = socket.recv(4096).decode("UTF-8") print("Recieved message from a socket, message was: "+str(msg)) for socket in write: socket.send(bytes("Hi", "UTF-8")) for socket in err: print("Error with a socket") socket.close() connections.remove(socket)
type: Answer
has comment: http://stackoverflow.com/comment/86981615

http://stackoverflow.com/a/50016794
downvote count: 0
answers question: http://stackoverflow.com/q/50016604
type: Answer
has body: You can delay name resolution by putting it into a lambda: class A: @staticmethod def __meth(x): pass def func(self, method = lambda s: A.__meth(s)): pass
score: 2
upvote count: 2

http://stackoverflow.com/comment/87022555
comment on: http://stackoverflow.com/a/49997219
score: 0
type: Comment
has text: More related info on this can be found in a similar question of mine https://stackoverflow.com/questions/49942487/python-for-net-how-to-explicitly-create-instances-of-c-sharp-classes-per-assem
type: AnswerComment

http://stackoverflow.com/q/50005941
has comment: http://stackoverflow.com/comment/87028314
score: 0
has comment: http://stackoverflow.com/comment/87029057
tagged with: python-requests
has comment: http://stackoverflow.com/comment/87028772
has comment: http://stackoverflow.com/comment/87028565
has body: I was wondering what causes the below error is it the site the data is being sent to or an issue with the script? I'm sending the following POST request: import requests session = requests.session() url = "private url" headers = {"Content-Type": "Application/json"} session.headers.update(headers) payload = {"test": "test", "quantity": 1} output = session.post(url, data=payload) print(output.text) Output: {"_v":"14.6","fault":{"type":"InvalidMessageException","message":"An error occurred while decoding the request, the body was 'test=test&amp;quantity=1'."}
has comment: http://stackoverflow.com/comment/87029119
has comment: http://stackoverflow.com/comment/87029259
type: Question
has comment: http://stackoverflow.com/comment/87028460
answer count: 0
has comment: http://stackoverflow.com/comment/87029038
has comment: http://stackoverflow.com/comment/87028379
tagged with: python
has title: Python, requests failed to decode the data?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87029466
has comment: http://stackoverflow.com/comment/87029368
has comment: http://stackoverflow.com/comment/87029407

http://stackoverflow.com/comment/87152416
has text: @abarnert I tried multiple things of everything. should I post all of it? I am new to matplotlib... so I messed with many things. E.g I commented out plt.add_patch(rect). But I tried tons of other things. adding subplots.. etc.
type: Comment
comment on: http://stackoverflow.com/q/50067977
score: 0
type: QuestionComment

http://stackoverflow.com/q/50045617
has title: yaml.load, force dict keys to strings
upvote count: 6
score: 6
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/50048075
has body: In Python3 I am loading a piece of YAML. The loader tries to guess the right types but I'm not quite satisfied. I want dict keys always to be strings. First a minimalistic piece of YAML to demonstrate, easy to paste directly into your python interpreter. Needless to say my real world data is far more complex. txt = """ --- one: 1 2: two """ First the "regular" load: yaml.load(txt) {2: 'two', 'one': 1} Notice how the key 2 got loaded as a number and not as a string. Then lets try something different: yaml.load(txt, Loader=yaml.BaseLoader) {'2': 'two', 'one': '1'} Now everything is made as strings. Unfortunately also 1, which, as a value, I need as a number. So I can can either have both keys and values forced to strings, or none. I can of course make a post-processor that traverses through the loaded data and copies it to a new variable, with dict keys forced to strings, but I imagine it could be done more elegant within the YAML loader. Suggestions?
possible better answer: http://stackoverflow.com/a/73359840
favorite count: 0
has answer: http://stackoverflow.com/a/50048075
tagged with: python-3.x
has answer: http://stackoverflow.com/a/73359840
type: Question
tagged with: yaml
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/87126703
has text: If an event is ABC will the next event always be DEF?
score: 0
comment on: http://stackoverflow.com/q/50055065
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49938731
has comment: http://stackoverflow.com/comment/86895860
has title: How can increment a sequence only once on a bulk insert?
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/49940360
type: Question
tagged with: postgresql
has comment: http://stackoverflow.com/comment/86895502
tagged with: python
has body: Given a model like this: class MyModel(Base): __tablename__ = 'my_model' id = Column(Integer, nullable=False, primary_key=True, index=True) value = Column(Numeric, doc='value') batch = Column(Integer, Sequence('my_model_batch_seq'), doc='Batch ID of the update') I want to issue a batch insert that adds all the new objects with the same batch ID. The code below increments for each object which is not what I'm looking for. objects = [ MyModel( value=x, ) for x in range(10) ] db.bulk_save_objects(objects)
has answer: http://stackoverflow.com/a/49940360
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86895915
answer count: 1

http://stackoverflow.com/q/49948581
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86938475
answer count: 1
has comment: http://stackoverflow.com/comment/86914500
has comment: http://stackoverflow.com/comment/86913932
has comment: http://stackoverflow.com/comment/86960928
has comment: http://stackoverflow.com/comment/86960314
type: Question
has comment: http://stackoverflow.com/comment/86914553
type: UnansweredQuestion
tagged with: python
has body: Say I have a call to matplotlib.pyplot.plt that looks like this: import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 1, 100) y = x**2 plt.plot(x, y, 'k--', color=[1, 0, 0]) The output will be a red dashed line, even though I have specified a black dashed line in the fmt arg. This makes sense, as the matplotlib documentation explicitly says: When conflicting with fmt, keyword arguments take precedence. Is there any tricky way to reverse this behavior, though? I want fmt to take precedence over the color parameter. Edit: Why I want to do this... I have a function plotStuff(dataDirs, formats=None) where dataDirs is a list of directory names containing some data. the function ultimately plots len(dataDirs) lines. Each line will be colored based on a colors array which is internal to the function. However, I'd like the user to be able to override this with the optional formats argument (an array of strings, of length len(dataDirs)). I could ask whether or not the optional argument formats was passed, and if so, ignore colors. But, that won't work, because if the formats passed by the user happen to only contain a linestyle (like '--'), and no color (like 'k--'), then the color would be chosen from the matplotlib color cycle which I don't want. I could go through the annoying task of determining if the strings in the formats array contains a color, but surely there's a simpler way.
has answer: http://stackoverflow.com/a/49949956
has title: Allos matplotlib fmt value override any other keyword parameters
has comment: http://stackoverflow.com/comment/86913739

http://stackoverflow.com/q/50019769
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50021743
has title: Using LetsEncrypt / Certbot with django dev server?
favorite count: 0
has answer: http://stackoverflow.com/a/50021743
type: AnsweredQuestion
has body: I'm trying to implement SSL on my dev server, purely just so I can see it working. I see from the Certbot page that Certbot works with Apache, Nginx, Haproxy and Plesk. How would I go about implementing this with Django's dev server? I'm not working in a production environment of any kind yet.
score: 1
has answer: http://stackoverflow.com/a/50019940
tagged with: ssl
tagged with: https
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50019940
linked to: http://stackoverflow.com/q/8023126
tagged with: lets-encrypt

http://stackoverflow.com/q/49933747
answer count: 1
has title: Why is os.fchmod not working with a socket file descriptor?
accepted answer: http://stackoverflow.com/a/49945748
has comment: http://stackoverflow.com/comment/86883588
type: Question
has comment: http://stackoverflow.com/comment/86883691
has comment: http://stackoverflow.com/comment/86883708
has comment: http://stackoverflow.com/comment/86883718
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/86883737
tagged with: permissions
has body: I'm trying to use os.fchmod() as specified in this tutorial. However, when I pass in a file descriptor and a mode, I get back a vague "Invalid Argument" error. import socket import stat import os s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) os.fchmod(s.fileno(), stat.S_IRWXO) How do I fix this? The goal is to create a Unix Domain Socket with changed permissions (this git issue implies its possible).
has answer: http://stackoverflow.com/a/49945748
tagged with: unix-socket
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87030819
comment on: http://stackoverflow.com/a/50004675
type: AnswerComment
has text: what do you mean? also, how do I pass the keywords from the dict to the func?
type: Comment
score: 0

http://stackoverflow.com/a/49927016
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49926983
has body: I think what you are looking for is a message queue. import queue class Processor(object): """ Makes sure that all operations the user requires to be processed are processed in order Also makes sure that the users are still pickle-able """ def __init__(self): self.tasks = queue.Queue() self.killed = False def begin_processing(self): while not self.killed: task = self.tasks.get()
type: Answer
answers question: http://stackoverflow.com/q/49926983
has comment: http://stackoverflow.com/comment/86870052
has comment: http://stackoverflow.com/comment/86870132
has comment: http://stackoverflow.com/comment/86870104
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86956094
has text: @hpaulj I posted this question because it answered all of the complaints left on my last one. I'm not sure what you're asking when you ask if there is enough information to reproduce the situation. I have posted all of the code which causes the error, and I assume that if you tried to run the code on your machine it would yield the same. What more should I add?
comment on: http://stackoverflow.com/q/49969861
type: QuestionComment
type: Comment
score: 0

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/49963752

http://stackoverflow.com/a/49979840
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49979749
upvote count: 2
answers question: http://stackoverflow.com/q/49979749
score: 2
has body: You should use str.casefold for case insensitivity: current_users = ['lana', 'matthew', 'kevin', 'lars', 'louis', 'sarah'] new_users = ['tom', 'tim', 'gus', 'david'] for user in new_users: if user.casefold() in current_users: print("Sorry, " + user.title() + ", but that username is already taken. Please choose a new username.") else: print("Hello, " + user.title() + ", that username is available. Welcome aboard!") As per the docs: Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".
type: AcceptedAnswer

http://stackoverflow.com/comment/87011879
comment on: http://stackoverflow.com/q/49996737
score: 0
has text: Okay I will try the things you have suggested, just to let you know I have this line below the `self.enterAnswer = Entry` line which is, `self.Submit = Button(self.quizf,text = "submit", command = self.confirmAnswer)`. I dont know if this makes a difference?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50057919
downvote count: 0
has body: !start excel works in Jupyter notebook because the Jupyter shell is able to understand the ! prefix and run a native (Windows) command. !: to run a shell command. E.g., ! pip freeze | grep pandas to see what version of pandas is installed. But !start excel isn't valid python syntax. You need the exact python equivalent (for Windows at least): import os os.startfile("excel")
type: Answer
answers question: http://stackoverflow.com/q/50057820
score: 3
upvote count: 3

http://stackoverflow.com/a/50062095
type: Answer
answers question: http://stackoverflow.com/q/50062029
score: 2
upvote count: 2
has body: Do you want keyword args? class DummyData: def __init__(self,lat,long,**kwargs): self.lat = lat self.long = long self.data = kwargs loc_1 = DummyData(12,22,mess_11=0.002,mess_22=2.222,mess_33=3.23) print(loc_1.data['mess_11']) # 0.002 or just a dict argument? class DummyData: def __init__(self,lat,long,dct): self.lat = lat self.long = long self.data = dct loc_1 = DummyData(12,22,{ "mess_11" : 0.002, "mess_22" : 2.222, "mess_33" : 3.23 }) print(loc_1.data['mess_11']) # 0.002 or what else? class DummyData: def __init__(self,lat,long,dct): self.lat = lat self.long = long self.data = type('myobj', (), dct) loc_1 = DummyData(12,22,{ "mess_11" : 0.002, "mess_22" : 2.222, "mess_33" : 3.23 }) print(loc_1.data.mess_11) # 0.002
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50062029

http://stackoverflow.com/q/50006318
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/87031831
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87029304
has answer: http://stackoverflow.com/a/50006658
favorite count: 0
type: Question
has body: i looked at the documentation of SKL but they used a multiple algorithms for anaomaly detection , but am looking into python code for elliptic envelope only
has title: i want to detect outliers only using elliptic envelope using python so how?
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87031911

http://stackoverflow.com/comment/122244097
has text: after several days i found this post thanks - have troubleshooted all about ptoxy and certificates, but it was due to failing PIP versions. I installed latest version of python, and downloaded https://pypi.org/project/pip/9.0.3/#files and did manual downgrade "pip install pip-9.0.3.tar.gz" now it works
comment on: http://stackoverflow.com/a/49998943
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50044405
has body: there isn't a way to react to filter changes as far as I know, but you can "recreate" the filter as a property control and execute the script when that property value changes. typical example is for a listbox/dropdown property control representing a listbox filter.
score: 1
answers question: http://stackoverflow.com/q/50042009
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/87056515
comment on: http://stackoverflow.com/q/50016800
score: 0
type: Comment
type: QuestionComment
has text: This is my main url ---> urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('myapp.urls',namespace='myapp')), ]

http://stackoverflow.com/comment/86882185
has text: thank you, I do short the date first then do for loop. it works as expected.
comment on: http://stackoverflow.com/a/49932848
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86932127
type: QuestionComment
has text: could you rewrite the code to that pls... I'm trying to keep both up and down server in same mail.
score: 0
comment on: http://stackoverflow.com/q/49957918
type: Comment

http://stackoverflow.com/comment/87047297
comment on: http://stackoverflow.com/a/49986030
score: 0
type: Comment
has text: I'm puzzled - this works fine for me (with a 5 by 6 input array). Try deleting the `dtype=complex` - it should be able to work it out anyway. Also try replacing `np.array` with `np.vstack`. But those are all guesses because it does work for me.
type: AnswerComment

http://stackoverflow.com/comment/87045230
type: Comment
has text: https://stackoverflow.com/a/50011617/6361531 Does this SO post help?
type: QuestionComment
comment on: http://stackoverflow.com/q/50013162
score: 0

http://stackoverflow.com/comment/86965884
score: 0
has text: not clear what u asking, please provide actual and expected result
type: QuestionComment
comment on: http://stackoverflow.com/q/49974918
type: Comment

http://stackoverflow.com/q/50031376
type: Question
tagged with: python-3.x
score: 3
has answer: http://stackoverflow.com/a/50136024
accepted answer: http://stackoverflow.com/a/50136024
has title: override relationship behaviour in sqlalchemy
tagged with: python
tagged with: relationships
has body: Say I have three tables in a declarative fashion, Parent, Child, and Pet, in such way that Parent has a many-to-many relationship with both Child and Pet Child has a one-to-many relationship with Pet The code for them is (using Flask-SQLAlchemy, although I believe the solution lives in the realm of SQLAlchemy rather than in Flask). class Parent(db.Model): __tablename__ = 'parents' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) # many to many relationship between parent and children # my case allows for a children to have many parents. Don't ask. children = db.relationship('Child', secondary=parents_children_relationship, backref=db.backref('parents', lazy='dynamic'), lazy='dynamic') # many to many relationship between parents and pets pets = db.relationship('Pet', secondary=users_pets_relationship, backref=db.backref('parents', lazy='dynamic'), # lazy='dynamic') # many to many relationship between parents and children parents_children_relationship = db.Table('parents_children_relationship', db.Column('parent_id', db.Integer, db.ForeignKey('parents.id')), db.Column('child_id', db.Integer, db.ForeignKey('children.id')), UniqueConstraint('parent_id', 'child_id')) # many to many relationship between User and Pet users_pets_relationship = db.Table('users_pets_relationship', db.Column('parent_id', db.Integer, db.ForeignKey('parents.id')), db.Column('pet_id', db.Integer, db.ForeignKey('pets.id')), UniqueConstraint('parent_id', 'pet_id')) class Child(db.Model): __tablename__ = 'children' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) # parents = &lt;backref relationship with User model&gt; # one to many relationship with pets pets = db.relationship('Pet', backref='child', lazy='dynamic') class Pet(db.Model): __tablename__ = 'pets' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) # child = backref relationship with cities child_id = db.Column(db.Integer, db.ForeignKey('children.id'), null…
tagged with: sqlalchemy
type: AnsweredQuestion
answer count: 2
upvote count: 3
downvote count: 0
tagged with: flask-sqlalchemy
has answer: http://stackoverflow.com/a/50031564
possible better answer: http://stackoverflow.com/a/50031564
favorite count: 0

http://stackoverflow.com/q/50020436
has answer: http://stackoverflow.com/a/50020630
has answer: http://stackoverflow.com/a/50020574
favorite count: 0
type: Question
has body: I want to strip hyphen from block of string: e.g: "(CB)-year-(3F)-year- (56)-ADDR(01)-DATA(06)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new- (56)-ADDR(01)-DATA(03)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new- (05)-ADDR5-[address0]-(E0)-tWHR2-nintK- (56)-ADDR(01)-DATA(05)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new-" This is how my string looks like. Need a generic method to remove - from end of every line. Note: This is one complete string copied from excel I have tried the following: if data.endswith('-'): data=seq[:-1] data.strip("\r\n") This is how i want my output/Result to look like: (CB)-year-(3F)-year (56)-ADDR(01)-DATA(06)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new (56)-ADDR(01)-DATA(03)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new (05)-ADDR5-[address0]-(E0)-tWHR2-nintK (56)-ADDR(01)-DATA(05)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new
has title: Python strip hyphen from block of string
possible better answer: http://stackoverflow.com/a/50020690
upvote count: 2
has comment: http://stackoverflow.com/comment/87056624
accepted answer: http://stackoverflow.com/a/50020630
has answer: http://stackoverflow.com/a/50020690
tagged with: python
has comment: http://stackoverflow.com/comment/87056670
has comment: http://stackoverflow.com/comment/87056636
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/87056601
score: 2
has comment: http://stackoverflow.com/comment/87056797
has comment: http://stackoverflow.com/comment/87056703
downvote count: 0

http://stackoverflow.com/comment/87071196
has text: Please update your question with what you've tried.
comment on: http://stackoverflow.com/q/49985657
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49937997
downvote count: 2
answer count: 3
tagged with: selenium
has answer: http://stackoverflow.com/a/49938097
has answer: http://stackoverflow.com/a/49938158
upvote count: 1
has comment: http://stackoverflow.com/comment/86891871
favorite count: 0
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/49940324
type: Question
has answer: http://stackoverflow.com/a/49940324
tagged with: python
has body: I have created a python selenium script that should navigate through a website and collect people profiles (https://www.shearman.com/people). The program won't loop through the pages to collect the links. I have used this which doesn't work; try: # this is navigate to next page driver.find_element_by_xpath('//div[@id="searchResultsSection"]/ul/li[12]').click() time.sleep(1) except NoSuchElementException: break The syntax behind the next button can be seen below; &lt;a href="" onclick="PageRequest('2', event)" class="xh-highlight"&gt;&amp;gt;&lt;/a&gt; Does anybody no how to write the code to click the next button?
tagged with: webdriver
score: -1
tagged with: xpath
has title: Python Selenium - How to loop to the last element in a site
possible better answer: http://stackoverflow.com/a/49938097
type: AnsweredQuestion

http://stackoverflow.com/comment/86945172
comment on: http://stackoverflow.com/q/49958396
score: 0
type: Comment
has text: See @IljaEverilä's link to a pre-existing dupe of this question. What you want is basically `session.query(func.max(HostsModel.risk))`
type: QuestionComment

http://stackoverflow.com/comment/87091930
comment on: http://stackoverflow.com/a/50017626
score: 0
type: Comment
type: AnswerComment
has text: The sample code is updated in the question. @Dan D,that is how solution is being designed,however,I do not see multiple thread getting triggered when I execute it. It executes the way it was doing earlier and no performance improvement. Any suggestions!

http://stackoverflow.com/comment/86953724
type: Comment
score: 0
type: QuestionComment
has text: I apologize, I meant to write unicode. Thank you for pointing that out. Any help with this I would highly appreciate it Goyo
comment on: http://stackoverflow.com/q/49968414

http://stackoverflow.com/comment/87027622
has text: That's because your answer isn't as generic as it could be.
type: Comment
comment on: http://stackoverflow.com/a/49999557
score: 0
type: AnswerComment

http://stackoverflow.com/q/49971723
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49971978
score: 0
type: UnansweredQuestion
answer count: 1
has title: Smooth lines on stacked line plot python matplotlib
type: Question
has body: I have the following code to generate a stacked line chart. Is it possible to smooth the lines? y1, y2, y3, y4, y5, y6, y7= y1_dict.values(), y2_dict.values(), y3_dict.values(), y4_dict.values(), y5_dict.values(), y6_dict.values(), y7_dict.values() fig, ax = plt.subplots() ax.stackplot(y1_dict.keys(), y1, y2, y3, y4, y5, y6, y7) plt.xticks(y1_dict.keys(), times, rotation="vertical") #times holds str representations of minutes in 15 min intervals in a 24 hr period plt.xlabel("x-axis") plt.ylabel("y-axis") plt.title("title") plt.show() Here is a picture of the graph below:

http://stackoverflow.com/q/49965770
linked to: http://stackoverflow.com/q/8356336
linked to: http://stackoverflow.com/q/44432276
tagged with: stdout
tagged with: python
has comment: http://stackoverflow.com/comment/86948833
has comment: http://stackoverflow.com/comment/86947613
has comment: http://stackoverflow.com/comment/86948576
accepted answer: http://stackoverflow.com/a/49966865
has comment: http://stackoverflow.com/comment/86947683
tagged with: pyqt
answer count: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86947682
has comment: http://stackoverflow.com/comment/86948460
type: Question
has answer: http://stackoverflow.com/a/49966865
type: AnsweredQuestion
score: 0
has title: Stdout stops showing in QTextEdit once another window has opened
has comment: http://stackoverflow.com/comment/86947709
has comment: http://stackoverflow.com/comment/86947564
has comment: http://stackoverflow.com/comment/86947321
has body: I am trying to get stdout and error messages to show on my main window. The window is by pyqt and made via designer. I have a QTextEdit on it. This is where the output should show itself. Also I have a dialog box (again made via designer) where i set some settings for my program before running it. The dialog box is opened like this: def open_settings(self): dialog = SettingsDialog() dialog.open_settings_tab() # its on a tab widget I already read and used the info on these links to achieve my goal: Print out python console output to Qtextedit How to capture output of Python&#39;s interpreter and show in a Text widget? Both are pretty much the same with different object names. The issue I'm having is that whenever I open a dialog box and return to the main window the stdout no longer shows itself on the QTextEdit. Instead it goes back to showing itself on Sublime Editor. I believe it has something to do with the class instancing. Here is how the Dialog class starts: class SettingsDialog(QDialog): def __init__(self, parent=None): super(SettingsDialog, self).__init__(parent) self.ui = Ui_SettingsDialog() self.ui.setupUi(self) and finally here is how my main window (form) class starts: class MyForm(QMainWindow): def __init__(self, parent=None): super(MyForm, self).__init__(parent) # Install the custom output stream sys.stdout = EmittingStream(textWritten=self.normalOutputWritten) self.ui = Ui_MyForm() self.ui.setupUi(self) Any ideas of why the stdout stops working (in qtextedit) once i go into the dialog screen and come back? NEW Update: The code is very long. I made a small program thats showing the issue: PS: I found that the problem is related with this line shown below: self.ui.pushButton_path.clicked.connect(Form(self).change_path) if i comment it out the problem goes away.. But I need to call that function (which opens a QDialog, from the main form). What is the proper way? main: import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog from PyQt5.Q…

http://stackoverflow.com/q/50027635
downvote count: 0
has answer: http://stackoverflow.com/a/58220161
score: 11
favorite count: 0
accepted answer: http://stackoverflow.com/a/50027898
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50027898
answer count: 3
tagged with: tensorboard
possible better answer: http://stackoverflow.com/a/58220161
tagged with: python
has body: I am using Tensorflow's object detection framework. Training and evaluation jobs are going well, but in tensorboard I am only able to see 10 images for the evaluation job. Is there a way to increase this number to look at more images? I tried changing the config file: eval_config: { num_examples: 1000 max_evals: 50 } eval_input_reader: { tf_record_input_reader { input_path: "xxx/eval.record" } label_map_path: "xxx/label_map.pbtxt" shuffle: false num_readers: 1 } I thought the max_eval parameter would change this but it doesn't. This is the command i'm running for the evaluation job: python ../models/research/object_detection/eval.py \ --logtostderr \ --pipeline_config_path=xxx/ssd.config \ --checkpoint_dir="xxx/train/" \ --eval_dir="xxx/eval"
tagged with: object-detection
tagged with: tensorflow
upvote count: 11
type: Question
has answer: http://stackoverflow.com/a/53023916
has title: Show more images in Tensorboard - Tensorflow object detection

http://stackoverflow.com/comment/86906026
type: Comment
score: 0
type: AnswerComment
has text: Doesn't really fulfil the requirement as stated, no?
comment on: http://stackoverflow.com/a/49944817

http://stackoverflow.com/comment/87052487
has text: Why are you mixing numpy arrays and lists?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50018149
score: 1

http://stackoverflow.com/comment/86930899
type: QuestionComment
score: 2
type: Comment
has text: @user3613025 it's better to create a class in that case with position, speed, energies, ... for each. Quit Fortran-programming style with only indices binding all related values.
comment on: http://stackoverflow.com/q/49957157

http://stackoverflow.com/comment/87137245
comment on: http://stackoverflow.com/q/50045251
score: 1
type: Comment
type: QuestionComment
has text: @VikramShinde what do you mean the "current" datetime? Current when you instantiate an instance of your class? Current when you dump some output somewhere? Also terminal, app engine, doesn't matter, python is python. The way you have it now since you're storing it in a class property it's the time when the file is parsed - 7 days. If you want when the class is instantiated (for each instance) do it in the constructor.

raspbian
tags question: http://stackoverflow.com/q/50004263
type: Tag
tag name: raspbian

http://stackoverflow.com/q/49951249
has body: Python 3.6. New to Python...first post be gentle... I cant wrap my mind around this... As described in the title, I have CSV formatted data that I need to write to a CSV file with a variable filename. Currently my code creates the CSV with the appropriate filename, and writes data to the CSV, but the data is 1 letter on each row. Code looks like: import csv filename = os.environ['USERPROFILE'] + '\Downloads\Somefolder\\'+ variablefilename + '.csv' myfile = open(filename, 'w', newline='') with myfile: writer = csv.writer(myfile) writer.writerows(csvformatteddata.decode('utf-8')) #csvformatteddata was generated prior to this code. Any help would be greatly appreciated, but I would like an explanation with the "solution" code if possible. I am looking to learn/grow, not have my ignorance enabled.
has comment: http://stackoverflow.com/comment/86919082
has title: Python - Writing CSV formatted data to a CSV with a variable filename
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86919131
accepted answer: http://stackoverflow.com/a/49951282
favorite count: 0
has answer: http://stackoverflow.com/a/49951282
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49951439
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
score: 1
possible better answer: http://stackoverflow.com/a/49951364
tagged with: python
has answer: http://stackoverflow.com/a/49951364
type: Question

http://stackoverflow.com/a/50458804
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50011676
has comment: http://stackoverflow.com/comment/87977041
answers question: http://stackoverflow.com/q/50011676
score: 7
has comment: http://stackoverflow.com/comment/106340677
type: Answer
has body: I'm also running a Mid-2010 MacbookPro and have been facing the same issue. It seems the only solution is to downgrade to Tensorflow 1.5. You can do so by running the following: pip3 uninstall tensorflow pip3 install tensorflow==1.5 Credit given to the solution to this post.
upvote count: 7

http://stackoverflow.com/q/50053585
favorite count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/8049798
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
tagged with: python-3.6
has title: Merging n'th level multidimensional dictionary
type: AnsweredQuestion
has body: Ok so what I have is: foo = {1: {'f1': 'c1'}, 2: {'f2': 'c2'}} What I want to get using list comprehension(if possible of course) is merge all 2nd level dictionary values this: bar = {'f1': 'c1', 'f2': 'c2'} What I tried is this: bar = {k:v for k, v in tmp.items() for tmp in list(foo.values())} Now this gets me: NameError: name 'tmp' is not defined This seamed like logical solution but apparently its a no go, could you please suggest a solution using list comprehension if possible, or some other one liner, or if that would not be possible an insight into why I get this error will be good knowledge to have. Thanks,
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/50053726
has answer: http://stackoverflow.com/a/50053726
downvote count: 1
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87140383
comment on: http://stackoverflow.com/q/50061883
has text: To quote from the official docs: `You can send up to 25 MB in attachments.`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86971586
has text: What is the expected output?
comment on: http://stackoverflow.com/q/49977561
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49990420
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87259465
upvote count: 1
answers question: http://stackoverflow.com/q/49990152
type: Answer
has body: Please take a look at this post: need to convert UTC (aws ec2) to PST in python from datetime import datetime from pytz import timezone import pytz date_format='%m/%d/%Y %H:%M:%S %Z' date = datetime.now(tz=pytz.utc) print 'Current date &amp; time is:', date.strftime(date_format) date = date.astimezone(timezone('US/Pacific')) print 'Local date &amp; time is :', date.strftime(date_format)
accepted answer of: http://stackoverflow.com/q/49990152
score: 1

http://stackoverflow.com/comment/86872270
comment on: http://stackoverflow.com/q/49927690
score: 0
type: Comment
type: QuestionComment
has text: You can do `if "jrn." in line.lower() and "username" in line.lower():`

http://stackoverflow.com/a/49962823
answers question: http://stackoverflow.com/q/49962741
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86941896
has comment: http://stackoverflow.com/comment/86945330
has body: Django promotes the separation of concerns means filtering data should be performed in py file (in your case, same method written above) or in model class. It's still not clear what's filter object in your template from where qs is being fetched? If you can provide that detail then I would be able to help.

http://stackoverflow.com/q/50017061
answer count: 1
has comment: http://stackoverflow.com/comment/87059756
favorite count: 0
has body: I have quite some difficulties formulating the question hence please find an example below: I have: 2017-11-23 16:30:52+01:00 20 2017-11-23 16:30:58+01:00 30 2017-11-23 16:31:30+01:00 25 I would like to have: 2017-11-23 16:30:52+01:00 20 2017-11-23 16:30:53+01:00 20 2017-11-23 16:30:54+01:00 20 ... 2017-11-23 16:30:58+01:00 30 2017-11-23 16:30:59+01:00 30 ... Actually, I thought this would be an easy job using pandas resample with pad df=df.resample('1s').pad() However, this returns the following: 2017-11-23 16:30:52+01:00 20 2017-11-23 16:30:53+01:00 NaN 2017-11-23 16:30:54+01:00 NaN ... 2017-11-23 16:30:58+01:00 NaN 2017-11-23 16:30:59+01:00 NaN ... The column is of type (float64).. Any help appreciated. Thank you!
has comment: http://stackoverflow.com/comment/87051482
tagged with: pandas
downvote count: 1
tagged with: python
score: -1
has title: python change random time index to second base index
type: Question
has answer: http://stackoverflow.com/a/50017808
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50050680
upvote count: 0
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50050543
answers question: http://stackoverflow.com/q/50050543
type: Answer
has body: This should be enough code to get you started. You just need a flag to determine whether a number should be hidden or not: grid = [ [{"number": 1, "hidden": True}, {"number": 5, "hidden": False}, {"number": 8, "hidden": True}], [{"number": 3, "hidden": True}, {"number": 2, "hidden": True}, {"number": 4, "hidden": False}], [{"number": 9, "hidden": True}, {"number": 7, "hidden": False}, {"number": 3, "hidden": False}] ] for row in grid: for column in row: print("*" if column["hidden"] else column["number"], "", end="") print() Prints: * 5 * * * 4 * 7 3
score: -1

http://stackoverflow.com/comment/86875211
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49929615
has text: Use https://docs.python.org/3/library/functools.html#functools.lru_cache ?

http://stackoverflow.com/q/50058396
possible better answer: http://stackoverflow.com/a/63014094
has answer: http://stackoverflow.com/a/63014094
has comment: http://stackoverflow.com/comment/87134209
tagged with: python
has title: jupyter notebook: error when specifying IP for server access
has answer: http://stackoverflow.com/a/50101437
accepted answer: http://stackoverflow.com/a/50101437
tagged with: tornado
tagged with: jupyter-notebook
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87133433
has comment: http://stackoverflow.com/comment/87134522
has body: when i run jupyter notebook --ip=172.17.67.24 in cmd under windows 7 professional i get the following error C:\Users\nhs&gt;jupyter notebook --ip=172.17.67.24 Traceback (most recent call last): File "C:\ProgramData\Anaconda3\Scripts\jupyter-notebook-script.py", line 10, in &lt;module&gt; sys.exit(main()) File "C:\ProgramData\Anaconda3\lib\site-packages\jupyter_core\application.py", line 267, in launch_instance return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\traitlets\config\application.py", line 657, in launch_instance app.initialize(argv) File "&lt;decorator-gen-7&gt;", line 2, in initialize File "C:\ProgramData\Anaconda3\lib\site-packages\traitlets\config\application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 1296, in initialize self.init_webapp() File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 1120, in init_webapp self.http_server.listen(port, self.ip) File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\tcpserver.py", line 142, in listen sockets = bind_sockets(port, address=address) File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\netutil.py", line 197, in bind_sockets sock.bind(sockaddr) OSError: [WinError 10049] The requested address is not valid in its context jupyter versions are: jupyter 1.0.0 jupyter_client 5.1.0 jupyter_console 5.2.0 jupyter_core 4.3.0 jupyterlab 0.27.0 jupyterlab_launcher 0.4.0 if i use '*' as ip everything works fine, but i dont want to use that option due to security issues. If i specify the ip in the config file it doesn't work either. Any ideas why this doesn't work?
tagged with: jupyter
favorite count: 0
type: Question

http://stackoverflow.com/comment/87125208
score: 0
has text: Save_screenshot can screenshots, but he is not full screen, and can not take node screenshots.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50040823

nlp
tags question: http://stackoverflow.com/q/49956178
tags question: http://stackoverflow.com/q/49921552
tags question: http://stackoverflow.com/q/50003363
tags question: http://stackoverflow.com/q/49986115
tags question: http://stackoverflow.com/q/50048962
tags question: http://stackoverflow.com/q/49946245
tags question: http://stackoverflow.com/q/49917033
tags question: http://stackoverflow.com/q/49952762
tags question: http://stackoverflow.com/q/50019632
tags question: http://stackoverflow.com/q/49930725
tags question: http://stackoverflow.com/q/49933974
tags question: http://stackoverflow.com/q/49946942
tags question: http://stackoverflow.com/q/49941646
tag name: nlp
tags question: http://stackoverflow.com/q/50004797
tags question: http://stackoverflow.com/q/50049805
type: Tag
tags question: http://stackoverflow.com/q/49950347
tags question: http://stackoverflow.com/q/50024431
tags question: http://stackoverflow.com/q/50061181
tags question: http://stackoverflow.com/q/49967931
tags question: http://stackoverflow.com/q/50068013
tags question: http://stackoverflow.com/q/50009030
tags question: http://stackoverflow.com/q/50015665
tags question: http://stackoverflow.com/q/50009296
tags question: http://stackoverflow.com/q/49945812
tags question: http://stackoverflow.com/q/49983977
tags question: http://stackoverflow.com/q/50038347

http://stackoverflow.com/comment/87141454
type: Comment
has text: How is the data structured? Can the data be seperated by `split` (the unix command line utility) or is it variable in size?
comment on: http://stackoverflow.com/q/50062474
type: QuestionComment
score: 1

plumber
tags question: http://stackoverflow.com/q/49975264
tag name: plumber
type: Tag

http://stackoverflow.com/comment/86940326
type: AnswerComment
has text: Thanks, I didn't think of this way, I was thinking in the direction of np.loadtxt and all
type: Comment
comment on: http://stackoverflow.com/a/49961559
score: 0

http://stackoverflow.com/a/49936271
upvote count: 2
score: 2
downvote count: 0
has body: The migrations created by the makemigrations command are not database specific, they can be run on any database. python manage.py sqlmigrate # which displays the SQL statements for a migration From Django Doc : Migrations will run the same way on the same dataset and produce consistent results, meaning that what you see in development and staging is, under the same circumstances, exactly what will happen in production Yes from @Klaus D. comment, I don't think Django have information that the migrations are DB dependent.
answers question: http://stackoverflow.com/q/49935857
type: Answer

http://stackoverflow.com/q/50037297
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50037501
upvote count: 2
has comment: http://stackoverflow.com/comment/87090731
tagged with: python
has body: I want to run a python script at a particular time. say Everyday 10am or every 2 hours. How can I achieve that? I have read these questions- Q1 Q2
linked to: http://stackoverflow.com/q/32404
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50037501
score: 1
has comment: http://stackoverflow.com/comment/87090670
answer count: 1
has title: How to write windows service to schedule run python script in particular time
has comment: http://stackoverflow.com/comment/87091081
tagged with: windows-services
favorite count: 0
type: Question

http://stackoverflow.com/comment/90671488
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50006669
has text: okay ill just delete this file. thanks
type: Comment

http://stackoverflow.com/q/49917705
tagged with: python
type: Question
score: 0
has body: I got the results I wanted by doing this: list = [1, 2, 3, 4, 5] def new(x): for i in x: print i and then calling new(list) Results would be: 1 2 3 4 5 What I would like to do is something like print [x for x in list] but I can't seem to find the right answer searchin. Is there a more compact way to plint out each item in the list on new lines?
has answer: http://stackoverflow.com/a/49918028
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49917919
has title: Printing items in list on new lines with compact code
has answer: http://stackoverflow.com/a/49917754
answer count: 3

http://stackoverflow.com/comment/87143357
comment on: http://stackoverflow.com/a/50063220
type: AnswerComment
score: 0
has text: Define "normalize".
type: Comment

http://stackoverflow.com/comment/87152898
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50067957
type: QuestionComment
has text: I added it. Feel free to give me some street cred. :)

http://stackoverflow.com/a/49942523
accepted answer of: http://stackoverflow.com/q/49941426
type: Answer
has body: It is not a model file, instead, this is a state file. In a model file, the complete model is stored, whereas in a state file only the parameters are stored. So, your OrderedDict are just values for your model. You will need to create the model and then need to load these values into your model. So, the process will be something in form of import torch import torch.nn as nn class TempModel(nn.Module): def __init__(self): self.conv1 = nn.Conv2d(3, 5, (3, 3)) def forward(self, inp): return self.conv1(inp) model = TempModel() model.load_state_dict(torch.load(file_path)) model.eval() You'll need to define your model properly. The one given in the example above is just a dummy. If you construct your model yourself, you might need to update the keys of the saved dict file as mentioned here. The best course of action is to define your model in exactly the same way from when the state_dict was saved and then directly executing model.load_state_dict will work.
answers question: http://stackoverflow.com/q/49941426
score: 57
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92522570
has comment: http://stackoverflow.com/comment/92522668
upvote count: 57

http://stackoverflow.com/q/49968576
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/86953017
has comment: http://stackoverflow.com/comment/86953178
possible better answer: http://stackoverflow.com/a/49968643
type: Question
has answer: http://stackoverflow.com/a/49968643
has answer: http://stackoverflow.com/a/49968731
has comment: http://stackoverflow.com/comment/86953005
tagged with: python
tagged with: dictionary
has title: Defaultdict - assign strings to key value in loop
accepted answer: http://stackoverflow.com/a/49968731
tagged with: defaultdict
type: AnsweredQuestion
has body: I am struggling to understand why the string values I am trying to loop through and assign to dictionary key-value pairs in a default dictionary are not properly working. The desired outcome here is to loop through the string values in each of the two lists, and return a dictionary that has websites for keys and team names for values. However, neither append nor the equal sign work. In addition, I am not sure why the defaultdict returns of the form defaultdict(None, {}) (or defaultdict(list, {}) if i initiate it as a list). Is there a way to assert that both the keys and values of this dict will be strings? Thank you for your help. teams=['yankees','redsox','giants'] websites=['xasfsgrwg.cc','redsox.com','giants.org'] from collections import defaultdict baseballdict=defaultdict() #defaultdict(None, {}) #baseballdict=defaultdict(list) for i in range(len(websites)): baseballdict[websites[i]]=baseballdict[teams[i]] #does not work baseballdict[websites[i]].append(baseballdict[teams[i]]) # does not work

http://stackoverflow.com/q/49958976
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/49959047
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49959047
tagged with: concatenation
has comment: http://stackoverflow.com/comment/86934349
has answer: http://stackoverflow.com/a/49959067
tagged with: newline
downvote count: 0
accepted answer: http://stackoverflow.com/a/49959143
tagged with: python
tagged with: string
has title: Merge multiline strings horizontally
has answer: http://stackoverflow.com/a/49959143
has body: I have multiple strings containing new lines. I want to merge them horizontally so all the first lines are concatenated together, as are the second lines, third lines, and so forth. That is: """line 1 line 2 line 3 line 4""" + """addition 1 addition 2 addition 3 addition 4""" = """line 1 addition 1 line 2 addition 2 line 3 addition 3 line 4 addition 4""" But with way more than two entries. How can I do this?
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/87252607
score: 0
comment on: http://stackoverflow.com/a/50048119
type: Comment
type: AnswerComment
has text: Glad I was able to help. I do know it is pretty easy to do case insensitive stuff with pandas by taking a whole columns of text as lower or upper case. May help you with you proper-case titles. IE: df.titles.str.lower().isin(['cool title 1', 'cool title 2'])

http://stackoverflow.com/a/69833276
upvote count: 2
downvote count: 0
has body: Similar to other answers here, my problem lied in the fact that I was trying to use a new client when I've already mocked one with moto. My bad setup: app.py import boto3 _DYNAMO_RESOURCE = boto3.resource('dynamodb') _METADATA_TABLE_NAME = 'metadata' def my_ddb_func(): table = _DYNAMO_RESOURCE.Table(_METADATA_TABLE_NAME) # perform some Dynamo call response = table.scan(...) return response unit_test.py import boto3 import moto import app @fixture(name='dynamo_resource') def fixture_dynamo_resource(): with mock_dynamodb2(): resource = boto3.resource('dynamodb') yield resource def test_my_ddb_func(dynamo_resource): # perform some base level call and assert response = app.my_ddb_func() assert response This would lead to the UnrecognizedClientException. After hours of searching for my issue, I couldn't find any fixes that worked for me, hence me putting it here for those in the future. What fixed it was following this blog on how to unit test for AWS Chalice apps (which is what my app is, but should still apply to anyone not using AWS Chalice): https://aws.amazon.com/blogs/developer/introducing-the-new-test-client-for-aws-chalice/ In the section titled, "Testing with the AWS SDK for Python", it has a code snippet that specified an S3 constant and a getter, like so: _S3 = None def get_s3_client(): global _S3 if _S3 is None: _S3 = boto3.client('s3') return _S3 @app.route('/resources/{name}', methods=['PUT']) def send_to_s3(name): s3 = get_s3_client() s3.put_object( Bucket='mybucket', Key=name, Body=app.current_request.raw_body ) return Response(status_code=204, body='') which helped the solution from @Alasdair click. My resulting files changed to this: app.py import boto3 _DYNAMO_RESOURCE = None # ^^^^ Note the new default of None _METADATA_TABLE_NAME = 'metadata' # New getter method def get_dynamo_resource(): global _DYNAMO_RESOURCE if _DYNAMO_RESOURCE is None: _DYNAMO_RESOURCE = boto3.resource('dynamodb') return _DYNAMO_RESOURCE def my_ddb_func(): table = get_dynamo_res…
type: Answer
answers question: http://stackoverflow.com/q/49943938
score: 2

http://stackoverflow.com/a/74171805
score: 0
has body: I ran into the same problem and the solution in my case was to unset the HTTPS_PROXY variable, because my proxy does not accept https requests. I found the solution in this page : https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#https-proxy-error-http-proxy All proxy variables are set by the os admin : HTTP_PROXY=http://my_domain:8888 NO_PROXY=*.internal_domain,172.*, HTTPS_PROXY=http://my_domain:8888 To update pip for example, I have to run : unset HTTPS_PROXY ; pip install -U pip
answers question: http://stackoverflow.com/q/49979354
type: Answer

http://stackoverflow.com/comment/129045372
comment on: http://stackoverflow.com/a/72997244
score: 0
type: Comment
has text: well, you can also put the delimiter "\x01" , which is an equivalent of "\u0001"
type: AnswerComment

http://stackoverflow.com/q/50002738
has answer: http://stackoverflow.com/a/50002858
has comment: http://stackoverflow.com/comment/87022353
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20250771
has comment: http://stackoverflow.com/comment/87021936
tagged with: pandas
has comment: http://stackoverflow.com/comment/87022429
score: 0
has comment: http://stackoverflow.com/comment/87021869
answer count: 1
has title: Replacing a string by an integer dictionary in python pandas dataframe
duplicate of: http://stackoverflow.com/q/20250771
accepted answer: http://stackoverflow.com/a/50002858
type: Question
has body: I have the following pandas dataframe. epi_week state loc_type disease cases incidence 21835 200011 WY STATE MUMPS 2 0.40 21836 197501 WY STATE POLIO 3 0.76 21837 199607 WY STATE HEPATITIS 3 0.61 21838 197116 WY STATE MUMPS 6 1.73 21839 200048 WY STATE HEPATITIS 6 1.21 I am trying to replace each disease by a unique integer. For example 'MUMPS'==1, 'POLIO'==2 etc. The final dataframe should look like follows: epi_week state loc_type disease cases incidence 21835 200011 WY STATE 1 2 0.40 21836 197501 WY STATE 2 3 0.76 21837 199607 WY STATE 3 3 0.61 21838 197116 WY STATE 1 6 1.73 21839 200048 WY STATE 3 6 1.21 I am using the following code: # creating a dictionary disease_dic = {'MUMPS':1, 'POLIO':2, 'MEASLES':3, 'RUBELLA':4, 'PERTUSSIS':5, 'HEPATITIS A':6, 'SMALLPOX':7, 'DIPHTHERIA':8} data.disease = [disease_dic[item] for item in data.disease] I am getting following errors: KeyErrorTraceback (most recent call last) &lt;ipython-input-115-52394901c90d&gt; in &lt;module&gt;() ----&gt; 1 cdc.disease = [disease_dic[item2] for item2 in cdc.disease] KeyError: 1 Can anyone please help about this issue? Thank you.

http://stackoverflow.com/comment/87183633
has text: You're welcome! Could you please mark the question as solved.?
type: AnswerComment
comment on: http://stackoverflow.com/a/50068588
score: 0
type: Comment

http://stackoverflow.com/comment/87024350
score: 0
type: Comment
has text: @Giroud2 Hehe, well, i hadn't checked the other answers when posted, also, you can see with the attached code I'm using snake_case convention for variables, that way you follow [PEP8](https://www.python.org/dev/peps/pep-0008/)
type: AnswerComment
comment on: http://stackoverflow.com/a/50003836

http://stackoverflow.com/q/50056169
type: UnansweredQuestion
answer count: 1
tagged with: laravel
type: Question
score: 0
has body: I need to develop a hybrid app with node js for user authentication and laravel for app functionalities and python for complex computations.So every request from the front should reach node js and from there request will be diverted to corresponding platform(laravel or pyhton).Node js should act as a middleware for this.How can it be possible to communicate between these multiple platforms and is any architecture available for these kind of hybrid app development.It can be possible to communicate using REST apis,But how the authentication can be done.
tagged with: python
has comment: http://stackoverflow.com/comment/87143875
tagged with: node.js
has answer: http://stackoverflow.com/a/50064756
has title: Node js+Laravel +python communication for hybrid app development

http://stackoverflow.com/comment/86967885
type: AnswerComment
comment on: http://stackoverflow.com/a/49974614
type: Comment
has text: try to run filename.py with python3 filename.py
score: 0

http://stackoverflow.com/comment/87153932
type: Comment
type: QuestionComment
has text: After I see this error no request goes through and it completely gets stuck.
score: 0
comment on: http://stackoverflow.com/q/50068613

http://stackoverflow.com/q/49932428
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/49933733
score: 1
tagged with: numerical-methods
upvote count: 1
tagged with: math
answer count: 1
has title: Find the root of a multivariable equation using scipy.optimize
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has body: I have the following functions import numpy as np import scipy.optimize as optimize def x(theta1, theta2, w, h, L1, L2): sint1 = np.sin(theta1) cost1 = np.cos(theta1) sint2 = np.sin(theta2) cost2 = np.cos(theta2) i1 = L1 * (cost1 + cost2) + w j1 = L1 * (sint1 - sint2) - h D = np.sqrt((L1*(cost2-cost1)+w)**2+(L1*(sint2-sint1)+h)**2) a = (0.25)*np.sqrt((4*L2**2-D**2)*D**2) return i1/2 + 2*j1*a/(D**2) def y(theta1, theta2, w, h, L1, L2): sint1 = np.sin(theta1) cost1 = np.cos(theta1) sint2 = np.sin(theta2) cost2 = np.cos(theta2) i2 = L1 * (sint1 + sint2) + h j2 = L1 * (cost1 - cost2) - w D = np.sqrt((L1*(cost2-cost1)+w)**2+(L1*(sint2-sint1)+h)**2) a = (0.25)*np.sqrt((4*L2**2-D**2)*D**2) return i2/2 - 2*j2*a/(D**2) def det_jacobiano(theta, w, h, L1, L2,eps): theta1,theta2 = theta dxdt1 = (-x(theta1+eps, theta2, w, h, L1, L2)+4*x(theta1, theta2, w, h, L1, L2)-3*x(theta1-eps, theta2, w, h, L1, L2))/(2*eps) dxdt2 = (-x(theta1, theta2+eps, w, h, L1, L2)+4*x(theta1, theta2, w, h, L1, L2)-3*x(theta1, theta2-eps, w, h, L1, L2))/(2*eps) dydt1 = (-y(theta1+eps, theta2, w, h, L1, L2)+4*y(theta1, theta2, w, h, L1, L2)-3*y(theta1-eps, theta2, w, h, L1, L2))/(2*eps) dydt2 = (-y(theta1, theta2+eps, w, h, L1, L2)+4*y(theta1, theta2, w, h, L1, L2)-3*y(theta1, theta2-eps, w, h, L1, L2))/(2*eps) return dxdt1*dydt2 - dxdt2*dydt1 And I want to find the values of theta 1 and theta2 that make det_jacobiano 0. As you can see the function det_jacobiano is evaluated in the functions x and y. When I try to use scipy.optimize to find the root initial_guess = [2.693, 0.4538] result = optimize.root(det_jacobiano, initial_guess,tol=1e-8,args=(20,0,100,100,1e-10),method='lm') Obtengo el error: TypeError: Improper input: N=2 must not exceed M=1
has answer: http://stackoverflow.com/a/49933733
tagged with: python

http://stackoverflow.com/a/50066287
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50066152
type: Answer
score: 1
has body: If the global variable show_image is True when the function is called but the cursor is out of the bounds defined by your first if-statement (or in bounds, but click[0] is False), then num will never be defined, so when the if show_image == True: statement runs, it tries to use num before num is ever assigned a value.

http://stackoverflow.com/comment/87109886
type: Comment
comment on: http://stackoverflow.com/q/50043664
type: QuestionComment
score: 0
has text: I have not tested that but you can browse through your Windows Registry to `HKEY_CURRENT_USER/Software/Classes/http/shell/open/command` and then change the value to `python "C:\path\to\your_script.py" "%1"`. I would suggest the same for https... But again: this might corrupt your web browser.

http://stackoverflow.com/comment/87155339
comment on: http://stackoverflow.com/a/50050441
type: AnswerComment
has text: Whoops, that'll teach me for not testing the code I post. Thanks for the heads up, I've corrected it.
score: 3
type: Comment

http://stackoverflow.com/q/50062663
has comment: http://stackoverflow.com/comment/87143181
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87142116
has comment: http://stackoverflow.com/comment/87142974
has answer: http://stackoverflow.com/a/50063211
has title: Encryption/Decryption using AES/CBC/PKCS7Padding
has comment: http://stackoverflow.com/comment/87142147
accepted answer: http://stackoverflow.com/a/50063211
tagged with: encryption
tagged with: android
has comment: http://stackoverflow.com/comment/87160835
tagged with: python
tagged with: cryptography
upvote count: 2
tagged with: php
has comment: http://stackoverflow.com/comment/87143227
has body: I need help in encrypting with AES/CBC/PKCS7Padding. I need the same results like here.
has comment: http://stackoverflow.com/comment/87142049
has comment: http://stackoverflow.com/comment/87141942
has comment: http://stackoverflow.com/comment/87142296
has comment: http://stackoverflow.com/comment/87142480
has comment: http://stackoverflow.com/comment/87143764
score: -5
has comment: http://stackoverflow.com/comment/87143109
has comment: http://stackoverflow.com/comment/87142792
has comment: http://stackoverflow.com/comment/87142416
has comment: http://stackoverflow.com/comment/87142404
has comment: http://stackoverflow.com/comment/87142389
has comment: http://stackoverflow.com/comment/87142616
answer count: 1
has comment: http://stackoverflow.com/comment/87142089
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87141808

http://stackoverflow.com/comment/86887810
comment on: http://stackoverflow.com/q/49935993
has text: I think you should get the summary as `issue['fields']['summary']`. I suggest to check the value of the `summary` key.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86904907
type: Comment
type: AnswerComment
score: 0
has text: I checked on the website and the url to include in the post request is: `https://www.e-ams.at/eams-sfa-account/p/j_security_check`. Please retry with `r = s.post(https://www.e-ams.at/eams-sfa-account/p/j_security_check', data=data)`
comment on: http://stackoverflow.com/a/49944182

http://stackoverflow.com/a/57329972
answers question: http://stackoverflow.com/q/49938766
has body: Here's my solution for Sign In on Instagram def login(self, username, password): """ Methods that log in to Instagram by taking user's credentials as parameters""" self.driver.get("https://www.instagram.com/accounts/login/") try: self.driver.find_element_by_xpath("//input[@name=\"username\"]").send_keys(username) # filling username self.driver.find_element_by_xpath("//input[@name=\"password\"]").send_keys(password) # filling password self.driver.find_element_by_xpath("//button[@type=\"submit\"]").click() # submit form except NoSuchElementException: print("Failed to log in: Unable to locate Username/Password/LogIn element(s)") # If login is unsuccessful, Instagram will show a message "Sorry, your password was incorrect. Please double-check your password." success = self.driver.find_elements_by_xpath("//p[@id = \"slfErrorAlert\"]") if len(success) == 0: print("Login successful!") else: print("Sorry, sign in unsuccessful. Please double-check your credentials.") See my Github repo for more: https://github.com/mlej8/InstagramBot
type: Answer
score: 0

http://stackoverflow.com/comment/87010952
has text: @CristiFati `wintypes.PULONG` is not found with Python2 but `wintypes.ULONG` seems to work. Can I replace?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49983901
score: 0

http://stackoverflow.com/comment/87001548
comment on: http://stackoverflow.com/a/49970082
score: 0
type: AnswerComment
has text: The source is the .tar.gz file listed among these files; https://pypi.org/project/Pillow/#files A wheel is a file with binary libraries used by pip to install a package without requiring a build. This allows users to install packages on computers that don't have a compiler.
type: Comment

http://stackoverflow.com/q/49935487
accepted answer: http://stackoverflow.com/a/49947993
type: Question
score: 0
tagged with: ibm-cloud-infrastructure
has answer: http://stackoverflow.com/a/49947993
has title: default vlan span status
tagged with: python
has body: the correct result of vlan spanning status is like this: import SoftLayer username='xxxxxx' key='xxxxxx' client = SoftLayer.create_client_from_env(username=username, api_key=key, timeout=600) account = client['Account'] account.getNetworkVlanSpan() {'lastVerifiedDate': '2018-04-19T22:02:23-05:00', 'modifyDate': '2018-04-19T22:02:23-05:00', 'enabledFlag': True, 'lastAppliedDate': '2018-04-19T20:45:27-05:00', 'id': xxxxx} while I found in a new created account, before I choose vlan spanning status on web portal, result of account.getNetworkVlanSpan() will be an empty dict. is this right? In this situation, what is the default status of vlan span, on or off ? thanks.
tagged with: vlan
type: AnsweredQuestion
answer count: 1

http://stackoverflow.com/comment/86957417
type: Comment
comment on: http://stackoverflow.com/q/49970748
has text: Can you post enough code to reproduce the problem?
type: QuestionComment
score: 5

http://stackoverflow.com/comment/87050173
has text: Unfortunately my templates folder is actually called 'templates' so I do not think that is the issue here. Thanks for responding.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50015399
type: AnswerComment

http://stackoverflow.com/comment/86880647
has text: I mean your model architecture
type: Comment
comment on: http://stackoverflow.com/q/49930725
type: QuestionComment
score: 0

http://stackoverflow.com/q/50016381
downvote count: 0
has comment: http://stackoverflow.com/comment/87049124
upvote count: 1
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50016565
has comment: http://stackoverflow.com/comment/87049074
answer count: 3
has answer: http://stackoverflow.com/a/50016565
possible better answer: http://stackoverflow.com/a/50016562
has comment: http://stackoverflow.com/comment/87049324
has body: Using regex, I need to get the expected ouput: string="Tue Apr 24 22:35:48 2018 53/e33 hello:55|Wordcap|abc|abc generate|6|Wordcapdata_proto_req=WINTER Wordcapdata_sample_resp=summer 2.4.5 WordcapTotal_reject=56 WordcapAddition_sum=TEA CUP ONE" Expected output = ['data_proto_req=WINTER', 'data_sample_resp=summer 2.4.5', 'Total_reject=56', 'Addition_sum=TEA CUP ONE'] The problem is dealing with the spaces in these strings : summer 2.4.5 or TEA CUP ONE This is my intial attempt at getting the regex: print re.findall(r'[W]*ordcap([^|].*?=.*?)[\s|\t]*(?:W|$)', string) The output I'm getting is : ['data_proto_req=', 'data_sample_resp=summer 2.4.5', 'Total_reject=56', 'Addition_sum=TEA CUP ONE']
tagged with: python
has comment: http://stackoverflow.com/comment/87051629
tagged with: regex
has answer: http://stackoverflow.com/a/50016562
linked to: http://stackoverflow.com/q/24085680
type: Question
has title: Extract text with spaces followed by string or end of line
score: 1
has answer: http://stackoverflow.com/a/50016574

http://stackoverflow.com/comment/86980194
has text: @etene Thanks very much for hints about h5 format, now everything is Ok with RAM, though very slow. Is there a way to iterate h5 file to load everything faster?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49980179
type: Comment

http://stackoverflow.com/a/49968119
score: 0
has body: You can see the possible authentication methods in the REST API wiki page: https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-Authentication API Key can be used as password in basic authentication, as well as using the "X-JFrog-Art-Api" dedicated header.
type: Answer
answers question: http://stackoverflow.com/q/49947367

http://stackoverflow.com/q/49967176
has comment: http://stackoverflow.com/comment/86950049
score: 0
has comment: http://stackoverflow.com/comment/86950025
linked to: http://stackoverflow.com/q/522563
tagged with: python
has answer: http://stackoverflow.com/a/49967212
has title: Attaching a list in based on Indice Python
duplicate of: http://stackoverflow.com/q/522563
has body: If I have a text such as: There was no possibility of taking a walk that day We had been wandering indeed in the leafless shrubbery an hour in the morning but since dinner (Mrs Reed when there was no company dined early) the cold winter wind had brought with it clouds so sombre and a rain so penetrating that further out door exercise was now out of the question I was glad of it I never liked long walks especially on chilly afternoons dreadful to me was the coming home in the raw twilight with nipped fingers and toes and a heart saddened by the chidings of Bessie the nurse and humbled by the consciousness of my physical inferiority to Eliza John and Georgiana Reed The said Eliza John and Georgiana were now clustered round their mama in the drawing room she lay reclined on a sofa by the fireside and with her darlings about her (for the time neither quarrelling nor crying) looked perfectly happy and I wanted to create a list such as: (I want to attach like a listing in front of the sentences, but depending on the position of the sentence) 0: There was no possibility of taking a walk that day 1: We had been wandering indeed in the leafless shrubbery an hour in the morning but since dinner (Mrs Reed when there was no company dined early) the cold winter wind had brought with it clouds so sombre and a rain so penetrating that further out door exercise was now out of the question 2: I was glad of it I never liked long walks especially on chilly afternoons dreadful to me was the coming home in the raw twilight with nipped fingers and toes and a heart saddened by the chidings of Bessie the nurse and humbled by the consciousness of my physical inferiority to Eliza John and Georgiana Reed 3: The said Eliza John and Georgiana were now clustered round their mama in the drawing room she lay reclined on a sofa by the fireside and with her darlings about her (for the time neither quarrelling nor crying) looked perfectly happy How would i go about it? Obviously, the first sentence w…
type: UnansweredQuestion
answer count: 1
type: Question

http://stackoverflow.com/a/49990494
has comment: http://stackoverflow.com/comment/86998118
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86997858
has comment: http://stackoverflow.com/comment/86997807
has comment: http://stackoverflow.com/comment/86997944
accepted answer of: http://stackoverflow.com/q/49990435
has comment: http://stackoverflow.com/comment/86997905
has comment: http://stackoverflow.com/comment/86997873
answers question: http://stackoverflow.com/q/49990435
has comment: http://stackoverflow.com/comment/86997982
has comment: http://stackoverflow.com/comment/86997775
has comment: http://stackoverflow.com/comment/86997712
type: Answer
has comment: http://stackoverflow.com/comment/86997744
score: 2
has body: As the docs say, in the write method: file is a file name, or a file object opened for writing. This includes a StringIO object. So: outfile = cStringIO.StringIO() tree.write(of) Then you can just pretty-print outfile using your favorite method—just outfile.seek(0) then pass outfile itself to a function that takes a file, or pass outfile.getvalue() to a function that takes a string. However, notice that many of the ways to pretty-print XML in the question you linked don't even need this. For example: lxml.etree.tostring (answer #2): lxml.etree is a near-perfect superset of the stdlib etree, so if you're going to use it for pretty-printing, just use it to build the XML in the first place. Effbot indent/prettyprint (answer #3): This expects an ElementTree tree, which is exactly what you already have, not a string or file.
has comment: http://stackoverflow.com/comment/86998167

http://stackoverflow.com/q/50072501
type: UnansweredQuestion
tagged with: machine-learning
has body: I am trying different classifiers with different parameters and stuff on a dataset provided to us as part of a course project. We have to try and get the best performance on the dataset. The dataset is actually a reduced version of the online news popularity I have tried the SVM, Random Forest, SVM with cross-validation with k = 5 and they all seem to give approximately 100% training accuracy, while the testing accuracy is between 60-70. I think the testing accuracy is fine, but the training accuracy bothers me. I would say maybe it was a case of overfitting data but none of my classmates seem to be getting similar results so maybe the problem is with my code. Here is the code for my cross-validation and random forest classifier. I would be very grateful if you help me find out why I am getting such a high Training accuracy def crossValidation(X_train, X_test, y_train, y_test, numSplits): skf = StratifiedKFold(n_splits=5, shuffle=True) Cs = np.logspace(-3, 3, 10) gammas = np.logspace(-3, 3, 10) ACC = np.zeros((10, 10)) DEV = np.zeros((10, 10)) for i, gamma in enumerate(gammas): for j, C in enumerate(Cs): acc = [] for train_index, dev_index in skf.split(X_train, y_train): X_cv_train, X_cv_dev = X_train[train_index], X_train[dev_index] y_cv_train, y_cv_dev = y_train[train_index], y_train[dev_index] clf = SVC(C=C, kernel='rbf', gamma=gamma, ) clf.fit(X_cv_train, y_cv_train) acc.append(accuracy_score(y_cv_dev, clf.predict(X_cv_dev))) ACC[i, j] = np.mean(acc) DEV[i, j] = np.std(acc) i, j = np.argwhere(ACC == np.max(ACC))[0] clf1 = SVC(C=Cs[j], kernel='rbf', gamma=gammas[i], decision_function_shape='ovr') clf1.fit(X_train, y_train) y_predict_train = clf1.predict(X_train) y_pred_test = clf1.predict(X_test) print("Train Accuracy :: ", accuracy_score(y_train, y_predict_train)) print("Test Accuracy :: ", accuracy_score(y_test, y_pred_test)) def randomForestClassifier(X_train, X_test, y_train, y_test): """ clf = RandomForestClassifier() clf.fit(X_train, y_train) y_predict_trai…
tagged with: python
score: 2
upvote count: 3
has title: Getting a 100% Training Accuracy, but 60% Testing accuracy
has answer: http://stackoverflow.com/a/50072702
answer count: 1
downvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question

http://stackoverflow.com/q/49978662
tagged with: django-forms
has comment: http://stackoverflow.com/comment/86974027
has comment: http://stackoverflow.com/comment/86974088
type: Question
type: UnansweredQuestion
has title: How to get values from a linked model for validation?
has answer: http://stackoverflow.com/a/49994595
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87005339
score: 0
has body: I don't know how get other fields, linked by OnetoOne with User model, in the clean method. I have models Profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) books = models.CharField(max_length=25) And I want validation in method clean: class ProfileForm(UserCreationForm): class Meta: fields = '__all__' def clean(self): cleaned_data = super().clean() get_books = cleaned_data.get('books') #this I get error I only get the default user model fields (username, first_name..) How get value from the field 'books'?
answer count: 1
tagged with: django-models

http://stackoverflow.com/comment/87006699
type: Comment
type: QuestionComment
has text: I tried that option .Give me the same error . @ZdaR
comment on: http://stackoverflow.com/q/49994760
score: 0

http://stackoverflow.com/q/49931307
tagged with: rdbms
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/4048151
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86880134
has comment: http://stackoverflow.com/comment/86879003
favorite count: 0
type: Question
has body: i have a website that simulate courses dependencies like this : i found that network model is the best model or my case but i haven't found any implementation to it in RDBMS. i am using now adjacent list but it have problems in some scenarios and weak performance. i have read about modified pre-order traversal tree but it is useful in tress not graphs so how can i simulate graph in database ?
tagged with: graph
has comment: http://stackoverflow.com/comment/86887418
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/86899866
tagged with: python
has comment: http://stackoverflow.com/comment/86880098
has title: how to simulate graph in database
has answer: http://stackoverflow.com/a/49937081
has comment: http://stackoverflow.com/comment/86887069
tagged with: sql

http://stackoverflow.com/comment/87104805
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50033387
has text: True, do you know if there is any way for it to infer consistently? (i.e. _"If not all rows can have month first, it can never be month first"_)
type: Comment

http://stackoverflow.com/comment/98637994
has text: cool, I'm not working on the project that caused the original question but next time I come across this problem I'll try out your solution.
type: Comment
comment on: http://stackoverflow.com/a/55973157
type: AnswerComment
score: 0

http://stackoverflow.com/comment/117187508
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50461221
has text: Absolutely do not do this.

http://stackoverflow.com/comment/87039160
has text: You could rename `self.__dict` to `self._only_write_from_add_to_dict_method` (both easy to implement and obvious to users of the class).
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50010964

http://stackoverflow.com/comment/87108120
type: QuestionComment
comment on: http://stackoverflow.com/q/50045775
has text: can't it be called with `soupparser.fromstring(html_goo)` then ? I'm quite surprised it doesn't work when this is directly from their doc :p
score: 0
type: Comment

http://stackoverflow.com/comment/87909520
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49943662
has text: Possible duplicate of *[Not able to install Python packages \[SSL: TLSV1\_ALERT\_PROTOCOL\_VERSION\]](https://stackoverflow.com/questions/49768770/not-able-to-install-python-packages-ssl-tlsv1-alert-protocol-version)*.
score: 0

http://stackoverflow.com/comment/87055544
type: QuestionComment
comment on: http://stackoverflow.com/q/50019210
has text: Do they have to install pandas to use your software?
type: Comment
score: 0

http://stackoverflow.com/a/49994246
score: 2
has comment: http://stackoverflow.com/comment/87004877
has body: This should help, it is not useing the full range of list, but just the "borders" you are interested in, some creative zip()ping and fixes whats wrong after creating the ranges: def split(l, n): stride =(l//n) r = list(range(1, l+stride, stride)) # overbuild needed range # adjust zipped value by 1 if needed k = [ [a , b-1 ] for a,b in zip(r,r[1:]) ] # fix special cases for _ in range(n+1): # guesstimate of fixes needed if k[-1][0] == k[-1][1]: # last pair identical k.pop() # remove it and fix new last index to be l instead k[-1][1] = l elif k[-1][1] != l: k[-1][1] = l return k print(split(100, 2)) print(split(100, 4)) print(split(103, 3)) print(split(6, 3)) Output: [[1, 50], [51, 100]] # split(100, 2) [[1, 25], [26, 50], [51, 75], [76, 100]] # split(100, 4) [[1, 34], [35, 68], [69, 103]] # split(103, 3) [[1, 2], [3, 4], [5, 6]] # split(6, 3) I gave it a cursory testing with your examples, check the logic if it fits all your special cases. Especially the # guesstimate of fixes needed might be too many... I have a hunch that at most 2 should be enough
upvote count: 2
answers question: http://stackoverflow.com/q/49993689
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87005366

http://stackoverflow.com/comment/87098331
comment on: http://stackoverflow.com/q/50040056
score: 1
type: Comment
type: QuestionComment
has text: Can't run your code. You renamed the `grad()` function to `derivative()` but the calls are still to `grad()`. Also, how do you get `x` from `input_tensor`. Can you please post a runnable, one-piece code I can just copy-paste to see what's going on?

http://stackoverflow.com/comment/87067965
score: 2
has text: Maybe I misunderstood but isn't OP asking for `a.iloc[:2]"C", "D" /= 5`? *"I want to divide columns C and D by 5 but only upto 2nd index"*
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50025811

http://stackoverflow.com/comment/87044155
comment on: http://stackoverflow.com/q/50013902
has text: @MattM. Here is the link http://pipeline.lbl.gov/cgi-bin/textBrowser2?act=mvista&run=u233-9GR6Sl35 it is also in the code. It's the part that says url =
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/49972165
has body: I'm trying to calculate a disparity map using openCV3 in python but the result is not satisfactory. I made sure that the calibration and rectification are done correctly: I tried disparity function in Matlab using these rectified images and results were quite good. However, the opencv output looks like a Van Gogh paitning: . Here is the python code related to disparity: block_matcher = cv2.StereoBM_create(numDisparities=16, blockSize=15) disp = block_matcher.compute(rectified_l, rectified_r) Interestingly, a range of disparity is [-16,240], however, I expect it to be in [0,16] since I set numDisparities to 16. Am I misunderstanding the concept of numDisparities? I tried varying the numDisparities and blockSize but didn't get any meaningful improvement. Let me know if you have ideas on what is going on.
tagged with: python
favorite count: 0
has title: Bad disparity map using OpenCV
upvote count: 2
has answer: http://stackoverflow.com/a/50053400
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: computer-vision
tagged with: disparity-mapping
type: Question
tagged with: opencv
score: 2
tagged with: stereo-3d

http://stackoverflow.com/a/50058671
type: Answer
has body: Try to divide your efforts into smaller bits. Solve the problem of comparing strings separately from the GUI part. Your code only counts the number of differences but I think you want to find out which characters in the strings are the same and which are different: string_1 = 'aaaaaaaa' string_2 = 'aaXaaXXa' result = '' for index, char in enumerate(string_1): # Loop through the string if char == string_2[index]: result = result + 'o' else: result = result + 'x' print(result) # prints: "ooxooxxo", where x means different. Note: this code snippet only works for strings of equal length, but it's the idea that's important. After you have got this to function properly for strings of different sizes you can start to think about presenting them in a text widget.
answers question: http://stackoverflow.com/q/50045719
score: 0

http://stackoverflow.com/q/49977283
type: Question
has answer: http://stackoverflow.com/a/49978145
has answer: http://stackoverflow.com/a/49977327
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/62800822
tagged with: python
score: -1
tagged with: http://stackoverflow.com/tag/xml
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/122573814
has comment: http://stackoverflow.com/comment/86971004
has title: Python : error in working on xml file
tagged with: openpyxl
downvote count: 1
tagged with: load
has body: import openpyxl import os workbook = openpyxl.load_workbook('data.xlsx' ) The above three lines code I have written to load the XML file. I am getting the below error: *****Warning (from warnings module): File "C:\Users\gprasad8\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\packaging\workbook.py", line 92 warn(msg) UserWarning: File contains an invalid specification for Sheet1. This will be removed***** The XML file location is same as with the python file path. Can any one help me out with this error?
favorite count: 0

http://stackoverflow.com/comment/87150705
type: Comment
has text: Thank you, the point on avoiding a parsing library like parse_qs is to learn the inner workings etc.I gave up on parse_qs last night let me try this answer see where I get. I'll also make sure to avoid confusing var names.
score: 0
comment on: http://stackoverflow.com/a/50058384
type: AnswerComment

http://stackoverflow.com/q/49946551
has answer: http://stackoverflow.com/a/49966114
has comment: http://stackoverflow.com/comment/86911556
has comment: http://stackoverflow.com/comment/86909592
downvote count: 5
has comment: http://stackoverflow.com/comment/86909612
has comment: http://stackoverflow.com/comment/86909579
has body: So lets say you have a text file called myfile.txt, and it contains four sentences, each on a different line. Here's a crude example Hello I like the color red Red is a primary color I do not like blue I like orange as well How would one go about on coding in python, that would display each word, and the corresponding line it is located on, in a new text file? Example Output Hello 1 I 1 3 like 1 3 the 1 color 1 2 red 1 2 is 2 a 2 primary 2 do 3 not 3 blue 3 orange 4 as 4 well 4 My current Code #Dictionaries and variables word_Dic = {} line_Num = 0 #Opening text file text = open("myfile.txt", "r") #For statement splitting text file for t in text: line_Num = line_Num + 1 line1 = text.readline() line2 = text.readline() line3 = text.readline() line4 = text.readline() #Creating a list, splitting all text #files within text file. split1 = (line1.split()) split2 = (line2.split()) split3 = (line3.split()) split4 = (line4.split()) #print(words_Split)
tagged with: python
has comment: http://stackoverflow.com/comment/86910020
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/49966114
score: -5
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86909551
has title: In Python 3.6, How to display which lines a word occurs in a text file?
tagged with: python-3.x

http://stackoverflow.com/a/50044739
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50044407
has body: I assume that you don't actually require try_recording to be recursive, so it can be rewritten like this: def try_recording(stream,RATE, CHUNK): while flag != 1: for i in range(0,int(RATE/CHUNK)): data = stream.read(CHUNK) frames.append(data) Also you are not starting your processes correctly. They should be: p1 = Process(target=try_recording, args=(stream,RATE,CHUNK)) p2 = Process(target=scan_input) And your flag should be a shared variable: # flag = 0 flag = multiprocessing.Value('i', 0)
has comment: http://stackoverflow.com/comment/87107128
has comment: http://stackoverflow.com/comment/87106433
has comment: http://stackoverflow.com/comment/87107305
answers question: http://stackoverflow.com/q/50044407
type: Answer
has comment: http://stackoverflow.com/comment/87106549
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86905145
type: QuestionComment
has text: You're appending a list of employees. Change `append([people2])` to `append(people2)`.
score: 2
type: Comment
comment on: http://stackoverflow.com/q/49944482

deserialization
type: Tag
tags question: http://stackoverflow.com/q/49956569
tag name: deserialization

http://stackoverflow.com/a/49957309
type: AcceptedAnswer
has body: This is one way using vectorised functionality. df = pd.DataFrame({'WO No': ['OR-20180422-12345']}) df'CO', 'WO Date', 'WO ID' = df['WO No'].str.split('-', expand=True) df['WO Date'] = pd.to_datetime(df['WO Date']).dt.strftime('%d/%m/%Y') df = df'CO', 'WO Date' print(df) # CO WO Date # 0 OR 22/04/2018
type: Answer
accepted answer of: http://stackoverflow.com/q/49957164
has comment: http://stackoverflow.com/comment/86930788
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49957164
downvote count: 0

http://stackoverflow.com/q/49917936
answer count: 0
has body: I'm trying to build a random forest wit a csv file. My code so far: CSV_PATH = "C:/Users/xxxxx/Documents/tutorials/features_cut.csv" APP_NAME = "Random Forest Example" SPARK_URL = "local[*]" RANDOM_SEED = 13579 TRAINING_DATA_RATIO = 0.7 RF_NUM_TREES = 3 RF_MAX_DEPTH = 4 RF_NUM_BINS = 32 from pyspark import SparkContext from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName(APP_NAME) \ .master(SPARK_URL) \ .getOrCreate() data = spark.read \ .options(header = "true", inferschema = "true") \ .csv(CSV_PATH) print("Total number of rows: %d" % df.count()) #470121 All the values in the DataFrame are Strings. from pyspark.mllib.linalg import Vectors from pyspark.mllib.regression import LabeledPoint transformed_data = data.rdd.map(lambda x: LabeledPoint(x[-1], Vectors.dense(x[0:-1]))) splits = [TRAINING_DATA_RATIO, 1.0 - TRAINING_DATA_RATIO] training_data, test_data = transformed_data.randomSplit(splits, RANDOM_SEED) Here the ERROR occures: print("Number of training set rows: %s" % training_data.count()) print("Number of test set rows: %s " % test_data.count()) #Value Error: could not convert string to float 'PLOT' I have trouble to understand how the rdd.map function works. I would appreciate your help. UPDATEd: indexers = [StringIndexer(inputCol=column, outputCol=column+"_index").setHandleInvalid("keep") for column in list(set(data.columns)) ] pipeline = Pipeline(stages=indexers) df_r = pipeline.fit(data).transform(data) with the help of StringIndexer and Pipeline I could transform my strings into doubles.
has comment: http://stackoverflow.com/comment/86861924
has comment: http://stackoverflow.com/comment/86890127
type: Question
tagged with: random-forest
type: UnansweredQuestion
has title: Value Error: could not convert string to float 'PLOT' after data.rdd.map
tagged with: pyspark
tagged with: python
tagged with: rdd
has comment: http://stackoverflow.com/comment/86862256
score: 0
has comment: http://stackoverflow.com/comment/86855437
has comment: http://stackoverflow.com/comment/86860251

http://stackoverflow.com/comment/86938673
type: Comment
type: QuestionComment
has text: @Charlie nothing of that sort happens. When quit() is placed somewhere in your code, the program will just stop no matter what is happening. It won't do anything else.
score: 0
comment on: http://stackoverflow.com/q/49961051

http://stackoverflow.com/q/50058811
has title: How to access video stream from an ip camera using opencv in python?
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/50060784
has answer: http://stackoverflow.com/a/62761109
answer count: 4
has answer: http://stackoverflow.com/a/50701911
upvote count: 3
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/53984522
favorite count: 0
tagged with: ip
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/87134121
type: UnansweredQuestion
has body: Right now I am using a web cam and it works perfectly fine with the code below -: capture = cv2.VideoCapture(0) Now instead of web cam, I want to use the ip camera(https://192.168.0.60) What would be the easiest way to do it with OpenCV(Python)? I saw a bunch of posts, but couldn't find a straight answer to this. Can someone help, who already got it running? Thank you!

http://stackoverflow.com/q/49930102
has title: Can PyCharm have multiple conda environment variables for the same project
tagged with: pycharm
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50027348
accepted answer: http://stackoverflow.com/a/50027348
has body: There are many discussions on how to use conda environment variables in PyCharm projects. These discussions, however, often assume that for each PyCharm project only one conda environment variable is used. Then here is my question: is it possible to have multiple conda enviroment variables for the same project? I give the following example to make my point much clearer: pycharm_project_name abc.py (use conda environment variable: TensorFlow) def.py (use conda environment variable: Caffe) In this example, the PyCharm project has two python scripts with each depending on its own environment variable. In this case, how could I set the PyCharm project in a proper way?
favorite count: 0
type: AnsweredQuestion
tagged with: python
type: Question

http://stackoverflow.com/a/49959114
score: 0
has comment: http://stackoverflow.com/comment/86945946
has body: Try it: ## error (r'"[^"\\]*(\\.[^"\\]*)*.', 0, STYLES['error']), (r"'[^'\\]*(\\.[^'\\]*)*.", 0, STYLES['error']), # Double-quoted string, possibly containing escape sequences (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']), # Single-quoted string, possibly containing escape sequences (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
answers question: http://stackoverflow.com/q/49956992
type: Answer

python-datetime
tags question: http://stackoverflow.com/q/49965578
tag name: python-datetime
tags question: http://stackoverflow.com/q/50050657
tags question: http://stackoverflow.com/q/50045251
type: Tag
tags question: http://stackoverflow.com/q/49954438

http://stackoverflow.com/comment/86852393
type: Comment
type: QuestionComment
has text: I'm using MySQL
comment on: http://stackoverflow.com/q/49918095
score: 0

http://stackoverflow.com/comment/86963728
has text: @Lien - Yes, so `fillna(0)` is what need. But not sure if understand, what happens if there are not only `0` and `NaN`s in some Series? Then what need?
comment on: http://stackoverflow.com/a/49973838
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87049562
type: QuestionComment
comment on: http://stackoverflow.com/q/50016628
score: 0
has text: `import myEnv.Scripts.gdal_calc`? but import and subprocess do different thing.
type: Comment

http://stackoverflow.com/q/50074545
tagged with: multiprocessing
type: Question
tagged with: named-pipes
has answer: http://stackoverflow.com/a/50084044
tagged with: python
has body: Multiprocessing's Pipes and Queue are based on anonymous pipes, does the multiprocessing of Python provide named pipes （FIFO）?
has title: Does multiprocessing support named pipes （FIFO)?
has comment: http://stackoverflow.com/comment/87165909
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50084044
downvote count: 0
accepted answer: http://stackoverflow.com/a/50074720
has answer: http://stackoverflow.com/a/50074720
favorite count: 0
linked to: http://stackoverflow.com/q/50084557

http://stackoverflow.com/comment/86949031
type: QuestionComment
comment on: http://stackoverflow.com/q/49966596
has text: yes, that's what im asking, and that works , But lambda,is just creating a function which could be replaced with its own type and call method?
score: 0
type: Comment

http://stackoverflow.com/comment/87079241
comment on: http://stackoverflow.com/a/50014545
score: 0
type: AnswerComment
has text: Every XML node is going to trigger both a `start` and `end` event, so you only really need to handle one of them. When the `start` event fires it's not guaranteed that all the attributes of the current XML node have been processed yet, so the safer approach is to only handle the `end` event.
type: Comment

http://stackoverflow.com/q/49952014
has title: Splitting lines in python 2.7 throws error in Linux, works in Windows
downvote count: 1
favorite count: 0
has body: Here is my code: d = each_data[0].strip().split("\x0a") works as expected in Windows, but in Linux it throws error below: TypeError: a bytes-like object is required, not 'str' each_data[0] contains two lines Any clue is appreciated, thank you. Update: Please refer to the script here: https://raw.githubusercontent.com/mdivk/solr_demo/master/scripts/script_p2.py Environment requirement: python 2.6.6 (sorry I Know this is a low version, it is the built-in python we have on all the CentOS with Cloudera CDH installed, it would be un-realistic to upgrade python in a short time and I need this be fixed in shortest time) Keep in mind: the code is working as expected in Windows in python 2.7
score: 0
has answer: http://stackoverflow.com/a/49952046
has comment: http://stackoverflow.com/comment/86920521
tagged with: python
has comment: http://stackoverflow.com/comment/86926896
has answer: http://stackoverflow.com/a/49988388
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86926542
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33054527
has comment: http://stackoverflow.com/comment/86920452
has comment: http://stackoverflow.com/comment/86927309
upvote count: 1

http://stackoverflow.com/a/49943741
downvote count: 0
has comment: http://stackoverflow.com/comment/99848639
answers question: http://stackoverflow.com/q/49942388
upvote count: 6
type: Answer
score: 6
has body: Try to uninstall the package from anaconda and then install it with pip: conda uninstall pillow: Conda remove Pillow Install pillow with pip: pip install pillow

http://stackoverflow.com/a/49919551
answers question: http://stackoverflow.com/q/49918701
has body: f.readLines not effective solution. If you work on huge file why do you want to read all file into memory? def getNthLine(i): if i&lt;1: return 'NaN'; else: with open('temp.text', 'r') as f: for index, line in enumerate(f): if index == i: line = line.strip() return line f = open('temp.text','r'); for i,line in enumerate(f): print(line.strip()); print(getNthLine(i-1)); There is no much more options to solve that kind of a problem. you could also use tell and seek methods to play around but generally no need for ninja :). If you using on huge file just do not forget to use enumerate
type: Answer
score: 0

http://stackoverflow.com/q/50013613
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87387003
type: AnsweredQuestion
score: 1
tagged with: validation
has comment: http://stackoverflow.com/comment/87043575
answer count: 1
accepted answer: http://stackoverflow.com/a/50015080
has body: I'm trying to make a little guessing game in python by using the random import. Problem is, I want the user to be able to enter "exit" to end, but I also need to compare their data to the random number. My thinking now is, how can I ask the user for an int, but also check if they entered a string called exit? The code is supposed to let them keep playing if they guess it right. so far i have this. import random num = random.randint(1, 100) guess = input("Enter your guess: ") while guess != "exit": if guess.isdigit() == False: guess = input("Please enter valid number: ") elif guess &gt; num: print("Lower!") elif guess &lt; num: print("Higher!") elif guess == num: print("YOU GOT IT!!!!!") print("Setting new number.") num = random.randint(1, 100) guess = input("Enter number now: ") print("Terminating game now.")
has title: How to validate data in python using both string and int?
downvote count: 1
has answer: http://stackoverflow.com/a/50015080
favorite count: 0

http://stackoverflow.com/q/49977765
tagged with: python
type: Question
score: 2
has title: Python multiple process share the same object or not?
has body: I found this why multiple processes have the same object id in python, but I do not quite understand what does it mean "because both processes execute the same code", I try the code, it seems the outputs are always the same. ➜ ~ python test2.py 4419085696 4419085696 ➜ ~ python test2.py 4342830464 4342830464 ➜ ~ python test2.py 4510156160 4510156160 ➜ ~ python test2.py 4329948544 4329948544 ➜ ~ python test2.py 4468004224 4468004224 ➜ ~ python test2.py 4326647168 4326647168 ➜ ~ python test2.py 4445738368 4445738368 ➜ ~ python test2.py 4388980096 4388980096 ➜ ~ python test2.py 4511999360 4511999360 ➜ ~ python test2.py 4562851200 4562851200 ➜ ~ python test2.py 4535031168 4535031168 ➜ ~ python test2.py 4314420608 4314420608 ➜ ~ python test2.py 4536034688 4536034688 I also find this refer http://code.activestate.com/lists/python-list/656748/ on web. It also seems that python multiple processes shares the same object. Anyone could help to explain a bit further? Thanks in advance.
upvote count: 2
has comment: http://stackoverflow.com/comment/86976493
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86971702
linked to: http://stackoverflow.com/q/33817442
accepted answer: http://stackoverflow.com/a/49977892
favorite count: 0
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/49977892
type: AnsweredQuestion

http://stackoverflow.com/q/49959727
type: Question
has body: I am doing this project in which i applied minibatches in neural network and calculating epoch cost:- def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1500, minibatch_size = 32, print_cost = True): ops.reset_default_graph() tf.set_random_seed(1) seed = 3 costs = [] (n_x, m) = X_train.shape n_y = Y_train.shape[0] #create placeholder X, Y = create_placeholder(n_x, n_y) # init parameter parameters = init_parameter() # forward prop Z3 = forward_prop(X, parameters) # compute cost cost = compute_cost(Z3, Y) # optimizer optimizer = tf.train.AdamOptimizer(learning_rate= learning_rate).minimize(cost) # Initialize all variables init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(num_epochs): epoch_cost = 0 num_minibatche = int(m/ minibatch_size) seed = seed + 1 minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed) for minibatch in minibatches: (minibatch_X, minibatch_Y) = minibatch _, minibatch_cost = sess.run([optimizer, cost], feed_dict = {X: minibatch_X, Y: minibatch_Y}) epoch_cost += minibatch_cost / num_minibatche # Print the cost every epoch if print_cost == True and epoch % 100 == 0: print ("Cost after epoch " ,epoch, np.mean(epoch_cost)) if print_cost == True and epoch % 5 == 0: costs.append(epoch_cost) # plot the cost plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per tens)') plt.title("Learning rate =" + str(learning_rate)) plt.show() # save the parameters parameters = sess.run(parameters) print ("Parameters have been trained!") # Calculate the correct predictions correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y)) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train})) print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test})) return parameters SO when i run this code i am getting this error on line:- ---->epoch_cost +=…
type: UnansweredQuestion
tagged with: neural-network
tagged with: machine-learning
tagged with: python
has title: Getting error in epoch_cost "operands could not be broadcast together with shapes (32,) (5,) (32,) " while applying minibatches in neural net
has answer: http://stackoverflow.com/a/49959971
score: 0
tagged with: deep-learning
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/q/50017186
has comment: http://stackoverflow.com/comment/87050587
has comment: http://stackoverflow.com/comment/87050643
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87050600
has answer: http://stackoverflow.com/a/50017290
accepted answer: http://stackoverflow.com/a/50017290
has comment: http://stackoverflow.com/comment/87050652
has title: How to use glob on python
has body: I'm trying to get a list of files on python using glob, however it is returning zero. the method goes: def read(self,folders) "folders" input contain the files needed to be looped through I used files = glob(folders)
linked to: http://stackoverflow.com/q/7409780
score: -6
favorite count: 0
type: Question
upvote count: 0
answer count: 1
tagged with: python
downvote count: 6

http://stackoverflow.com/comment/86989755
type: Comment
type: QuestionComment
has text: Posting the exact same question on Super User is just going to get it migrated here and closed. If you want to know how to fix your FTP connection in general, you probably write a more general question there—ideally one that shows using a standard FTP client instead of your own code, then mentions what you tried in Python (with a link to this question) to demonstrate that it's not client-specific.
comment on: http://stackoverflow.com/q/49976095
score: 0

http://stackoverflow.com/a/76056258
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: For what its worth, I managed to build and install cartopy (and cartes) on Windows 10 with python 3.10.9 and Cartopy==0.21.1 : using pip i.e. without anaconda/conda without the tricky global-options stuff as seen here The base for all of this is to do a custom build of https://libgeos.org You'll need : powershell console and admin rights, everything below should work within the powershell - EDIT : one can probably use a standard DOS shell using the Visual Studio DOS shell launchers (see edit 2 below) MSVC C++ build tools, possibily visual studio cmake Procedure create a fresh ptyhon 3.9 venv python -m venv venv or py -3.10 -m venv venv Install Visual Studio and MSVC c++ build tools https://visualstudio.microsoft.com/fr/downloads/ I don't remember which versions I installed ... Retro analysis shows that this was invoked or referenced at some point subsequently to the pip install cartopy command: MSBuild version 17.5.1+f6fdcf537 for .NET Framework C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.35.32215\ and child dirs C:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ and child dirs see also Cannot open include file: 'io.h': No such file or directory Install chocolatey Open a Powershell console "Developer PowerShell for VS 2022" and activate your venv venv\Scripts\activate.ps1 Install cmake chocolatey install cmake Partially apply procedure indicated here https://libgeos.org/usage/download/ : unzip geos source zip, then go to unzipped dir I took version 3.11.2, but take whatever suits your needs. I choose to install into %ProgramFiles%, again, take whatever suits you. cd the_unzip_dir mkdir _build cd _build cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="%ProgramFiles%\geos-3.11.2" .. Cmake will detect the Visual Studio toolsuite and generate a bunch of MSVS project files (*.vcxproj). (What happens if you try without VS but minggw or else ... I don't know.) Build the Visual Studio projects then perform "installation" step (…
answers question: http://stackoverflow.com/q/50001347

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/49952480
tags question: http://stackoverflow.com/q/49970116
tags question: http://stackoverflow.com/q/50062126
tags question: http://stackoverflow.com/q/49975227
tags question: http://stackoverflow.com/q/50027501
tags question: http://stackoverflow.com/q/50013902
tags question: http://stackoverflow.com/q/49998508
tags question: http://stackoverflow.com/q/50002386
tags question: http://stackoverflow.com/q/50017584
tags question: http://stackoverflow.com/q/49994136
tags question: http://stackoverflow.com/q/50071153
tags question: http://stackoverflow.com/q/49986038
tags question: http://stackoverflow.com/q/50046945
tags question: http://stackoverflow.com/q/50004209
tags question: http://stackoverflow.com/q/50052053
tags question: http://stackoverflow.com/q/50067015
tags question: http://stackoverflow.com/q/50042492
tags question: http://stackoverflow.com/q/49988566
tags question: http://stackoverflow.com/q/49939449
tags question: http://stackoverflow.com/q/50062237
tags question: http://stackoverflow.com/q/50018249
tags question: http://stackoverflow.com/q/49959329
tags question: http://stackoverflow.com/q/49936127
tags question: http://stackoverflow.com/q/50003815
tags question: http://stackoverflow.com/q/49946180
tags question: http://stackoverflow.com/q/50070515
tags question: http://stackoverflow.com/q/49951814
tags question: http://stackoverflow.com/q/49971228
tags question: http://stackoverflow.com/q/49949370
tags question: http://stackoverflow.com/q/49962413
tags question: http://stackoverflow.com/q/50007054
tags question: http://stackoverflow.com/q/50064426
tags question: http://stackoverflow.com/q/49972237
tags question: http://stackoverflow.com/q/49999665
tags question: http://stackoverflow.com/q/50001220
tags question: http://stackoverflow.com/q/49955536
tags question: http://stackoverflow.com/q/50043221
tags question: http://stackoverflow.com/q/50026264
tags question: http://stackoverflow.com/q/50023796
tags question: http://stackoverflow.com/q/49961214
tags question: http://stackoverflow.com/q/49996057
tags question: http://stackoverflow.com/q/50016011
tags question: http://stackoverflow.com/q/49940129
tags question: http://stackoverflow.com/q/50057928
tags question: http://stackoverflow.com/q/49984257
tags question: http://stackoverflow.com/q/50014456
tags question: http://stackoverflow.com/q/49949020
tags question: http://stackoverflow.com/q/49991604
type: Tag
tags question: http://stackoverflow.com/q/49961349
tags question: http://stackoverflow.com/q/49959206
tags question: http://stackoverflow.com/q/49946213
tag name: html
tags question: http://stackoverflow.com/q/50030354
tags question: http://stackoverflow.com/q/50065151
tags question: http://stackoverflow.com/q/49925460
tags question: http://stackoverflow.com/q/49959241
tags question: http://stackoverflow.com/q/49993754
tags question: http://stackoverflow.com/q/50054116
tags question: http://stackoverflow.com/q/49980826
tags question: http://stackoverflow.com/q/50014068
tags question: http://stackoverflow.com/q/49934551
tags question: http://stackoverflow.com/q/49969337
tags question: http://stackoverflow.com/q/50014339
tags question: http://stackoverflow.com/q/50035039
tags question: http://stackoverflow.com/q/50012384
tags question: http://stackoverflow.com/q/50040255
tags question: http://stackoverflow.com/q/50064601
tags question: http://stackoverflow.com/q/49988421
tags question: http://stackoverflow.com/q/49957034
tags question: http://stackoverflow.com/q/50054863
tags question: http://stackoverflow.com/q/50057220
tags question: http://stackoverflow.com/q/49988239
tags question: http://stackoverflow.com/q/49922463
tags question: http://stackoverflow.com/q/50000807
tags question: http://stackoverflow.com/q/49991987
tags question: http://stackoverflow.com/q/49962741
tags question: http://stackoverflow.com/q/49918742

http://stackoverflow.com/comment/87203047
type: AnswerComment
has text: I know it scheduled 4 executors. I took a screenshot of those: https://www.dropbox.com/s/fmrctpi0umt6qh3/yarn-spark-executors1.png?dl=0
score: 0
comment on: http://stackoverflow.com/a/50077472
type: Comment

http://stackoverflow.com/a/49941304
downvote count: 1
type: Answer
has body: After your append operation, you need to return the object. class Problem: def __init__(self): self.lItems = [] def __iadd__(self, other): self.lItems.append(other) return self Example &gt;&gt;&gt; problem = Problem() &gt;&gt;&gt; problem += 'text' &gt;&gt;&gt; problem.lItems ['text'] &gt;&gt;&gt; problem += 'foobar' &gt;&gt;&gt; problem.lItems ['text', 'foobar']
answers question: http://stackoverflow.com/q/49941192
score: 0
upvote count: 1

http://stackoverflow.com/q/49954080
has comment: http://stackoverflow.com/comment/86924862
tagged with: excel
has comment: http://stackoverflow.com/comment/86924886
has title: OpenPyXL: Compare a string in a cell to a string set to print all cell values in row
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/50054065
tagged with: openpyxl
answer count: 1
downvote count: 1
favorite count: 0
has body: I've been using Python with OpenPyXL to access an Excel file with 3000+ rows. I've been trying to print whole rows (or certain cell values in rows) containing a string cell value that I want to search but it seems I encounter an error: TypeError: argument of type 'NoneType' is not iterable This is the code I'm using (For now, I'm just trying to output the cell.value of the cell containing the string I want to search but I want to output a certain cell in the row or the whole row itself) &gt;&gt;&gt; from openpyxl import * &gt;&gt;&gt; wb = load_workbook('C:\Users\Aldwin\Desktop\Excel1.xlsx',read_only=True) for row in ws.iter_rows(min_row=1, min_col=1): for cell in row: if 'DRLDMEM' in cell.value: #String I want to search: 'DRLDMEM' print(cell.value, end=" ") print() Traceback (most recent call last): File "&lt;pyshell#19&gt;", line 3, in &lt;module&gt; if 'DRLDMEM' in cell.value: TypeError: argument of type 'NoneType' is not iterable When I do a check on individual cells it works. Say, cell AA13 contains a part of the string: &gt;&gt;&gt; print(ws['AA13'].value) DRLDMEM, READ, PCINC &gt;&gt;&gt; 'DRLDMEM' in ws['AA13'].value True I want to output print like this: T1 FETCH2: DR←M, PC←PC+1 DRLDMEM, READ, PCINC T3 SUBIMM1: DR←M DRLDMEM, READ T3 ANDIMM1: DR←M DRLDMEM, READ Out of 3000+ rows, the output desired are only the rows with a cell that has DRLDMEM (or preferably, the cell with values: FETCH2, SUBIMM1, ANDIMM1) I don't know what to do to solve this. Any thoughts and suggestions are much appreciated.
has comment: http://stackoverflow.com/comment/86924693
type: Question
accepted answer: http://stackoverflow.com/a/50054065
has comment: http://stackoverflow.com/comment/86925016
tagged with: python
score: -1

http://stackoverflow.com/q/49944010
has comment: http://stackoverflow.com/comment/87291639
downvote count: 0
has comment: http://stackoverflow.com/comment/93310570
answer count: 1
has comment: http://stackoverflow.com/comment/87451671
tagged with: machine-learning
tagged with: keras
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86925042
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87451909
has comment: http://stackoverflow.com/comment/87475189
tagged with: time-series
has body: I'm currently working on a bigger project. The goal is to automatically find split points in time series which splits the series into elementary patterns. I have a lot of training data in form of time series with different lengths and split points manually recorded on useful positions. Basically, I have the x, y, z positions and the distances between those points over a centered window of the lengths 2, 25 and 50 (dist2, dist25, dist50). I also divided the room into a 3D grid and figured out in which cell the position lies (cell_x, cell_y, cell_z). I think this could be useful because elementary operations will more likely be in one or two cells. cell_x, cell_y, cell_z based on size 50. The vertical red lines are the split points of the training data. Now I want to know at every point in the time series if it is a split point or not. In my opinion, these are enough features to start with but I think my Keras model isn't correct because the result is always and only 1 at the 0's time series index. It's basically, a binary classification problem based on past and future values. This was the reason I've tried to solve it with an LSTM. It looks like this: model = Sequential() model.add(LSTM(20, input_shape = (None, input_dim), return_sequences = True)) model.add(Dropout(0.5)) model.add(LSTM(20)) model.add(Dropout(0.5)) model.add(Dense(1, activation = 'sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) Because I'm at the very beginning of the whole Machine Learning topic and the mass of materials is a bit overwhelming I'm here to ask for some help. I know that there are a lot of other things (bad training data, wrong features, wrong parameters, ...) which can cause to this results but I want to know how I can build a Keras model for this problem correctly. I already found a lot of Keras examples but I'm not sure if they fit the problem.
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/86913368
has comment: http://stackoverflow.com/comment/87485636
has comment: http://stackoverflow.com/comment/86924934
has title: Keras LSTM model for binary classification with sequences
tagged with: python
has comment: http://stackoverflow.com/comment/87489737
has comment: http://stackoverflow.com/comment/86927429
has answer: http://stackoverflow.com/a/50243951
accepted answer: http://stackoverflow.com/a/50243951
type: AnsweredQuestion

http://stackoverflow.com/comment/86875142
has text: I have also tried upgrading the selenium package using the pip `pip install -U selenium` Also, running the Firefox latest version (59.0.2), Python (3.6.5) and Selenium Gecko webdriver (0.20.0). Not sure if anything is needed to help on this.
comment on: http://stackoverflow.com/q/49929374
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86935612
has text: @officialaimm I actually forgot `exec` existed. Unsurprisingly, I've never used either for actual code I've written.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49959358

http://stackoverflow.com/a/50019111
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: This is just an idea of what you could do: Extract the JS code into a Python variable. Make a regex operation extracting the value of the variable. "JSONify" such variable value. Extract the data you need. As an extract: a = '''var LifeTimeStats = [{"Key":"Top 3","Value":"31"},{"Key":"Top 5s","Value":"36"},{"Key":"Top 3s","Value":"13"},{"Key":"Top 6s","Value":"27"},{"Key":"Top 12s","Value":"76"},{"Key":"Top 25s","Value":"58"},{"Key":"Score","Value":"99,788"},{"Key":"Matches Played","Value":"502"},{"Key":"Wins","Value":"9"},{"Key":"Win%","Value":"2%"},{"Key":"Kills","Value":"730"},{"Key":"K/d","Value":"1.48"}];''' b = re.findall(r'var.*?=\s*(.*?);', a)[0] c = json.loads(b) See the dummy full code I wrote. UPDATE After seeing the full code... This could be a solution for your problem.
has comment: http://stackoverflow.com/comment/87061245
has comment: http://stackoverflow.com/comment/87058830
has comment: http://stackoverflow.com/comment/87063880
has comment: http://stackoverflow.com/comment/87061867
accepted answer of: http://stackoverflow.com/q/50018614
has comment: http://stackoverflow.com/comment/87059781
has comment: http://stackoverflow.com/comment/87063024
type: Answer
answers question: http://stackoverflow.com/q/50018614
has comment: http://stackoverflow.com/comment/87061107
score: 1

http://stackoverflow.com/comment/86896718
score: 0
type: Comment
has text: No, just added the year to the dataframe like you. I will update the code in my question the way I have done it.
type: AnswerComment
comment on: http://stackoverflow.com/a/49929393

http://stackoverflow.com/q/49959531
accepted answer: http://stackoverflow.com/a/49959625
has comment: http://stackoverflow.com/comment/86935523
tagged with: python
has title: I am getting this error: SyntaxError: invalid syntax
upvote count: 2
type: AnsweredQuestion
score: 0
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49959625
has comment: http://stackoverflow.com/comment/86935463
has answer: http://stackoverflow.com/a/49959607
tagged with: syntax
has body: class Student(object): def__init__(self, name='', school='', grade=''): #This is where I get the error if not name: name = raw_input('what is the student\'s name: ') if not school: school = raw_input('What is the studnet\'s school: ') if not grade: grade = self.get_grade() self.name = name self.school = school self.grade = grade self.print_student() def get_grade(self): while True: grade = input('What is the student\'s grade: [K, 1-5]') if grade.lower() not in ['k','2','3','4','5']: print('I\'m sorry, but {} isn\'t valid.'.format(grade)) else: return grade def print_student(): print('Name: {}'.format(self.name)) print('School: {}'.format(self.school)) print('Grade: {}'.format(self.grade)) def main(): student1 = Student() studnet2 = Student(name='Bethmi Amalya', grade = '5', school= 'Visakha Vidyalaya') if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/86935518
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49959607
tagged with: python-3.x

http://stackoverflow.com/comment/87064106
has text: i found the answer that is use function of reset_index() , maybe i didn't explain my question clearly, the answer is too simple.....,but also thank you, when i was in dispirted , there is also a human want to help me.
score: 0
comment on: http://stackoverflow.com/q/50013743
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87037096
type: QuestionComment
comment on: http://stackoverflow.com/q/50010169
score: 0
type: Comment
has text: My thoughts exactly @erocoar. How exactly does searching for the word "Chris Hemsworth" return a value "GreaterEuropean"? Am I missing something about the url en.wikipedia.org/wiki that will somehow translate someone's name into an arbitrary value?

http://stackoverflow.com/q/49946462
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49958434
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49958434
has body: I am trying to use trained BoW, tfidf, and SVM model to do prediction: def bagOfWords(files_data): count_vector = sklearn.feature_extraction.text.CountVectorizer() return count_vector.fit_transform(files_data) files = sklearn.datasets.load_files(dir_path) word_counts = util.bagOfWords(files.data) tf_transformer = sklearn.feature_extraction.text.TfidfTransformer(use_idf=True).fit(word_counts) X = tf_transformer.transform(word_counts) clf = sklearn.svm.LinearSVC() X_train, X_test, y_train, y_test = sklearn.cross_validation.train_test_split(X, y, test_size=test_size) I can run following: clf.fit(X_train, y_train) y_predicted = clf.predict(X_test) But following will get error: clf.fit(X_train, y_train) new_word_counts = util.bagOfWords(["a place to listen to music it s making its way to the us"]) ready_to_be_predicted = tf_transformer.transform(new_word_counts) predicted = clf.predict(ready_to_be_predicted) I think am already using the former tf_transform, and don't know why still got the error. Any help is greatly appreciated!
answer count: 1
has title: ValueError: Input has n_features=10 while the model has been trained with n_features=4261
tagged with: machine-learning
tagged with: scikit-learn

http://stackoverflow.com/a/49986030
has comment: http://stackoverflow.com/comment/87031072
has comment: http://stackoverflow.com/comment/87038427
has body: A list-of-lists is not a structure that can get much speed-up from Cython. The structure you should use is a 2D typed memoryview: def f(double[:,:] m): # ... These are indexed as m[j,k] rather than m[j][k]. You can pass them any suitably shaped object that exposes the Python buffer protocol. Most frequency this will be a Numpy array. You should also avoid using decorators like @cython.boundscheck(False) and @cython.wraparound(False) unless you understand what they do and have considered whether they're appropriate for your function. For your current version (where you're using lists) they actually do nothing and suggest you have copied them without understanding. They do speed up the indexing of memoryviews (at the cost of some safety). Edit: In terms of initializing c you have two options. Initialize a numpy array with the list of lists. This probably isn't hugely quick (but if other steps are slower then it may not matter): c = np.array([b[(j+1)*(j+2)/2+k+2,:] for j in range(1, s-2) for k in range(j)], dtype=complex) # note that I've changed the indexing of b slightly Set up c with an appropriately sized np.zeros array. Swap the list comprehension for two loops. It isn't 100% obvious to me exactly what this translates to, but it's something like c = np.zeros("some size you'll have to work out",dtype=complex) for k in range(j): for j in range(1,s-2): c["some function of j and k",:] = b["some function of j and k",:] You'll also want to replace len(c) with c.shape[0], etc.
has comment: http://stackoverflow.com/comment/87051675
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/87038121
has comment: http://stackoverflow.com/comment/87070670
has comment: http://stackoverflow.com/comment/87016622
has comment: http://stackoverflow.com/comment/87037437
has comment: http://stackoverflow.com/comment/87047297
has comment: http://stackoverflow.com/comment/87030360
answers question: http://stackoverflow.com/q/49964757
upvote count: 6
type: Answer

http://stackoverflow.com/q/50009682
tagged with: python
has title: Pip install of scikit-learn: No matching distribiution found.
has answer: http://stackoverflow.com/a/50009710
downvote count: 4
answer count: 1
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87041790
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49768770
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/49768770
score: -3
has body: I am trying to install scikit-learn through pip on Mac OSX. I have updated all of numpy, scipy and pip itself but when I type: "pip install scikit-learn -U" I receive an error saying: "Could not find a version that satisfies the requirement scikit-learn (from versions: ) No matching distribution found for scikit-learn"
tagged with: pip

http://stackoverflow.com/q/50068554
has title: Anaconda not working with atom terminal for python
has body: I tried installing Anaconda in my windows 10 but for using with atom editor. But it only works with anaconda prompt and not with terminal of atom for python
type: AnsweredQuestion
tagged with: atom-editor
score: 0
has answer: http://stackoverflow.com/a/50069680
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/50069680
has comment: http://stackoverflow.com/comment/87153607
tagged with: python

http://stackoverflow.com/comment/86935215
score: 0
comment on: http://stackoverflow.com/q/49959442
type: Comment
type: QuestionComment
has text: `c = [b[aa] for aa in a]`

http://stackoverflow.com/a/50049932
type: Answer
answers question: http://stackoverflow.com/q/50049560
score: 3
accepted answer of: http://stackoverflow.com/q/50049560
upvote count: 3
has body: One way is to use itertools.compress and itertools.cycle. It basically uses a mask to repeatedly select the elements at indices 1 and 2 for every 4-element chunk. import itertools as it print([x for x in it.compress(column, it.cycle([0, 1, 1, 0]))]) # ['b1', 'c1', 'b2', 'c2', 'b3', 'c3']
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86996520
type: Comment
comment on: http://stackoverflow.com/q/49989956
type: QuestionComment
has text: Added more detail
score: 0

http://stackoverflow.com/a/49919339
type: Answer
has comment: http://stackoverflow.com/comment/86857174
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49918268
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49918268
has body: Your conditions are unboundedly transitive. Say in rows 2i, 2i + 1 the name is shared and in rows 2i + 1, 2i + 2 the rate is shared, you need to keep linking rows. One way to solve this is using the graph theory's connected components algorithm. For this you can use networkx. In code, it could be as follows: import networkx as nx import itertools G = nx.Graph() G.add_nodes_from(df.id) G.add_edges_from( [(r1[1]['id'], r2[1]['id']) for (r1, r2) in itertools.product(df.iterrows(), df.iterrows()) if r1[1].id &lt; r2[1].id and (r1[1]['rate'] == r2[1]['rate'] or r1[1]['name'] == r2[1]['name'])] ) Let's create a group column, indicating, for each row, its group: df['group'] = df['id'].map( dict(itertools.chain.from_iterable([[(ee, i) for ee in e] for (i, e) in enumerate(nx.connected_components(G))]))) &gt;&gt;&gt; df.group 0 0 1 0 2 0 3 1 Now you just need to groupby the group column, and apply a list.
score: 3

http://stackoverflow.com/comment/86869944
comment on: http://stackoverflow.com/q/49926934
type: QuestionComment
score: 0
has text: `'"RCM","Interlock error"'` this is ONE string, not two. The string is delimited by `'` only the firstand last `"` is at the start/end of a string. so it is removed - the other one is _inside_ it - and not touched by `strip()` .Voting to close, strip is working **exactly** as intended and the comma does nothing to invalidate its mechanics.
type: Comment

http://stackoverflow.com/a/51766810
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50061716
answers question: http://stackoverflow.com/q/50061716
has body: @Khelili, thanks for sharing it. Adding a context worked fine for me. I got it somewhere by googling. for i in range(0, self.product_quantity): values = { 'name': self.env['ir.sequence'].next_by_code('sale.order'), 'opportunity_id': self.id, 'state': 'draft', 'date_order': datetime.now(), 'partner_id': self.partner_id.id, 'count_total': self.total_count, 'product_categ': self.product_categ.id } res = self.env['sale.order'].with_context(mail_create_nosubscribe=True).create(values)
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/93209284

http://stackoverflow.com/a/50064015
type: Answer
answers question: http://stackoverflow.com/q/50063717
score: 0
has body: You can use a combination of zip and map: list(map(list, zip(*l))) # [[16, 24], [19, 17]]

http://stackoverflow.com/q/49988119
tagged with: github
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86992716
has title: How I start this Python-Project from Github?
accepted answer: http://stackoverflow.com/a/49988268
upvote count: 2
has answer: http://stackoverflow.com/a/49988268
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86992554
score: 2
has body: I started with Python and looked at some tutorial and downloaded Python 3.6. Now I wanted to look at some sample projects and came across at this LoL-project. But unfortunately I have no idea how to start this project. I installed it pip install riotwatcher and next comes the section "Using It" There is a code. Do I have to add that somewhere or what do I have to do here? I'm just a beginner. Can someone help me? :) Thx Project-link: https://github.com/pseudonym117/Riot-Watcher
type: AnsweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/87149962
type: Comment
has text: The function is `fonctionRegex`.
type: AnswerComment
comment on: http://stackoverflow.com/a/50066566
score: 0

http://stackoverflow.com/q/49987631
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49988734
tagged with: python
has comment: http://stackoverflow.com/comment/100294138
answer count: 2
score: 1
has title: Multi-label classifciation: keras custom metrics
downvote count: 0
has answer: http://stackoverflow.com/a/56871839
tagged with: machine-learning
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has body: Contextualization I am working on a multi_label classification problem with images. I am trying to predict 39 labels. In other words, I am trying to identifying which one of the 39 characteristics is present in a given image( many characteristics can be found in one image that's why I am on a multi label classification situation. Data My input data are (X,Y): X is of shape (1814,204,204,3) and Y is of shape (1814,39). So basically X are the set of images and Y are the labels associated to each images which will be used for the supervised learning process. Model I am building a Convolutional neural network in order to make predictions. For this task, I am using Keras in order to create my model. What I have done In order to validate my model, I need to choose a metric. However, metrics available in Keras are irreverent in my case and won't help me validate my model since I am in multi-label classification situation. That's why I decided to create my custom metric. I created recall and precision metrics applied to columns of Y and Y_predict . In other words, I will calculate recall and precision for each class of the 39 classes. So here is the code of my metrics: def recall(y_true, y_pred): #Recall metric. true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)),axis=0) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)),axis=0) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): #Precision metric. true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)),axis=0) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)),axis=1) precision = true_positives / (predicted_positives + K.epsilon()) return precision My vector Y is of shape (n,39) that's why I am doing operations over axis=0. In other words, for each label, I am caluclating precision and recall. Next step, I called these two metrics by precising it to keras fit function. In other words I used this line of code: model.compile(loss='binary_cross…

http://stackoverflow.com/q/49936467
answer count: 1
has body: I created several Keras models (Model_1, Model_2...Model_N) in one code. I would like to clear only one specified model (e.g. Model_1). I guess K.clear_session(), which will clear all models from the memory, is not useful in this case. Is there any solution? Thank you in advance.
has title: How can a specific model be cleared from the memory?
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86899172
tagged with: python
tagged with: keras
has answer: http://stackoverflow.com/a/49936800
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/50002896
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/87022202
has comment: http://stackoverflow.com/comment/87023647
has comment: http://stackoverflow.com/comment/87023336
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has body: This is similar except I do not get a single value and instead segfault on [0] or .contents How can I access the elements in 'array' from Python? In C I have something like #pragma pack(push, 1) struct Data { int i; int *array; }; #pragma pack(pop) typedef struct { bool (* const get) (struct Data*, const char *source); void (* const print) (struct Data*); } DataFn; extern DataFn const DATAFUNC; In Python I have something like class Data(ctypes.Structure): _fields_ = [ ("i", ctypes.c_int), ("array", ctypes.POINTER(ctypes.c_int)) ] class DATA_FN(ctypes.Structure): _fields_ = [ ("get" , ctypes.CFUNCTYPE( ctypes.c_bool, ctypes.POINTER(Data), ctypes.c_char_p)), ("print" , ctypes.CFUNCTYPE(None, ctypes.POINTER(Data))) ] From python I can do something like .. with open("xx0c.exx", "rb") as f: fdata = f.read() dfn.get(ctypes.byref(data),f fdata) dfn.print(ctypes.byref(data)) print(data) print(data.i) #7, correct #print(data.array.contents) #segfault #print(data.array) #segfault ptr = ctypes.pointer(data) print(ptr.contents.array[0]) #segfault C function called from python will print .. which is correct i = 7 array = 0x6ffff360034 array 0 = 20 array 1 = 27a40 array 2 = 127e20 array 3 = 128ae0 array 4 = 47e850 array 5 = 57ec30 array 6 = 580230 I can see the array in python isn't anywhere near the array in C. Sample C code as asked. These are static, but they can be accessed through DATAFUNC. The C programs that use these are fine. static bool getdata(struct Data *d, const char *filedata) { bool good = false; if (d != NULL && filedata != NULL) { d -> i = (int32_t)filedata[0]; d -> array = (uint32_t*)(filedata + sizeof(int32_t)); if ( d->i > 0 ) { good = true; } } return good; } static void printdata(struct Data *d) { if (d == NULL) { return; } printf("i = %i\n", d -> i); printf("array = %p\n", d -> array); unsigned int i; for (i = 0; i < d -> i; i++) { printf("array %i = %x\n", i, d -> array[i]); } }
has title: Python/Ctypes - Segmentation Fault on Access to Pointer (to Array)
type: Question
has comment: http://stackoverflow.com/comment/87030185
tagged with: ctypes
has answer: http://stackoverflow.com/a/50013010
has comment: http://stackoverflow.com/comment/87023271
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87030030
answer count: 1
has comment: http://stackoverflow.com/comment/87023866
linked to: http://stackoverflow.com/q/3620348
upvote count: 1
tagged with: segmentation-fault
tagged with: pointers
has comment: http://stackoverflow.com/comment/87022386
has comment: http://stackoverflow.com/comment/87030151
downvote count: 1

http://stackoverflow.com/a/49976127
answers question: http://stackoverflow.com/q/49956569
has body: Well, you need to implement custom Serializer(at producer end) and Deserializer (at consumer end). Make sure to put same custom value class on class path at consumer end as that of producer. public class CustomDeserializer implements Deserializer&lt;ValueClass&gt; { public CustomDeserializer() { } public void configure(Map&lt;String, ?&gt; map, boolean b) { } public ValueClass deserialize(String s, byte[] MessageBytes) { ValueClass eEventMessage = null; ObjectMapper objectMapper = new ObjectMapper(); try { eEventMessage = (ValueClass)objectMapper.readValue(MessageBytes, ValueClass.class); } catch (IOException ex) { // your stuffs } return eEventMessage; } public void close() { } } Set this custom class at consumer end properties.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87004970

http://stackoverflow.com/comment/87060692
comment on: http://stackoverflow.com/q/50021737
type: Comment
type: QuestionComment
has text: @KlausD. Yes, I know what the mistake is. ;) It is there by intention to test if `mypy` can find it. I will adjust the question to clarify this.
score: 0

http://stackoverflow.com/comment/126936320
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50037803
has text: That's not the only scenario. Something like "=ABC" will still cause an issue.
score: 0

http://stackoverflow.com/comment/87013062
has text: @GiacomoCatenazzi Your suggestion isn't really applicable to the described problem, where it's lxml's HTML parser that has problems parsing the document, not a text file decoded by the OP's code. Or can you show how to ignore encoding errors in this context?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49975013
type: QuestionComment

http://stackoverflow.com/q/49918487
tagged with: python
score: 15
upvote count: 16
tagged with: matlab
has answer: http://stackoverflow.com/a/50544260
has body: I've installed SMOP via pip and it seemed to work fine. I have smop-script.py and smop.exe files in my python folder \scripts\ folder. Let's say I have a matlab file called myMatlabFile.m located in C:\Users\MyMatlabCode. How do I use smop to translate that file? The SMOP documentation only includes an example of opening a file contained in a \smop\ folder with a main.py and I don't have anything like that. Also, the github page doesn't say whether it works only with 2.7 or 3. or whatever. I was hoping that this package would speed up my Matlab -> Python 3.6 conversion, but if there are better translators out there now please let me know that too/instead.
downvote count: 1
favorite count: 0
has title: How to use SMOP to convert Matlab into Python code
type: Question
answer count: 2
tagged with: translate
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52266699
has comment: http://stackoverflow.com/comment/87439314
has comment: http://stackoverflow.com/comment/86853613

http://stackoverflow.com/comment/90565594
type: QuestionComment
has text: Did you ever figure this out?
comment on: http://stackoverflow.com/q/50018125
score: 0
type: Comment

http://stackoverflow.com/q/49934314
tagged with: python
has title: How to get installed python package folder path?
tagged with: python-c-api
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49934587
accepted answer: http://stackoverflow.com/a/49934587
answer count: 1
has body: How to get installed python package folder path in Python C API? Suppose I want to open a file data.txt from the Python C-API module.pyd that resides as follows: package |--module.pyd |--data | |-data.txt How do I get the path name of data.txt?
type: Question
score: 0
linked to: http://stackoverflow.com/q/247770

http://stackoverflow.com/a/49952780
answers question: http://stackoverflow.com/q/49952712
type: Answer
has comment: http://stackoverflow.com/comment/86922138
score: 0
has body: Well, one solution to increase the performance is to use GPU. If you are running on the TensorFlow backend, your code will automatically run on GPU if any available GPU is detected. pip install tensorflow-gpu Also, you can choose to have data parallelism using multi_gpu_model class. from keras.utils import multi_gpu_model # Replicates `model` on 8 GPUs. # This assumes that your machine has 8 available GPUs. parallel_model = multi_gpu_model(model, gpus=8) parallel_model.compile(loss='categorical_crossentropy', optimizer='rmsprop') # This `fit` call will be distributed on 8 GPUs. # Since the batch size is 256, each GPU will process 32 samples. parallel_model.fit(x, y, epochs=20, batch_size=256) I see that your output layer uses sigmoid as activation function. That's wrong. You have to use softmax because sigmoid is for binary classification or two-class models. Softmax function calculates the probabilities distribution of the event over n different class.(15 in your case). In general way of saying, this function will calculate the probabilities of each target class over all possible target classes. Later the calculated probabilities will be helpful for determining the target class for the given inputs. The main advantage of using Softmax is the output probabilities range. The range will 0 to 1, and the sum of all the probabilities will be equal to 1.

http://stackoverflow.com/q/49983921
downvote count: 1
accepted answer: http://stackoverflow.com/a/49984924
favorite count: 0
tagged with: celery
type: Question
has title: Run celery periodic task for 1 hour, it it takes more then 1 hour, expire that task?
tagged with: celerybeat
tagged with: celery-task
upvote count: 5
tagged with: django
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49985302
has body: I have a periodic task for data purging which run once a day. I want that task to run only for 1 hour. If the duration of processing that task is more than 1 hour, then expire that task. It will run again the next day for 1 hour. I would like to do this is because if the traffic is high then that particular cerely task keeps on running for 10-15 hours.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49984924
answer count: 2
possible better answer: http://stackoverflow.com/a/49985302

http://stackoverflow.com/comment/86967429
comment on: http://stackoverflow.com/q/49923479
score: 0
has text: sorry for late comment, but yes, It can either be outputted like this in the linux terminal, or stored in a file, that looks like the snippit above
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49973026
type: AnsweredQuestion
score: 0
tagged with: python
has body: when I use scrapy item_loader to fill item, the selector extract data is None. Then, I use mysql to save data, but it gives me a mistake: key Error, the reason is this instance no this key. after i researched, there is no solution. Could you help me? Thank you very much! real_time_hot_loader = WeiBoRealTimeHotLoader(item=WeiBORealTimeHotItem(),selector=real_time_hot_node) real_time_hot_loader.add_css('search_rank', 'tr[action-type*="hover"] td.td_01 span em::text') real_time_hot_loader.add_css('star_name', 'td.td_02 p.star_name a::text') real_time_hot_loader.add_css('star_url', 'td.td_02 p.star_name a::attr(href)') real_time_hot_loader.add_css('star_num', 'td.td_03 p.star_num span::text') real_time_hot_loader.add_css('hot_txt','td.td_02 p.star_name i.icon_txt::text') real_time_hot_loader.add_value('update_time', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) real_time_hot_loader.add_value('id', real_time_hot_date_time_id) real_time_hot_item = real_time_hot_loader.load_item()
accepted answer: http://stackoverflow.com/a/49973494
has answer: http://stackoverflow.com/a/49973494
answer count: 1
tagged with: scrapy
has title: use scrapy ltem_loader add_css extract data, but the value is None, how do i set default value
type: Question

http://stackoverflow.com/q/49961349
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49961685
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: bottle
score: 3
has body: So, I have a Bottle page within PythonAnywhere that is displaying a list of items in my SQLite database. In each of those tappable items, I want to give the other page relevant information from the database based on the name of the list item that was clicked. So in this case, I want to grab the value of this element and use the variable in my SQLite query via Python. However, it is to my knowledge that the value of an HTML element isn't possible to retrieve. I am wondering if anyone knows of a way to grab this dynamic value with Python. <% result = c.execute("SELECT * FROM caseFanPart")%> Back Case Fan Parts %for record in result: {{ record[1] }} {{ record[2] }} %end <% id = request.form.get("itembtn","") itemResult = c.execute("SELECT * FROM caseFanPart WHERE caseFanID = ?", (id,)) %> Back Spec Sheet %for item in itemResult: {{ item[1] }} Price: {{ item[2] }} Rating: {{ item[3] }} Color: {{ item[4] }} Size: {{ item[5] }} RPM: {{ item[6] }} Airflow: {{ item[7] }} Noise Level:{{ item[8] }} %end
upvote count: 3
has title: Getting HTML element value from a specific id via Python
tagged with: http://stackoverflow.com/tag/html
downvote count: 0

http://stackoverflow.com/q/50065911
has body: Is there any way to use 'pick_event' while using Tkinter back-end? I can use tk canvas to show my plots but couldn't find any document that handles pick_evet within tkinter.
type: UnansweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87148952
tagged with: python
has title: matplotlib pick_event in tkinter
linked to: http://stackoverflow.com/q/39936869
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87216952
score: 0
tagged with: tkinter
answer count: 0
type: Question

http://stackoverflow.com/q/49971393
has answer: http://stackoverflow.com/a/50027607
has title: Serializing Python Object to JSON Created with eulxml.xmlmap.XmlObject
possible better answer: http://stackoverflow.com/a/58504839
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/58504839
tagged with: http://stackoverflow.com/tag/json
has body: I have a set of python objects that I create using eulxml.xmlmap.XmlObject (I use this method primarily because I'm working with an eXistDB server and eulxml offers a pretty easy mapping function). I am able to successfully query my eXistDB and load an xquery result set into some python objects I've created. My problem is that I then want to be able to write these objects out as JSON when I pass them to the webserver (using Angular for the front end). I've tried using jsonpickle but it seems as though eulxml is doing some kind of lazy loading magic. A standard call to jsonpickle to serialize my object to json gives me this result: python code: jsonpickle.encode(myObject) result: "py/object": "models.alcalaPage.AlcalaPage", "context": {"namespaces": {"exist": "http://exist.sourceforge.net/NS/exist"} }, "node": { "py/object": "lxml.etree._Element", "py/seq": [ {"py/object": "lxml.etree._Comment", "py/seq": []}, {"py/object": "lxml.etree._Element", "py/seq": []}, ... ] }... it seems to be only outputting the type of the attribute but not the value of the attribute itself. If I change my jsonpickle code to set unpickable=False, all I get is an empty set of json (meaning that the structure is there in terms of the right number of curly braces and brackets but there is literally no data. The json output is just curly braces and brackets). I thought perhaps if I attempted to access a value in the field and then output the json that might work (at least for the field I accessed) but no luck. I get the same result as stated above (and yes I've double checked that there is data in the object itself). I'm sort of at a loss at this point. I could migrate to something like BeautifulSoup but it means writing A LOT more code (eulxml lets me simply specify the xpath to the value I want to fill my attribute with and bing, I'm done). Is there something I'm missing with jsonpickle? Or is there another json package I should look at? Or maybe I'm making this way more difficult than I ne…
tagged with: exist-db
tagged with: jsonpickle
answer count: 2
accepted answer: http://stackoverflow.com/a/50027607
tagged with: python

http://stackoverflow.com/comment/87094150
type: Comment
has text: @data_garden thanks a lot, this was helpful.
type: AnswerComment
comment on: http://stackoverflow.com/a/50011558
score: 0

http://stackoverflow.com/a/50059401
type: Answer
accepted answer of: http://stackoverflow.com/q/50058579
upvote count: 0
type: AcceptedAnswer
downvote count: 2
has body: I guess you could use UDP datagrams to communicate between C and Python. If you have to send from Python to C import socket UDP_IP = "127.0.0.1" UDP_PORT = 5005 YOUR_DATAS = "Some datas" print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "datas to send:", YOUR_DATAS sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(YOUR_DATAS, (UDP_IP, UDP_PORT)) (taken from https://wiki.python.org/moin/UdpCommunication) I guess you'll need to add a While loop to this example to send your datas. Then create an UDP client in C that receives the data from you python script.
answers question: http://stackoverflow.com/q/50058579
score: -2

http://stackoverflow.com/comment/87017805
type: QuestionComment
has text: Yeah, I just tried that and I got the same results.
comment on: http://stackoverflow.com/q/50000018
score: 0
type: Comment

http://stackoverflow.com/a/49982308
upvote count: 1
answers question: http://stackoverflow.com/q/49982204
type: Answer
score: 1
has body: df[df['Rank'] == 1] # Filter by rank before summing
downvote count: 0

http://stackoverflow.com/q/50019036
tagged with: numpy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34670112
accepted answer: http://stackoverflow.com/a/50026609
upvote count: 0
has answer: http://stackoverflow.com/a/50026609
downvote count: 2
answer count: 1
has body: I am trying to create a variable-sequence length data for LSTM model.So, i created a list of numpy arrays of variable length. For example, one array is of length => (11,20) and other is of length => (9,20).Here 20 is the number of features and 11/9 denote sequence length Each array has zeros and a numerical value(class index) at the end. If audio file belongs to class index = 1 and number of frames are 8 then y will be [0,0,0,0,0,0,0,1] I wanted to know that when model.fit is called on each variable length audio data, then last Dense layer() will have output shape equal to number of frames the audio has So, how can I create a variable output shape of Dense layer(8 or 9 or 11) I do not want to pad sequences instead give a 'None' in LSTM input layer shape. But, on converting into categorical, I get error: setting array element with sequence. Here , 11 is number of classes y_train=to_categorical(y_train,11) y_test=to_categorical(y_test,11) Tensorflow version : 1.3.0 Keras version : 2.0.9
tagged with: scikit-learn
tagged with: keras
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87054318
score: -2
has comment: http://stackoverflow.com/comment/87054559
has comment: http://stackoverflow.com/comment/87054397
tagged with: python
has comment: http://stackoverflow.com/comment/87054638
has comment: http://stackoverflow.com/comment/87054501
tagged with: lstm
has comment: http://stackoverflow.com/comment/87054486
has comment: http://stackoverflow.com/comment/87054705
has title: Create categorical numpy array for output labels of array containing variable length sequence

http://stackoverflow.com/q/50047922
score: 0
has title: Fix error: Cannot load pickle file from other machine
has comment: http://stackoverflow.com/comment/87112885
tagged with: python
linked to: http://stackoverflow.com/q/2121874
has comment: http://stackoverflow.com/comment/87112434
type: Question
answer count: 1
has body: I have a pickle file that I need to load from another project. It seems that the folder structure of that project is a little different. i.e: The model class was defined in main, but in my project, it put in "model.fraud_model.py". So when I try to load the pickle file, I get this exception: 'module' object has no attribute 'FraudModel' I'm trying to modify the pickle file from this: ccopy_reg _reconstructor p0 (c__main__ FraudModel To this: ccopy_reg _reconstructor p0 (cmodel.fraud_model FraudModel And it works. But this solution will change pickle file. I don't want this. So I import by hand: from model.fraud_model import FraudModel import sys sys.modules['model.fraud_model'] = FraudModel But it seems not work. Please help me how to fix this. Thanks
has comment: http://stackoverflow.com/comment/87112286
has answer: http://stackoverflow.com/a/50048399
tagged with: pickle
accepted answer: http://stackoverflow.com/a/50048399
type: AnsweredQuestion

http://stackoverflow.com/comment/87045782
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50014803
has text: `while cur.next!=None:` should not be indented

http://stackoverflow.com/a/50031270
answers question: http://stackoverflow.com/q/50031180
type: Answer
score: 2
has body: You could try something like this for brevity and clarity DNA_TO_RNA_MAP = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'} dna = input() if any(base not in DNA_TO_RNA_MAP.keys() for base in dna): print('Invalid Input') else: print(''.join(DNA_TO_RNA_MAP[base] for base in dna))
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87037330
comment on: http://stackoverflow.com/q/50010318
score: 3
type: Comment
type: QuestionComment
has text: What view function is the error message talking about? You have 23 of them in your code.

http://stackoverflow.com/q/49961216
has answer: http://stackoverflow.com/a/50421886
accepted answer: http://stackoverflow.com/a/50421886
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: macos
has title: PyCaffe build fails, lboost_python not found
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50413643
downvote count: 0
tagged with: caffe
tagged with: python
has answer: http://stackoverflow.com/a/50413643
tagged with: boost-python
linked to: http://stackoverflow.com/q/40616527
has body: I am on MacOS 10.13.3 (17D47) with Python 2.7.14. I am in the process of building caffe w/ python. The project is CPU only. I am able to build caffe through make run test however, after attempting make pycaffe I get an error. This is the result: touch python/caffe/proto/__init__.py CXX/LD -o python/caffe/_caffe.so python/caffe/_caffe.cpp PROTOC (python) src/caffe/proto/caffe.proto In file included from python/caffe/_caffe.cpp:17: In file included from ./include/caffe/caffe.hpp:12: ./include/caffe/net.hpp:41:5: warning: unused typedef 'INVALID_REQUESTED_LOG_SEVERITY' [-Wunused-local-typedef] LOG_EVERY_N(WARNING, 1000) &lt;&lt; "DEPRECATED: ForwardPrefilled() " ^ /usr/local/include/glog/logging.h:943:30: note: expanded from macro 'LOG_EVERY_N' INVALID_REQUESTED_LOG_SEVERITY); \ ^ 1 warning generated. ld: library not found for -lboost_python clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [python/caffe/_caffe.so] Error 1 I have a Makefile.config that calls out boost-python from the brew install set as: # Whatever else you find you need goes here. INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/local/Cellar/boost-python/1.67.0/lib My two initial questions are: 1)Am I not allowed to link to the boost library using the system python? 2)What is the correct way to tell make to grab boost-python?

http://stackoverflow.com/comment/86955252
type: QuestionComment
has text: Thank you, I knew I had to use that function, but had no idea how to implement the `os.chdir` inside the loop. It is solved and the code working properly.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49966534

http://stackoverflow.com/a/75973396
score: 7
type: Answer
answers question: http://stackoverflow.com/q/50035681
downvote count: 0
upvote count: 7
has body: ALLOWED_HOSTS: It is a whitelist of host/domain names that your web server can be served on. It is a mechanism to stop HTTP Host header attacks, which are nevertheless possible under many setups of web servers that seem to be secure. Hence, it is risky to use ALLOWED_HOSTS = [&quot;*&quot;] as it allows any host to server your webserver. Instead, you want to list it in your production environment as ALLOWED_HOSTS = ['example.io', 'example.com', 'example.prod.com']. where these values are hostnames known to you, websites that handle the value of the Host header in a risky manner are targets of HTTP Host header attacks. An attacker may utilize this input to inject dangerous payloads that alter server-side behavior if the server fails to verify or escape it properly and implicitly trusts the Host header. Hence avoid using ALLOWED_HOSTS = [&quot;*&quot;] at all costs. For INTERNAL_IPS: It is also a whitelist of IP ADDRESS names that your web server can share sensitive information or exhibit a custom behavior. This Django setting is basically a filter that you can configure to consider a range of IP addresses. To get a practical use case, You can install the django-debug-toolbar. Your web server can have a different behavior i.e having a popup in your test environment IP ADDRESS displaying sensitive information within its requests and debug output. I hope this explanation was helpful. I do not think the documentation did give a satisfactory explanation but from experience, I am able to give this response.

http://stackoverflow.com/a/49963323
downvote count: 0
has comment: http://stackoverflow.com/comment/86942904
has comment: http://stackoverflow.com/comment/86942629
accepted answer of: http://stackoverflow.com/q/49963291
has comment: http://stackoverflow.com/comment/86942806
score: 6
has body: In your screenshot, I do not see double quotes, I see HTML tags. If you are entering HTML into the content, rather than letting untrusted users enter it, then you should consider it safe for rendering onto the page (you're not likely to post malicious javascript, or to screw up your layout with bad HTML, right?). Therefore you want to use Django's safe filter on your content: That will allow the entered and stored HTML to be interpreted, rather than rendered.
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/49963291
has comment: http://stackoverflow.com/comment/86942873
has comment: http://stackoverflow.com/comment/86942937
has comment: http://stackoverflow.com/comment/86942666
type: AcceptedAnswer

http://stackoverflow.com/comment/87154329
type: Comment
comment on: http://stackoverflow.com/a/50068924
has text: @WStokvis fixed that
type: AnswerComment
score: 1

http://stackoverflow.com/a/49984487
has body: If you read docs on minimize you will find optional args argument ( and also see @sacha's comment ) So since your function of two arguments and you want to minimize it across one of them you need to pass values for other's minimize(chi_square_fv, x0, args=(cv,)) Which will pass some cv value as second parameter to the function chi_square_fv
score: 0
answers question: http://stackoverflow.com/q/49984323
type: Answer

http://stackoverflow.com/a/49959625
type: Answer
has comment: http://stackoverflow.com/comment/86935646
has comment: http://stackoverflow.com/comment/86935664
has body: you have 2 issues in code : 1 . def__init__(.... , there should be a space between def keyword and init( i.e def __init__(... 2 . self should be passed to def print_student() i.e print_student(self): and all variable accesses should be with self e.g self.name etc in print_student function . class Student(object): def __init__(self, name='', school='', grade=''): #This is where I get the error if not name: name = raw_input('what is the student\'s name: ') if not school: school = raw_input('What is the studnet\'s school: ') if not grade: grade = self.get_grade() self.name = name self.school = school self.grade = grade self.print_student() def get_grade(self): while True: grade = raw_input('What is the student\'s grade: [K, 1-5]') if grade.lower() not in ['k','2','3','4','5']: print('I\'m sorry, but {} isn\'t valid.'.format(grade)) else: return grade def print_student(self): print('Name: {}'.format(self.name)) print('School: {}'.format(self.school)) print('Grade: {}'.format(self.grade)) def main(): student1 = Student() studnet2 = Student(name='Bethmi Amalya', grade = '5', school= 'Visakha Vidyalaya') if __name__ == '__main__': main()
score: 3
accepted answer of: http://stackoverflow.com/q/49959531
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49959531
type: AcceptedAnswer

http://stackoverflow.com/comment/87140433
comment on: http://stackoverflow.com/a/50058153
has text: research for it . If you don't find an answer please ask another question
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50064118
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50064221
score: 0
answer count: 2
has title: Python / Django makemigrations Error
has answer: http://stackoverflow.com/a/50064351
accepted answer: http://stackoverflow.com/a/50064351
type: Question
has answer: http://stackoverflow.com/a/50064221
tagged with: python-3.x
has body: I have been messing around with Python and Django recently, following this tutorial - https://www.codementor.io/jadianes/get-started-with-django-building-recommendation-review-app-du107yb1a I will be altering that app as I go, just to experiment, however I am at a bit of a standstill with 'makemigrations'. When I run python manage.py makemigrations reviews I get a traceback as follows: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "C:\Users\CalPC\Desktop\review_app\prodrevie…
has comment: http://stackoverflow.com/comment/87145017
has comment: http://stackoverflow.com/comment/87144937
tagged with: django
tagged with: python

http://stackoverflow.com/q/50024376
has body: Here is an example code: import pandas as pd from datetime import datetime, timezone import matplotlib.dates as mdates import matplotlib.pyplot as plt import datetime as dt x = [] d = dt.datetime(2013, 7, 4) for i in range(30): d = d + dt.timedelta(days=1) x.append(d) y = range(len(x)) df = pd.DataFrame({'x': x, 'y': y}) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y')) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5)) # Line A # plt.bar(x, y, align='center') # center the bars on their x-values # Line B # df.plot(x='x', y='y', kind='bar', ax=plt.gca()) plt.title('DateLocator with interval=5') plt.gcf().autofmt_xdate() plt.show() With line A, it draws: With line B, it draws: Why doesn't pandas's Dataframe.plot respect the axis configuration? Here's my conda env export: dependencies: - libcxx=4.0.1=h579ed51_0 - libcxxabi=4.0.1=hebd6815_0 - pandas=0.22.0=py36h0a44026_0 - pyspark=2.3.0=py36_0 - certifi=2016.2.28=py36_0 - click=6.7=py36_0 - cycler=0.10.0=py36_0 - freetype=2.5.5=2 - icu=54.1=0 - libpng=1.6.30=1 - matplotlib=2.0.2=np113py36_0 - mkl=2017.0.3=0 - numpy=1.13.1=py36_0 - openssl=1.0.2l=0 - pip=9.0.1=py36_1 - py4j=0.10.6=py36_0 - pyparsing=2.2.0=py36_0 - pyqt=5.6.0=py36_2 - python=3.6.2=0 - python-dateutil=2.6.1=py36_0 - pytz=2017.2=py36_0 - qt=5.6.2=2 - readline=6.2=2 - requests=2.14.2=py36_0 - scikit-learn=0.19.0=np113py36_0 - scipy=0.19.1=np113py36_0 - setuptools=36.4.0=py36_1 - sip=4.18=py36_0 - six=1.10.0=py36_0 - sqlite=3.13.0=0 - tk=8.5.18=0 - wheel=0.29.0=py36_0 - xz=5.2.3=0 - zlib=1.2.11=0
tagged with: pandas
tagged with: matplotlib
linked to: http://stackoverflow.com/q/30133280
tagged with: python
has comment: http://stackoverflow.com/comment/87065268
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: pandas does not respect matplotlib axis?

http://stackoverflow.com/comment/86910945
comment on: http://stackoverflow.com/a/49946066
score: 0
type: Comment
has text: Not much, first of all, the df is filtered where `Channel.isin(['A`, `B`]), so there `NaN` columns will be discarded. Second, the slicing for the first element would be 1 + 4, but for element 3, it would be 3-2: 3+2?
type: AnswerComment

http://stackoverflow.com/comment/86959255
score: 2
comment on: http://stackoverflow.com/q/49971679
has text: Possible duplicate of [Sublime Text 2 console input](https://stackoverflow.com/questions/10604409/sublime-text-2-console-input)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50030950
type: UnansweredQuestion
downvote count: 0
has title: Python - convert hour from EDT/EST to UTC based on time of year
favorite count: 0
type: Question
score: 3
tagged with: datetime
has comment: http://stackoverflow.com/comment/87118727
tagged with: timezone-offset
tagged with: python
has body: Eastern Standard Time is -5 (to UTC) Eastern Daylight Time is -4 (to UTC) so why doesn't this work properly? &gt;&gt;&gt; import datetime, pytz # 5 hour difference during Eastern Standard Time &gt;&gt;&gt; datetime.datetime(2018, 1, 25, 16, 26, tzinfo=pytz.timezone('US/Eastern')).hour &gt;&gt;&gt; 16 &gt;&gt;&gt; datetime.datetime(2018, 1, 25, 16, 26, tzinfo=pytz.timezone('US/Eastern')).astimezone(pytz.utc).hour &gt;&gt;&gt; 21 # 4 hour difference during Eastern Daylight Time &gt;&gt;&gt; datetime.datetime(2018, 4, 25, 16, 26, tzinfo=pytz.timezone('US/Eastern')).hour &gt;&gt;&gt; 16 # So why does this not say 20? &gt;&gt;&gt; datetime.datetime(2018, 4, 25, 16, 26, tzinfo=pytz.timezone('US/Eastern')).astimezone(pytz.utc).hour &gt;&gt;&gt; 21
answer count: 0
upvote count: 3

http://stackoverflow.com/a/78566917
has comment: http://stackoverflow.com/comment/138511427
upvote count: 2
has comment: http://stackoverflow.com/comment/138526450
type: Answer
has comment: http://stackoverflow.com/comment/138538493
has comment: http://stackoverflow.com/comment/139346339
answers question: http://stackoverflow.com/q/49936222
score: 2
has comment: http://stackoverflow.com/comment/139327025
downvote count: 0
has body: 1 Billion primes in about 4 seconds I liked stopping at sqrt(n) for selecting multiples to clear. I liked using slicing views in NumPy because to clear all multiples of 3 we just need: p[9::3] = 0 # clear 9,12,15... I was using numpy because np.sum() and slicing is several times faster than vanilla Python. I had used uint8 because a normal python bool takes up 4 bytes instead of 1. For a sieve of 100 it doesn't matter. For 2 billion it adds up. I should've used a bit per prime. At Mark Dickerson's suggestion I changed the i*3 and h*3 to i*i and h*h Thanks very much. He also pointed out that my int8 array was the same size as a numpy dtype=bool array. So I switched to a bitarray() It works just like a numpy array at 1/8 of the space. Now instead of 5 seconds for a billion wide sieve it takes about 4 seconds. All prime numbers are in the 6k±1 range. 6(2)+1 is 13 6(2)-1 is 11. Not all numbers in that pattern are prime. All primes are in that pattern. So when clearing 1's I skip from 5 by 6 until I get to the sqrt(n) limit. This uses Bitarray() and skip slicing: from datetime import timedelta import time,sys from bitarray import bitarray def get_primes(a_prime, start=0, end=100): """Return list of prime numbers in the range [start, end] using a_prime bitarray.""" return [i for i in range(start, end + 1) if a_prime[i]] def pretty_primes(a_prime, start=0, end=100): """Return list of prime numbers in the range [start, end] using a_prime bitarray.""" return [f'{i:,}' for i in range(start, end + 1) if a_prime[i]] def make_sieve(size): """Create a sieve of Eratosthenes up to the given size.""" sieve_time = time.time() print(f"Creating new sieve of {size:,} primes.") limit = int(1 + size**0.5) + 2 p = bitarray(size) # One bit per value p.setall(True) p[0] = p[1] = False p[4::2] = False # Clear multiples of 2 p[9::3] = False # Clear multiples of 3 for i in range(5, limit, 6): # Process only numbers of the form 6k-1 and 6k+1 h = i + 2 # 6k+1 if p[i]: # If 6k-1 is prime p[i*i::2 …

http://stackoverflow.com/comment/87168277
comment on: http://stackoverflow.com/a/50063365
has text: putting .ix instead of .loc helped.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/86910043
type: Comment
type: QuestionComment
score: 0
has text: I am also thinking so. Thank you for your suggestion
comment on: http://stackoverflow.com/q/49927107

http://stackoverflow.com/comment/87284488
comment on: http://stackoverflow.com/a/50088572
type: AnswerComment
has text: @JOHN I would also consider using a [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor), or a [ProcessPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor) (in order to run the numpy computation in parallel).
score: 1
type: Comment

http://stackoverflow.com/q/50067231
upvote count: 11
tagged with: python
tagged with: conda
downvote count: 0
has title: Equivalent of apt-get install python3.6-dev for conda
answer count: 1
score: 11
favorite count: 0
type: Question
has body: How can I create a conda environment with the development version of python? Or does it already include all the necessary extension when I create one. conda create -n py36 python=3.6
has answer: http://stackoverflow.com/a/50068178
type: UnansweredQuestion

http://stackoverflow.com/q/49938375
score: 0
has answer: http://stackoverflow.com/a/49983945
tagged with: unicode-string
tagged with: tkinter-entry
has title: Tkinter entry get unicode content error
type: Question
has answer: http://stackoverflow.com/a/49942185
tagged with: tkinter
type: UnansweredQuestion
has body: I have a strange problem trying to get some values from a Tkinter Entry. Basically if in the Entry I have a no-ascii value and use get() content, sometime I have a correct unicode string and sometime I have and ascii string a-la unicode without the canonical 'u'. Here my code: def create(): try: cols = [] values = [] for name in names: if (pk &lt;&gt; name): if (name in fk_columns): cols.append(name) values.append(box[name].get()) else: cols.append(name) values.append(entry[name].get()) print values dbutils.create(mDBname, mTable,cols,values) frame.master.destroy() tkMessageBox.showinfo("New record", "Record created") scrolled_view(root,mDBname,mTable,'g',0, editable) except Exception, err: tkMessageBox.showerror("Error", err) def update(): try: cols = [] new_values = [] old_values = [] i = 0 for name in names: if (name in fk_columns): cols.append(name) new_values.append(box[name].get()) else: cols.append(name) new_values.append(entry[name].get()) if rows[record][i] == None: old_values.append('') else: old_values.append(rows[record][i]) i = i + 1 print new_values dbutils.update(mDBname, mTable, cols, new_values, old_values) frame.master.destroy() tkMessageBox.showinfo("Update", "Record updated") scrolled_view(root,mDBname,mTable,'g',0, editable) except Exception, err: tkMessageBox.showerror("Error", err) So the problem is if I use the "create" function and I have an Entry with the value for example "John Canà", when I print the values in the shell (notice the "print values" before the call to dbutils) I got: [u'John Can\xe0', 'Amministrazione'] and the function work without error. When I use the update function, even updating just the second value not the one with "John Canà" on the python shell (calling print new_values before the call to dbutils) I got: ['17', 'John Can\xe0', 'Marketing'] The string 'John Can\xe0' is without the 'u'. This in end produce the classic error "ordinal not in range 128'. So my question why the same Entry.get() call produce this differen…
tagged with: python
answer count: 2

http://stackoverflow.com/q/50016604
type: AnsweredQuestion
has title: Python: Use private static method as default
answer count: 3
has comment: http://stackoverflow.com/comment/87049578
has comment: http://stackoverflow.com/comment/87049574
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87049595
has body: I have a class member which accepts a function: class A: def func(self, method): ... I want to set a default method since that behavior is desired 99% of the time. This default behavior is static since it does not depend on any members of the class. However, I would like this default method to be private and invisible to the user. Is there any way of accomplishing that? This is what I have tried: class A: @staticmethod def __meth(x): pass def func(self, method = meth): pass Error: 'staticmethod' object is not callable class A: @staticmethod def __meth(x): pass def func(self, method = A.__meth): pass Error: NameError: name 'A' is not defined class A: @staticmethod def __meth(x): pass def func(self, method = self.__meth): pass Error: NameError: name 'self' is not defined I am using Python 3.5 and do not want to rely on newer features.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50016783
has comment: http://stackoverflow.com/comment/87049570
possible better answer: http://stackoverflow.com/a/50016783
has comment: http://stackoverflow.com/comment/87049612
has answer: http://stackoverflow.com/a/50016794
has comment: http://stackoverflow.com/comment/87049495
tagged with: python
has comment: http://stackoverflow.com/comment/87049673
has answer: http://stackoverflow.com/a/50016765
accepted answer: http://stackoverflow.com/a/50016765
score: 2

http://stackoverflow.com/q/50037213
score: 2
tagged with: plotly
favorite count: 0
has body: I'm trying to use a discrete colorscale when I'm using plotly (in python). I need a discrete colorscale as some values I'm plotting for specific cities are way too large as compared to all others, hence a discrete color scale would help me visualize all values with ease. Here's an example to explain my situation better: I have a dataset that contains details about certain events by city (in USA). The event occurred in New York City 50000 times whereas in other cities in the USA, the same event occurred less that 1000 times. When I use a continuous colorscale, all other city values fall to the low end and NYC is the only value which utilizes the color at the top of the colorscale. Thanks for your help in advance! Best Regards, Rishabh
type: Question
has answer: http://stackoverflow.com/a/53949752
answer count: 2
upvote count: 2
type: UnansweredQuestion
has title: How to use a discrete colorscale in plotly scattergeo usa map
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/69959400

http://stackoverflow.com/comment/87147573
has text: Are you referring to linear regression where you would take the log of the equation and fit to that form? Can you provide an example of this? Thanks for all the help.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50051130
type: Comment

http://stackoverflow.com/q/50017403
score: 4
type: AnsweredQuestion
tagged with: elasticsearch
downvote count: 0
favorite count: 0
upvote count: 4
tagged with: pyelasticsearch
type: Question
accepted answer: http://stackoverflow.com/a/50044188
has body: i'm working with py-elasticsearch-dsl for my master, i'm creating a index of title documents in a corpus of turkish titles, and i need implements a custom lowercase analyzer for turkish language: https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lowercase-tokenfilter.html#analysis-lowercase-tokenfilter I'm trying do it with this: turkish = analysis.token_filter('turkish_lowercase', type="lowercase", language="turkish") turkish_lowercase = analyzer('turkish_lowercase', type = "custom", tokenizer="standard", filter=["turkish_lowercase"], ) class Document(DocType): # title = Text() query = Percolator( analyzer=turkish_lowercase, filter=turkish ) # query is a percolator class Meta: index = 'titles' # index name doc_type = '_doc' def save(self, **kwargs): return super(Document, self).save(**kwargs) But i'm getting this error: python percolator.py  1 ↵  1736  17:37:54 PUT http://localhost:9200/title-index [status:400 request:0.004s] Traceback (most recent call last): File "percolator.py", line 55, in &lt;module&gt; Document.init() File "/home/salahaddin/Proyectos/Works/seminer/lib/python3.6/site-packages/elasticsearch_dsl/document.py", line 161, in init cls._doc_type.init(index, using) File "/home/salahaddin/Proyectos/Works/seminer/lib/python3.6/site-packages/elasticsearch_dsl/document.py", line 85, in init self.mapping.save(index or self.index, using=using or self.using) File "/home/salahaddin/Proyectos/Works/seminer/lib/python3.6/site-packages/elasticsearch_dsl/mapping.py", line 116, in save return index.save() File "/home/salahaddin/Proyectos/Works/seminer/lib/python3.6/site-packages/elasticsearch_dsl/index.py", line 219, in save return self.create() File "/home/salahaddin/Proyectos/Works/seminer/lib/python3.6/site-packages/elasticsearch_dsl/index.py", line 203, in create self.connection.indices.create(index=self._name, body=self.to_dict(), **kwargs) File "/home/salahaddin/Proyectos/Works/seminer/lib/python3.6/site-packages/elasticsearch/clien…
has answer: http://stackoverflow.com/a/50044188
tagged with: python
answer count: 1
has title: Create custom analyzer filter for a index in py-elasticsearch-dsl

http://stackoverflow.com/comment/86916729
type: Comment
type: AnswerComment
score: 1
has text: Friendly hint: Generally if you don't understand a question, it's a good idea to ask for clarification, rather than just post an answer based on a wild guess. Use a comment, downvote ("This question does not show any research effort; **it is unclear** or not useful") or flag as "should be closed ... unclear what you're asking" depending on severity.
comment on: http://stackoverflow.com/a/49949779

http://stackoverflow.com/q/49993578
has comment: http://stackoverflow.com/comment/87014984
tagged with: pyyaml
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49993928
tagged with: yaml
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87003886
has comment: http://stackoverflow.com/comment/87003429
has title: How to iterate a YAML file to give all possible combinations from items in different lists in PYTHON
upvote count: 1
tagged with: parser-combinators
has body: I have a YAML document with sequences like this --- One: - a - b - c Two: - d - e Three: - f - g - h - i I need to get all possible combinations of the elements taken from each list one at a time, only one element at every instance from the list and all list must be used. I need to do this is python. Until now, I can print the YAML file using: #!/usr/bin/env python import yaml with open("parameters.yaml", 'r') as stream: try: print(yaml.load(stream)) except yaml.YAMLError as exc: print(exc)
favorite count: 0
type: Question
tagged with: combinations
has comment: http://stackoverflow.com/comment/87004002
has answer: http://stackoverflow.com/a/49993928
has comment: http://stackoverflow.com/comment/87003794
tagged with: python
linked to: http://stackoverflow.com/q/798854

http://stackoverflow.com/q/50028629
answer count: 2
has comment: http://stackoverflow.com/comment/87073519
has comment: http://stackoverflow.com/comment/87073587
upvote count: 0
score: -2
downvote count: 2
tagged with: python
has body: I want it here A Student comes and registers his account, his name is Sammy and his age is 16 I want to program like automatically it will pick his first 3 letter of his name and then his age After creating an account his username should not be Sammy it should be sam16 First 3 letter and then age. Please Help First 3 Letter Jhonny His Age 12 Final Look jho12 Register def register(): while True: username = input("New username: ") if not len(username) &gt; 1: print("Username should be more than 2 characters") continue else: break print("") while True: password = input("New password: ") if not len(password) &gt; 3: print("Password should be more than 5 characters, " + username ) continue else: break print("") while True: age = input("Enter Your age: ") if not len(age) &gt; 0: print("Age can't be blank, " + username ) continue else: break print("") print("Creating account...") users[username] = {} users[username]["password"] = password users[username]["group"] = "user" time.sleep(2) print("") print("Account has been created, " + username)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50028751
has answer: http://stackoverflow.com/a/50028751
has title: How to make username and age first 3 characters of his name then age?
tagged with: authentication
possible better answer: http://stackoverflow.com/a/50028746
favorite count: 0
has answer: http://stackoverflow.com/a/50028746
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86916165
score: 0
type: Comment
type: QuestionComment
has text: I have two companies that have different year-ends. The index when company=1 corresponds with the eight quarters for company 1 which has a January year-end, and the index when company=2 corresponds with the eight quarters for company 2 which has a December year-end.
comment on: http://stackoverflow.com/q/49949300

http://stackoverflow.com/q/49970596
has comment: http://stackoverflow.com/comment/86957295
has comment: http://stackoverflow.com/comment/86957072
favorite count: 0
type: Question
has title: sub popen multiple files
has body: Is it possible to use sub popen to open multiple files? The code I am using is for a GUI and upon selecting a button, it should open the png file but I need the button to open more than one png file. my code: def look2(): sub.Popen('open myplot1.png', stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/86960212
score: 2
upvote count: 2
answer count: 0
tagged with: subprocess
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87065023
type: Comment
type: QuestionComment
has text: What do `which python` and `python --version` output?
score: 0
comment on: http://stackoverflow.com/q/50023434

http://stackoverflow.com/q/49987042
has answer: http://stackoverflow.com/a/49989069
score: 0
tagged with: list
has body: I have a list containing list of tuples which was obtained after applying postag on word tokenizer. the sample is lis=[('This', 'DT') ('PM', 'NNP') ('Doctor', 'NNP'), ('Sambit', 'NNP'), ('Patra', 'NNP'), ('Spokesperson', 'NNP'),('Can', 'MD'), ('Media', 'NNP'), ('lambast', 'VB'), ('Sonia', 'NNP'), ('Gandhi', 'NNP'), ('up', 'RP'), ('Dalit', 'NNP'), ('Sitaram', 'NNP'), ('Dalit', 'NNP'), ('President', 'NNP')] I want to remove the tuples when the second element of the tuple is 'NNP'.The OutputList will look like this; Final_lis=[('This', 'DT'),('Can', 'MD'), ('lambast', 'VB'), ('up', 'RP')] I am writing the code: print(len(lis[0][1])) #to print the length of first list containing tuples f_list=[] for i in range(0,len(lis)): for j in range(len(lis[l])): if lis[i][j][1]!='NNP': f_list.append(lis[i][j]) But it's showing error Traceback (most recent call last): File "&lt;ipython-input-51-02562b867f97&gt;", line 1, in &lt;module&gt; runfile('C:/Users/meet/t1.py', wdir='C:/Users/meet') File "C:\Users\meet\Anaconda3\lib\site- packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\Users\meet\Anaconda3\lib\site- packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/meet/t1.py", line 9, in &lt;module&gt; print(len(lis[0][1])) IndexError: list index out of range
answer count: 3
has answer: http://stackoverflow.com/a/49987620
tagged with: pos-tagger
has answer: http://stackoverflow.com/a/49987121
type: Question
tagged with: tuples
has comment: http://stackoverflow.com/comment/86990510
has title: Remove tuple from list containing list of tuples if certain condition is met
has comment: http://stackoverflow.com/comment/114486160
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50040012
accepted answer of: http://stackoverflow.com/q/50037745
has comment: http://stackoverflow.com/comment/87108562
type: Answer
has body: Seems like your issue is not delay but concurrency. When you have 1 concurrent request per minute it works, when you have more it doesn't. Most likely reason of this is that the website is serving you content based on your cookies. Try disabling cookies via COOKIES_ENABLED settings in your settings.py file: COOKIES_ENABLED = False If you see that content is not being served without cookies at all you need to use cookiejars to start multiple cookie instances that are working in parallel. See: https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#multiple-cookie-sessions-per-spider
has comment: http://stackoverflow.com/comment/87104405
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50037745

http://stackoverflow.com/q/50051587
type: UnansweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/87119574
has title: pip install in python 3.6.5
has comment: http://stackoverflow.com/comment/87119612
has comment: http://stackoverflow.com/comment/87119503
has body: I'm trying to install some libraries on python, and I open cmd and type-m pip install &lt;lib_name&gt; but it says there's syntax error. When I skip the "&lt;" it says pip is not a recognized command. Any help? I'm using Python 3.6.5. enter image description here this is the output for almost every command I'm trying...
has comment: http://stackoverflow.com/comment/87119560
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/50051744
upvote count: 1
tagged with: libraries
has answer: http://stackoverflow.com/a/50068774
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87119601
has answer: http://stackoverflow.com/a/50051644
tagged with: python

http://stackoverflow.com/comment/87116446
has text: Your error claims it's on `draw_button`, not `button_draw`. Somewhere in code you haven't shown us, you're trying to reference `draw_button`. Also, you've posted way too much code. Please try to condense it down to a [mcve].
comment on: http://stackoverflow.com/q/50050123
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/50071688
accepted answer of: http://stackoverflow.com/q/50071669
answers question: http://stackoverflow.com/q/50071669
type: Answer
has comment: http://stackoverflow.com/comment/87165652
has body: You can pass the additional variable directly as a named argument to pd.DataFrame.apply: def DummyFunction2(row, threshold): return row['a']*row['b']*threshold df['Dummy2'] = df.apply(DummyFunction2, threshold=2, axis=1)
downvote count: 0
type: AcceptedAnswer
score: 6
upvote count: 6

http://stackoverflow.com/comment/87138396
has text: @NannanAV There was no logic behind the calculation of `c` (`c = ''`)
type: AnswerComment
comment on: http://stackoverflow.com/a/50060319
score: 0
type: Comment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/49920953
tag name: kivy-language
tags question: http://stackoverflow.com/q/50006684
tags question: http://stackoverflow.com/q/50017886
tags question: http://stackoverflow.com/q/50012762
tags question: http://stackoverflow.com/q/49935190

http://stackoverflow.com/comment/87033037
type: QuestionComment
has text: Nothing yet as I am only a beginner and I'm not sure of what you can use. I was hoping for some help and guidance
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50008234

http://stackoverflow.com/comment/86891832
score: 7
has text: [Read the docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html) - `The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on.`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49938122

http://stackoverflow.com/q/49931993
has answer: http://stackoverflow.com/a/49932047
has title: Element wise cross product of vectors contained in 2 arrays with Python
type: AnsweredQuestion
has body: I have two arrays, one containing a list of vectors (A) and one containing a 2D list of vectors (B). I am looking to do an element wise cross product of the vectors in each array in a specific way. The fist vector in A should be cross producted (?) by all 3 vectors contained in the first element of B. Here is a minimal example: import numpy as np A = np.random.rand(2,3) B = np.random.rand(2,3,3) C = np.random.rand(2,3,3) C[0,0] = np.cross(A[0],B[0,0]) C[0,1] = np.cross(A[0],B[0,1]) C[0,2] = np.cross(A[0],B[0,2]) C[1,0] = np.cross(A[1],B[1,0]) C[1,1] = np.cross(A[1],B[1,1]) C[1,2] = np.cross(A[1],B[1,2]) I would like to avoid using for loops for efficiency. I managed doing the same with the dot product by using: C = np.einsum('aj,ijk-&gt;ij',A,B) But I cant seem to be able to do the same with the cross product.
score: 1
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
tagged with: vector
accepted answer: http://stackoverflow.com/a/49932047
upvote count: 1
tagged with: python

http://stackoverflow.com/a/52259445
has comment: http://stackoverflow.com/comment/91466526
has body: You can also use _fg=True, for example import sh sh.ls("/", _fg=True) Output: /usr/bin/python3.6 /home/steve/test.py bin boot dev etc home initrd.img initrd.img.old lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var vmlinuz vmlinuz.old
type: Answer
has comment: http://stackoverflow.com/comment/102998875
downvote count: 1
answers question: http://stackoverflow.com/q/49990671
upvote count: 0
score: -1

http://stackoverflow.com/q/49932120
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49932438
possible better answer: http://stackoverflow.com/a/49932438
favorite count: 0
type: Question
has title: Pandas Count values across rows that are greater than another value in a different column
has body: I have a pandas dataframe like this: X a b c 1 1 0 2 5 4 7 3 6 7 8 9 I want to print a column called 'count' which outputs the number of values greater than the value in the first column('x' in my case). The output should look like: X a b c Count 1 1 0 2 2 5 4 7 3 1 6 7 8 9 3 I would like to refrain from using 'lambda function' or 'for' loop or any kind of looping techniques since my dataframe has a large number of rows. I tried something like this but i couldn't get what i wanted. df['count']=df [ df.iloc [:,1:] &gt; df.iloc [:,0] ].count(axis=1) I Also tried numpy.where() Didn't have any luck with that either. So any help will be appreciated. I also have nan as part of my dataframe. so i would like to ignore that when i count the values. Thanks for your help in advance!
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/49932146
accepted answer: http://stackoverflow.com/a/49932146
score: 4
upvote count: 4
tagged with: rows
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/86963822
type: AnswerComment
comment on: http://stackoverflow.com/a/49963205
score: 0
has text: File "C:\ProgramData\Anaconda2\lib\ast.py", line 80, in literal_eval return _convert(node_or_string) File "C:\ProgramData\Anaconda2\lib\ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string
type: Comment

http://stackoverflow.com/comment/86901105
type: Comment
comment on: http://stackoverflow.com/q/49941484
type: QuestionComment
has text: You may be interested in creating an external DSL (domain specific language) for your equations and emit readable Python code from it.
score: 1

http://stackoverflow.com/comment/86988023
score: 0
type: AnswerComment
has text: so I changed my first loop to start with 1. I am now having trouble with the taxes and deposits being added into the grand total. I am also having troubles with the user being able to end
type: Comment
comment on: http://stackoverflow.com/a/49985494

http://stackoverflow.com/q/49998161
tagged with: hash
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49998190
tagged with: function
linked to: http://stackoverflow.com/q/20059011
downvote count: 0
has answer: http://stackoverflow.com/a/78428493
score: 3
has body: I'm working on a sort of distributed build system. The system allows execution of snippets of scripts as build steps. I need to be able to hash these snippets of code in a way that comments and doc strings don't affect the hash. I'm getting part way there by using the ast module to parse the code, then doing an ast.dump and hashing the resulting string. The natural next step for me is to clear the first Expr(str()) node in the body of every FunctionDef node. Is there a better way to solve this problem?
has title: How can I hash the body of a Python function?
upvote count: 3
has comment: http://stackoverflow.com/comment/87013456
tagged with: python
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/86865127
type: Comment
has text: True. But since it will be imported in `matplotlib` anyway, it must be installed and available for use, even if it means adding an extra import to the code. Just my 2¢
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49924332

http://stackoverflow.com/a/50014042
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50013845
has body: def antisymmetric(l): for i in range(len(l)): for j in range(len(l[i])): if l[i][j] != -l[j][i] and i != j: return False return True To evaluate if matrix is antisymmetric you need to check all the cases hence you should check negative condition that for any element if test not satisfies it immediately return False In case of anti-symmetric it will evaluates all test cases and as shown in above example function will return True if for loop ends. Your test result is failing because you are immediately returning True after matching one condition only. your loop will match i=0, j=0 as A[0][0] which is 0 and 0 == -0 will evaluate True and you immediately returned it hence it's giving you unwanted result. Also you need to skip diagonal element because it doesn't changes
type: Answer
answers question: http://stackoverflow.com/q/50013845
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86954286
type: QuestionComment
has text: C:\>pip --version pip 9.0.3 from c:\users\victor~1\envs\virtual\lib\site-packages (python 3.6)
comment on: http://stackoverflow.com/q/49969085
score: 0
type: Comment

http://stackoverflow.com/a/49956263
score: 0
has body: The method readlines() reads until EOF and returns a list containing the lines. So you are getting a list in ips. You will need to iterate over this list and call check() on each iteration. Also, you have used try block without except or finally. This will result into error. You can put catch() inside the try-except block as: try: catch(ip, port) except Exception as e: print(str(e))
answers question: http://stackoverflow.com/q/49956156
type: Answer

http://stackoverflow.com/q/49997347
upvote count: 2
score: 1
downvote count: 1
favorite count: 0
has body: I've been writing this program using the Tkinter module in Python3.6.2. There are buttons to to open a list of teams and a list of competitors and I'd prefer to keep the outputs in one window, however if I click the "Teams" button followed by the "Individuals" button, the two elements open one after the other. I'm hoping to add a button that resets the window (removing the outputs, leaving just the buttons), but I haven't found any solutions online that work with my program. from tkinter import * import tkinter as tk bgcol = "#0B8CFF" class MainMenu: def __init__(self, master): self.master = master master.title("Scoring System GUI") master.geometry("500x750+75+60") self.label = Label(master, text="GUI") self.label.pack() self.team_button = Button(master, text="Teams", command=self.openTeams) self.team_button.pack() def openTeams(self): self.label = Label(text="Team #1:") self.label.pack() team1 = open("team1.csv", "r") message = team1.read() text = Text(root, width = "50", height = "6", fg = "#000000") text.pack() text.insert(END, message) redteam.close() Here's a photo of the current output:
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49997520
has title: How to refresh the window in Tkinter?
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/50001836

python-3.6
tags question: http://stackoverflow.com/q/49929025
tags question: http://stackoverflow.com/q/50017724
tags question: http://stackoverflow.com/q/50020025
tags question: http://stackoverflow.com/q/49977561
tags question: http://stackoverflow.com/q/50045417
tags question: http://stackoverflow.com/q/49957822
tags question: http://stackoverflow.com/q/49999369
tags question: http://stackoverflow.com/q/49922983
tags question: http://stackoverflow.com/q/49918108
tags question: http://stackoverflow.com/q/49992636
tags question: http://stackoverflow.com/q/50053953
tags question: http://stackoverflow.com/q/49977257
type: Tag
tags question: http://stackoverflow.com/q/49972533
tag name: python-3.6
tags question: http://stackoverflow.com/q/49927254
tags question: http://stackoverflow.com/q/49989861
tags question: http://stackoverflow.com/q/49950769
tags question: http://stackoverflow.com/q/50070877
tags question: http://stackoverflow.com/q/49932651
tags question: http://stackoverflow.com/q/50005341
tags question: http://stackoverflow.com/q/49932791
tags question: http://stackoverflow.com/q/50028834
tags question: http://stackoverflow.com/q/50053585
tags question: http://stackoverflow.com/q/49962659

django-forms
tags question: http://stackoverflow.com/q/49951293
tags question: http://stackoverflow.com/q/50056946
tags question: http://stackoverflow.com/q/49958248
tags question: http://stackoverflow.com/q/49932426
tags question: http://stackoverflow.com/q/50017584
tags question: http://stackoverflow.com/q/50007474
tags question: http://stackoverflow.com/q/50014809
tags question: http://stackoverflow.com/q/49952760
tags question: http://stackoverflow.com/q/50003815
tags question: http://stackoverflow.com/q/49973016
tags question: http://stackoverflow.com/q/49984898
tags question: http://stackoverflow.com/q/49955132
tags question: http://stackoverflow.com/q/49978662
tags question: http://stackoverflow.com/q/49982788
tags question: http://stackoverflow.com/q/49978455
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/49966892
tags question: http://stackoverflow.com/q/50026427
tags question: http://stackoverflow.com/q/49922773
tags question: http://stackoverflow.com/q/49925590
tags question: http://stackoverflow.com/q/50040255
tags question: http://stackoverflow.com/q/49946980
tags question: http://stackoverflow.com/q/50020279

http://stackoverflow.com/q/50030744
has comment: http://stackoverflow.com/comment/87078105
type: Question
has comment: http://stackoverflow.com/comment/87077907
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87078006
has title: pandas: df.apply() behind-the-scene calculation with df.groupby()
has body: I am very confused about how df.apply() work. Here is one of the issues I have: import seaborn as sns tips = sns.load_dataset("tips") tips['tip_pct'] = tips['tip'] / tips['total_bill'] tips.head() total_bill tip smoker day time size tip_pct 0 16.99 1.01 No Sun Dinner 2 0.059447 1 10.34 1.66 No Sun Dinner 3 0.160542 2 21.01 3.50 No Sun Dinner 3 0.166587 3 23.68 3.31 No Sun Dinner 2 0.139780 4 24.59 3.61 No Sun Dinner 4 0.146808 I am trying to sort tips by tips['tip_pct'] column. I can apply sort_values directly. In [153]: tips.sort_values(by='tip_pct').head() Out[153]: total_bill tip smoker day time size tip_pct 237 32.83 1.17 Yes Sat Dinner 2 0.035638 102 44.30 2.50 Yes Sat Dinner 3 0.056433 57 26.41 1.50 No Sat Dinner 2 0.056797 0 16.99 1.01 No Sun Dinner 2 0.059447 187 30.46 2.00 Yes Sun Dinner 5 0.065660 Now, I am trying to group this data frame by smoker column first, and sort by tip_pct column. In [156]: tips.groupby('smoker').apply(lambda x: x.sort_values(by='tip_pct')).head() Out[156]: total_bill tip smoker day time size tip_pct smoker No 57 26.41 1.50 No Sat Dinner 2 0.056797 0 16.99 1.01 No Sun Dinner 2 0.059447 48 28.55 2.05 No Sun Dinner 3 0.071804 146 18.64 1.36 No Thur Lunch 3 0.072961 130 19.08 1.50 No Thur Lunch 2 0.078616 I tried to understand how does groupby and apply work together, so I tried the following, but it failed. In [157]: for name, group in tips.groupby('smoker'): ...: group.apply(lambda x: x.sort_values(by='tip_pct')) ...: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-157-5b5096eaa4d6&gt; in &lt;module&gt;() 1 for name, group in tips.groupby('smoker'): ----&gt; 2 group.apply(lambda x: x.sort_values(by='tip_pct')) 3 //anaconda/lib/python3.5/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds) 4260 f, axis, 4261 reduce=reduce, -&gt; 4262 ignore_failures=ignore_failures) 4263 else: 4264 return self._app…
has comment: http://stackoverflow.com/comment/87078275
tagged with: data-analysis
tagged with: pandas
tagged with: dataframe

http://stackoverflow.com/q/49944345
has comment: http://stackoverflow.com/comment/86907293
score: -2
downvote count: 2
tagged with: python
has body: I have the following Dataframe: Rec Channel Value1 Value2 Pre 10 20 Pre 35 42 Event A 23 39 FF 50 75 Post A 79 11 Post B 88 69 And have got to the point where with the following code: res = df[df['Channel'].isin({'A', 'B'}) I am able to find all the instances in the Dataframe where the column 'Channel' has values of either A or B. I now am trying to determine a way to use a For Loop so that it will go through and print each row where A or B is found separately. The reasoning for a For Loop is that this is just a sample Dataframe, my application is going to have a dynamic value of A and B's found depending on the Dataframe and I would like to be able to call upon each individually regardless of the number of instances. Additionally, I would like an easy way to index upon the first and last instance where an A or B is found (again, the location is going to be changing from Dataframe to Dataframe) so I can't just do: res1 = res.loc[4] to identify the first one in this case, I need something that is going to be more robust regardless of the index I can call upon the first and last instance. Can someone please assist?
has comment: http://stackoverflow.com/comment/86905942
tagged with: indexing
tagged with: pandas
has comment: http://stackoverflow.com/comment/86905168
has title: Python Pandas: Indexing Instances of a Dataframe Separately within a For Loop
answer count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/86906100
has answer: http://stackoverflow.com/a/49946066
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86906327
tagged with: for-loop
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50032976
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87082535
has comment: http://stackoverflow.com/comment/87082485
has comment: http://stackoverflow.com/comment/87082094
has title: Int(2) to 16 bit conversion python
has comment: http://stackoverflow.com/comment/87082350
favorite count: 0
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/87082431
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50033023
tagged with: python
has body: I am working with a dataset that has some data stored in the format INT(2). I need to convert this to binary (16 bits) to read the data back in a meaningful manner via python. I am currently using: format(value, '016b') To convert the int to binary to read the bits back. So I am looking for simple verification that the conversion I am doing is correct given the types I am using (since the output I see doesn't quite align with the expected output in the documentation). For instance, do these converted values make sense given the description above? 2369 -> 0000100101000001 18767 -> 0100100101001111
tagged with: int
has comment: http://stackoverflow.com/comment/87082144
score: 0
has comment: http://stackoverflow.com/comment/87082702
upvote count: 1

http://stackoverflow.com/comment/86929852
comment on: http://stackoverflow.com/a/49955631
type: Comment
has text: Oops , my bad. Sorry for the trouble.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49985362
score: 4
answers question: http://stackoverflow.com/q/49984377
downvote count: 0
type: Answer
has body: You need to take autofit() outside of the loop as it will auto fit the column width for each row. Unless the last row has the longest text this won't work. If you want to auto fit the entire column you can use rng.entirecolumn.autofit() or specify your range to include all rows that you want to auto fit the column width such as sht.range("A1:A20").columns.autofit()
upvote count: 4

http://stackoverflow.com/q/49922920
score: 2
has body: I had search for an API which provides access to firbase. I got python-firebase api which only interacts with database of firebase. Is there any way from where, we can get aggregate data listed on the analytics dashboard.
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/35095707
has answer: http://stackoverflow.com/a/49936484
tagged with: python
type: UnansweredQuestion
has title: Google firebase retrieve analytics data through the API
answer count: 1
tagged with: firebase
tagged with: firebase-analytics
duplicate of: http://stackoverflow.com/q/35095707

http://stackoverflow.com/q/50015521
has body: I have a very simple code and am attempting to plot my resulting numpy array pos as a function of t, but I'm getting a random unicode error. I've never had this error appear before, and I'm at a loss for what it means or why it would appear in this code: import numpy as np import matplotlib.pyplot as plt h = 0.5 x_0 = 1 w = 1 t = np.arange(0, 20, h) pos, v = np.zeros(len(t)), np.zeros(len(t)) pos[0], v[0] = x_0, 0 def a(pos): return -w**2 * pos for i in range(1, len(t)): # Stormer-Verlet method pos[i] = pos[i-1] + h*(v[i-1] + 0.5*h*a(pos[i-1])) v[i] = v[i-1] + 0.5*h*a(pos[i-1]) + 0.5*h*a(pos[i]) # Plotting position as a function of time plt.plot(t, pos, label='Störmer-Verlet approximation') At the plt.plot line, I'm getting this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128). I also printed pos and confirmed that it is an array as expected, with length 100 (the same length as t). Does anyone know why this is happening?
has title: Unicode error when trying to plot arrays?
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87047471
type: Question
has comment: http://stackoverflow.com/comment/87047426
score: 0
has answer: http://stackoverflow.com/a/50015615
answer count: 1
accepted answer: http://stackoverflow.com/a/50015615
tagged with: python
tagged with: unicode
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/87136732
type: Comment
score: 0
type: AnswerComment
has text: If you're going to post a code-only answer, can you please at least post code that doesn't throw syntax errors?
comment on: http://stackoverflow.com/a/50058981

http://stackoverflow.com/q/50009734
has body: I have the following list of dictionaries containing a household id (HID) for each year: list_of_dicts = [{'HID':'1','year':'2017'}, {'HID':'1','year':'2018'}, {'HID':'2','year':'2017'}, {'HID':'2','year':'2018'}, {'HID':'3','year':'2017'}, {'HID':'3','year':'2018'}] I want to read in each dict and add a new numeric id. I can do something similar to this using the following code: i = 0 for line in list_of_dicts: line['id'] = i i += 1 However, this make the id item run continuously like this: list_of_dicts = [{'HID':'1','year':'2017','id':1}, {'HID':'1','year':'2018','id':2}, {'HID':'2','year':'2017','id':3}, {'HID':'2','year':'2018','id':4}, {'HID':'3','year':'2017','id':5}, {'HID':'3','year':'2018','id':6}] I want to allocate the same numeric id variable to each HID across each year, like so: list_of_dicts = [{'HID':'1','year':'2017','id':1}, {'HID':'1','year':'2018','id':1}, {'HID':'2','year':'2017','id':2}, {'HID':'2','year':'2018','id':2}, {'HID':'3','year':'2017','id':3}, {'HID':'3','year':'2018','id':3}] How do I control id allocation to be the same for each household, for each year?
downvote count: 0
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50009797
has answer: http://stackoverflow.com/a/50009883
tagged with: list
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/50009803
has title: Add new item to list of dictionaries controlling based on other item values
upvote count: 1
has comment: http://stackoverflow.com/comment/87036172
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/50037178
has body: Use pandas.series import pandas as pd series = pd.Series(scores) result = series.rank(method="dense", ascending=0).astype(int).values.tolist() output: [1, 1, 2, 3, 3, 4, 5]
type: Answer
answers question: http://stackoverflow.com/q/50036882
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87157262
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50070265
score: 0
has text: this above is just a pseudo code... I wrote a tf.op and want to check it if it works correctly. Therefore, it is a general question... and I want to know if it works... So, I have to write the forward pass by hand instead of using `tf.conv`.

subsequence
tags question: http://stackoverflow.com/q/49985779
tag name: subsequence
type: Tag

http://stackoverflow.com/a/49928496
has comment: http://stackoverflow.com/comment/86873405
has body: Just mere seconds before posting this, I tried purely on a whim to change this code to use groupby(...).apply(...). To my amazement, my first attempt at using apply appears to have produced exactly what I wanted: result = ( ds.groupby('kind') .apply(lambda d: d['prob'] .unstack('stacked_layer_qpoint') .sum(dim='qpoint') ) ) # result has dims: (kind: 3, mode: 18, layer: 2) However, this still fails with MergeError if naively assigned to a new variable of ds. It turns out that this error is simply because I had set kind as a variable instead of a coordinate. That can be corrected after-the-fact by using set_coords to "upgrade" kind into a coordinate: ds['kind-prob'] = result # this would give MergeError ds = ds.set_coords('kind') ds['kind-prob'] = result # ok now Edit: Nope, that's a bad idea, too. result has 'kind' as a dimension, but after this assignment, the 'kind' is merely a coordinate. Perhaps the real issue here is that I am trying to have both a dimension and a variable share the same name, which simply is not supported. I also discovered two more possible improvements to the definition: DataArray.groupby can take a DataArray containing the values to use for grouping (making it unnecessary to use groupby on the entire Dataset) I can avoid the unstack by making nested calls to groupby. The idea is to groupby each individual thing you want to have as a dimension in the output array. This works because the original layer and qpoint coordinates are still there; if you inspect one of the arrays produced by the first groupby, you will see it has one dimension (stacked_layer_qpoint) but three coordinates (stacked_layer_qpoint, layer, qpoint). Edit: It turns out that nested groupby-apply is insanely slow compared to the solution using unstack, presumably because it puts a lot of pure python code (the lambdas) in a hot loop. This results in the following: kind_prob = ( ds['prob'] .groupby(ds['kind']) .apply(lambda d: d.unstack('stacked_layer_qpoint').sum(dim='qpoint')…
type: Answer
answers question: http://stackoverflow.com/q/49928495
has comment: http://stackoverflow.com/comment/86873728
score: 0

http://stackoverflow.com/comment/87131816
score: 0
has text: would you please put the main command here in the comments?
comment on: http://stackoverflow.com/q/50039222
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87042525
type: AnswerComment
has text: You can use a dictionary instead of a list for you cart. Then, the key can be the name of the item and the value can be the amount of the item in cart
comment on: http://stackoverflow.com/a/50012916
score: 0
type: Comment

http://stackoverflow.com/a/49943600
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49942864
score: 1
type: Answer
has body: So you are looking for itertools.izip_longest(): import itertools files = ['pizza', 'pasta', 'drinks'] result = [] for f in files: with open('{}.txt'.format(f)) as menu: result.append([item.strip() for item in menu]) final = list(itertools.izip_longest(*result, fillvalue=''))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49942864
downvote count: 0

http://stackoverflow.com/q/49992390
answer count: 0
tagged with: subprocess
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: Python: Unicode error when passing password to sudo using subprocess.Popen.communicate
has body: I have a tkinter Python 3 program that needs sudo privileges, so it checks for that and if you don't have it, it'll ask for your password and then rerun the program with sudo. My current code works when just running the code like, python3 myscript.py, but if I compile the script with python3 -m py_compile and run it it gives me the below error. Traceback (most recent call last): File "myscript.py", line 339, in &lt;module&gt; prompt = reload.communicate(input='{}\r\n'.format(password))[1] File "/usr/lib/python3.5/subprocess.py", line 1072, in communicate stdout, stderr = self._communicate(input, endtime, timeout) File "/usr/lib/python3.5/subprocess.py", line 1757, in _communicate self.stderr.encoding) File "/usr/lib/python3.5/subprocess.py", line 976, in _translate_newlines data = data.decode(encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 259: invalid start byte Again, this only happens after compiling the script and seems to be related to translate newlines option in subprocess.Popen. Here's the bits of the troublesome code: def get_userpassword(): userpassword = simpledialog.askstring("Password", "Please enter your password:", show='*') return userpassword password = get_userpassword() reload = subprocess.Popen(['sudo', '-k', '-S', './' + __file__], stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) prompt = reload.communicate(input='{}\r\n'.format(password))[1] I'm sure I'm missing something as I've put all this together using other bits of code found across the StackExchange, but no one seems to be doing it quite like this (compiling it). Or should I just forget it and give the users a warning to rerun the script with sudo? A little more background, I'm trying to freeze this code with PyInstaller and found that the compiling process is where this stops working. Also, I'm writing this for some Linux users, who though being Linux users, are not experts and tend to shy away from doing things in the terminal. So i…
tagged with: popen
tagged with: python
score: 1
favorite count: 0
type: Question
tagged with: sudo

http://stackoverflow.com/q/49966464
has answer: http://stackoverflow.com/a/49991170
downvote count: 4
upvote count: 0
answer count: 1
has title: make a balance command discord.py
favorite count: 0
type: Question
tagged with: discord.py
type: UnansweredQuestion
score: -4
has body: So I'm trying to make a betting game for my bot and I want to add a currency but I have no idea on how to do it. Would I need to open a txt file and list out all members names? any help would be great thx.
tagged with: python

watson-nlu
type: Tag
tags question: http://stackoverflow.com/q/50008200
tag name: watson-nlu
tags question: http://stackoverflow.com/q/49989968
tags question: http://stackoverflow.com/q/49977879

http://stackoverflow.com/q/49928825
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76337309
has answer: http://stackoverflow.com/a/57814767
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/135051849
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86873696
has comment: http://stackoverflow.com/comment/86874107
tagged with: docker-compose
has body: I'm trying to get gunicorn working with nginx in a docker compose file. My python code is just a flask CRUD app. The entry point for my flask app is at ./flask_app/app.py and I've got the following for a docker compose yaml file version: '3' services: flask_app: container_name: flask_app restart: always build: ./flask_app ports: - "8000:8000" command: gunicorn -w 1 -b :8000 app:server nginx: container_name: nginx restart: always build: ./nginx ports: - "80:80" depends_on: - flask_app and here's my app file from flask import Flask from flask_marshmallow import Marshmallow from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_pyfile('config.py') db = SQLAlchemy(app) ma = Marshmallow(app) if __name__ == '__main__': app.run(host='0.0.0.0', port=6000, debug=True) However when I run the above I'm getting the following error Recreating ce38627418c1_ce38627418c1_ce38627418c1_ce38627418c1_ce38627418c1_flask_app ... error ERROR: for ce38627418c1_ce38627418c1_ce38627418c1_ce38627418c1_ce38627418c1_flask_app Cannot start service flask_app: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"gunicorn\": executable file not found in $PATH": unknown ERROR: for flask_app Cannot start service flask_app: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"gunicorn\": executable file not found in $PATH": unknown ERROR: Encountered errors while bringing up the project. As far as I can tell it doesn't seem my app = Flask(__name__) variable and I'm not sure why. I'm basing my approach on this working example https://github.com/sladkovm/docker-flask-gunicorn-nginx. Does anyone have any ideas? EDIT: In my flask_app directory I have a Dockerfile that the docker_compose file is pointing to. Here is what it looks like: FROM python:3.6.2 RUN mkdir -p /flask_app/app WORKDIR /flask_app/app COPY . /flask_app/app RUN pip install --no-cache-dir -r requirements.txt COPY . /flask_app/app
tagged with: nginx
has title: Gunicorn throwing error - cannot find executable on $PATH (Docker/Nginx)
has comment: http://stackoverflow.com/comment/86873858
has comment: http://stackoverflow.com/comment/86873802
tagged with: python
has answer: http://stackoverflow.com/a/72882156
score: 12
tagged with: gunicorn
answer count: 3
has comment: http://stackoverflow.com/comment/86873737
upvote count: 12
has comment: http://stackoverflow.com/comment/86874040

http://stackoverflow.com/q/49952510
has comment: http://stackoverflow.com/comment/86921589
has comment: http://stackoverflow.com/comment/86921675
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86921584
tagged with: python
has comment: http://stackoverflow.com/comment/86921692
score: 0
has comment: http://stackoverflow.com/comment/86921578
has title: Can't break while True
type: Question
tagged with: python-3.x
has body: First post here! I know there are few threads like this one, I've read them, but didn't succeed. Can't break out of while True loop (at the bottom of the code where "break" is) and continue to a sound file. I am new to programming, just learning... Thanks in advance. # calculating coin price coinprice = Decimal(binance()) * Decimal(binancecr()) shorted = round(coinprice, 4) # creating list highestvalue = [0.0001] # getting current time formattime = "%H:%M:%S" now_utc = datetime.now(timezone('UTC')) now_currenttime = now_utc.astimezone(timezone('Europe/Berlin')) # getting current price print(shorted, "$", "= Starting Price", "(", now_currenttime.strftime(formattime), ")") while True: # getting current time formattime = "%H:%M:%S" now_utc = datetime.now(timezone('UTC')) now_currenttime = now_utc.astimezone(timezone('Europe/Berlin')) # formatting coin price deciplaces = Decimal(binance()) * Decimal(binancecr()) rounded = round(deciplaces, 4) # getting highest price for item in highestvalue: if item &lt; rounded: del highestvalue[0] highestvalue.append(rounded) # printing highest price print(highestvalue[0], "$", "= Highest Price ", "(", now_currenttime.strftime(formattime), ")") # calculating desired price percentage = Decimal(highestvalue[0]) * Decimal(0.001) / Decimal(100) percentcalc = Decimal(highestvalue[0]) - Decimal(percentage) percconv = Decimal(percentcalc) percround = round(percconv, 4) # calculating percentage change change_percent = ((Decimal(highestvalue[0]) - Decimal(rounded)) / Decimal(rounded)) * Decimal(100.00) convchange_percent = Decimal(change_percent) roundchange_percent = round(convchange_percent, 4) # printing current price, desired price and percentage changes print(rounded, "$", "= Current Price ", "(", now_currenttime.strftime(formattime), ")") print(percround, "$", "= Desired Price ", "(", now_currenttime.strftime(formattime), ")") print(roundchange_percent, " %", "= Percent Change", "(", now_currenttime.strftime(formattime), ")") print("----…
answer count: 0

http://stackoverflow.com/comment/86937420
comment on: http://stackoverflow.com/q/49960374
has text: No, I agree, I was just showing how to use `[mcve]`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86938464
score: 0
comment on: http://stackoverflow.com/q/49961051
type: QuestionComment
has text: Do you have created any resources/opened files, etc.?
type: Comment

http://stackoverflow.com/q/49933952
score: 5
has answer: http://stackoverflow.com/a/70208435
type: UnansweredQuestion
tagged with: python
has body: I am trying to return two cookies from Lambda to client(Postman) via APIGateway. I referred to the aws blog, and could return 1 cookie to client. https://aws.amazon.com/jp/blogs/compute/simply-serverless-using-aws-lambda-to-expose-custom-cookies-with-api-gateway/ But I have no idea to return 2 kind of cookies. I tried like this, but not working. return { 'cookie': 'aaa=bbb; secure' -&gt; Okay, but just one cookie # 'cookie': 'aaa=bbb; ccc=ddd; secure' -&gt; × # 'cookie': ['aaa=bbb','ccc=ddd'] -&gt; × } Could anyone give me an advise?
tagged with: aws-api-gateway
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/73615532
linked to: http://stackoverflow.com/q/39769222
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86974195
favorite count: 0
tagged with: aws-lambda
has title: How to return multiple cookies with AWS APIGateway and Lambda?
tagged with: serverless-framework
type: Question
has answer: http://stackoverflow.com/a/49935095
upvote count: 5

http://stackoverflow.com/comment/87147150
comment on: http://stackoverflow.com/q/50065192
has text: @chepner: *Python3* doesn't have it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87002500
has text: You're welcome! Nice being helpful!. *PEP8* rules are not mandatory but definitely a guideline to follow...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49983901
type: AnswerComment

http://stackoverflow.com/q/49949885
has title: How python object memory works for int less than -5 and greater 256
score: 0
has comment: http://stackoverflow.com/comment/86916582
answer count: 0
has comment: http://stackoverflow.com/comment/86916438
has body: In my understanding, all things in python are object and some of them per-allocate memory to them (for int the range is from -5 to 256). My question is if the address not per-allocate, does it create in fly? for example: print id(256) a = 256 print id(a) 36609008 36609008 this example indicates variable a is referring the object 256's memory, thus they have same address. print id(300) a = 300 print id(a) 106711544 106708304 for the example above: does python create two objects? (it seems yes) why -5 to 256? would those per-allocated object be reused to create new objects?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86916442
upvote count: 1
linked to: http://stackoverflow.com/q/306313
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/306313
has comment: http://stackoverflow.com/comment/86916552
has comment: http://stackoverflow.com/comment/86916656
tagged with: python
has comment: http://stackoverflow.com/comment/86916454
has comment: http://stackoverflow.com/comment/86916531
has comment: http://stackoverflow.com/comment/86916483

http://stackoverflow.com/q/49962740
type: Question
has title: multiple linear regression Python statsmodel shows predictorVariable[T.x] in the output
upvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49963563
has answer: http://stackoverflow.com/a/49963563
type: AnsweredQuestion
has body: OLS Regression Results ============================================================================== Dep. Variable: BTCUSD R-squared: 0.989 Model: OLS Adj. R-squared: 0.985 Method: Least Squares F-statistic: 260.6 Date: Sun, 22 Apr 2018 Prob (F-statistic): 1.87e-171 Time: 13:10:27 Log-Likelihood: -2119.3 No. Observations: 280 AIC: 4383. Df Residuals: 208 BIC: 4644. Df Model: 71 Covariance Type: nonrobust ========================================================================================================== coef std err t P&gt;|t| [0.025 0.975] ---------------------------------------------------------------------------------------------------------- Intercept -3.013e+05 1.8e+05 -1.674 0.096 -6.56e+05 5.36e+04 howtobuycryptocurrencyWorldwide[T.1] 284.2228 436.490 0.651 0.516 -576.289 1144.735 howtobuycryptocurrencyWorldwide[T.2] -834.5288 918.605 -0.908 0.365 -2645.499 976.442 howtobuycryptocurrencyWorldwide[T.3] -1639.0373 892.061 -1.837 0.068 -3397.677 119.603 howtobuycryptocurrencyWorldwide[T.4] -1822.9216 1349.968 -1.350 0.178 -4484.296 838.453 howtobuycryptocurrencyWorldwide[T.5] -461.3566 751.629 -0.614 0.540 -1943.144 1020.431 howtobuycryptocurrencyWorldwide[T.6] -1590.4795 1084.831 -1.466 0.144 -3729.153 548.194 howtobuycryptocurrencyWorldwide[T.7] -667.8484 506.288 -1.319 0.189 -1665.962 330.265 howtobuycryptocurrencyWorldwide[T.8] -575.7590 1297.502 -0.444 0.658 -3133.698 1982.180 howtobuycryptocurrencyWorldwide[T.9] -2449.3509 1565.416 -1.565 0.119 -5535.466 636.764 howtobuycryptocurrencyWorldwide[T.10] 1362.5353 1131.645 1.204 0.230 -868.429 3593.499 howtobuycryptocurrencyWorldwide[T.11] 1.206e+04 5006.070 2.408 0.017 2186.460 2.19e+04 howtobuycryptocurrencyWorldwide[T.13] -8135.2934 3056.663 -2.661 0.008 -1.42e+04 -2109.283 howtobuycryptocurrencyWorldwide[T.14] -333.8614 1012.361 -0.330 0.742 -2329.665 1661.943 howtobuycryptocurrencyWorldwide[T.17] -9448.2497 3586.911 -2.634 0.009 -1.65e+04 -2376.888 howtobuycryptocurrencyWorldwide[T.19] -8515.1383 37…
tagged with: linear-regression
answer count: 1
tagged with: google-trends
downvote count: 1
score: -1
favorite count: 0

http://stackoverflow.com/comment/87033605
comment on: http://stackoverflow.com/q/50007474
score: 0
type: QuestionComment
type: Comment
has text: Ok thanks for the traceback, now edit your codes with the views, I am pretty sure, the bug is there

http://stackoverflow.com/q/50036796
has comment: http://stackoverflow.com/comment/87096430
tagged with: selenium
type: Question
has title: Python + Selenium: for loop went wrong
tagged with: python-3.x
tagged with: for-loop
type: UnansweredQuestion
has body: I am trying to get "href" of divs in for loop and enter the "href" in each "season". It's working but after the first season, it's not finding the second season and next... It's breaking in season.get_attribute after the first episode and not continue, I tried to fix it 3 hours. If someone can help me, thanks in advance. The URL : http://www.tvil.me/view/181/1/1/v/הומלנד_Homeland.html seasons_num = driver.find_elements_by_xpath("//*[contains(@id, 'change-season-')]/a") I = 0; for season in seasons_num: I += 1 print("Season: %i" % (I)) try: season_link = season.get_attribute("href") // It's breaks here ## seasons.append(season_link) except: print("---- Faild to fetch season %i -----" % (I)) raise print("%s Season %i" % (post_id, I)) driver.get(season_link) episodes = driver.find_elements_by_xpath("//*[contains(@id, 'change-episode-')]/a") E = 0; for episode in episodes: E += 1 print("Post ID:%s Season:%i Episode: %i" % (post_id,I,E)) time.sleep(1) episode_link = episode.get_attribute("href") The response: Post_ID: 100 Season: 1 100 Season 1 Post ID:100 Season:1 Episode: 1 Post ID:100 Season:1 Episode: 2 Post ID:100 Season:1 Episode: 3 Post ID:100 Season:1 Episode: 4 Post ID:100 Season:1 Episode: 5 Post ID:100 Season:1 Episode: 6 Post ID:100 Season:1 Episode: 7 Post ID:100 Season:1 Episode: 8 Post ID:100 Season:1 Episode: 9 Post ID:100 Season:1 Episode: 10 Post ID:100 Season:1 Episode: 11 Post ID:100 Season:1 Episode: 12 Post ID:100 Season:1 Episode: 13 Post ID:100 Season:1 Episode: 14 Post ID:100 Season:1 Episode: 15 Post ID:100 Season:1 Episode: 16 Season: 2 Failed to fetch season 2: Traceback (most recent call last): File C:\Users\maorb\OneDrive\Desktop\Maor\python\serethd\tvil.me.py", line 54, in &lt;module&gt; season_link = season.get_attribute("href") File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 112, in get_attribute resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name}) File "C:\Program F…
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/87090224
answer count: 0
has comment: http://stackoverflow.com/comment/87089924

http://stackoverflow.com/q/50012064
upvote count: 1
tagged with: urllib
has answer: http://stackoverflow.com/a/50012084
favorite count: 0
type: Question
has title: python urllib.error.HTTPError
has body: I have a function that works as followed: def pull_sector(sym): company_data_link = "url%s%s" % (sym,API_KEY_COMPANY) with urllib.request.urlopen(company_data_link) as url: company_data = json.loads(url.read().decode()) return company_data this function works 95% of the time but every once in a while I get a 404 error and this is not a big deal, but it screws me up, how can i instead of crashing my scripts pass something like 404 on the return?
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/50012084

http://stackoverflow.com/comment/86907297
type: AnswerComment
score: 0
has text: `.format` works as it should - `%s` is not used here, it is used in `execute` method. You can do `print(q)` to see what I mean. I will add a good doc link about providing parameters in queries and my thoughts about `NoneType`.
type: Comment
comment on: http://stackoverflow.com/a/49945166

class
tags question: http://stackoverflow.com/q/50017405
tags question: http://stackoverflow.com/q/49964129
tags question: http://stackoverflow.com/q/50054626
type: Tag
tags question: http://stackoverflow.com/q/50051365
tags question: http://stackoverflow.com/q/49971479
tags question: http://stackoverflow.com/q/49967183
tags question: http://stackoverflow.com/q/50071047
tags question: http://stackoverflow.com/q/49946616
tags question: http://stackoverflow.com/q/50011561
tags question: http://stackoverflow.com/q/50054322
tags question: http://stackoverflow.com/q/49927797
tags question: http://stackoverflow.com/q/50048681
tags question: http://stackoverflow.com/q/50066396
tag name: class
tags question: http://stackoverflow.com/q/50065610
tags question: http://stackoverflow.com/q/50033608
tags question: http://stackoverflow.com/q/50049337
tags question: http://stackoverflow.com/q/50015719
tags question: http://stackoverflow.com/q/49921057
tags question: http://stackoverflow.com/q/50032571
tags question: http://stackoverflow.com/q/49922205
tags question: http://stackoverflow.com/q/50061029
tags question: http://stackoverflow.com/q/50041035
tags question: http://stackoverflow.com/q/49941192
tags question: http://stackoverflow.com/q/49960790
tags question: http://stackoverflow.com/q/49991947
tags question: http://stackoverflow.com/q/49944797
tags question: http://stackoverflow.com/q/49968581
tags question: http://stackoverflow.com/q/50049369
tags question: http://stackoverflow.com/q/50037275

http://stackoverflow.com/q/50040238
tagged with: python
has title: Train-test Split of a CSV file in Python
has comment: http://stackoverflow.com/comment/87096488
possible better answer: http://stackoverflow.com/a/50040383
tagged with: data-science
has comment: http://stackoverflow.com/comment/87097110
accepted answer: http://stackoverflow.com/a/50040416
type: AnsweredQuestion
score: 0
has body: I have a .csv file that contains my data. I would like to do Logistic Regression, Naive Bayes and Decision Trees. I already know how to implement these. However, my teacher wants me to split the data in my .csv file into 80% and let my algorithms predict the other 20%. I would like to know how to actually split the data in that way. diabetes_df = pd.read_csv("diabetes.csv") diabetes_df.head() with open("diabetes.csv", "rb") as f: data = f.read().split() train_data = data[:80] test_data = data[20:] I tried to split it like this (sure it isn't working).
has answer: http://stackoverflow.com/a/50040416
has comment: http://stackoverflow.com/comment/87096609
favorite count: 0
has answer: http://stackoverflow.com/a/50040383
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87096586
linked to: http://stackoverflow.com/q/41585078
type: Question
upvote count: 2
downvote count: 2
answer count: 2
tagged with: machine-learning

http://stackoverflow.com/q/50020885
has body: I have this: alert = Alert(title=a, tlp=3, tags=tags, description='N/A', type='external', source='instance1', sourceRef=sourceRef, artifacts=artifacts) And I want to know how to get the value of 'title', I tried to do this: print(alert['title']) but doesnt work: TypeError: 'Alert' object is not subscriptable Any idea?
type: Question
tagged with: python
has title: get the value of a json
type: AnsweredQuestion
tagged with: python-3.x
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50020929
score: 0
has answer: http://stackoverflow.com/a/50020929
answer count: 1

http://stackoverflow.com/a/49929552
downvote count: 0
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/49929482
has body: Iterate over the the zip of the two lists: startxy = [(0,0),(1,0),(2,0),...etc.] endxy = [(1,1),(2,1),(3,1),...etc.] for start, end in zip(startxy, endxy): cv2.rectangle(img, start, end, color, thickness)
accepted answer of: http://stackoverflow.com/q/49929482
type: AcceptedAnswer

music21
type: Tag
tag name: music21
tags question: http://stackoverflow.com/q/49939275

http://stackoverflow.com/a/50003491
answers question: http://stackoverflow.com/q/50003297
upvote count: 3
downvote count: 0
has body: No, you won't have anyway of commanding via the RSTP link using the opencv built in functions. These work at driver level and all the RTSP link provides is a place to pull frames from. If you want to resize the images, you can do this after you grab the frame using OpenCV resize If you want to size the stream itself, then you will need to recode the stream at the source i.e. go into the settings and change it. Although you may not have access to this if it is somebody elses stream, you dont have permissions etc.
score: 3
type: Answer

http://stackoverflow.com/q/49963298
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86942518
has comment: http://stackoverflow.com/comment/86942745
has comment: http://stackoverflow.com/comment/86943383
has comment: http://stackoverflow.com/comment/86942597
has comment: http://stackoverflow.com/comment/86942861
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49963343
favorite count: 0
has comment: http://stackoverflow.com/comment/86943097
type: Question
has answer: http://stackoverflow.com/a/49963570
has comment: http://stackoverflow.com/comment/86942627
has body: I am learning python by trying to solve question as follows. Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. The following solution that I have came up works with positive integers but it does not work if a= -1 and b =1. I wonder how do you handle negative values. class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ while b != 0: carry = a&amp;b a= a^b b= carry&lt;&lt;1 return a
type: UnansweredQuestion
has title: Calculate the sum of two positive or negative integers
tagged with: python
linked to: http://stackoverflow.com/q/38557464
has comment: http://stackoverflow.com/comment/86942583
has comment: http://stackoverflow.com/comment/86942570
has comment: http://stackoverflow.com/comment/86942516
has comment: http://stackoverflow.com/comment/86942755
has comment: http://stackoverflow.com/comment/86943111

pandas-groupby
tags question: http://stackoverflow.com/q/49999166
tags question: http://stackoverflow.com/q/49969834
tags question: http://stackoverflow.com/q/50045353
type: Tag
tags question: http://stackoverflow.com/q/50009955
tags question: http://stackoverflow.com/q/50037805
tags question: http://stackoverflow.com/q/50018512
tags question: http://stackoverflow.com/q/49981190
tags question: http://stackoverflow.com/q/50050617
tags question: http://stackoverflow.com/q/50052570
tags question: http://stackoverflow.com/q/49924634
tags question: http://stackoverflow.com/q/49955304
tags question: http://stackoverflow.com/q/49982204
tags question: http://stackoverflow.com/q/49944803
tags question: http://stackoverflow.com/q/50040989
tags question: http://stackoverflow.com/q/50018191
tags question: http://stackoverflow.com/q/49924427
tags question: http://stackoverflow.com/q/49955674
tags question: http://stackoverflow.com/q/50061714
tags question: http://stackoverflow.com/q/50047844
tags question: http://stackoverflow.com/q/49924864
tags question: http://stackoverflow.com/q/49952409
tags question: http://stackoverflow.com/q/49931414
tags question: http://stackoverflow.com/q/49968316
tags question: http://stackoverflow.com/q/50029347
tags question: http://stackoverflow.com/q/50049055
tags question: http://stackoverflow.com/q/50045537
tags question: http://stackoverflow.com/q/49919454
tags question: http://stackoverflow.com/q/49925331
tags question: http://stackoverflow.com/q/50068443
tags question: http://stackoverflow.com/q/50047703
tags question: http://stackoverflow.com/q/49962989
tags question: http://stackoverflow.com/q/49950324
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/50048689
tags question: http://stackoverflow.com/q/49999334
tags question: http://stackoverflow.com/q/49926279
tags question: http://stackoverflow.com/q/49977810
tags question: http://stackoverflow.com/q/49922644
tags question: http://stackoverflow.com/q/49949796
tags question: http://stackoverflow.com/q/50039771
tags question: http://stackoverflow.com/q/49993889

http://stackoverflow.com/a/50046781
type: Answer
answers question: http://stackoverflow.com/q/50045714
accepted answer of: http://stackoverflow.com/q/50045714
type: AcceptedAnswer
score: 0
has body: The method you used is good for creating a new database from an existing database from scratch. The best way I can think of for updating you database will actually require some more code. You will have to determine what tables are in recent_db. Iterate through the list of available tables in recent_db: Append the records from recent_db to archive_db Assuming you have enforced some type of uniqueness for your columns in archive_db, you can catch SQLite's IntegrityError and just skip the records that already exist in the table based on the uniqueness condition Note: I'm going to assume that all the tables in recent_db also exist in archive_db. If not, then you will have to do an additional check to create the new tables in archive_db, but that would be out of the scope of this problem. I'm also going to assume that you don't really want to update the sqlite_sequence table since it's an internal table used to track ROWIDs. And lastly, I'm going to assume that the order of columns in your recent_db tables are the same for archive_db import sqlite3 recent_con = sqlite3.connect('recent.db') archive_con = sqlite3.connect('archive.db') recent_cur = recent_con.cursor() archive_cur = archive_con.cursor() # table query tbl_q = """ SELECT name FROM sqlite_master WHERE type='table' AND name != 'sqlite_sequence' """ tables = [t[0] for t in recent_cur.execute(tbl_q)] for table in tables: for row in recent_cur.execute("SELECT * FROM {}".format(table)): try: archive_cur.execute("INSERT INTO {} VALUES ({})".format(table, ','.join('?' * len(row))), row) except sqlite3.IntegrityError: pass # skip record since unique constraint failed archive_con.commit() # commit inserts archive_cur.close() recent_cur.close() archive_conn.close() recent_conn.close()

http://stackoverflow.com/a/49948905
has body: Assuming you only want to show that banner at the top of the page for logged in users (those that have a User instance in the current request), you could create a Model (or, if you have your own user profile model, add a field to it) to save that. class Access(models.Model): user = models.ForeignKey(User) has_been_here_before = models.BooleanField(default=False) In your view you would have to check that Model to see if the user is registered there and has the flag set. See this post for detecting first login. See also this similar post for detecting a visit to each individual page or view. EDIT: according to your comments you want to show the welcome banner to anonymous users (not logged in) if they visit for the first time. You could achieve that using djangos session framework. You can use request.session just like a simple dict. In your home page view (or through a custom middleware so it affects all pages not just the home page) you could check if a user has already dismissed the welcome banner or not. def my_home_view(request): ... # as default 'show_welcome_banner' will be True context['show_welcome_banner'] = request.session.get('show_welcome_banner', True) ... Then, in your template use: {% if show_welcome_banner %} First time here? Follow these steps... {% endif %} Your banner could have a 'dismiss' button that posts a hidden to a different url (maybe even through ajax). This url would alter the users session info: def dismiss_welcome_banner(request): ... if request.method == 'POST': request.session['show_welcome_banner'] = False ... Notes: if a user access the site through incognito mode (the session cockie gets deleted when he closes the browser) he will need to click the dismiss button every time he opens the incognito browser. You could additionally check that loggen in users do not get to see that banner, depending of how you prefer it.
score: 3
accepted answer of: http://stackoverflow.com/q/49948280
type: Answer
has comment: http://stackoverflow.com/comment/134514557
answers question: http://stackoverflow.com/q/49948280
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86875945
comment on: http://stackoverflow.com/q/49929927
score: 3
type: Comment
type: QuestionComment
has text: It sounds like you want OS-level protection. I imagine that you can't prevent your code from just calling into exposed APIs that modify files. You probably just want to change permissions on those files. (which you can do by the way with [`os.chmod`](https://stackoverflow.com/questions/16249440/changing-file-permission-in-python))

http://stackoverflow.com/comment/95551083
comment on: http://stackoverflow.com/a/54368405
score: 1
type: Comment
has text: While this may theoretically answer the question, it could be suggested as a comment only. Maybe you can expand the answer a bit by clicking [edit] and tell from which version onwards this module is removed.
type: AnswerComment

http://stackoverflow.com/a/49967649
answers question: http://stackoverflow.com/q/49966159
type: Answer
has body: Looks like your problem is one of timing and one of understanding1: The enum member names ('mainMenu', 'pause', etc.) are not actually converted into Enum members until after the class is completed; this means that any class-level references ('allGameStates' = ...) are referring to strings. self.curgamestate = ... -- this is setting the current game state on an instance (an Enum member), not on the class -- so what the "current" game state is can (and will!) be a confused mess. What you need there is self.__class__.curgamestate = ... finally, a rule of thumb for what gets converted into an Enum -- anything that is a simple name assignment. So, not only are mainMenu, inGame, pause, and exit converted into Enums, but so is allGameStates and curgamestate2. Some hints: once GameState is built, list(GameState) will give you the (correct) list of members self.gamestate is the same as self.name self.allGameStates should just be self.__class__ (unlike normal classes, an Enum class is iterable) -- 1 see When and where to use for some ideas on how to use Enum 2 see Define a class constant for ways to have simple name assignment not get transformed into Enum members
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49966159

http://stackoverflow.com/comment/87044883
score: 0
has text: Possible duplicate of [Django Forms and Bootstrap - CSS classes and <divs>](https://stackoverflow.com/questions/8474409/django-forms-and-bootstrap-css-classes-and-divs)
comment on: http://stackoverflow.com/q/50014339
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50067993
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87152599
has comment: http://stackoverflow.com/comment/87152438
answer count: 3
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50068347
has answer: http://stackoverflow.com/a/50068405
possible better answer: http://stackoverflow.com/a/50068382
has answer: http://stackoverflow.com/a/50068347
tagged with: difference
type: Question
has answer: http://stackoverflow.com/a/50068382
has title: Diff between time string and current time without year
tagged with: python
tagged with: date
has body: I want to determine the difference between a date string and the current time. The problem is that the time string does not contain a year (But the current datetime does, so that would be make trouble on year change?) Here's my current code: date_parsed = datetime.strptime('Fri Apr 27 19:09:53', '%a %b %d %H:%M:%S') current_time = datetime.now()
has comment: http://stackoverflow.com/comment/87152446

http://stackoverflow.com/q/49963449
has body: I want to write a code which locates the two closest numbers to a given argument without using any modules. Below is what I have at the moment. list1 = (1,3,5,8,12) x = 9 for value in list1: point = list1[x - 1], list1[x + 1] expected output is [8,12]
has answer: http://stackoverflow.com/a/49964310
has comment: http://stackoverflow.com/comment/86943144
type: Question
tagged with: python-3.x
answer count: 2
has title: How to find the two closest values to an argument in a sequence?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49964164
score: 0
tagged with: list

http://stackoverflow.com/q/50033275
has answer: http://stackoverflow.com/a/50033772
downvote count: 0
answer count: 1
has body: I want to write a custom function to integrate an expression (python or lambda function) numerically with a specific tolerance. I know with scipy.integrate.quad one can simply change the epsabs but I want to write the function myself using numpy. From this blogpost I know the function: def integrate(f, a, b, N): x = np.linspace(a+(b-a)/(2*N), b-(b-a)/(2*N), N) fx = f(x) area = np.sum(fx)*(b-a)/N return area gives me the numerical integration with N segments. How can I write another function or extend this to take a tol input and increase N until the difference between the two subsequent calculations is smaller than the given tolerance?
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
tagged with: numerical-integration
has title: Write a function with NumPy to calculate integral with a specific tolerance
score: 3
upvote count: 3

time-series
tags question: http://stackoverflow.com/q/49938782
tags question: http://stackoverflow.com/q/49957263
tags question: http://stackoverflow.com/q/50050447
tags question: http://stackoverflow.com/q/50033145
tags question: http://stackoverflow.com/q/49930518
tags question: http://stackoverflow.com/q/49919650
type: Tag
tags question: http://stackoverflow.com/q/50045054
tags question: http://stackoverflow.com/q/49944010
tags question: http://stackoverflow.com/q/50045558
tags question: http://stackoverflow.com/q/50071518
tag name: time-series
tags question: http://stackoverflow.com/q/49991670
tags question: http://stackoverflow.com/q/49927320
tags question: http://stackoverflow.com/q/50030108
tags question: http://stackoverflow.com/q/49955478
tags question: http://stackoverflow.com/q/49939762

http://stackoverflow.com/q/49989445
upvote count: 3
downvote count: 0
tagged with: python
has title: Pandas: Add one column's value to another if index exists
has body: I have two dataframes: A: foo bar foo2 0 1 1 1 1 2 2 2 2 3 3 3 3 3 3 3 B: foo 0 1 2 2 3 1 4 5 I would like to add up values of B whose index exists in A to a column of A (on the row with corresponding index) WITHOUT values from B which have no corresponding index in A being added or removing indices not present in both A and B: foo bar foo2 0 2 1 1 1 2 2 2 2 5 3 3 3 6 3 3 I feel like this should be straight forward but using add and concat I end up with either not all rows from A or a union of A and B
has answer: http://stackoverflow.com/a/49989637
accepted answer: http://stackoverflow.com/a/49989502
favorite count: 0
has answer: http://stackoverflow.com/a/49989502
type: AnsweredQuestion
score: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49989558
possible better answer: http://stackoverflow.com/a/49989490
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/49989490

http://stackoverflow.com/comment/87110546
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50047055
has text: oh wait no is it Python 2? D: In that case `print ' '.join(map(str, x))` I guess...
type: Comment

http://stackoverflow.com/q/49990986
type: UnansweredQuestion
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86998609
linked to: http://stackoverflow.com/q/3019909
has title: splitting nested dictionaries in python
has answer: http://stackoverflow.com/a/49991038
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86998968
favorite count: 0
has body: I have a simple thing but for some reason my mind is blocked now what is the name of this type of data [{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'}] how to split them into 2 dictionaries it can be also dynamic and change to [{'self': 'test', 'id': 4, 'name': 'IT Network Support'}, {'self': 'tes_1', 'id': 5, 'name': 'IT PC Support'} ,{'self': 'tes_2', 'id': 6, 'name': 'IT Voice Support'} ] I want a solution which can be dynamic
has answer: http://stackoverflow.com/a/49991040
type: Question
tagged with: python

http://stackoverflow.com/comment/88977891
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50105654
has text: I'm very (very) late. But I'd day thanks you: I didn't see your response but ultimately I also used a python socket (with a concurrency of 1 client at a time). This seems to be the right solution; it worked well for me.
type: Comment

http://stackoverflow.com/a/50003522
score: 0
has body: Create a fraud Dataframe I will use a 10% probability of fraud cases: data = pd.DataFrame({'val':[random.randint(0,1000) for _ in range(1000)], 'fraud':list(np.random.binomial(1, 0.1, 1000))}) data.head(10) [out] fraud val 0 0 359 1 0 731 2 0 146 3 0 975 4 0 295 5 0 467 6 0 366 7 1 69 8 0 18 9 0 297 Fraud cases should be oversampled 9 times compared to non-fraud cases. data['weights'] = data.fraud * 9 data['weights'] += 1 Weighted samples spl = data.sample(100,weights=data.weights) sum(spl.fraud) [out] 45 Fraud cases are about 50% of the total samples.
answers question: http://stackoverflow.com/q/50002579
type: Answer

http://stackoverflow.com/a/49977139
answers question: http://stackoverflow.com/q/49971318
has comment: http://stackoverflow.com/comment/87008356
has comment: http://stackoverflow.com/comment/87038876
has body: You could try to implement this almost exactly the way you did in numpy by using the low level TensorFlow distributions. Most of what is needed is already implemented and since you can use the uniform distribution you can essentially create whatever distribution you want yourself, I do this all the time. For example creating a uniform sampling node and sampling a vector of length N out of it: import tensorflow as tf N = 100 uni_pdf = tf.distributions.Uniform() z = uni_pdf.sample(N) if __name__ == '__main__': with tf.Session() as sess: print(sess.run(z)) I can't really say anything about the tf.nn samplers, since I do not use them.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86997522

http://stackoverflow.com/comment/86931413
type: Comment
comment on: http://stackoverflow.com/q/49957509
score: 0
has text: Translated it !
type: QuestionComment

http://stackoverflow.com/comment/86887838
type: QuestionComment
comment on: http://stackoverflow.com/q/49935993
score: 0
type: Comment
has text: issue['fields']['summary'] gives summary for parent ticket, not for subtasks

http://stackoverflow.com/a/49993974
answers question: http://stackoverflow.com/q/49987686
type: Answer
has comment: http://stackoverflow.com/comment/87051866
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49987686
has body: Thats because, in the CustomLabelBinarizer you are fitting the LabelBinarizer on each call to transform(), so it will learn different labels each time and hence different number of columns in each run depending on the number of rows. Change that to this: class CustomLabelBinarizer(BaseEstimator, TransformerMixin): def __init__(self, sparse_output=False): self.sparse_output = sparse_output def fit(self, X, y=None): self.enc = LabelBinarizer(sparse_output=self.sparse_output) self.enc.fit(X) return self def transform(self, X, y=None): return self.enc.transform(X) And now I'm getting correct shape on your code: (5, 14) (1000, 14) (10000, 14) Note: The same issue has been asked here. I'm assuming you are using the link here for the code. If you are using any other website, its likely that the code there is an old version of code I linked. Try the code on the above link for an error free updated version.
score: 3

http://stackoverflow.com/comment/87037567
type: AnswerComment
has text: only within the line or block. They don’t wipe the active memory.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49993593

http://stackoverflow.com/comment/103654173
comment on: http://stackoverflow.com/a/56488622
score: 0
has text: Thanks for sharing. Was curious as I am not able to do same on Vivotek cameras.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50004649
accepted answer: http://stackoverflow.com/a/50004754
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50004754
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
has title: TypeError: '<' not supported between instances of 'int' and 'Toy' Python
tagged with: oop
has comment: http://stackoverflow.com/comment/87025776
answer count: 1
has body: I'm new to python OOP and I'm struggling with figuring out my error in this code, if anyone can help that would be great! class Toy: def __init__(self, price): self.__price = price def SetPrice(self, p): self.__price = p def GetPrice(self): return(self.__price) def InsertionSort(x): for index in range(1, len(x)): value = x[index].GetPrice() i = index -1 while i &gt;= 0: if value &lt; (x[i].GetPrice()): x[i+1].SetPrice(x[i]) x[i].SetPrice(value) i = i -1 else: break prices = [] prices.append(Toy(200)) prices.append(Toy(10)) prices.append(Toy(20)) Toy.InsertionSort(prices) but when I run it I get back this, but I don't really understand what the error means and I've tried writing it other ways but I'm not sure what to do now. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py", line 34, in &lt;module&gt; Toy.InsertionSort(prices) File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py", line 20, in InsertionSort if value &lt; (x[i].GetPrice()): TypeError: '&lt;' not supported between instances of 'int' and 'Toy' Thank you in advance!

http://stackoverflow.com/comment/87127767
type: Comment
type: AnswerComment
has text: While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
comment on: http://stackoverflow.com/a/50055477
score: 0

http://stackoverflow.com/a/50003712
type: AcceptedAnswer
has body: Python uses indentation to mark the scope of a block of code. Since your __init__ is not indented, python ended the compilation of the class and compiled a module level function called __init__. That class already had an init that takes no additional parameters and since you didn't override it, that's the one you got.
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50003534
type: Answer
accepted answer of: http://stackoverflow.com/q/50003534
score: 0

http://stackoverflow.com/comment/86931094
score: 0
has text: Yes I see. So each list when compared to **any** other list must differ by two items. That is a thorough response thank you.
type: Comment
comment on: http://stackoverflow.com/q/49947163
type: QuestionComment

http://stackoverflow.com/a/50104840
score: 2
has comment: http://stackoverflow.com/comment/87268136
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49941005
type: Answer
has comment: http://stackoverflow.com/comment/87263594
has body: 1) I can't clone the xlwriter object in my styling function One wouldn't be able to clone a workbook that doesn't exist yet(or just created with nothing worth in it, here worthiness is checked via if path exts). Let's act on the error that is being thrown, change:- def fmt_func_blue(wrt, sheet_name): # ERROR Cannot clone `wrt` path is not set writer = copy.deepcopy(wrt) to def fmt_func_blue(wrt, sheet_name): # ERROR Cannot clone `wrt` path is not set writer=wrt if writer.book.filename: writer = copy.deepcopy(wrt) else: # Any changes to the new workbook will be reflected on the new # workbook of the writer(created in init) not on a copy. # If you want your class init writer untouched, # and want to format a completely new instance of workbook, recreate # a new writer and assign it to the local writer here. print('Warning: Working with new workbook')#or use log This should take care of it, remember it is ok to not clone a perfectly empty workbook. But if for some design you need to do so, then create a clone yourself, that is create a perfectly empty workbook yourself like you did in init. 2) There are no sheets in my workbook at the time I try to style the excel files. Well one cannot format sheets that do not exist yet. So just create one and populate with dataframe(or any other) data later into the already formatted sheet. I suggest a change as below:- # I haven't saved the excel file so there are no sheets sheet = writer.sheets[sheet_name] to sheet=None if sheet_name in writer.sheets: sheet = writer.sheets[sheet_name] else: print('Warning: Creating new sheet for formatting &lt;'+sheet_name+'&gt;') # or use log sheet= workbook.add_worksheet(sheet_name) Working code is here. It will take sometime to install the libs when you to try to run it.I made a few changes for fail safety and altered methods a bit in my example code. Output from my example code is as below:- Warning: Working with new workbook Warning: Creating new sheet for formatting &lt;red&gt; Warning: Work…

http://stackoverflow.com/comment/86931420
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49957157
has text: @Jean-FrançoisFabre I tried creating class but in the end i don't understand how to use it. I did this `def Constants(): def __init__(self, type, mass = None, xcoord = None, ycoord = None, xvel = None, yvel = None, h = None): self.type = type self.mass = mass self.xcoord = xcoord self.ycoord = ycoord self.xvel = xvel self.yvel = yvel self.h = h ` then I don't know where to go from here lol. The concept of class baffles me even after I read up about them
score: 0

http://stackoverflow.com/q/49929988
type: Question
has body: It seems that you can look at columns in a file no problem, but there's no apparent way to look at rows. I know I can read the entire file (CSV or excel) into a crazy huge dataframe in order to select rows, but I'd rather be able to grab particular rows straight from the file and store those in a reasonably sized dataframe. I do realize that I could just transpose/pivot the df before saving it to the aforementioned CVS/Excel file. This would be a problem for Excel because I'd run out of columns (the transposed rows) far too quickly. I'd rather use Excel than CSV. My original, not transposed data file has 9000+ rows and 20ish cols. I'm using Excel 2003 which supports up to 256 columns. EDIT: Figured out a solution that works for me. It's a lot simpler than I expected. I did end up using CSV instead of Excel (I found no serious difference in terms of my project) Here it is for whoever may have the same problem: import pandas as pd selectionList = (2, 43, 792, 4760) #rows to select df = pd.read_csv(your_csv_file, index_col=0).T selection = {} for item in selectionList: selection[item] = df[item] selection = pd.DataFrame.from_dict(selection) selection.T.to_csv(your_path)
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
tagged with: excel
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49930086
tagged with: pandas
has title: Pandas: How to read rows from CSV or Excel file?
has answer: http://stackoverflow.com/a/49930086
favorite count: 0

http://stackoverflow.com/comment/87054100
score: 0
type: AnswerComment
has text: nice suggestion.
comment on: http://stackoverflow.com/a/50018793
type: Comment

http://stackoverflow.com/q/49976676
score: -1
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49976809
downvote count: 2
upvote count: 1
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49976928
has title: Convert strings from input file to tuple list
possible better answer: http://stackoverflow.com/a/49976809
accepted answer: http://stackoverflow.com/a/49976912
has answer: http://stackoverflow.com/a/49977179
has answer: http://stackoverflow.com/a/49976912
tagged with: python
has body: I have a input file &amp; it contains: TEST.JOB TEST.LAST_LOGIN,10 TEST.DATA,12 TEST.QUEUE_PARAM,09 TEST.ENTITY_PROFILE I am expecting the return as below tuple list: [('TEST','JOB'),('TEST','LAST_LOGIN','10'),('TEST','DATA','12'), .....] Please advise how to achieve this.
answer count: 4

http://stackoverflow.com/q/50020130
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/87067893
has body: I want to know the dominant colors present in the image below. I know a algorithm in openCV named k-mean algorithm but one should know the k before hand so I want to know how to find that k and exact RGB value of colors that are dominant and not the mean of those. Lets take a example : In above image : k is 2 how to find that out and also how to find out Exact RGB value of pink(used on left most side) and blue (used on right most side) used in this (not the mean of their shades) NOTE : Images will contain specific number of colors say 5 or 6 or 7 or 2 just like pictures designed by professionals. If there is a gradient present I want the RGB value of the extreme and not the mean of those colors. EDIT 1 : The pink on the left turns to blue on the right so basically I want to find out from which color to which color is a gradient going.
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/87085538
tagged with: opencv3.0
has title: Know exact value of gradients and colors not mean in OpenCV?
has comment: http://stackoverflow.com/comment/87061939
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87064563
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87062533
has comment: http://stackoverflow.com/comment/87057587
has comment: http://stackoverflow.com/comment/87068743

http://stackoverflow.com/comment/87048310
type: Comment
type: QuestionComment
has text: In one of the answers to the linked question, I see that `axis=1` is used instead. `Y` has the shape `(1, N)`, so the summation should be performed over the 2nd axis.
comment on: http://stackoverflow.com/q/50015475
score: 0

http://stackoverflow.com/comment/87077417
comment on: http://stackoverflow.com/q/50030354
score: 0
has text: Then if it exist you will render the template within the if statement. and data ='test' in your template. If you would like to read render with the data in the file you should try to read the content of the file before rendering passing it with the first statement.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50090721
has body: It's pretty much up to you, there aren't any particular pros or cons to either. I guess if you plan on using the slug property elsewhere in your application it makes sense to put it on your model. If it's just going to be used in your GraphQL api then keep it in the resolvers. To implement it in Graphene you can do it like this: class User(graphene.ObjectType): id = graphene.ID(required=True) def resolve_id(user, info): return uuid_to_slug(user.uuid)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50030569
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50030569

http://stackoverflow.com/a/50031413
has comment: http://stackoverflow.com/comment/87079173
has comment: http://stackoverflow.com/comment/87079064
has body: Just adding the operator "*" between num1 and num3 parentheses did the trick: import math num1 = int(input("Enter a:")) num2 = int(input("Enter b:")) num3 = int(input("Enter c:")) result1 = (-num2 + math.sqrt(num2**2 - 4 * (num1)*(num3))) result2 = (result1 / (2 * num1)) print(result2) Edit If you want to allow complex results, use cmath's sqrt function. import cmath num1 = int(input("Enter a:")) num2 = int(input("Enter b:")) num3 = int(input("Enter c:")) result1 = (-num2 + cmath.sqrt(num2**2 - 4 * (num1)*(num3))) result2 = (result1 / (2 * num1)) print(result2)
has comment: http://stackoverflow.com/comment/87079138
has comment: http://stackoverflow.com/comment/87079002
has comment: http://stackoverflow.com/comment/87079264
has comment: http://stackoverflow.com/comment/87079228
has comment: http://stackoverflow.com/comment/87079653
has comment: http://stackoverflow.com/comment/87079109
type: Answer
answers question: http://stackoverflow.com/q/50031385
has comment: http://stackoverflow.com/comment/87078989
has comment: http://stackoverflow.com/comment/87079029
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87079410
has comment: http://stackoverflow.com/comment/87079548
accepted answer of: http://stackoverflow.com/q/50031385
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87109405
score: 0
has text: You are correct in a way. Multiprocessing is using multiple processes, that, unlike threads, are not blocked by the GIL it seems. The mistake I made was introduced by copying the example from the question in my original post, which, for whatever reason uses multiprocessing.dummy instead of multiprocessing.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50045500

http://stackoverflow.com/a/50096424
type: Answer
has body: Explaining the error: This route (r"/api/cars/?", CarHandler) points to CarHandler but it is passing no argument to handler's methods. I believe get and post method are defined this way: def get(self):, so they really do not need any argument; On the other hand, put and delete methods are defined as def put(self, carId):, so they need to get an argument. For this reason you got the error: Error: TypeError: put() missing 1 required positional argument: The same way, (r"/api/cars/[0-9]/?", CarHandler) is passing no argument too. Fixing the route error: First, as explained by another member, you need to fix (r"/api/cars/[0-9]/?", CarHandler) to pass an argument to your methods. You can do it just typing ( and ) in your route. It should be like this: (r"/api/cars/([0-9])/?", CarHandler). Fixing the method definition error: You can see that even you doing what I said, you probably are still getting the same error. The problem is that all routes are pointed to all methods in a handler. So the handler's methods are supposed to have the same method signature or they should be able to be called all the same way. This point is a little tricky. PUT and DELETE methods expect getting a carId, but not all routes are passing a carId as argument ((r"/api/cars/?", CarHandler) isn't). This route call methods this way: self.method(); it will work to self.get() or self.post(), but not to put or delete, once they are expecting an argument. You can fix it splitting your handler in two or changing your method definition to: def delete(self, carId=None): ... def put(self, carId=None): ... And adding some logic validation as if carId is None: return
answers question: http://stackoverflow.com/q/50051919
score: 0

http://stackoverflow.com/a/50010106
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50010021
downvote count: 0
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/87048513
score: 8
has comment: http://stackoverflow.com/comment/87037146
accepted answer of: http://stackoverflow.com/q/50010021
has comment: http://stackoverflow.com/comment/87037174
has body: Since you're doing this as a learning experience: To avoid creating a second list, the most interesting alternative is to create a lazy iterator instead. Under the covers, this works out the next filtered value on demand, instead of building a list of them up-front. But from much of your code, it can actually look as if you created a list. There are different ways to create lazy iterators—an explicit iterator class, the filter builtin, a generator function—but in your case, you can just use a generator expression instead of a list comprehension: passed = (x for x in mymarks if x &gt;= mypass) All I had to do was change the square brackets to parentheses, and you've magically got a lazy iterator. However, an iterator can only be used to go through the values in order, once. You can't do things like indexing (passed[0]). So you need to rethink your code a bit. But that turns out to be very easy: def minpass(mymarks, mypass): passed = (x for x in mymarks if x &gt;= mypass) min_value = next(passed) # this consumes the first value for x in passed: # this loops over all the remaining values if x &lt; min_value: min_value = x return min_value While we're at it, you might want to consider refactoring your code into two functions—write your own minvalue function that takes any iterable (an iterable is a lazy iterator, or a sequence like a list, or anything else that can go in a for loop) and returns the minimum value: def minvalue(it): it = iter(it) # this makes sure we have a lazy iterator min_value = next(it) # this consumes the first value for x in it: # this loops over all the remaining values if x &lt; min_value: min_value = x return min_value def minpass(mymarks, mypass): return minvalue(x for x in mymarks if x &gt;= mypass) Or maybe refactor further: def passvalues(it, mypass): return (x for x in it if x &gt;= mypass) def minpass(mymarks, mypass): return minvalue(passvalues(mymarks, mypass)) Notice that this approach solves your second problem automatically. Your prob…

http://stackoverflow.com/comment/87018880
comment on: http://stackoverflow.com/a/49999585
type: Comment
has text: create sites-avliable folder and enable site its create symbolink
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87152596
has text: You don't need to post everything. Just post one example, and the errors you got (and, if it's not obvious, how you wanted that example to work). There's a good chance we can show you how to fix that exact example to do what you wanted (or at least get you in the direction of what you wanted). If not, we can ask followup questions.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50067977

http://stackoverflow.com/a/50071851
upvote count: 6
type: Answer
has body: The delimiter in your output file is still ,. What you need to modify is the quoting argument: import csv csvfiledf.to_csv(outputcsv, index=False, delimiter=',', quoting=csv.QUOTE_ALL) The delimiter argument is optional, since , is implied.
accepted answer of: http://stackoverflow.com/q/50071727
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50071727
score: 6
has comment: http://stackoverflow.com/comment/87179068

query-optimization
tags question: http://stackoverflow.com/q/49929305
tag name: query-optimization
type: Tag

http://stackoverflow.com/q/50057787
has comment: http://stackoverflow.com/comment/87172169
has body: I'm a beginner in Python. I noticed the DOC said the function decimal.getcontext().divmod(x,y) returns the integer part of the result. But the code is: def divmod(self, a, b): a = _convert_other(a, raiseit = True) r = a.__divmod__(b, context = self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r and the a.__divmod__(b, context = self) is（I just paste the end of the function）: def __divmod__(self, other, context = None): #omit by me quotient, remainder = self._divide(other, context) remainder = remainder._fix(context) return quotient, remainder Does that mean that the function returns a tuple includes quotient and remainder? If that is so, why the doc said 'returns the integer part of the result.' I tried to find that it did return to a tuple. So, does the doc wrong?
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87132366
downvote count: 0
has title: docs.python.org is different with the code
has answer: http://stackoverflow.com/a/50080801
answer count: 1
accepted answer: http://stackoverflow.com/a/50080801
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87132275
has comment: http://stackoverflow.com/comment/87163436

plot
tags question: http://stackoverflow.com/q/49957840
tags question: http://stackoverflow.com/q/49983192
tags question: http://stackoverflow.com/q/49917748
tags question: http://stackoverflow.com/q/50062080
type: Tag
tags question: http://stackoverflow.com/q/49945069
tags question: http://stackoverflow.com/q/49984510
tags question: http://stackoverflow.com/q/50056073
tags question: http://stackoverflow.com/q/49922535
tags question: http://stackoverflow.com/q/50016979
tags question: http://stackoverflow.com/q/49999636
tags question: http://stackoverflow.com/q/50039928
tags question: http://stackoverflow.com/q/49932569
tag name: plot
tags question: http://stackoverflow.com/q/49948000
tags question: http://stackoverflow.com/q/50009266
tags question: http://stackoverflow.com/q/49992507
tags question: http://stackoverflow.com/q/49956879
tags question: http://stackoverflow.com/q/50045439
tags question: http://stackoverflow.com/q/49926379
tags question: http://stackoverflow.com/q/49976192
tags question: http://stackoverflow.com/q/50013378
tags question: http://stackoverflow.com/q/49971915
tags question: http://stackoverflow.com/q/49984575
tags question: http://stackoverflow.com/q/49958638
tags question: http://stackoverflow.com/q/50033091

http://stackoverflow.com/q/49931629
score: 1
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49931718
favorite count: 0
type: Question
has title: Grouping values in comma delimited string
downvote count: 0
upvote count: 1
tagged with: string
has body: I have the following string: "paid,paid,paid,paid,unpaid,paid,paid,paid,paid,unpaid,unpaid,unpaid,paid,paid,Pinterest,unpaid,Pinterest,unpaid,unpaid" I want to turn it into this: "paid x4, unpaid x1, paid x4, unpaid x3, paid x2, Pinterest x1, unpaid x1, Pinterest x1, unpaid x2" Basically, I want to group the items together if the next item is the same as the previous one and get a count of the number of times this holds true. So in the example, four unpaid in a row turn into paid x4 then one unpaid in a row turns into unpaid x1 then four paid in a row turns into unpaid x4, and so on. I wrote the following function that I think accomplishes what I want. Is there a more pythonic/efficient way to do this? counter = 1 split_string = string_test.split(',') len_string = len(split_string) new_string = '' for num, string in enumerate(split_string): # Edge case: last string in list if len_string == num + 1: if split_string[num] == split_string[num-1]: new_string += split_string[num] + ' x' + str(counter) #print("new string:", new_string) else: new_string += split_string[num] + ' x1 ' break else: if split_string[num] == split_string[num+1]: counter += 1 #print("string match") else: new_string += split_string[num] + ' x' + str(counter) + ', ' #print("new string:", new_string) counter = 1 print(new_string)
has answer: http://stackoverflow.com/a/49931718
type: AnsweredQuestion

http://stackoverflow.com/comment/87277887
comment on: http://stackoverflow.com/a/50017626
has text: Thanks @DanD and sandwood for suggestions/solutions. The code is updated with solution
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49942690
type: Question
has comment: http://stackoverflow.com/comment/86901713
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86901509
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49942820
score: -3
has comment: http://stackoverflow.com/comment/86901690
has title: How to make this Python for-loop run faster?
has body: for j in range(0, NumberOfFeatures): for k in range(j+1,NumberOfFeatures): countArray = np.ones((2,2)) for i in range(0,NumberOfTrainingExamples): countArray[XTrain[i,j],XTrain[i,k]] += 1 The innermost for loop takes quite some time for large NumberOfFeatures, NumberOfTrainingExamples
has comment: http://stackoverflow.com/comment/86901838
has comment: http://stackoverflow.com/comment/86901918
upvote count: 0
tagged with: performance
downvote count: 3
answer count: 1
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/36778568

http://stackoverflow.com/a/49958931
has comment: http://stackoverflow.com/comment/86934529
has comment: http://stackoverflow.com/comment/86937133
score: 0
has comment: http://stackoverflow.com/comment/86934836
has comment: http://stackoverflow.com/comment/86935295
has body: If you want to access slug from self.kwargs in the view, then you need slug in the URL. For example: url(r'^new_proof/(?P&lt;slug&gt;[-\w]+)/$', views.ProofCreate.as_view(), name='new_proof') You don't need username because you are getting the user from self.request.user. In your second attempt, post.slug is incorrect because variable names can't contain dots. In the view, I would use slug = self.kwargs['slug'] unless you want it to be optional. At the moment get() returns None, so you get the error later on in your code.
accepted answer of: http://stackoverflow.com/q/49958000
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87560463
has comment: http://stackoverflow.com/comment/86937720
has comment: http://stackoverflow.com/comment/86934588
type: Answer
has comment: http://stackoverflow.com/comment/86935368
has comment: http://stackoverflow.com/comment/86935645
has comment: http://stackoverflow.com/comment/86937805
has comment: http://stackoverflow.com/comment/86934817
answers question: http://stackoverflow.com/q/49958000

http://stackoverflow.com/comment/87115656
score: 0
type: AnswerComment
has text: No, numbers are not relevant, the order is relevant. The basic idea behind is as follows: Suppose you have feature a,b,c,d and for all of them you have mean, standard deviation, min and max. If you only interested in showing feature b and c, how to show them?
comment on: http://stackoverflow.com/a/50049637
type: Comment

http://stackoverflow.com/q/49953471
answer count: 1
has comment: http://stackoverflow.com/comment/86923430
has title: Generate csv from nested json python
accepted answer: http://stackoverflow.com/a/49953818
type: Question
tagged with: pandas
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/49953818
tagged with: dataframe
has body: I have following nested json file, which I need to convert in pandas dataframe, the main problem is there is only one unique item in the whole json and it is very deeply nested. I tried to solve this problem with the following code, but it gives repeating output. [{ "questions": [{ "key": "years-age", "responseKey": null, "responseText": "27", "responseKeys": null }, { "key": "gender", "responseKey": "male", "responseText": null, "responseKeys": null } ], "transactions": [{ "accId": "v1BN3o9Qy9izz4Jdz0M6C44Oga0qjohkOV3EJ", "tId": "80o4V19Kd9SqqN80qDXZuoov4rDob8crDaE53", "catId": "21001000", "tType": "80o4V19Kd9SqqN80qDXZuoov4rDob8crDaE53", "name": "Online Transfer FROM CHECKING 1200454623", "category": [ "Transfer", "Acc Transfer" ] } ], "institutions": [{ "InstName": "Citizens company", "InstId": "inst_1", "accounts": [{ "pAccId": "v1BN3o9Qy9izz4Jdz0M6C44Oga0qjohkOV3EJ", "pAccType": "depo", "pAccSubtype": "check", "_id": "5ad38837e806efaa90da4849" }] }] }] I need to convert this to pandas dataframe as follows: id pAccId tId 5ad38837e806efaa90da4849 v1BN3o9Qy9izz4Jdz0M6C44Oga0qjohkOV3EJ 80o4V19Kd9SqqN80qDXZuoov4rDob8crDaE53 The main problem I am facing is with the "id" as it very deeply nested which is the only unique key for the json. here is my code: import pandas as pd import json with open('sub.json') as f: data = json.load(f) csv = '' for k in data: for t in k.get("institutions"): csv += k['institutions'][0]['accounts'][0]['_id'] csv += "\t" csv += k['institutions'][0]['accounts'][0]['pAccId'] csv += "\t" csv += k['transactions'][]['tId'] csv += "\t" csv += "\n" text_file = open("new_sub.csv", "w") text_file.write(csv) text_file.close() Hope above code makes sense, as I am new to python.
has comment: http://stackoverflow.com/comment/86923717
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/50103711
accepted answer of: http://stackoverflow.com/q/50022814
score: 0
has body: Following @czr 's example; the solution was to go through and convert the object mappings into explicit dictionaries and then output an array of those nested dictionaries as follows: def serialize(self): processArray =[] decisionItems = [] for process in self.processes: processObj = {} laneArray = [] for lane in process.laneObjects: laneObj = {} taskArray = [] for task in lane.associatedTasks: taskObj = {} for variableName, value in task.__dict__.items(): temp = value placeHolderArray =[] if isinstance(value, Task) or isinstance(value, StartEvent) or isinstance(value, EndEvent): temp = value.name taskObj[variableName] = temp elif isinstance(value,list): #fix these lines for n in value: if isinstance(n, Task) or isinstance(n, StartEvent) or isinstance(n, EndEvent) or isinstance(n, DecisionBranch): placeHolderArray.append(n.name) taskObj[variableName] = placeHolderArray elif isinstance(value, DecisionBranch): taskObj['junctionPath'] = task.junctionPath decisionBranch = {} decisionBranch['name'] = value.name decisionBranch['options'] = value.decisionBranch decisionBranch['source'] = value.source #taskObj['DecisionTree'] = decisionBranch taskObj['URLs'] = task.urls taskArray.append(taskObj) laneObj['name'] = lane.name laneObj['associatedTasks'] = taskArray laneArray.append(laneObj) processObj['name'] = process.name processObj['laneObjects'] = laneArray processArray.append(processObj) return processArray def outputJsonFile(self, fileContents): tempString = self.fileName.split('.') outputName = tempString[0]+'.json' with open(outputName, 'w') as outfile: outfile.write(json.dumps(fileContents, sort_keys=True, indent=4)) where fileContents takes the returned processArray from serialize() The takeaway note is that iterating through a classes variables as follows: for variableName, value in objectName.__dict__.items(): Allows you to retrieve the class variables and their respective values as a dictionary. As you is my code above, if it so happens that your value is an object …
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50022814
type: Answer

http://stackoverflow.com/q/50044895
has comment: http://stackoverflow.com/comment/87106292
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50045097
downvote count: 0
tagged with: django
linked to: http://stackoverflow.com/q/50042927
answer count: 1
favorite count: 0
has title: IntegrityError at /posts/create/18/: Key (group_id)=(18) is not present in table "auth_group"
tagged with: django-views
type: Question
has body: getting this error when running the following code when trying to create a post, which belongs to a group and a user: from django.shortcuts import render, get_object_or_404 from groups.models import Group from .models import Post from django.utils import timezone def create(request, group_id): group = get_object_or_404(Group, pk= group_id) if request.method == 'POST': if request.POST['body'] and request.POST['body']: post = Post() post.title = request.POST['title'] post.body = request.POST['body'] post.pub_date = timezone.datetime.now() post.author = request.user post.group = group post.save() return redirect('/groups/' + str(group_id)) else: return render(request, 'groups/detail.html', {'group':group}) else: return render(request, 'groups/detail.html', {'group':group}) TO clarify, Groups is a model I created, not the default Django model, which is why i imported it from groups.models. this is what my model for a Post looks like: from django.db import models from django.contrib.auth.models import User from groups.models import Group class Post(models.Model): title = models.CharField(max_length=255, unique=True) body = models.TextField() likes_total = models.IntegerField(default=0) pub_date = models.DateTimeField() author = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) def __str__(self): return self.name def summary(self): # return the 1st 100 chars return self.body[:100] def pub_date_pretty(self): # strftime is how to break down time return self.pub_date.strftime('%b %e %Y') I dont get why the error is looking for the group in the auth_group table, when I imported it from my groups.models file! any help would be really appreciated!
tagged with: django-models
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/49968984
has title: Python :Sort filenames in a directory and add a number in the beginning of each filename
type: Question
score: 1
has comment: http://stackoverflow.com/comment/86954049
has comment: http://stackoverflow.com/comment/86954241
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49969487
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49969487
has answer: http://stackoverflow.com/a/49976600
has comment: http://stackoverflow.com/comment/86953926
has body: 1-intro-to deepleanring and computer visionk.MKV 2.Kaggle Deep Learning - YouTube.MP4 Convolutional Neural Networks - Fun and Easy Machine Learning - YouTube.MP4 Convolutional Neural Networks - The Math of Intelligence (Week 4)YouTube.MKV Introduction to Deep Learning- What Are Convolutional Neural Networks- YouTube.MP4 Kaggle Deep Learning 3 - YouTube.MP4 Kaggle Deep Learning 4 - YouTube.MP4 Kaggle Deep Learning 5 Data Augmentation - YouTube.MP4 Kaggle Deep Learning 6 - YouTube.MP4 Kaggle Deep Learning 7.mp4 Kaggle Deep Learning 8 - YouTube.MP4 These are the files that needs to be sorted .A filename that contains a number(like 3 in this case) Kaggle Deep Learning 3 -YouTube.MP4 should be renamed as 3 Kaggle Deep Learning - YouTube.MP4. A file name that doesn't contain any number or a file which contains a number in the beginning need not to be renamed. I have written the following code till now and i am stuck for f in os.listdir(): filename,extension = os.path.splitext(f)) In short i want these files to look like this in my directory.. 1-intro-to deepleanring and computer visionk.MKV 2 Kaggle Deep Learning - YouTube.MP4 3 Kaggle Deep Learning - YouTube.MP4 4 Kaggle Deep Learning - YouTube.MP4 5 Kaggle Deep Learning Data Augmentation - YouTube.MP4 6 Kaggle Deep Learning - YouTube.MP4 7 Kaggle Deep Learning .mp4 8 Kaggle Deep Learning - YouTube.MP4 Convolutional Neural Networks - Fun and Easy Machine Learning - YouTube.MP4 Convolutional Neural Networks - The Math of Intelligence (Week 4)YouTube.MKV Introduction to Deep Learning- What Are Convolutional Neural Networks- YouTube.MP4
favorite count: 0
has comment: http://stackoverflow.com/comment/86954374
accepted answer: http://stackoverflow.com/a/49976600

http://stackoverflow.com/a/50039383
score: 0
has body: Firstly change the field type in your models.py as: avatar = models.ImageField(upload_to='www-avatar/', null=True) secondly, in your settings file you should define a media directory MEDIA_DIR = os.path.join(BASE_DIR, "www-avatar") then, you should modify your urls.py file as urlpatterns = [ url(r'^admin/', admin.site.urls), ....... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) last but not least do not forget to install pillow library pip install Pillow (https://pypi.org/project/Pillow/2.2.1/)
has comment: http://stackoverflow.com/comment/87095588
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50039269
has comment: http://stackoverflow.com/comment/87095023
has comment: http://stackoverflow.com/comment/87094935
type: Answer
has comment: http://stackoverflow.com/comment/87349779
has comment: http://stackoverflow.com/comment/87095186
answers question: http://stackoverflow.com/q/50039269

http://stackoverflow.com/q/49926727
linked to: http://stackoverflow.com/q/27118687
has comment: http://stackoverflow.com/comment/86869445
has title: Update dictionary inside of dictionary without deleting contents
type: Question
has comment: http://stackoverflow.com/comment/86869721
duplicate of: http://stackoverflow.com/q/27118687
has body: I'm looping through a data set, and updating a dictionary as needed. As a precursor to the dictionary update, I have a "default" dictionary "template" like so: databody_item = {'name': 'Kermit', 'interests': { 'test1':True, }, } I want to update the interests dictionary inside of the databody_item dictionary, so I run: databody_item.update({'interests':{'test2':True}}) This however cleared the entire interests dict, leaving me with this: {'interests': {'test2': True}, 'name': 'Kermit'} However, I need the dictionary to be updated like this: {'interests': {'test1': True, 'test2': True}, 'name': 'Kermit'}
tagged with: python
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86869473

http://stackoverflow.com/comment/86942237
type: Comment
comment on: http://stackoverflow.com/q/49962987
type: QuestionComment
has text: @cricket_007, what do you mean x[1] is a single value?
score: 0

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/49991649
tag name: google-oauth

http://stackoverflow.com/a/49927479
has comment: http://stackoverflow.com/comment/86872084
has comment: http://stackoverflow.com/comment/86872002
has comment: http://stackoverflow.com/comment/86872645
score: 0
accepted answer of: http://stackoverflow.com/q/49927254
has comment: http://stackoverflow.com/comment/86870922
has body: To convert the object type columns, you can use : df['Market Cap'] = df['Market Cap'].str.replace(',', '').astype(float) df['Volume'] = df['Volume'].str.replace(',', '').astype(float)
has comment: http://stackoverflow.com/comment/86884625
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86871058
has comment: http://stackoverflow.com/comment/86872735
has comment: http://stackoverflow.com/comment/86871012
has comment: http://stackoverflow.com/comment/86871122
type: Answer
answers question: http://stackoverflow.com/q/49927254
has comment: http://stackoverflow.com/comment/86872179
has comment: http://stackoverflow.com/comment/86870963
has comment: http://stackoverflow.com/comment/86871080

http://stackoverflow.com/q/49967691
downvote count: 0
has answer: http://stackoverflow.com/a/49975208
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 1
tagged with: javadoc
accepted answer: http://stackoverflow.com/a/49975208
has body: I am currently building a documentation for an API. I am using both Sphinx documentation and Javadoc for that purpose : Javadoc to display the data model, explain the classes serialized, Sphinx to explain routes and general concepts. I've added my javadoc to a /javadoc subfolder in my sphinx project and declared it as "html_extra_path" in my conf.py. Currently after build, I can see in my /build folder the /javadoc folder, navigate through it. In my sphinx documentation, I would like to create a link to a page of my javadoc (direct link to the class documentation). How can I do that ?
favorite count: 0
type: Question
upvote count: 2
has title: Sphinx: link to an internal file declared as html_extra_path
tagged with: python-sphinx

gnuradio
tags question: http://stackoverflow.com/q/49954902
tag name: gnuradio
type: Tag

tensorflow-lite
tags question: http://stackoverflow.com/q/50037848
tag name: tensorflow-lite
tags question: http://stackoverflow.com/q/49954439
type: Tag

http://stackoverflow.com/a/50051816
answers question: http://stackoverflow.com/q/50050631
downvote count: 0
type: Answer
upvote count: 1
has body: You can use numba for this purpose (you can add nopython=True or use static types for more speedup): from numba import jit import numpy as np n = 200 size = (n,n) x = np.zeros(size) m = 0 # mean if n%2 == 0: m = int((n+1)/2) else : m = int(n/2) x[m][m] = 100000 z = int(x[m][m]) def f(x): count = 0 for i in range(0,n): for j in range(0,n): if x[i][j] &gt; 3: x[i][j] = x[i][j] - 4 if i-1 &gt;= 0 : x[i-1][j] = x[i-1][j] + 1 if i+1 &lt; n : x[i+1][j] = x[i+1][j] + 1 if j-1 &gt;= 0 : x[i][j-1] = x[i][j-1] + 1 if j+1 &lt; n : x[i][j+1] = x[i][j+1] + 1 elif x[i][j] &lt;= 3: count = count + 1 return x, count @jit def f_jit(x): count = 0 for i in range(0,n): for j in range(0,n): if x[i][j] &gt; 3: x[i][j] = x[i][j] - 4 if i-1 &gt;= 0 : x[i-1][j] = x[i-1][j] + 1 if i+1 &lt; n : x[i+1][j] = x[i+1][j] + 1 if j-1 &gt;= 0 : x[i][j-1] = x[i][j-1] + 1 if j+1 &lt; n : x[i][j+1] = x[i][j+1] + 1 elif x[i][j] &lt;= 3: count = count + 1 return x, count %%timeit f(x) 28.7 ms ± 602 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %%timeit f_jit(x) 59.9 µs ± 7.22 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
score: 1

http://stackoverflow.com/a/49999185
has comment: http://stackoverflow.com/comment/87384541
downvote count: 0
score: 8
upvote count: 8
has body: Based on the feedback here, I dived into the argparse code. A reasonable solution that uses subparsers is posted at https://stackoverflow.com/a/49977713/428542. In addition, I was able to find a solution that added a pseudo-action for each option, as well a solution that modified the formatter. Finally I present a hybrid solution that adds pseudo-action for each option, but in such a way that only the formatter uses them, by exploiting some implementation details. The first solution defines a custom action, whose purpose is to do nothing at all, but still prints some usage information. The different options are given this NoAction class. import argparse class NoAction(argparse.Action): def __init__(self, **kwargs): kwargs.setdefault('default', argparse.SUPPRESS) kwargs.setdefault('nargs', 0) super(NoAction, self).__init__(**kwargs) def __call__(self, parser, namespace, values, option_string=None): pass parser = argparse.ArgumentParser() parser.register('action', 'none', NoAction) parser.add_argument('--customer', default='Mr. and Mrs. Bun', action='store', help='salutation for addressing the customer') parser.add_argument('ingredients', nargs='*', metavar='INGREDIENT', choices=['bacon', 'egg', 'sausage', 'spam', 'tomato'], help='List of ingredients') group = parser.add_argument_group(title='your choice of ingredients') group.add_argument('bacon', help="Lovely bacon", action='none') group.add_argument('egg', help="The runny kind", action='none') group.add_argument('sausage', help="Just a roll", action='none') group.add_argument('spam', help="Glorious SPAM", action='none') group.add_argument('tomato', help="Sliced and diced", action='none') options = parser.parse_args('--customer=Vikings egg sausage bacon'.split()) print("Dear {}, we are happy to serve you {}" \ .format(options.customer, ', '.join(options.ingredients))) options = parser.parse_args(['--help']) which outputs: Dear Vikings, we are happy to serve you egg, sausage, bacon usage: customchoices.py [-h] [--cus…
answers question: http://stackoverflow.com/q/49969605
type: Answer
has comment: http://stackoverflow.com/comment/115658467

http://stackoverflow.com/q/49963188
has title: python ceil() and floor() for rounding integer
upvote count: 1
accepted answer: http://stackoverflow.com/a/49963200
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86942410
has body: I have a number like 1.4 and 1.5 and want to round it. when using ceil(), all the number going to 2 and with floor() it's going to 1 but I want if number 1.5 its going to 2, and if 1.4 its going to 1 maybe you guys got my point, sorry for noob question.
has comment: http://stackoverflow.com/comment/86942372
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/49963200
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86942307
score: -2
answer count: 1

http://stackoverflow.com/comment/87117955
comment on: http://stackoverflow.com/q/50049769
type: Comment
type: QuestionComment
score: 0
has text: That's splitting hairs. Unbounded cache is exactly the kind of thing that this is guarding against. Python won't do this itself.

http://stackoverflow.com/comment/87152762
has text: Why aren't you just use y1 = y0, y2 = y0+2*np.sqrt(3)
type: Comment
comment on: http://stackoverflow.com/q/50067977
score: 0
type: QuestionComment

http://stackoverflow.com/q/49955821
tagged with: django
has answer: http://stackoverflow.com/a/49956349
possible better answer: http://stackoverflow.com/a/49956349
favorite count: 0
type: Question
has body: I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying out.hour+1 with this code, but didn't work. overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours how to add 1 hour every loop?...
has title: add +1 hour to datetime.time() django on forloop
tagged with: python
has answer: http://stackoverflow.com/a/49955858
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49955858
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/a/49949786
has comment: http://stackoverflow.com/comment/86916507
has comment: http://stackoverflow.com/comment/86916285
answers question: http://stackoverflow.com/q/49949638
has body: you can use an if statement to check if its the last number: def fibonaci_num(n): if n &lt;= 1: return n else: return fibonaci_num(n-1) + fibonaci_num(n-2) N = 10 for i in range(N): print(fibonaci_num(i), end='') if i != N-1: print(' add -&gt; ', end='')
type: Answer
has comment: http://stackoverflow.com/comment/86917257
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86916205
downvote count: 0

http://stackoverflow.com/q/49975999
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: I am trying to make a script that you run it and you can Bookmark PDFs and then run a split script that will separate the pages. However this script that bookmarks them is mean't to rename them however it currently isn't and I can't see why. This is my code and I need desperate help: with open('+Renamed.csv', 'ab') as fout: writer = csv.writer(fout) for filename in os.listdir(path): filepath = os.path.join(path, filename) filename_no_ext, ext = os.path.splitext(filename) if ext.lower() == '.pdf': n = str(idx).zfill(8) new_filename = name_fmt % (ftoday, n) new_filepath = os.path.join(path, new_filename) new_filename_no_ext, ext = os.path.splitext(new_filename) while new_filename_no_ext in db_list: idx += 1 n = str(idx).zfill(8) new_filename = name_fmt % (ftoday, n) new_filepath = os.path.join(path, new_filename) new_filename_no_ext, ext = os.path.splitext(new_filename) while os.path.exists(new_filepath): cmd = 'INSERT into [BLACKSTONE].[dbo].[Filename] ' \ 'VALUES (?)' cursor.execute(cmd, new_filename_no_ext) cnxn.commit() idx += 1 n = str(idx).zfill(8) new_filename = name_fmt % (ftoday, n) new_filepath = os.path.join(path, new_filename) new_filename_no_ext, ext = os.path.splitext(new_filename) idx += 1 print filepath try: os.rename(filepath, new_filepath) print new_filepath except: print &gt;&gt;sys.stderr, 'Unable to rename:', filepath sys.exit() Please help, I have tried to complete this for roughly a weekend now and I can't see why nothing is renaming, it's only mean't to rename the files in the +Renamed folder, please let me know if you'd like to see the whole code. Thanks!
favorite count: 0
tagged with: python-2.7
score: 1
has title: Renaming PDFs with script (Bookmarking)
type: Question

http://stackoverflow.com/q/50031699
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
score: 1
has title: Getting data from a task to a connection with asyncio
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/50037901
tagged with: asynchronous
favorite count: 0
type: Question
has body: So this should be fairly simple, i have a client that connects to a server, and it can receive messages from the server just fine. However i need to be able to send messages to the server. I am using asyncio to handle these asynchronously but i have a problem with that. How do i get the user input to my client so it can use its transport to send the data up to the server. Heres the code. import asyncio, zen_utils, json from struct import * class ChatClient(asyncio.Protocol): def connection_made(self, transport): self.transport = transport self.address = transport.get_extra_info('peername') self.data = b'' print('Accepted connection from {}'.format(self.address)) self.username = b'jacksonm' json_name = b'{"USERNAME": "'+self.username+b'"}' length = len(json_name) code_len = pack(b'!I', length) message = code_len + json_name self.json_loaded = False self.next_length = -1 self.transport.write(message) def data_received(self, data): self.data += data if (self.json_loaded == False): self.compile_server_data(data) elif(self.json_loaded): if (len(self.data) &gt; 4 and self.next_length == -1): self.next_length = self.data[:4] self.next_length = unpack(b'!I', self.next_length)[0] print("LENGTH: ", self.next_length) elif (len(self.data) &gt;= self.next_length): self.data = self.data[4:] print("MESSAGE: ", self.data) self.next_length = -1 def compile_server_data(self, data): if (self.data.find(b'}') != -1): start_index = self.data.find(b'{') end_index = self.data.find(b'}') self.json_data = self.data[start_index:end_index + 1] self.data = self.data[end_index + 1:] self.json_data = self.json_data.decode('ascii') self.json_data = json.loads(self.json_data) self.json_loaded = True self.print_server_status() def send_message(self, message): message = message.encode('ascii') length = len(message) code_len = pack(b'!I', length) message = code_len + message def parse_message(self, raw_message): message = {} message['SRC'] = self.username message['DEST'] = b'ALL' message['TIMESTAMP'] …
tagged with: network-programming
type: UnansweredQuestion

http://stackoverflow.com/q/50021493
tagged with: docker
has title: Docker + Python3 UTF8 argv problems
has comment: http://stackoverflow.com/comment/87059690
type: Question
score: 0
tagged with: command-line-arguments
tagged with: utf-8
has comment: http://stackoverflow.com/comment/87058847
linked to: http://stackoverflow.com/q/43356982
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50022444
has comment: http://stackoverflow.com/comment/87059682
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87059364
has body: Consider the following Python program that prints its understanding of what command line arguments it got: #!/usr/bin/env python3 print(repr(__import__("sys").argv)) Here's what happens when I run it with a Chinese character as an argument: $ /tmp/mytest 我 ['/tmp/mytest', '我'] Now, consider the following Dockerfile that puts it in /tmp/mytest: FROM ubuntu:18.04 RUN apt-get update &amp;&amp; apt-get install -y python3 RUN echo '#!/usr/bin/env python3' &gt;&gt; /tmp/mytest RUN echo 'print(repr(__import__("sys").argv))' &gt;&gt; /tmp/mytest RUN chmod +x /tmp/mytest When I try to run it, the output differs: $ sudo docker build -t mytest . Sending build context to Docker daemon 20.48kB Step 1/5 : FROM ubuntu:18.04 ---&gt; 02f9d6707661 Step 2/5 : RUN apt-get update &amp;&amp; apt-get install -y python3 ---&gt; Using cache ---&gt; 5c9a6768a337 Step 3/5 : RUN echo '#!/usr/bin/env python3' &gt;&gt; /tmp/mytest ---&gt; Using cache ---&gt; e0410fc9684e Step 4/5 : RUN echo 'print(repr(__import__("sys").argv))' &gt;&gt; /tmp/mytest ---&gt; Using cache ---&gt; d123c9645c5c Step 5/5 : RUN chmod +x /tmp/mytest ---&gt; Using cache ---&gt; 9b2ac9b174e0 Successfully built 9b2ac9b174e0 Successfully tagged mytest:latest $ sudo docker run -ti mytest /tmp/mytest 我 ['/tmp/mytest', '\udce6\udc88\udc91'] Why is that? Is Docker or Python to blame here? How do I make the script work the same way in both cases?

http://stackoverflow.com/comment/88059230
type: Comment
type: AnswerComment
has text: Thanks @Caleb Kuester & Shobi P P a lot. For the ***rosdep init*** problem, I had solved it with **j7nn7k** answer from: https://stackoverflow.com/questions/40684543/how-to-make-python-use-ca-certificates-from-mac-os-truststore/42107877. Which just help me get through the ***init-step***, although there're a lot of problems after this step to install ros on my macos. Anyway, thanks again!
comment on: http://stackoverflow.com/a/50475345
score: 0

http://stackoverflow.com/comment/87115700
has text: For your ADA/Cardano example, you can access a specific object in the list a number of ways - one way is the following: `specific_coin = next(filter(lambda x: x.currency == 'ADA', list_of_coin_obs))` which you could then print with `print('CurrencyName: ',specific_coin.currency,'CurrencyLong: ',specific_coin.currencyLong,)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50049277
score: 0

http://stackoverflow.com/comment/86935463
score: 3
comment on: http://stackoverflow.com/q/49959531
type: Comment
has text: Looks like missing space. Try `def __init__` instead of `def__init__`
type: QuestionComment

http://stackoverflow.com/a/50040463
score: 1
has body: It is not what you asked for. But if you are looking for a simpler solution , you can use the pandas approach. df = pd.DataFrame({'a' :np.arange(11)}) # your data window_lengths = np.arange(2,len(a)) # define window lengths from 2 to n [rolling_win.mean() for rolling_win in [df.rolling(length) for length in window_lengths]] output : [ a 0 NaN 1 0.5 2 1.5 3 2.5 4 3.5 5 4.5 6 5.5 7 6.5 8 7.5 9 8.5 10 9.5, a 0 NaN 1 NaN 2 1.0 3 2.0 4 3.0 5 4.0 6 5.0 7 6.0 8 7.0 9 8.0 10 9.0, a 0 NaN 1 NaN 2 NaN 3 1.5 4 2.5 5 3.5 6 4.5 7 5.5 8 6.5 9 7.5 10 8.5, a 0 NaN 1 NaN 2 NaN 3 NaN 4 2.0 5 3.0 6 4.0 7 5.0 8 6.0 9 7.0 10 8.0, a 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 2.5 6 3.5 7 4.5 8 5.5 9 6.5 10 7.5, a 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 3.0 7 4.0 8 5.0 9 6.0 10 7.0, a 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 3.5 8 4.5 9 5.5 10 6.5, a 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 4.0 9 5.0 10 6.0, a 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 4.5 10 5.5]
type: Answer
has comment: http://stackoverflow.com/comment/87097259
answers question: http://stackoverflow.com/q/50036888
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87147373
type: QuestionComment
has text: is your indentation correct?, why is your `while` for?
comment on: http://stackoverflow.com/q/50065320
score: 0
type: Comment

http://stackoverflow.com/comment/86933180
comment on: http://stackoverflow.com/q/49928903
type: Comment
type: QuestionComment
has text: With -3, I do not care. I can always make a new account, you can turn it to -50. I do not give a damn. I just thank those people who will help or who are ready to help. If you are too perfect, win the famous challenges among yourselves and do not bother!
score: 0

http://stackoverflow.com/q/49985447
linked to: http://stackoverflow.com/q/2029523
possible better answer: http://stackoverflow.com/a/50032785
has title: How can I find an open pyqtgraph GraphicsWindow similar to how 'matplotlib.pyplot.gcf()` works?
type: Question
accepted answer: http://stackoverflow.com/a/50050264
has answer: http://stackoverflow.com/a/50032785
answer count: 2
has answer: http://stackoverflow.com/a/50050264
tagged with: python
tagged with: pyqtgraph
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: I would like a pyqtgraph counterpart to the matplotlib.pyplot.gcf() function, which returns a reference to the current figure. I would like a function that returns a reference to the current pyqtgraph GraphicsWindow instance. Is there a way to do this?

http://stackoverflow.com/comment/86906309
type: AnswerComment
comment on: http://stackoverflow.com/a/49943496
score: 0
type: Comment
has text: `gte` is `>=`, the OP wants `>`.

http://stackoverflow.com/comment/138285859
comment on: http://stackoverflow.com/a/78436446
score: 0
type: Comment
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment

http://stackoverflow.com/a/61110881
downvote count: 2
has body: f as function you create i.e local m as method v as variable p as Python function that required parameters c as class
type: Answer
answers question: http://stackoverflow.com/q/50022252
upvote count: 2
score: 0

http://stackoverflow.com/comment/86961135
type: QuestionComment
has text: The code is executed correctly. I don't see any problem. Try to add file encoding and see what happen. ```#!/usr/bin/python # -*- coding: utf-8 -*-```
comment on: http://stackoverflow.com/q/49972533
score: 0
type: Comment

http://stackoverflow.com/q/50039288
has title: how to print string variable in python
answer count: 1
has comment: http://stackoverflow.com/comment/87094628
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87094718
accepted answer: http://stackoverflow.com/a/50631603
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87094698
has body: name = input("What is your name: ") age = int(input("How old are you: ")) year = str((2014 - age)+100) print(name + " will be 100 years old in the year " + year) I am trying this code in python, but it is not executing, what corrections needs to be done?
has answer: http://stackoverflow.com/a/50631603
downvote count: 6
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/87095868
has comment: http://stackoverflow.com/comment/87106239

http://stackoverflow.com/q/49972062
score: 1
answer count: 1
has body: I basically want to write a vectorized function in Numpy that will element-wise compare the binary representations and the data types of involved arrays. For example, f(np.nan, np.nan) should be True. f(np.datetime64('NaT'), np.nan) should be False. f(np.datetime64('NaT'), np.datetime64('NaT')) should be True. f(np.NZERO, np.PZERO) should be True on platforms that have an identical binary representation for both but False otherwise. Any other weird exceptions (?) Also, the function should be vectorized, fast (C speed) and at least "look like" a ufunc in the sense that it should support broadcasting and stringing over arrays. I've tried this, but it doesn't work for NaT, etc: Comparing NumPy arrays so that NaNs compare equal The following require Pandas, which I don't want to do, and they'll make NaN == NaT. Numpy: Checking if a value is NaT I could add np.isnat to problem 1, but that wouldn't compare the precision of the object. And none of these can do the NZERO/PZERO thing.
tagged with: equality
linked to: http://stackoverflow.com/q/38509538
has comment: http://stackoverflow.com/comment/86960406
favorite count: 0
type: Question
tagged with: numpy
tagged with: python
has comment: http://stackoverflow.com/comment/86960028
has comment: http://stackoverflow.com/comment/86960101
linked to: http://stackoverflow.com/q/10819715
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49972198
accepted answer: http://stackoverflow.com/a/49972198
has comment: http://stackoverflow.com/comment/86960422
downvote count: 0
upvote count: 1
has title: NumPy - Testing equality including np.nan, np.nat, np.NZERO and np.PZERO in a vectorized way

http://stackoverflow.com/q/49991380
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49991809
tagged with: python
type: UnansweredQuestion
tagged with: icalendar
has body: The following code throws an exception, which most probably pertains to the TZID replacements I needed to do to fix some other bugs. If I remove the the "UNTIL" statement from the ical string, the code works just fine. from icalendar.cal import Calendar import datetime from dateutil import rrule from dateutil.tz import gettz cal_str = "BEGIN:VEVENT\nDTSTART;TZID=America/Los_Angeles:20171019T010000\nDTEND;TZID=America/Los_Angeles:20171019T230000\nRRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;UNTIL=20180423T191500\nX-OP-ENTRY-STATE:unlocked\nEND:VEVENT" ical = Calendar.from_ical(cal_str) start_time_dt = ical.get("DTSTART").dt end_time_dt = ical.get("DTEND").dt tzinfo = gettz(str(start_time_dt.tzinfo)) start_time_dt = start_time_dt.replace(tzinfo=tzinfo) recurring_rule = ical.get('RRULE').to_ical().decode('utf-8') rules = rrule.rruleset() first_rule = rrule.rrulestr(recurring_rule, dtstart=start_time_dt) rules.rrule(first_rule) event_delta = end_time_dt -start_time_dt now = datetime.datetime.now(datetime.timezone.utc) for s in rules.between(now - event_delta, now + datetime.timedelta(minutes=1)): print(s) Here is the exception: Traceback (most recent call last): File "ical_test.py", line 27, in &lt;module&gt; for s in rules.between(now - event_delta, now + datetime.timedelta(minutes=1)): File "/usr/local/lib/python3.5/dist-packages/dateutil/rrule.py", line 290, in between for i in gen: File "/usr/local/lib/python3.5/dist-packages/dateutil/rrule.py", line 1362, in _iter self._genitem(rlist, gen) File "/usr/local/lib/python3.5/dist-packages/dateutil/rrule.py", line 1292, in __init__ self.dt = advance_iterator(gen) File "/usr/local/lib/python3.5/dist-packages/dateutil/rrule.py", line 861, in _iter if until and res &gt; until: TypeError: can't compare offset-naive and offset-aware datetimes Anyone help for finding out the root cause of this error and a way to fix this?
has comment: http://stackoverflow.com/comment/86999694
has title: Timezone issue with UNTIL in ical RRULE statement
tagged with: timezone
downvote count: 0

http://stackoverflow.com/comment/86932376
type: QuestionComment
has text: Can you provide an exact example of the output you want? It's not clear what you want, but it *might* be `unicodedata.name(a)`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49958062

http://stackoverflow.com/comment/115207243
type: Comment
has text: @florian.isopp Ubuntu
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50039916

http://stackoverflow.com/comment/87122857
score: 1
type: Comment
has text: @ZeyadEtman Glad to help. I'll add some cropping of the detected "blobs" and will write up and answer. :)
type: QuestionComment
comment on: http://stackoverflow.com/q/50051916

http://stackoverflow.com/comment/86982030
score: 0
type: Comment
type: QuestionComment
has text: updated my question
comment on: http://stackoverflow.com/q/49981145

http://stackoverflow.com/q/50006611
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50006728
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50006728
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87029705
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87029682
type: Question
tagged with: dataframe
tagged with: python
has body: I have a dataframe that looks like this below with Date, Price and Serial. +----------+--------+--------+ | Date | Price | Serial | +----------+--------+--------+ | 2/1/1996 | 0.5909 | 1 | | 2/1/1996 | 0.5711 | 2 | | 2/1/1996 | 0.5845 | 3 | | 3/1/1996 | 0.5874 | 1 | | 3/1/1996 | 0.5695 | 2 | | 3/1/1996 | 0.584 | 3 | +----------+--------+--------+ I will like to make it look like this where the serial becomes the column name and the data sorts itself into the correct date row as well as Serial column. +----------+--------+--------+--------+ | Date | 1 | 2 | 3 | +----------+--------+--------+--------+ | 2/1/1996 | 0.5909 | 0.5711 | 0.5845 | | 3/1/1996 | 0.5874 | 0.5695 | 0.584 | +----------+--------+--------+--------+ I understand I can do this via a loop but just wondering if there is a more efficient way to do this? Thanks for your kind help. Also curious if there is a better way to paste such tables rather than attaching images in my questions =x
has title: Python - Pandas - Converting column with specific subsets into rows

http://stackoverflow.com/comment/87157304
score: 1
has text: There is most likely always a better solution not using globals.
type: QuestionComment
comment on: http://stackoverflow.com/q/50070360
type: Comment

http://stackoverflow.com/comment/87137982
type: QuestionComment
has text: No problem, amending my question now.
score: 0
comment on: http://stackoverflow.com/q/50059372
type: Comment

http://stackoverflow.com/comment/87035662
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50006720
has text: Thanks for the help. I used your approach but get `TypeError: filter function returned a Series, but expected a scalar bool` . Happy to provide a reproducible example if helpful

http://stackoverflow.com/a/51079224
has comment: http://stackoverflow.com/comment/89711867
has comment: http://stackoverflow.com/comment/89714108
type: Answer
answers question: http://stackoverflow.com/q/49922339
score: 0
has comment: http://stackoverflow.com/comment/89743356
has body: I encountered the same problem as you in not being able to specify a port when using the Micropython IDE extension on windows. I've found a simple way of running micropython scripts without leaving visual studio. First you'll need to install python, and then install ampy, using pip install ampy. Then add this task.json build task. You'll need to adjust your baud rate and port as needed. { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "ampy", "type": "shell", "command": "ampy -b 115200 -p COM5 -d 1 run ${file} --no-output", "group": { "kind": "build", "isDefault": true } } ] } Just type Ctrl+Shift+B to run the current python file on your device.

http://stackoverflow.com/comment/86941091
has text: Thank you to the people who helped edited my question. Im still new to this and is still learning, only started writing python for a week or so.
comment on: http://stackoverflow.com/q/49955462
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50051341
possible better answer: http://stackoverflow.com/a/50051386
has body: I am trying to return a single cell value from a dataframe of about 11.000 rows and 10 columns: df = pd.DataFrame({ 'A' : ('foo', 'foo', 'bar', 'bar'), 'B' : ('horse', 'car', 'horse', 'car'), 'C' : ('red', 'green', 'blue', 'black')}) df A B C 0 foo horse red 1 foo car green 2 bar horse blue 3 bar car black I've tried a few versions of loc, but always get an object returned, not the actual value ('green'). For instance: df.loc[(df['A'] == 'foo') &amp; (df['B'] == 'car'), 'C'] returns: 1 green Name: C, dtype: object The result is correct, but it is returned as an object, not as a string. I also tried setting columns A and B as indices in a multi-index frame. The loc code is then easier, but same result. So how can I get the value as a string, not as an object?
favorite count: 0
type: Question
has title: Return cell value in Pandas multi-index dataframe as string
has answer: http://stackoverflow.com/a/50051386
has answer: http://stackoverflow.com/a/50051458
tagged with: python
has comment: http://stackoverflow.com/comment/87119102
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50051458

http://stackoverflow.com/q/50026260
has title: Python Wheel creation, I don't get the description of the package in WinPython
has body: I am creating a wheel installation for a python (3.6 ) package I have done. Everything works well except a small thing : when I drag and drop the file.wheel in WinPython ( WinPython Control Panel ) I don't see the description of my package ( the one I have put in setup.py in the 'description' key ) I have also a long_description on a rst file... where do I see it once the package is installed ? I don't see also the description for my package in the list of the installed package... :-( Any ideas ? Thanks Christophe
has answer: http://stackoverflow.com/a/50043969
accepted answer: http://stackoverflow.com/a/50043969
type: Question
tagged with: setup.py
tagged with: package
tagged with: python-wheel
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/q/49958236
tagged with: python
has comment: http://stackoverflow.com/comment/86932858
has comment: http://stackoverflow.com/comment/86932870
has comment: http://stackoverflow.com/comment/86932775
has answer: http://stackoverflow.com/a/49958317
accepted answer: http://stackoverflow.com/a/49958317
type: AnsweredQuestion
score: 0
has title: 'NoneType' object has no attribute 'attrs' - If no value = Skip that function
answer count: 1
has comment: http://stackoverflow.com/comment/86932803
has body: So I have been trying to find out how to solve a issue that I have been stuck on - Basically what I want to do is that whenever there is a "NoneType" on a value = Skip that function so meaning if there is no value then just skip the rest of the code. So what I have tried to get is bs4.find("div", {'class': "clock"}).attrs['data-code'] meaning that sometimes this function is not working all the time so I tried to basically do - If there is no value from it then just continue the rest of the code - Else excute it - what I have done is if bs4.find("div", {'class': "clock"}).attrs['data-code'] == None: log("Does it work?") gettimer = bs4.find("div", {'class': "clock"}).attrs['data-code'] dothemath = int(gettimer) - 189386 releasetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(dothemath)) The issue im getting now that it stops whenever it reach to the if statement because it can't find the value and it automatic stops there - What can I do so whenever there is NoneType on it, Just skip the rest of the code?
linked to: http://stackoverflow.com/q/4978738
type: Question
tagged with: nonetype
tagged with: if-statement
has comment: http://stackoverflow.com/comment/86932842

swig
tags question: http://stackoverflow.com/q/49928983
tag name: swig
tags question: http://stackoverflow.com/q/50056859
tags question: http://stackoverflow.com/q/50024581
type: Tag
tags question: http://stackoverflow.com/q/50009202
tags question: http://stackoverflow.com/q/49984382
tags question: http://stackoverflow.com/q/50048048
tags question: http://stackoverflow.com/q/50050961
tags question: http://stackoverflow.com/q/49995905

http://stackoverflow.com/comment/86944251
comment on: http://stackoverflow.com/a/49964044
score: 1
type: Comment
type: AnswerComment
has text: Because it doesn't create a temporary in-memory list?

http://stackoverflow.com/q/49985450
upvote count: 1
favorite count: 0
has body: I'm trying to verify the signature on facebook signed_requests (https://developers.facebook.com/docs/reference/login/signed-request/), using python 3.6. So far I've tried: parse_signed_request() on the facebook python sdk here https://facebook-sdk.readthedocs.io this approach facebook signed request email this too http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas/ using python 2.7 and 3.2 using the python cryptography library like so from cryptography.hazmat.primitives import hashes, hmac from cryptography.hazmat.backends import default_backend h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend()) h.update(message) signature = h.finalize() replacing -_ chars with +/ a la Facebook signed_request Invalid via a simple replace("-", "+").replace("_", "/"). I had hopes for this one but I can't seem to verify a sig even if it lacks any of the above symbols like this one for example GlU46mFitdvtOnm56aLR3xQ1RUBzoCY0k2u1kMjBdQA.ey[...] ..so.. yeah.. I've attempted different string encodings (utf-8 / ascii) on the signature / payload different hashing algorithms (sha512 / md5 ..) hashing the base64 strings over decoding them from base64 first regenerating my app secret (I've double checked that the app ID that appears in the payload references the correct app, and thus secret) So far I've been unable to produce the same signature that comes on given signed request(s) .. so every facebook message is considered invalid (less than ideal!). How on earth does facebook generate these signatures? How do I generate them correctly (or incorrectly, if it matches facebook :P I'm not fussy) in order to validate them? Edit: Thanks for the comment. I've read that link too .. it doesn't seem to help work this out though. Here's a step by step with example - &gt; import json &gt; import base64 &gt; from cryptography.fernet import Fernet &gt; from cryptography.hazmat.backends import default_backend &gt; from cryptography.hazmat.primitives import hashes, hmac, padding…
score: 1
linked to: http://stackoverflow.com/q/20366041
tagged with: facebook
tagged with: python
has comment: http://stackoverflow.com/comment/87007132
tagged with: hmac
linked to: http://stackoverflow.com/q/15229022
type: Question
has title: Verifying facebook signed request urls in python3.6
type: UnansweredQuestion
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50005917

http://stackoverflow.com/comment/87014707
comment on: http://stackoverflow.com/q/49999369
type: QuestionComment
has text: it is like using format but takes the values from the scope...more or less...
score: 0
type: Comment

http://stackoverflow.com/a/50010133
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50010067
type: Answer
has body: %matplotlib inline If you're using jupyter notebook, you need to add the code above.
has comment: http://stackoverflow.com/comment/87036975
has comment: http://stackoverflow.com/comment/87037148
downvote count: 0

http://stackoverflow.com/comment/87150231
score: 0
type: Comment
type: AnswerComment
has text: I've ended up going with this so far (if anyone reads this in the future. It works, not sure if it's ideal. Thanks again for the help, Wen. `myDict= pd.Series(eduDict).apply(pd.Series).stack().reset_index(level=0).set_index(0)['level_0'].to_dict()` `df['col2'] = df['col1'].map(myDict)`
comment on: http://stackoverflow.com/a/50052474

http://stackoverflow.com/q/50005048
tagged with: python
linked to: http://stackoverflow.com/q/1500718
downvote count: 1
linked to: http://stackoverflow.com/q/986006
linked to: http://stackoverflow.com/q/47724517
type: AnsweredQuestion
has body: Consider this code: class MyClass: def __init__(self, x): self.x = x def myfunct(arg): arg.x += 1 return arg a = MyClass(0) print(a.x) b = myfunct(a) print(a.x) print(b.x) This returns: 0 1 1 I would expect this code to behave in the same way as this one: def myfunct(arg): arg += 1 return arg c = 0 print(c) d = myfunct(c) print(c) print(d) However the latter returns: 0 0 1 I understand this is due to Python's way of passing arguments by assignment, as explained in this post, or this post. However, I can't figure out a way to work around the behavior exhibited in the first code, which is unwanted in the project I am working on. How can I pass an object as an argument to a function, return a madified object, and keep the original one untouched?
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50005278
accepted answer: http://stackoverflow.com/a/50005217
has answer: http://stackoverflow.com/a/50005217
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50005220
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87026747
possible better answer: http://stackoverflow.com/a/50005278
has title: Python passing object as argument without overwriting
upvote count: 1

http://stackoverflow.com/comment/87027705
has text: As default, keras uses channels last, so I suggest using `input_shape=(45,6)` if length=45 and signals=6. For that you may need `np.swapaxes(X_train,1,2)` to invert the dimensions without changing the order of the data.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50005092

http://stackoverflow.com/comment/87065371
comment on: http://stackoverflow.com/a/50024469
has text: Panzer, ich begruesse sie :D Thanks a lot that worked great! I resorted back to using for loops which obviously isn't great. do you know how well your solution works when initializing larger arrays?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87085619
has text: I am getting this error: `Can't use string ("{0=2, 1=3, 2=4, 3=5, 4=6, 5=7, 6"...) as a HASH ref while "strict refs" in use at ./tester.pl line 83.` I think this is the line ` map sprintf('%s=[%s]', $_, join(', ', sort @{ $data->{$_} })),`
type: AnswerComment
comment on: http://stackoverflow.com/a/50034294
type: Comment
score: 0

http://stackoverflow.com/comment/86881472
comment on: http://stackoverflow.com/q/49932787
type: Comment
has text: Modify your map like `[list(map(lambda x: int(x) if x.isdigit() else x,a)) for a in listy]`
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87083001
comment on: http://stackoverflow.com/a/50033244
type: AnswerComment
score: 0
type: Comment
has text: Note that you use beta0 as a list, try func(x, parameter_list) as well.

http://stackoverflow.com/q/49965592
downvote count: 0
answer count: 1
tagged with: selenium
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86947411
linked to: http://stackoverflow.com/q/48369043
favorite count: 0
tagged with: qt
tagged with: selenium-webdriver
has body: I have an app QCalculator with qtwebdriver: https://github.com/cisco-open-source/qtwebdriver/pull/27/files I am trying to write simple python test, that will test this calculator, here is my script: #!/usr/bin/env python from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Remote( desired_capabilities=webdriver.DesiredCapabilities.FIREFOX, command_executor='http://127.0.0.1:9517' ) driver.get("qtwidget://Calculator"); btn = driver.find_elements_by_xpath("//Button[@name='5']")[0] btn.click(); This is interface of Calculator The script is supposed to click on number "5", but I got this error: Traceback (most recent call last): File "./testCalculator.py", line 12, in &lt;module&gt; btn = driver.find_elements_by_xpath("//Button[@name='5']")[0] IndexError: list index out of range Buttons are created like this: (in the link below on github) for (int i = 1; i &lt; NumDigitButtons; ++i) { int row = ((9 - i) / 3) + 2; int column = ((i - 1) % 3) + 1; mainLayout-&gt;addWidget(digitButtons[i], row, column); } How to change this code ("//Button[@name='5']")[0] to find the button ?
score: 1
has answer: http://stackoverflow.com/a/49965863
type: Question
type: UnansweredQuestion
has title: How can python script find the button in Qt application using qtwebdriver?

http://stackoverflow.com/comment/87041466
type: AnswerComment
comment on: http://stackoverflow.com/a/49991698
type: Comment
has text: The new table looks like it didn't merge the two dataframes together after calculation. It concatenated the population dataframe to the crime dataframe. All of the values were NaN.
score: 0

http://stackoverflow.com/comment/87051000
score: 0
comment on: http://stackoverflow.com/a/50017055
has text: i imported collections, what should i replace `index` with tho
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86932283
type: QuestionComment
score: 0
has text: I'll post an example as an answer.
comment on: http://stackoverflow.com/q/49957918
type: Comment

http://stackoverflow.com/q/50037369
upvote count: 1
tagged with: directory
tagged with: string
favorite count: 0
type: AnsweredQuestion
has title: find and replace string from multiple files in a folder using python
score: -2
tagged with: python
has body: I want to find string e.g. "Version1" from my files of a folder which contains multiple ".c" and ".h" files in it and replace it with "Version2.2.1" using python file. Anyone know how this can be done?
tagged with: find-replace
type: Question
accepted answer: http://stackoverflow.com/a/50037402
has answer: http://stackoverflow.com/a/50037402
answer count: 1
downvote count: 3

http://stackoverflow.com/comment/87068650
type: QuestionComment
comment on: http://stackoverflow.com/q/50020112
has text: Does it work if called from a *C* (*C++*) app?
score: 0
type: Comment

http://stackoverflow.com/comment/86940397
comment on: http://stackoverflow.com/q/49961993
score: 0
has text: `udtop` isn't doing any error checking, it just assumes requests will complete and expects you to catch failures when they happen. In this case the page had no `class_="meaning"` element so the find failed. You could read the url on your own and see what you get.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50019063
type: Answer
answers question: http://stackoverflow.com/q/50018387
has body: You need to check if the file has changed. You can do it with a loop wich checks the file timestamp every x-seconds. Or trigger it in the function who changes the data in your folder. Or you make a loop in Javascript who runs the function. EDIT: Here is an example from my current project how to render template with new data: prog.py @app.route('/show_all_persons', methods=['GET']) @login_required def show_all_persons(): all_persons_query = ''' SELECT * FROM persons ''' persons = sql_conn.query(all_persons_query) persons = [dict(p) for p in persons] return render_template('childs/show_all_persons.html', persons=persons) person.html ID Vorname Nachname {% for person in persons %} #{{ person.person_id }} {{ person.person_firstname }} {{ person.person_lastname }} {% endfor %}
score: 0
has comment: http://stackoverflow.com/comment/87090880
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87100731
has comment: http://stackoverflow.com/comment/87097170
has comment: http://stackoverflow.com/comment/87066517
has comment: http://stackoverflow.com/comment/87096670
has comment: http://stackoverflow.com/comment/87096149
accepted answer of: http://stackoverflow.com/q/50018387
has comment: http://stackoverflow.com/comment/87067035
has comment: http://stackoverflow.com/comment/87094385

http://stackoverflow.com/a/49990140
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/49990085
type: Answer
answers question: http://stackoverflow.com/q/49990085
has body: Solved this with sorting: def my_product(*args): return [tuple(i[1] for i in p) for p in sorted(itertools.product(*map(enumerate, args)), key=lambda x: (sum(y[0] for y in x), x))] Test: &gt;&gt;&gt; my_product([0,1,2],[3,4,5]) [(0, 3), (0, 4), (1, 3), (0, 5), (1, 4), (2, 3), (1, 5), (2, 4), (2, 5)] &nbsp; works also with non-sorted, non-numeric items: &gt;&gt;&gt; my_product(['s0','b1','k2'],['z3','a4','c5']) [('s0', 'z3'), ('s0', 'a4'), ('b1', 'z3'), ('s0', 'c5'), ('b1', 'a4'), ('k2', 'z3'), ('b1', 'c5'), ('k2', 'a4'), ('k2', 'c5')] &nbsp; &gt;&gt;&gt; my_product([2,1,0],['b','c','a']) [(2, 'b'), (2, 'c'), (1, 'b'), (2, 'a'), (1, 'c'), (0, 'b'), (1, 'a'), (0, 'c'), (0, 'a')] &nbsp; and with multiple args: &gt;&gt;&gt; my_product([2,1,0],['b','c','a'],['x','y','z']) [(2, 'b', 'x'), (2, 'b', 'y'), (2, 'c', 'x'), (1, 'b', 'x'), (2, 'b', 'z'), (2, 'c', 'y'), (2, 'a', 'x'), (1, 'b', 'y'), (1, 'c', 'x'), (0, 'b', 'x'), (2, 'c', 'z'), (2, 'a', 'y'), (1, 'b', 'z'), (1, 'c', 'y'), (1, 'a', 'x'), (0, 'b', 'y'), (0, 'c', 'x'), (2, 'a', 'z'), (1, 'c', 'z'), (1, 'a', 'y'), (0, 'b', 'z'), (0, 'c', 'y'), (0, 'a', 'x'), (1, 'a', 'z'), (0, 'c', 'z'), (0, 'a', 'y'), (0, 'a', 'z')]
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49948016
tagged with: django
favorite count: 0
type: Question
has body: I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get the categories but not the products to show in my HTML. models.py class Category(models.Model): title = models.CharField(max_length=225) slug = models.SlugField(unique=True, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('category_detail', kwargs={'slug': self.slug}) @property def get_products(self): return Products.objects.filter(category=self.title) class Products(models.Model): title = models.CharField(max_length=225) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) blank=True, on_delete=models.CASCADE) categories = models.ForeignKey(Category, related_name='Category', blank=True, on_delete=models.CASCADE) #this gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default="male") objects = ProductManager() def get_absolute_url(self): return reverse('product_detail', args=(self.id,)) def __str__(self): return self.title views.py def categories_m(request): query_Set = models.Category.objects.all() page = request.GET.get('page', 1) paginator = Paginator(query_Set, 20) try: cat = paginator.page(page) except PageNotAnInteger: cat = paginator.page(1) except EmptyPage: cat = paginator.page(paginator.num_pages) return render(request, 'products/categories.html', {'categories': cat}) html {% extends 'base.html' %} {% block content %} {% for category in categories %} &lt;h1&gt;{{ category }}&lt;/h1&gt; {% for product in categories.get_products %} &lt;p&gt;{{ product }}&lt;/p&gt; {% endfor %} {% endfor %} {% endblock %}
possible better answer: http://stackoverflow.com/a/49949554
tagged with: django-models
has answer: http://stackoverflow.com/a/49949554
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49948054
tagged with: django-templates
tagged with: django-views
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49948054
downvote count: 0
has title: Django: List Products of each Categories in a page

http://stackoverflow.com/comment/86879043
type: QuestionComment
comment on: http://stackoverflow.com/q/49931376
has text: It is hard to help if you don't have a basic understanding of the language you are trying to get help on, please read the **documentation** for python [HERE](https://docs.python.org/3/), then read: https://stackoverflow.com/help/how-to-ask and ask a complete question.
score: 0
type: Comment

http://stackoverflow.com/q/49972725
has comment: http://stackoverflow.com/comment/86962286
score: 0
tagged with: normalization
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: preprocessor
linked to: http://stackoverflow.com/q/31485526
type: Question
has title: Standardization of dataset into quantiles in Python
has body: I would like to standardize my dataset as part of preprocessing for a machine learning algorithm. Is there way using an existing packages (say sklearn.preprocessing) to put the data into buckets. I have found QuantileTransformer but that rather squishes all observations into a range of 0 to 1. I would like all of my observations to take on discrete values say 1 to 5, based on their distribution, i.e. first 20% in first bucket, second 20% in 2nd bucket etc. Maybe some combination of QuantileTransformer and pandas.qcut?? EDIT: For my future self who is going to google this problem and end up here, this works: df2=pd.qcut(df1['var1'],5, labels=False)
has comment: http://stackoverflow.com/comment/86961577
tagged with: python
has comment: http://stackoverflow.com/comment/86961701

http://stackoverflow.com/q/50065731
type: Question
possible better answer: http://stackoverflow.com/a/59369715
has title: Pandas Dataframe or similar in C#.NET
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50065808
score: 42
upvote count: 42
has answer: http://stackoverflow.com/a/74883586
has comment: http://stackoverflow.com/comment/90910964
answer count: 4
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50065808
downvote count: 0
tagged with: .net
has comment: http://stackoverflow.com/comment/93031879
has answer: http://stackoverflow.com/a/59369715
has body: I am currently working on implement the C# version of a Gurobi linear program model that was earlier built in Python. I have a number of CSV files from which I was importing the data and creating pandas dataframes, and I was fetching columns from those dataframes to create variables that I was using in my Linear Program. The python code for creating the variables using dataframes is as follows: dataPath = "C:/Users/XYZ/Desktop/LinearProgramming/TestData" routeData = pd.DataFrame.from_csv(os.path.join(dataPath, "DirectLink.csv"), index_col=None) #Creating 3 Python-dictionaries from Python Multi-Dict using column names and keeping RouteID as the key routeID, transportCost, routeType = multidict({x[0]:[x[1],x[2]] for x in routeData'RouteID', 'TransportCost','RouteType'.values}) Example: If the csv structure is as follows: RouteID RouteEfficiency TransportCost RouteType 1 0.8 2.00 F 2 0.9 5.00 D 3 0.7 6.00 R 4 0.6 3.00 T The 3 variables should be: RouteID: 1 2 3 4 TransportCost: 1:2.00 2:5.00 3:6.00 4:3.00 RouteType: 1:F 2:D 3:R 4:T Now, I want to create a C# version of the above code that does the same task, but I learnt that C# doesn't support dataframes. I tried looking for a few alternatives, but am unable to find anything. Please help me with this.
favorite count: 0
tagged with: c#
has answer: http://stackoverflow.com/a/71561592

http://stackoverflow.com/comment/87091081
score: 1
type: Comment
type: QuestionComment
has text: Why do you need a service for that? Can't you use [schtasks](https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx)?
comment on: http://stackoverflow.com/q/50037297

http://stackoverflow.com/q/50002958
has body: We would like to upload a string with python. I found here some examples and created the following script. import requests url = 'https://URL/fileupload?FileName=file.csv' headers = {'content-type': 'octet-stream'} files = {'file': ('ID,Name\n1,test')} r = requests.post(url, files=files, headers=headers, auth=('user', 'password')) The upload is working but the output contains some unexpected lines. --ec7b507f800f48ab85b7b36ef40cfc44 Content-Disposition: form-data; name="file"; filename="file" ID,Name 1,test --ec7b507f800f48ab85b7b36ef40cfc44-- The goal is to only upload the following from files = {'file': ('ID,Name\n1,test')}: ID,Name 1,test How is this possible?
upvote count: 4
duplicate of: http://stackoverflow.com/q/14551194
score: 4
accepted answer: http://stackoverflow.com/a/50007786
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/14551194
has answer: http://stackoverflow.com/a/50007786
downvote count: 0
has title: python upload string with https post
tagged with: python-requests
answer count: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/49932055
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: password-hash
has body: I'm trying to re-create PowerShell's PasswordDeriveBytes method in python using pycryptodome's KDF module. The main thing I can't get passed right now is getting the correct DerivedKey result in Python that I get from PowerShell. PARAMETERS: password = '1234567890' salt = '0987654321' length = 16 iterations = 2 SAMPLE POWERSHELL CODE: $AsciiEncoder = New-Object System.Text.ASCIIEncoding; $DerivedPass = New-Object System.Security.Cryptography.PasswordDeriveBytes('1234567890', $AsciiEncoder.GetBytes('0987654321'), "SHA1", 2); [Byte[]] $KeyBytes = $DerivedPass.GetBytes(16); -join($KeyBytes | ForEach { $_.ToString("X2")}); RESULT: C937511EBDBE12C7A0FCC8D6CB42BEDC *NOTE: The PowerShell code above is amended from https://github.com/PowerShellMafia/PowerSploit/blob/master/ScriptModification/Out-EncryptedScript.ps1. I am trying to re-implement the functionality in the Python code below. PYTHON CODE: from Crypto.Protocol import KDF from Crypto.Hash import SHA1 def password_derive_key(password, salt, length, count): return KDF.PBKDF2(password, salt, length, count) def main(): derivedKey = password_derive_key('1234567890', '0987654321', 16, 2) print derivedKey.encode('hex') if __name__ == "__main__": main() RESULT: 5a3f103f5dc4558f8dca5d5b145ed0b4 The only thing that I can think of us that the ".GetBytes" method of PasswordDeriveBytes is generating a different result than what pycryptodome's KDF module. Any help would be greatly appreciated.
has title: Convert PasswordDeriveBytes functionality to Python
tagged with: pycrypto
tagged with: kdf
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49933258
score: 0
tagged with: powershell
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87095779
score: 1
comment on: http://stackoverflow.com/q/50039915
has text: Can you show us the code which creates these errors?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49968934
has body: Your error comes from comparing a string diceI = input("Name: ") with an integer stored inside a variable D4 = int(randint(1, 4)). diceI is a string - so compare it to another string - not to a integer. Also D4 = randint(1, 4) is enough - randint already produces a integer, you do not need to convert it with int(randint(1, 4)) into one. You can get the dice to be rolled directly from the input and skip parts of your code like so: import random import os import time os.system('cls') print("What dice would you like to roll?") print("D4, D6, D10, D12, D20") dice = "" # continue to ask for input until the input is one of the ones in the list while dice not in ["D4", "D6", "D10", "D12", "D20"]: dice = input("Name: ") diceNr = int(dice[1:]) # remove the D and convert the remaining number to integer if (diceNr == 4): print("lol") else: # get a random number between 1 and diceNr print(random.randint(1,diceNr )) See randint-Doku random.randint(a, b) Return a random integer N such that a &lt;= N &lt;= b
answers question: http://stackoverflow.com/q/49968827
type: Answer
score: 0

http://stackoverflow.com/comment/87104954
type: AnswerComment
score: 0
has text: Sorry, I forgot about coming back. It is actually not that hard to read you were right. And now I get what you were saying about the momentum optimizer
comment on: http://stackoverflow.com/a/49977348
type: Comment

http://stackoverflow.com/q/49998457
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87014535
has comment: http://stackoverflow.com/comment/87013240
has body: I have a CSV file (not normalized, example, real file up to 100 columns): ID, CUST_NAME, CLIENT_NAME, PAYMENT_NUM, START_DATE, END_DATE 1, CUST1, CLIENT1, 10, 2018-04-01, 2018-04-02 2, CUST1, CLIENT1, 10, 2018-04-01, 2018-05-30 3, CUST1, CLIENT1, 101, 2018-04-02, 2018-04-03 4, CUST2, CLIENT1, 102, 2018-04-02, 2018-04-03 How can I find ALL possible sets of columns which could be used as Primary key. Desired output: 1) ID 2) PAYMENT_NUM,START_DATE,END_DATE 3) CUST_NAME, CLIENT_NAME, PAYMENT_NUM,START_DATE,END_DATE I could do it in Java but may be Python/Pandas already provides a quick solution
has answer: http://stackoverflow.com/a/50000979
has comment: http://stackoverflow.com/comment/87014434
accepted answer: http://stackoverflow.com/a/50000979
tagged with: algorithm
has comment: http://stackoverflow.com/comment/87014394
score: 10
tagged with: python
upvote count: 11
has title: How to find a columns set for a primary key candidate in CSV file?
has answer: http://stackoverflow.com/a/50000328
possible better answer: http://stackoverflow.com/a/50000328
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87013317
tagged with: pandas
tagged with: sql
downvote count: 1

http://stackoverflow.com/comment/87042535
has text: Yep, this is the way in Python. Takes some getting used to. You can always code it more verbosely, but better to learn.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50013064
type: Comment

http://stackoverflow.com/a/50413643
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87845603
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49961216
has comment: http://stackoverflow.com/comment/87868677
has body: Goto Makefile (and not the .config file) and change the name of the ld library to python27.

label
tags question: http://stackoverflow.com/q/50028608
tags question: http://stackoverflow.com/q/50010835
tags question: http://stackoverflow.com/q/50005341
tags question: http://stackoverflow.com/q/50005306
tags question: http://stackoverflow.com/q/50052879
tag name: label
type: Tag
tags question: http://stackoverflow.com/q/49995953

http://stackoverflow.com/a/49995933
answers question: http://stackoverflow.com/q/49995727
has body: What you have is a byte string, and there is no standard way to store raw bytes in a JSON object. You should instead encode the bytes into base64 and store the base64 string in your JSON object: import base64 b64String = base64.b64encode(myByteString)
has comment: http://stackoverflow.com/comment/87008838
score: 0
has comment: http://stackoverflow.com/comment/87009119
type: Answer

http://stackoverflow.com/comment/86943001
has text: What about using collections.Counter?
comment on: http://stackoverflow.com/q/49963436
type: Comment
type: QuestionComment
score: 0

vector
tags question: http://stackoverflow.com/q/50017485
type: Tag
tag name: vector
tags question: http://stackoverflow.com/q/50033364
tags question: http://stackoverflow.com/q/49972909
tags question: http://stackoverflow.com/q/49992507
tags question: http://stackoverflow.com/q/49927761
tags question: http://stackoverflow.com/q/49931993

http://stackoverflow.com/q/50022491
has comment: http://stackoverflow.com/comment/87065221
tagged with: string-matching
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87065428
upvote count: 1
downvote count: 1
answer count: 1
tagged with: string
has body: Let's say I know beforehand that the string "key1:key2[]:key3[]:key4" should map to "newKey1[]:newKey2[]:newKey3" then given "key1:key2[2]:key3[3]:key4", my method should return "newKey1[2]:newKey2[3]:newKey3" (the order of numbers within the square brackets should stay, like in the above example) My solution looks like this: predefined_mapping = {"key1:key2[]:key3[]:key4": "newKey1[]:newKey2[]:newKey3"} def transform(parent_key, parent_key_with_index): indexes_in_parent_key = re.findall(r'\[(.*?)\]', parent_key_with_index) target_list = predefined_mapping[parent_key].split(":") t = [] i = 0 for elem in target_list: try: sub_result = re.subn(r'\[(.*?)\]', '[{}]'.format(indexes_in_parent_key[i]), elem) if sub_result[1] &gt; 0: i += 1 new_elem = sub_result[0] except IndexError as e: new_elem = elem t.append(new_elem) print ":".join(t) transform("key1:key2[]:key3[]:key4", "key1:key2[2]:key3[3]:key4") prints newKey1[2]:newKey2[3]:newKey3 as the result. Can someone suggest a better and elegant solution (around the usage of regex especially)? Thanks!
favorite count: 0
type: Question
has title: Python elegant way to map string structure
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87065889
has comment: http://stackoverflow.com/comment/87065816
has answer: http://stackoverflow.com/a/50025512
accepted answer: http://stackoverflow.com/a/50025512

http://stackoverflow.com/q/49948000
has body: Currently I'm plotting coordinates in a polar plot using an array of angles with values. I have a text file: [angle] [value] 0 54.3 5 54.4 10 54.2 15 54.4 20 54.6 25 54.4 30 54.2 35 54.4 I'm plotting like this: import matplotlib.pyplot as plt #Define arrays angles=list() values=list() lines = [line.rstrip('\n') for line in open('values.txt')] for line in lines: # Iterate lines stringElement = str.split(line, &quot; &quot;) # Split elements angle = int(stringElement[0]) value = float(stringElement[1]) angles.append(angle) values.append(value) # Plot values ax = plt.subplot(111, projection='polar') #Plot dots plt.polar(angles, values, 'k.', zorder=3) #Plot lines #plt.polar(angles, values) ax.grid(True) plt.show() This looks like this: When I enable the lines, it should connect the dots to the closest neighbor, but connects to other lines instead. This looks like this: How to connect the dots to the closest neighbor instead?
has title: How to connect coordinates in Polar plot matplotlib
upvote count: 1
has answer: http://stackoverflow.com/a/50248635
downvote count: 1
tagged with: plot
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86915102
has comment: http://stackoverflow.com/comment/86917450
has comment: http://stackoverflow.com/comment/86917254
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50248635

http://stackoverflow.com/q/50027775
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
has body: In my BookSerializer, I have a nested field page: class PageSerializer(serializers.ModelSerializer): ... class BookSerializer(serializers.ModelSerializer): page = PageSerializer() and the page field validator expects an dictionary as value. But what I want is it should accept an integer as well (page's id). So in the BookSerializer, I tried to override the validate function for the page field but it didn't work: class BookSerializer(serializers.ModelSerializer): page = PageSerializer() def validate_page(self, value): if isinstance(value, int): return value # if value is not an integer, reuse the default validator # but django said that validate_page is not a function return super().validate_page() Seems like the validate_page function is never called because it's a nested field. Thanks !
tagged with: serialization
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/55832172
has title: Custom validator for nested field in serializer
upvote count: 2
tagged with: validation
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/111060245
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49962706
has text: I understand this behavior is intentional... but it is still "wrong". I feel like someone decided something like, "folks coming from R will like inclusive better, and they will use names more often". But we will all spend far more time *programming in Python* than *learning Python* (or any language, library, or framework). So, while the learning curve might be *marginally* higher, API consistency is far more important. This is just a bad design decision that will *rightfully* cause users to accidentally make off-by-one errors when refactoring. :(

http://stackoverflow.com/q/50053373
tagged with: python
duplicate of: http://stackoverflow.com/q/37088457
type: Question
has comment: http://stackoverflow.com/comment/87123205
type: UnansweredQuestion
has body: how to return result to the call function? I want my parse2 to return a value back to parse1, so parse1 can store it. right now I am just getting the url value, but not the return value from parse2 def parse1(self, response): for lst in response.css("tr.lst-rw"): url = lst.css('td[headers="lh_id"] &gt; a::attr(href)').extract_first() if url is not None: url = response.urljoin(url) res = scrapy.Request(url, callback=self.parse2) yield{ 'response-date' : res } def parse2(self, response): yield{ 'response date': response.css('div#dnf::text').extract_first().strip() }
answer count: 1
has answer: http://stackoverflow.com/a/50053479
tagged with: scrapy
linked to: http://stackoverflow.com/q/37088457
score: 0
has title: scrapy how to get return value from another function

http://stackoverflow.com/comment/86900512
type: QuestionComment
comment on: http://stackoverflow.com/q/49942096
has text: Replace `df[...].replace(..., inplace=True)` with `df[...] = df[...].replace(...)` everywhere
score: 0
type: Comment

http://stackoverflow.com/comment/86861469
comment on: http://stackoverflow.com/q/49922911
has text: Is the result your desired result? Or is that somehow wrong.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49988928
has body: So I am using python 2.7 on a rasberry pi and am trying to install a virtualenv. So when I type: $ sudo pip install virtualenv virtualenvwrapper I get this long error message: Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 353, in run wb.build(autobuilding=True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/usr/lib/python2.7/dist-packages/pip/download.py", line 821, in unpack_url hashes=hashes File "/usr/lib/python2.7/dist-packages/pip/download.py", line 659, in unpack_http_url hashes) File "/usr/lib/python2.7/dist-packages/pip/download.py", line 853, in _download_http_url stream=True, File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 501, in get return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/download.py", line 386, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 488, in request resp = self.send(prep, **send_kwargs) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 609, in send r = adapter.send(request, **kwargs) File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/adapter.py", line 47, in send resp = super(CacheControlAdapter, self).send(request, **kw) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/adapters.py", line 497, in send raise SSLEr…
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87429355
has title: Error upgrading pip or using it in any capacity. SSLError: ("bad handshake
upvote count: 1
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87003902
has comment: http://stackoverflow.com/comment/87383579
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86999310
tagged with: pip
tagged with: ssl
tagged with: python
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87388141

http://stackoverflow.com/comment/87011668
has text: from nltk.corpus import WordNetCorpusReader
score: 0
comment on: http://stackoverflow.com/q/49997560
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49962413
has body: I am trying to run certain python functions when buttons on my HTML page are clicked. The buttons use Ajax to communicate with my flask server. Currently when the buttons are clicked the Ajax does cause the python functions to run, and I am able to get the results that I need. However my console shows 500 (internal sever error) and I am unsure of what the issue is. Here is one of the Ajax call &lt;!-- stop button ajax calls --&gt; &lt;script&gt; $(document).ready(function() { $('#stopform').on('click', function(event) { alert("Chamber Stopped"); clearInterval(start_interval); $.ajax({ data : { }, type : 'POST', url : '/stop' }) }); }); &lt;/script&gt; and the python route that it calls too @app.route('/stop', methods=['POST']) def stop(): #stops control system gpio.control_stop()
score: 0
has comment: http://stackoverflow.com/comment/86940953
answer count: 0
tagged with: jquery
has comment: http://stackoverflow.com/comment/86940972
has title: Flask 500 (internal sever error) when Ajax calls are made
type: Question
tagged with: ajax
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/87054705
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169746/discussion-between-vivek-kumar-and-roma-jain).
score: 0
comment on: http://stackoverflow.com/q/50019036
type: QuestionComment

http://stackoverflow.com/a/50054551
accepted answer of: http://stackoverflow.com/q/50051606
type: Answer
answers question: http://stackoverflow.com/q/50051606
score: 0
type: AcceptedAnswer
has body: in fact，this error occurred by permission. in c://Users ,need adminster authority to do it . you should use shutil.copy(src,dst) copy file and authority

http://stackoverflow.com/comment/86936557
has text: you might wana get your maths checked out https://math.stackexchange.com/ first then concentrate on code.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49959807
type: QuestionComment

http://stackoverflow.com/comment/87040847
comment on: http://stackoverflow.com/q/50002131
type: Comment
score: 0
type: QuestionComment
has text: @zipa, not sure what you mean by column alignment but there are basically two tables with different number of columns and the tables are separated by some text in between. The same pattern repeats throughout. The number of rows, however, are the same for each table. Would be great if we could read the two tables in two separate data frames or concatenate the columns from two tables and read it as one data frame.

http://stackoverflow.com/comment/87138258
type: AnswerComment
score: 0
has text: If you'd rather not delete the information at the top, but scroll, I've added the line in insertLine that will do that automatically for you.
comment on: http://stackoverflow.com/a/50049814
type: Comment

http://stackoverflow.com/comment/116111274
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49980526
has text: I am having a similar challenge. Can you please share the code if available?
type: Comment

http://stackoverflow.com/comment/96642691
has text: we're getting off topic here but what type of manipulating do you find lacking? i thought pretty much everything was more flexible in pytorch.
type: Comment
comment on: http://stackoverflow.com/a/50063554
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87081662
has text: My Apache log says that my `mod_wsgi` is compiled against Python 2.7.11, whereas I'm running 2.7.12. Is a small version discrepancy like that generally impactful?
comment on: http://stackoverflow.com/q/50013067
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/65002839
answers question: http://stackoverflow.com/q/50045182
score: 0
type: Answer
has body: First of all, you have to always know with the type of data you are dealing with, in your case, you create a DatetimeIndex: DatetimeIndex(['2020-08-25 11:00:00.000307403', '2020-08-25 11:00:00.000558638', '2020-08-25 11:00:00.002280412', '2020-08-25 11:00:00.002440933']) &lt;class 'pandas.core.indexes.datetimes.DatetimeIndex'&gt; and inside the DatetimeIndex, each element of it is a Timestamp: 2020-08-25 11:00:00.000307403 &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt; As you are working with DatetimeIndexes, you have to index the values by the actual timestamp ('2020-08-25 11:00:00.000307403') and not by the full timestamp variable (Timestamp('2020-08-25 11:00:00.000307403')) So, instead of doing: df[Timestamp('2020-08-25 11:00:00.000307403')] you should do: df['2020-08-25 11:00:00.000307403'] I lost like two hours to catch this error, since it is a bit stupid to include the type of data inside the variable, the easiest way to solve this is just to parse the DatetimeIndex to string. For your solution: d[str(d.index[0]),'a'] should work

http://stackoverflow.com/a/49956119
has comment: http://stackoverflow.com/comment/86929727
type: Answer
has body: Write a function for the add button to call instead of "C". For example: def addfunction(event=None): statusDisplay.insert(END, operator) You will also want some validating code to make sure that global variable operator is not undefined or of the wrong type. Also it might be good to keep track of which OPs are already logged so you never log OPs several times. Additional explanation: The easiest way to make sure that global variable operator is not undefined is to set a default value of the correct type before you use it for the first time. operator = '' Otherwise you can check variable type with if type(operator) == str for strings. Same syntax for other types. For checking if a variable exists you can use a try clause. As for keeping track of inputs, I'm not really sure about exactly what you want. This is also something you'll have to spend some time thinking about. Let me give an example: Should outputs in statusDisplay be separated by spaces, tabs, commas? Is it important if "On time" appears first in a line or doesn't it matter? Is multiline results ok? Do I want "On time" and "Is late" to appear on the same line. Is the results something you will send to another program or function or maybe save to a file; what format will they want? When you have decided on a behaviour it's much easier to write the code and see if the output is what you want. Also: try implementing it yourself first, and if it doesn't work you are welcome to ask for further help. Before you do that: read the documentation and google for solutions.
answers question: http://stackoverflow.com/q/49955462
has comment: http://stackoverflow.com/comment/86941045
score: 0

http://stackoverflow.com/comment/86951701
type: QuestionComment
comment on: http://stackoverflow.com/q/49967832
has text: why not `if not basename in file: continue` just before your `reMatch = matcher.match(file)`? - or use `file.startswith(basename)` - or even: `if reMatch and basename in file:`
score: 0
type: Comment

http://stackoverflow.com/a/49962240
has comment: http://stackoverflow.com/comment/86940689
has body: This expression: kwargs.get("screen",self.screen) is equivalent to this expression: kwargs["screen"] if "screen" in kwargs else self.screen This statement: self.screen = kwargs.get("screen",self.screen) is equivalent to these statements: if "screen" in kwargs: self.screen = kwargs["screen"] else: self.screen = self.screen Note that it is not equivalent to these statements: if "screen" in kwargs: self.screen = kwargs["screen"] Because the statement self.screen = self.screen raises an AttributeError if self.screen is not yet defined. See that error in action by running the following program: d = {} x = object() x.attr = d.get("attr", x.attr) You can do away with kwargs by implementing update instead as: def update(self, screen=None, clock=None, active=None): if screen is not None: self.screen = screen if clock is not None: self.clock = clock if active is not None: self.active = active And then you can call debug.update and specify whichever of the keyword arguments you want. Defining it this way has the advantage that it raises a TypeError if you try to call it with a keyword argument other than screen, clock, or active. One caveat is that if you really mean to say debug.update(screen = None), then calling it that way actually does nothing; it does not set debug.screen to None. One way to get around that is to write this at the top of your file: _UNSPECIFIED = object() And then implement update as: def update(self, screen=_UNSPECIFIED, clock=_UNSPECIFIED, active=_UNSPECIFIED): if screen is not _UNSPECIFIED: self.screen = screen if clock is not _UNSPECIFIED: self.clock = clock if active is not _UNSPECIFIED: self.active = active
downvote count: 0
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/49961997
type: Answer

http://stackoverflow.com/a/49962172
has body: You should try setting the primary key to None. See this answer: How can I save the same form more than once in Django 1.8? I got my reference from: Save multiple data using loops in django models using save function with admin save button
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49962143
score: 1
answers question: http://stackoverflow.com/q/49962143
type: Answer
has comment: http://stackoverflow.com/comment/131191948
has comment: http://stackoverflow.com/comment/86940542

http://stackoverflow.com/comment/87079653
has text: @T.ps then i highly encourage you to use cmath library which has a built-it function sqrt() that allows complex results. i will update my edit with an example.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50031413
type: AnswerComment

http://stackoverflow.com/comment/87239107
score: 0
comment on: http://stackoverflow.com/a/50055467
type: Comment
type: AnswerComment
has text: Ah! I have have not used backport yet... but understand the concept, will check it out. Thanks.

http://stackoverflow.com/q/50062769
has comment: http://stackoverflow.com/comment/87142530
answer count: 1
has body: I'm using gevent and flask to create a streaming app. I've embedded an img element inside the html page and set its src=/video_feed The corresponding flask code is def gen(): global vc """Video streaming generator function.""" if vc is None: vc = cv2.VideoCapture(0) _, frame = vc.read() while True: rval, frame = vc.read() r, frame = cv2.imencode('.jpg', frame) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame.tobytes() + b'\r\n') @app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') The problem: The streaming works fine but the problem is Flask blocks and refuses to accept new requests until the client disconnects! This is the code I use to start it with gevent def start_gevent(app_port): http_server = WSGIServer(('', app_port), app) http_server.serve_forever() Here is my app log. ::1 - - [2018-04-27 18:02:56] "GET / HTTP/1.1" 200 1827 0.008464 ::1 - - [2018-04-27 18:02:59] "GET /video.html HTTP/1.1" 200 1850 &lt;--streaming starts here 0.001877 [wxpython.py] OnClose called &lt;-- client disconnect ::1 - - [2018-04-27 18:03:01] "GET /video_feed HTTP/1.1" 200 2951956 2.790426 &lt;-- flask log of the request comes late ::1 - - [2018-04-27 18:03:01] "GET /database.html HTTP/1.1" 200 118 0.003394 &lt;-- client made these requests concurrently, but flask didnt respond, it logs them now ::1 - - [2018-04-27 18:03:01] "GET /database.html HTTP/1.1" 200 118 0.000549 Can anyone advice?
has comment: http://stackoverflow.com/comment/87142610
tagged with: gevent
type: Question
has comment: http://stackoverflow.com/comment/87143429
has answer: http://stackoverflow.com/a/75841166
type: UnansweredQuestion
score: 0
tagged with: python
has title: Gevent, Flask app stuck while streaming video until client disconnects
has comment: http://stackoverflow.com/comment/87143649
tagged with: flask
has comment: http://stackoverflow.com/comment/87142742

http://stackoverflow.com/comment/87001069
type: QuestionComment
comment on: http://stackoverflow.com/q/49991870
has text: That's better discussed in the meta topic. So far, I've received nothing but support for the post as it is.
score: 0
type: Comment

http://stackoverflow.com/q/50009216
has title: Comparing integers from tuples in for loop
has body: I'm trying to compare int values from a list of tuples while iterate over the list. Concretely i have a list of tuples like so: numbers_tokenized = [('2900', 368),('7,', 378),('2900', 379),('33', 384),('34', 385),('40', 386),('00', 387),('33', 389),('34', 390),('40', 391),('01', 392),('7', 410),('2900', 412),('7', 422),('191', 424),('2900', 425),('33', 428),('34', 429),('40', 430),('00', 431),('33', 433),('34', 434),('40', 435),('01', 436)] What i wanna do is check if the second element in a tuple is the element of the tuple next in the list + 1. For instance 384,385,386,387 from the list above. I have the following loop that i think should do the job. cons_nums = list() for x in range(1,len(numbers_tokenized)): if numbers_tokenized[x][1]-1 == numbers_tokenized[x-1][1]: cons_nums.append(numbers_tokenized[x-1]) else: continue However this gives me the following output, which does not make much sense to me. cons_nums = [('7,', 329), ('7,', 338), ('7,', 349), ('7,', 367), ('7,', 378), ('33', 384), ('34', 385), ('40', 386), ('33', 389), ('34', 390), ('40', 391), ('191', 424), ('33', 428), ('34', 429), ('40', 430), ('33', 433), ('34', 434), ('40', 435)] Am i making some obvious mistake or why is this not working? EDIT: In a successful loop cons_nums would look like this: cons_nums = [('7,', 378),('2900', 379),('33', 384),('34', 385),('40', 386),('00', 387),('33', 389),('34', 390),('40', 391),('01', 392),('191', 424),('2900', 425),('33', 428),('34', 429),('40', 430),('00', 431),('33', 433),('34', 434),('40', 435),('01', 436)]
possible better answer: http://stackoverflow.com/a/50009432
has comment: http://stackoverflow.com/comment/87035144
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50009432
has comment: http://stackoverflow.com/comment/87035333
type: Question
has comment: http://stackoverflow.com/comment/87035113
tagged with: python
has comment: http://stackoverflow.com/comment/87035170
has comment: http://stackoverflow.com/comment/87035270
has comment: http://stackoverflow.com/comment/87035227
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87035087
tagged with: list
answer count: 2
accepted answer: http://stackoverflow.com/a/50009614
has answer: http://stackoverflow.com/a/50009614

http://stackoverflow.com/comment/87121249
type: QuestionComment
has text: You can literally write `np.random.choice(x[x>=2])`.
comment on: http://stackoverflow.com/q/50051619
score: 1
type: Comment

http://stackoverflow.com/q/49993936
has comment: http://stackoverflow.com/comment/87005815
possible better answer: http://stackoverflow.com/a/49994225
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 2
has body: Say I have a set of tuples, with each tuple containing two integers. mySet = ((1, 3), (3, 4), (3, 5)) What would be the best way to find a common element from tuples? For this case output will be : 3
has comment: http://stackoverflow.com/comment/87004515
tagged with: set
downvote count: 0
has answer: http://stackoverflow.com/a/49994225
has title: How to Determine a Common Element in a Set of Tuples - Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/49993988
type: Question
has comment: http://stackoverflow.com/comment/87004471
tagged with: tuples
has comment: http://stackoverflow.com/comment/87004304
has comment: http://stackoverflow.com/comment/87004227
has answer: http://stackoverflow.com/a/49993988
upvote count: 2
has comment: http://stackoverflow.com/comment/87004554

http://stackoverflow.com/q/50028913
type: UnansweredQuestion
tagged with: pyqtgraph
tagged with: pyserial
has title: Interacting pyqtgraph with command prompt
has body: Im trying to implement an interactive menu via the command prompt in python 3.X to plot serial data from an arduino using pyqtgraph. Ive read the documentation on Qt but i just cant get it to work. The objetive is that when the user send 'A' the plotting starts, and finally when he presses 'B' the plotting stops. I've tried to wrap the timer into an if statement but that wont do the trick, it pops the window and crash. Any help would be appreciate. here the code: from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg import threading, serial, time def main(): while True: flag=input('Press A to start plotting, Press B to close the plotting sequence') if flag is 'A': #Start my plotting sequence elif flag is 'B' #Close my plotting sequence app = QtGui.QApplication([]) win = pg.GraphicsWindow() win.setWindowTitle('Datos de Arduino') p1 = win.addPlot() p1.setYRange(0, 5, padding=0) curva1 = p1.plot() datos = [0.0] data = [0.0] fdatos1 = [0.0] y1 = np.zeros(1000, dtype=float) raw = serial.Serial('COM6', 9600) raw.close() raw.open() m = 0 def update(): global curva1, curva2, curva3, m, y1, fdatos1 with serial_lock: datos1 = raw.readline().decode('utf-8') #datos1 = datos.split(',') fdatos1[0]= float(datos1) y1[m] = fdatos1[0] if m == 999: y1 = np.zeros(1000, dtype=float) m = 0 else: m += 1 curva1.setData(y1) app.processEvents() timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(0) if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 0
downvote count: 0
tagged with: python

http://stackoverflow.com/q/50033119
has answer: http://stackoverflow.com/a/50033139
downvote count: 0
has title: How to sum the quantity grouped by more than one field?
linked to: http://stackoverflow.com/q/50297859
favorite count: 0
has body: How do i sum the 'qty' field grouped by [pid][sid][eid][dbid] fields: d = [ {'pid': 146, 'sid': 6, 'eid': 6212, 'dbid': 1, 'qty': 10}, {'pid': 146, 'sid': 6, 'eid': 6212, 'dbid': 1, 'qty': 20}, {'pid': 232, 'sid': 56, 'eid': 6212, 'dbid': 1, 'qty': 1}, {'pid': 232, 'sid': 56, 'eid': 6212, 'dbid': 1, 'qty': 1}, {'pid': 146, 'sid': 56, 'eid': 6212, 'dbid': 1, 'qty': 100}, {'pid': 146, 'sid': 56, 'eid': 6212, 'dbid': 1, 'qty': 100}, ] # non-working code sum_of_qty = [] for row in d: sum_of_qty[[row['pid']][row['sid']][row['eid']][row['dbid']]] += row['qty'] This is the final result i want: sum_of_qty = [ {'pid': 146, 'sid': 6, 'eid': 6121, 'dbid': 1, 'qty': 30}, {'pid': 232, 'sid': 56, 'eid': 6121, 'dbid': 1, 'qty': 2}, {'pid': 146, 'sid': 56, 'eid': 6121, 'dbid': 1, 'qty': 200} ]
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50033233
accepted answer: http://stackoverflow.com/a/50033139
has answer: http://stackoverflow.com/a/50033408
has answer: http://stackoverflow.com/a/50033233
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.4
answer count: 3
upvote count: 2

http://stackoverflow.com/comment/87103572
type: Comment
comment on: http://stackoverflow.com/q/50043664
has text: did googling not work? You can compile your python program into an exe then setting it should work fine
score: 0
type: QuestionComment

http://stackoverflow.com/a/50061878
has comment: http://stackoverflow.com/comment/87140439
type: Answer
has comment: http://stackoverflow.com/comment/87140934
has comment: http://stackoverflow.com/comment/87140823
has comment: http://stackoverflow.com/comment/87141238
score: 2
upvote count: 3
has body: An alternative to defaultdict is to use the .setdefault method of a plain dict. lst = [ ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'B1'], ['B', 'C1'], ['C', 'B2'], ['C', 'C2'], ['C', 'D2'], ] dic = {} for key, val in lst: dic.setdefault(key, []).append(val) print(dic) output {'A': ['B', 'C', 'D'], 'B': ['B1', 'C1'], 'C': ['B2', 'C2', 'D2']} This will preserve the order of the values in all versions of Python, and in Python 3.6+ it will also preserve the order of the keys.
answers question: http://stackoverflow.com/q/50061664
has comment: http://stackoverflow.com/comment/87140855
downvote count: 1
has comment: http://stackoverflow.com/comment/87140987
has comment: http://stackoverflow.com/comment/87141015

http://stackoverflow.com/a/50014545
has comment: http://stackoverflow.com/comment/87059352
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50010843
upvote count: 1
has comment: http://stackoverflow.com/comment/135290739
type: Answer
has body: It looks like you just need to loop through the end event for all row elements and do something with the attributes: from xml.etree.ElementTree import iterparse for evt, elem in iterparse('data/Users.xml', events=('end',)): if elem.tag == 'row': user_fields = elem.attrib print(user_fields) This will output: {'DisplayName': 'Community', 'Views': '649', 'DownVotes': '924377', 'LastAccessDate': '2008-08-26T00:16:53.810', 'Id': '-1', 'WebsiteUrl': 'http://meta.stackexchange.com/', 'Reputation': '1', 'Location': 'on the server farm', 'UpVotes': '245983', 'CreationDate': '2008-07-31T00:00:00.000', 'AboutMe': "&lt;p&gt;Hi, I'm not really a person.", 'AccountId': '-1'}
accepted answer of: http://stackoverflow.com/q/50010843
has comment: http://stackoverflow.com/comment/87079241
score: 1

http://stackoverflow.com/a/50038323
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50037992
score: 2
has body: If your real data also has alternating strings and integers, like your example, you can just iterate in steps of size 2, starting with the second element: values = ['filename1', 1696, 'filename2', 5809, ...] max(values[1::2]) # 5809 Note that this slicing creates a new list (so depending on the size of the original list it might be very large).

http://stackoverflow.com/comment/86980934
type: QuestionComment
comment on: http://stackoverflow.com/q/49976095
has text: OK, so your question has nothing to do with Python or ftplib. So it's off-topic on Stack Overflow. Consider moving it to [su].
score: 0
type: Comment

http://stackoverflow.com/q/49944747
has comment: http://stackoverflow.com/comment/86908612
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/24793351
tagged with: database
tagged with: django
has answer: http://stackoverflow.com/a/49946533
tagged with: python
has title: How to create python script to add row inside database in Django
has body: I tried to run this script but definitely something missing here... mysite this is the app, School is the class from mysite.models import School school1 = School(name='Oxford school', address='Shole St.33', email='ox-scholl@gmail.com', phone_number='3445348910') school1.save() And get this error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
has comment: http://stackoverflow.com/comment/86907862
has comment: http://stackoverflow.com/comment/86907333
has comment: http://stackoverflow.com/comment/86906239
score: 0
answer count: 1
type: Question

http://stackoverflow.com/a/50041208
has body: You can feed a list of dictionaries directly into pandas and then manipulate: df = pd.DataFrame(lst) res = df.pivot_table(index='hour', columns='dayname', values='avg', aggfunc=np.sum)\ .reset_index() res.columns.name = '' print(res) hour Friday Saturday 0 9 52 12 1 10 1 30 2 11 12 66 3 12 3 45
answers question: http://stackoverflow.com/q/50040989
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/50044447
type: Question
has comment: http://stackoverflow.com/comment/87481774
has answer: http://stackoverflow.com/a/50045382
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50044699
has answer: http://stackoverflow.com/a/50044563
has title: remove element in nested dict by list of keys
tagged with: python
linked to: http://stackoverflow.com/q/24217647
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87105198
answer count: 4
has answer: http://stackoverflow.com/a/50044557
linked to: http://stackoverflow.com/q/14692690
score: 0
has comment: http://stackoverflow.com/comment/87105220
has body: I have a nested dictionary structure like so: dataDict = { "a":{ "r": 1, "s": 2, "t": 3 }, "b":{ "u": 1, "v": { "x": 1, "y": 2, "z": 3 }, "w": 3 } } with a list of keys: maplist = ["b", "v", "y"] I want to remove the item in the dict that the maplist is pointing to. Any suggestions?
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50051924
has body: just need help to deploy recursive category algorhitm. I have this dataframe ID, PRICE, CAT_NAME, PARENT_CAT_NAME,TITLE 1, 25€, RED_WINE, WINES, Red wine from .... 2, 15€, BLACK_WINE,WINES, Nice black wine 3, 10€,WINES,DRINKS, Generic white wine... 4, 10, WOMEN_TSHIRT, WOMEN, Summer women T-Shirt 5, 10, WOMEN, DRESSES, Women winter dress ok now i would like to generate a dynamic algorithm to recreate dataframe with full path CATEGORIES in diferent columns For example final data set looks like this. ID,PRICE,CAT_1,CAT_2,CAT_3 ... CAT_X, TITLE 1, 25€, DRINKS,WINES,RED_WINE,...NULL Red wine from.. 2, 14€, DRINKS,WINES,BLACK_WINES,...NULL, Nice black wine... 3, 10€, DRINKS,WINES, NULL,...NULL Generic white wine... etc... Note on all data set i can have X inherithed categories this is some items have 3 categories and some item could have 5 or more sub categories.. for example if maxim inherited parent category is 10 then we need 10 new CAT_X columns on dataframe and set null. On Wine example could look like this DRINKS,WINES;RED_WIN,NULL,NULL,NULL,NULL,NULL... Im not a python expert and i apreciate you help or some coding idea. Thanks!
tagged with: pandas
has comment: http://stackoverflow.com/comment/87120500
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87120373
has title: Python dataframe algorithm parent category
score: 0

http://stackoverflow.com/a/50048431
type: Answer
answers question: http://stackoverflow.com/q/49956003
downvote count: 0
has body: There are shell commands for accessing the Mac Pasteboard: pbcopy and pbpaste. You can use them in python with os.system or subprocess. Here's another answer for using shell commands in python.
upvote count: 1
score: 1

http://stackoverflow.com/comment/86891302
type: Comment
comment on: http://stackoverflow.com/a/49937806
score: 0
type: AnswerComment
has text: Calling `super().__init__()` is actually good practice as it calls the `__init__()` method of the base class. `super(program)` won't do anything at all.

http://stackoverflow.com/comment/87159719
comment on: http://stackoverflow.com/q/50071515
has text: Use `argparse.sub_parser`: https://docs.python.org/3.6/library/argparse.html#sub-commands
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49996618
tagged with: recursion
tagged with: list
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87016606
favorite count: 0
has body: I have a use case where I need to traverse a dict (which could have strings, dicts and lists as nested values) and create a new one based on predefined mappings by my business team. My first implementation was straightforward when the requirements were: 1:1 transformations drop some key value pairs My code looked something like this: def recursively_transform(parent_keys='', current_key='', container=None): container_class = container.__class__ new_container_value = None if container is not None: if isinstance(container, basestring): new_container_value = do_something_and_return(parent_keys, current_key, container) if current_key in mapping: populate(parent_keys + current_key, new_container_value) elif isinstance(container, collections.Mapping): if parent_keys: parent_keys = ''.join([parent_keys, ":"]) new_container_value = container_class( (x, recursively_transform(parent_keys + x, x, container[x])) for x in container if key_required(parent_keys, current_key)) elif isinstance(container, collections.Iterable): new_container_value = container_class(recursively_transform( parent_keys + "[]", current_key, x) for x in container) else: raise Exception("") return new_container_value As you can see, within the method do_something_and_return, using the parameters parent_key and current_key, I do some transformation on the value and return new one. The steps for each parent_keys plus current_key combination is specified in an external mappings database. But, now, the requirement has changed to have complex transformations (not 1:1 anymore). i.e, inside my mappings database, the new path for the key will be specified. This could be any structure. For eg, key/value pairs have to be flattened, many times the reverse has to happen, sometimes there wouldn't be any direct correspondence between them. Examples, key1:key2:[]:key3 =&gt; key2:[]:key3 key1:key2:[]:key4 =&gt; key2:[]:key5 which means that an input dict like this: {key1:{key2:[{key3: "value3", key4: "value4"}, {key3:None…
has title: Python transform dict recursively based on predefined mappings
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/87014356
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50120040
tagged with: dictionary
answer count: 1
has comment: http://stackoverflow.com/comment/87016597

http://stackoverflow.com/q/50041473
has title: Stopping a while cycle modifying its condition (flag) from another python program
has comment: http://stackoverflow.com/comment/87098947
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50046575
tagged with: raspberry-pi3
upvote count: 1
tagged with: python
has body: i am programming in python on a Raspberry Pi 3 and i have the following problem: Raspberry has a temperature sensor and its data is printed on terminal by a simple module #!/usr/bin/python import sys import Adafruit_DHT flag = True while flag: humidity, temperature = Adafruit_DHT.read_retry(11, 4) print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity) i need to stop the cycle from another module, setting the flag to a False value. How can i do this? I need to have this possibility even from a button on an android application...a nonblocking queue would be the best fit, but i haven't found nothing similar on Pika documentation. Anyone could give me some help? Thanks in advance.
favorite count: 0
tagged with: python-2.7
score: 1
linked to: http://stackoverflow.com/q/1977362
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/comment/86889725
comment on: http://stackoverflow.com/q/49932998
type: QuestionComment
has text: This is strange. I would expect the package to be documented for both HTML and PDF versions or for neither, but not for only HTML. Have you tried building PDF locally? I did notice a few warnings in the [build log](https://readthedocs.org/projects/sensormotion/builds/7070401/) by clicking each item, but nothing stands out. Your `conf.py` looks fine, too. Compare to the [default Sphinx `conf.py`](http://www.sphinx-doc.org/en/1.6/config.html).
type: Comment
score: 0

http://stackoverflow.com/q/49947767
tagged with: celery
favorite count: 0
linked to: http://stackoverflow.com/q/31188499
accepted answer: http://stackoverflow.com/a/49952464
type: Question
has title: Pass QuerySet to Celery Task in Django 1.11
score: 3
has answer: http://stackoverflow.com/a/49952464
tagged with: django
tagged with: pickle
tagged with: python
linked to: http://stackoverflow.com/q/34765276
type: AnsweredQuestion
upvote count: 3
has body: I want to move some long query to the async task in Celery and next retrieve that extra-info with AJAX. Now I get QuerySet like this: brands = Brand.objects.filter(shops__shop_name__in=[shop]) Task: @task() def brand_count(querystr): querystr.annotate(amount_of_products=Count('products')) I want to do like here: task_run = brand_count.delay(brands) The question is: How to pass a QuerySet to Celery task? Now it throws an error that this couldn't be done. I have found that pickle might be used here, but I can't get the right way to use it. Specially - what does # Assuming 's' is the pickled string. in query = pickle.loads(s) mean.
answer count: 1
downvote count: 0
tagged with: asynchronous

http://stackoverflow.com/comment/86989705
score: 0
type: Comment
type: QuestionComment
has text: @Wen due to the weird nested list with ndarray (with a nested array inside), pd.DataFrame(a) smashes everything into the same column.
comment on: http://stackoverflow.com/q/49986647

http://stackoverflow.com/q/49964129
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86945053
has comment: http://stackoverflow.com/comment/86945049
favorite count: 0
has answer: http://stackoverflow.com/a/78034574
tagged with: mypy
has title: Why does Type[T] -> T classmethod fail in Unsupported type when the bound of T has an optional argument?
score: 1
has body: I love python's type hints, and I wrote the following script, which fails with Unsupported type Type["T"] in MyPy 0.590. from typing import Type, TypeVar AnyT = TypeVar('AnyT') T = TypeVar('T', bound='A') class A: def __init__(self, arg: AnyT = None) -&gt; None: pass @classmethod def fn(cls: Type[T]) -&gt; T: # E: Unsupported type Type["T"] return cls() Why this causes an error? In typical use case, AnyT equals to T and __init__(self, other) copies the other to self. Note that following slightly different programs have no errors: from typing import Type, TypeVar T = TypeVar('T', bound='A') class A: def __init__(self, arg: int = None) -&gt; None: pass @classmethod def fn(cls: Type[T]) -&gt; T: # No errors return cls() and from typing import Type, TypeVar AnyT = TypeVar('AnyT') T = TypeVar('T') # no bounds class A: def __init__(self, arg: AnyT = None) -&gt; None: pass @classmethod def fn(cls: Type[T]) -&gt; T: # No errors return cls() And also note that the following solution does not work for me: from typing import TypeVar AnyT = TypeVar('AnyT') class A: def __init__(self, arg: AnyT = None) -&gt; None: pass @classmethod def fn(cls) -&gt; 'A': # Obviously no errors return cls() That is because this does not consider the inheritance of A (if a class B inherits from A, B.fn() will return the instance of B, but MyPy thinks it returns that of A in this example). Any ideas?
tagged with: type-hinting
tagged with: python
tagged with: class
type: Question
linked to: http://stackoverflow.com/q/44640479

http://stackoverflow.com/comment/87140274
comment on: http://stackoverflow.com/q/50057243
type: QuestionComment
has text: I have checked and seen that every single value inputted into the equation is an integer (which it should be). You mentioned that commits are for updates, so say I have a hotness value of `None` could I use an update command to update the value to an integer using the above equation? I think using the SELECT keyword was a mistake on my part.
score: 0
type: Comment

http://stackoverflow.com/comment/86929614
type: AnswerComment
has text: Thank you @grand_chat. The option '\n'.join(text ) did the magic. I had used .join() before but apparently I was not using it in the right segment. Thank you and God bless.
type: Comment
comment on: http://stackoverflow.com/a/49952698
score: 0

http://stackoverflow.com/q/49925116
favorite count: 0
type: Question
has body: all, I have a dataframe which I have grouped and sorted and that looks like this brkrcy=data[data['upload_date']==Date].groupby(['CPTY','currency'], as_index=False).agg({"Gross Loan Amount": "sum"}) brkrcy=brkrcy.sort_values(by=['CPTY', 'Gross Loan Amount'], ascending=[True, False]) brkrcy = brkrcy.set_index('CPTY') Double Ranking currency Gross Loan Amount CPTY BARC RUB 2.178780e+07 BARC ZAR 7.779714e+07 BARC JPY 1.227676e+09 BARC EUR 3.301354e+09 BARC GBP 5.002534e+09 BARC USD 6.667446e+09 BMON CAD 2.018614e+08 BMON GBP 4.096820e+08 BMON USD 6.510318e+08 BNP CAD 2.349053e+08 BNP JPY 1.523716e+09 BNP GBP 3.234833e+09 BNP USD 4.576760e+09 BNP EUR 4.935927e+09 CALIP EUR 1.832390e+07 CALIP USD 1.448161e+09 CALIP GBP 3.492144e+09 CANTR USD 3.987880e+08 CIBC CAD 6.851792e+08 CIBC GBP 8.861776e+08 CITI CZK 7.549203e+06 brkrcy.set_index('currency',append=True)['Gross Loan Amount'].unstack().plot(kind="bar",stacked=True,figsize=(10,8)) plt.ylabel('Gross Loan Amount in Billions') plt.show() As you can see although it is double ranking, the stacked bar plot is not ranked in descending order. How can I change that please?
tagged with: python-3.x
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49944258
has comment: http://stackoverflow.com/comment/86874473
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pandas
has title: ranking a stacked Bar plot
accepted answer: http://stackoverflow.com/a/49944258
answer count: 1
downvote count: 0
tagged with: cptbarplot
has comment: http://stackoverflow.com/comment/86886674

http://stackoverflow.com/q/50051606
has comment: http://stackoverflow.com/comment/87125644
has answer: http://stackoverflow.com/a/50054551
tagged with: python
accepted answer: http://stackoverflow.com/a/50054551
has title: Move a file with Python
tagged with: movefile
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50051833
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87120047
answer count: 3
has answer: http://stackoverflow.com/a/50051765
possible better answer: http://stackoverflow.com/a/50051765
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87119870
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/10575750
has comment: http://stackoverflow.com/comment/87125638
has body: I want to move a file and I'm having the following bug: Traceback (most recent call last): File "G:\Programming\Hack\scripts\# cut file.py", line 4, in &lt;module&gt; shutil.move(src, dst) File "C:\Program Files 1\Python2\lib\shutil.py", line 316, in move copy2(src, real_dst) File "C:\Program Files 1\Python2\lib\shutil.py", line 144, in copy2 copyfile(src, dst) File "C:\Program Files 1\Python2\lib\shutil.py", line 97, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: 'E:\\windows.information.exe' my script: import shutil src = "C:\\Users\\Michael\\Desktop\\windows.information.exe" dst = "E:\\" shutil.move(src, dst) My main problem: IOError: [Errno 13] Permission denied: 'E:\\windows.information.exe

http://stackoverflow.com/q/49930667
upvote count: 1
possible better answer: http://stackoverflow.com/a/49932187
accepted answer: http://stackoverflow.com/a/49935770
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49932187
has answer: http://stackoverflow.com/a/49935770
has title: Django Selenium click button on ajax modal pop-up window
tagged with: django
tagged with: python
has body: I'm currently doing some task for my university. I'm writing Django Selenium tests for my app. I'm trying to write test for deleting object. They key parts of my code are: delete confirmation.html &lt;form action="" method="post" id="confirmForm"&gt;{% csrf_token %} &lt;p&gt;{% trans "Are you sure you want to delete this car?" %}&lt;/p&gt; &lt;input class="center-block btn btn-danger" type="submit" value="{% trans 'Confirm' %}"/&gt; &lt;/form&gt; modal.js function showModal(url) { $("#myModalBody").text(); $("#myModal").modal(); $.ajax({ url, cache: false }).done(function (html) { $("#myModalBody").html(html); $("#confirmForm").attr('action', url); }); } When I click following button &lt;button class="btn btn-primary btn-sm pull-left" value="" id="car-delete-modal-btn m-10-b" onclick="showModal('{% url 'c2crental:delete_car' details_car.id %}');"&gt;{% trans "Delete car" %}&lt;/button&gt; Modal appears And test stops with result: Unable to locate element. I was trying to use different selectors but none of them worked. For now test looks like this: # click 'delete' button to display popup confirmation window delete_btn = self.selenium.find_element_by_id('car-delete-modal-btn m-10-b') delete_btn.click() # click 'confirm' to delete object in popup window submit = 'input[type="submit"]' confirm_btn = self.selenium.find_element_by_id(submit) confirm_btn.click() I just can't seem to find proper selector for this button or it's a problem with a synchronization. Can someone help me fix it? Sorry for my broken english and i hope you will understand what I'm trying to do here but I'm just starting with Django, tests, programming in general so not everything is clear.
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 2
score: 1
tagged with: modal-dialog
downvote count: 0
tagged with: selenium

http://stackoverflow.com/a/49918805
has comment: http://stackoverflow.com/comment/86853875
type: Answer
has comment: http://stackoverflow.com/comment/86853736
has body: My approach would be converting the contents to a list splitting on \n and retrieving required line by index. lines = '''line 1 line 2 line 3 line 4 line 5 line 6''' s = lines.split('\n') current_line = 'line 6' output_line = s[s.index(current_line) - 4] # line 2 Since you are reading from file, you don't need to explicitly split on \n. You could read from file as list of lines using readlines: with open('path/to/your_file') as f: lines = f.readlines() current_line = 'line 6' output_line = lines[lines.index(current_line) - 4] # line 2
has comment: http://stackoverflow.com/comment/86853907
score: 1
has comment: http://stackoverflow.com/comment/86853536
downvote count: 0
answers question: http://stackoverflow.com/q/49918701
upvote count: 1
has comment: http://stackoverflow.com/comment/86854711

http://stackoverflow.com/q/49956100
tagged with: google-console-developer
answer count: 1
favorite count: 0
has body: I have created a client_secrets.json file and written all the required fields that I got from Google API's console. Now I have a test playlist which have same description on all the videos in that playlist and I want to update that playlist with changing the description of it using Python code. I have copied the code from this link https://developers.google.com/youtube/v3/docs/playlists/update#usage provided by developers google and now I don't know what are the next steps to continue as I am new to Python programming. Can anyone guide me to run this program and update the playlists description. Thanks in Advance Here is the code that I have copied import os import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow CLIENT_SECRETS_FILE = "client_secrets.json" SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) def print_response(response): print(response) def build_resource(properties): resource = {} for p in properties: prop_array = p.split('.') ref = resource for pa in range(0, len(prop_array)): is_array = False key = prop_array[pa] if key[-2:] == '[]': key = key[0:len(key)-2:] is_array = True if pa == (len(prop_array) - 1): if properties[p]: if is_array: ref[key] = properties[p].split(',') else: ref[key] = properties[p] elif key not in ref: ref[key] = {} ref = ref[key] else: ref = ref[key] return resource def remove_empty_kwargs(**kwargs): good_kwargs = {} if kwargs is not None: for key, value in kwargs.iteritems(): if value: good_kwargs[key] = value return good_kwargs def playlists_update(client, properties, **kwargs): resource = build_resource(…
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/50066857
tagged with: youtube-data-api
tagged with: python
type: UnansweredQuestion
tagged with: python-3.x
score: 8
has title: How to update all Youtube videos description in a playlist?
tagged with: youtube-api
downvote count: 1

http://stackoverflow.com/q/50040052
score: 2
has title: installing tensorflow without internet connection
tagged with: tensorflow
favorite count: 0
has body: I have to install TensorFlow + Keras on my computer, but I have not internet connection on it, so I have to download this package on another computer and then pass it on mine. My question is: where can I saefty downolad TensorFlow + Keras and then, how can I install it using Anaconda? Thanks a lot for helping!
has comment: http://stackoverflow.com/comment/87096437
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50041044
downvote count: 0
tagged with: python
type: UnansweredQuestion
tagged with: keras
answer count: 1
tagged with: installation

http://stackoverflow.com/comment/86963740
type: Comment
score: 0
has text: I think he's trying to say that if s.unique() == [nan, 0], THEN fillna(0), otherwise no
type: AnswerComment
comment on: http://stackoverflow.com/a/49973838

http://stackoverflow.com/comment/86988389
has text: https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list
comment on: http://stackoverflow.com/q/49985976
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50002551
type: Answer
has body: In your for loop this lines: data['title'] = container.h2.text data['author'] = container.p.text data['link'] = "https://open.umn.edu/opentextbooks/" + container.h2.a["href"] reset the value of the dictionary on each iteration of the loop. What I would advise you to do is to make them a list like so: data['title'] = [] data['author'] = [] data['link'] = [] and then in your for loop have data["title"].append(container.h2.text) data["author"].append(container.p.text) data["link"].append("https://open.umn.edu/opentextbooks/" + container.h2.a["href"]) that would save all of the found containers, and you should see everything in your JSON file. Hope this helps!
answers question: http://stackoverflow.com/q/50002465
score: 0

http://stackoverflow.com/q/49929668
type: AnsweredQuestion
score: 1
tagged with: qradiobutton
type: Question
tagged with: pyqt
tagged with: pyqt4
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86875648
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86875854
accepted answer: http://stackoverflow.com/a/49930079
has title: Disable and enable radiobuttons from another radiobutton in PyQt4 Python
favorite count: 0
has body: I have 3 radiobutton groups in forms of Yes or No. I want to disable the last 2 radiobutton groups if the first radiobutton is "No" and enable them when the first radiobutton is "Yes". I can make the enabled or disabled by default but toggling Yes/No from the first group doesn't change the result in the second and third group. Here is a summary of my code: self.yes_radioButtonGroup1 = QtGui.QRadioButton(self.centralwidget) self.yes_radioButtonGroup1.setObjectName(_fromUtf8("yes_radioButtonGroup1")) self.no_radioButtonGroup1 = QtGui.QRadioButton(self.centralwidget) self.no_radioButtonGroup1.setObjectName(_fromUtf8("no_radioButtonGroup1")) self.radioButtonGroup1= QtGui.QButtonGroup(MainWindow) self.radioButtonGroup1.setObjectName(_fromUtf8("radioButtonGroup1")) self.radioButtonGroup1.addButton(self.yes_radioButtonGroup1) self.radioButtonGroup1.addButton(self.no_radioButtonGroup1) self.yes_radioButtonGroup2 = QtGui.QRadioButton(self.centralwidget) self.yes_radioButtonGroup2.setObjectName(_fromUtf8("yes_radioButtonGroup2")) self.no_radioButtonGroup2 = QtGui.QRadioButton(self.centralwidget) self.no_radioButtonGroup2.setObjectName(_fromUtf8("no_radioButtonGroup2")) self.radioButtonGroup2= QtGui.QButtonGroup(MainWindow) self.radioButtonGroup2.setObjectName(_fromUtf8("radioButtonGroup2")) self.radioButtonGroup2.addButton(self.yes_radioButtonGroup1) self.radioButtonGroup2.addButton(self.no_radioButtonGroup1) self.yes_radioButtonGroup3 = QtGui.QRadioButton(self.centralwidget) self.yes_radioButtonGroup3.setObjectName(_fromUtf8("yes_radioButtonGroup3")) self.no_radioButtonGroup3 = QtGui.QRadioButton(self.centralwidget) self.no_radioButtonGroup3.setObjectName(_fromUtf8("no_radioButtonGroup3")) self.radioButtonGroup3= QtGui.QButtonGroup(MainWindow) self.radioButtonGroup3.setObjectName(_fromUtf8("radioButtonGroup3")) self.radioButtonGroup3.addButton(self.yes_radioButtonGroup3) self.radioButtonGroup3.addButton(self.no_radioButtonGroup3) if self.yes_radioButtonGroup1.isChecked() == …
has answer: http://stackoverflow.com/a/49930079

http://stackoverflow.com/comment/86873159
score: 0
has text: Thanks, I see expected output, but could you provide, also, input, from which you want to get that output.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49927952

http://stackoverflow.com/q/49989579
has answer: http://stackoverflow.com/a/49993133
type: Question
has answer: http://stackoverflow.com/a/49989672
possible better answer: http://stackoverflow.com/a/49989672
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/51086120
accepted answer: http://stackoverflow.com/a/51086120
answer count: 4
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50006156
has title: What is the simplest way to convert a Dataset object to a Pandas DataFrame?
tagged with: orm
tagged with: dataset
has body: The Python Dataset module is based on Sqlalchemy and exposes a function to return all records in a table called all(). all() returns an iterable Dataset object. users = db['user'].all() for user in db['user']: print(user['age']) What is the simplest way to convert a Dataset object to a Pandas DataFrame object? For clarity, I am interested in utilizing Dataset's functionality as it has already loaded the table into a Dataset object.
tagged with: sqlalchemy

http://stackoverflow.com/comment/87325069
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50151855
type: Comment
has text: Hi, thanks. I know how to "solve" this by coding. I don't want to do this. Because that requires that I know the precision of the underlying data. There are hundreds of tables and thousands of columns, with different precision in the databases I work on, and I dont want to keep track of all of them,

http://stackoverflow.com/comment/86871791
comment on: http://stackoverflow.com/q/49927660
score: 0
type: Comment
type: QuestionComment
has text: `df["b"].astype("int64")` will result in `ValueError: Cannot convert non-finite values (NA or inf) to integer`. I could convert to `"object"`, but I wasn't sure how to proceed from there without manually iterating over each value, checking if it was equal to `NaN`, and casting it conditionally.

http://stackoverflow.com/a/50024048
score: 9
upvote count: 9
type: Answer
has body: The answer I found is: import matplotlib.dates as mdates import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) plt.plot(date, price , label="Price") ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
downvote count: 0
answers question: http://stackoverflow.com/q/49975878

http://stackoverflow.com/comment/91995494
has text: can you show your configuration for pypi?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50035420
type: QuestionComment

multithreading
tags question: http://stackoverflow.com/q/49927635
tags question: http://stackoverflow.com/q/50045500
tags question: http://stackoverflow.com/q/49992329
type: Tag
tags question: http://stackoverflow.com/q/50029648
tags question: http://stackoverflow.com/q/49922221
tags question: http://stackoverflow.com/q/50010615
tags question: http://stackoverflow.com/q/49920154
tags question: http://stackoverflow.com/q/49947814
tags question: http://stackoverflow.com/q/49919348
tags question: http://stackoverflow.com/q/50066868
tags question: http://stackoverflow.com/q/49930725
tags question: http://stackoverflow.com/q/49932548
tags question: http://stackoverflow.com/q/50054527
tags question: http://stackoverflow.com/q/49947443
tags question: http://stackoverflow.com/q/49967109
tags question: http://stackoverflow.com/q/50017405
tags question: http://stackoverflow.com/q/50024296
tags question: http://stackoverflow.com/q/49939489
tags question: http://stackoverflow.com/q/50003947
tags question: http://stackoverflow.com/q/50065913
tags question: http://stackoverflow.com/q/50026368
tags question: http://stackoverflow.com/q/50017494
tags question: http://stackoverflow.com/q/49928261
tags question: http://stackoverflow.com/q/49987110
tags question: http://stackoverflow.com/q/49974429
tags question: http://stackoverflow.com/q/49971309
tags question: http://stackoverflow.com/q/50009396
tag name: multithreading
tags question: http://stackoverflow.com/q/49921844
tags question: http://stackoverflow.com/q/50012835
tags question: http://stackoverflow.com/q/49921099

http://stackoverflow.com/comment/86891876
type: QuestionComment
has text: When nothing is extracted it means your pattern doesn't exist in file or regex is not properly written. You should add a sample input to your question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49938058

http://stackoverflow.com/comment/87092163
type: Comment
comment on: http://stackoverflow.com/a/50037501
score: 0
type: AnswerComment
has text: That's okay can we do this scheduling through batch script? Basically i don't want to deal with GUI. If i run a simple batch script will it able to schedule task? any idea ? @BoarGules

http://stackoverflow.com/q/50040285
has comment: http://stackoverflow.com/comment/87098044
tagged with: python-3.x
score: 0
upvote count: 2
has title: Python 3: Represent bytestring as a string (without decoding)
downvote count: 2
has answer: http://stackoverflow.com/a/50040688
has comment: http://stackoverflow.com/comment/87097726
has comment: http://stackoverflow.com/comment/87097323
has answer: http://stackoverflow.com/a/50040812
has comment: http://stackoverflow.com/comment/87097089
has comment: http://stackoverflow.com/comment/87097048
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76398119
has comment: http://stackoverflow.com/comment/87096635
has body: Is there a builtin way to "convert" a bytestring to a unicode string? I don't want to decode it, I want the string i see on print without the "b". e.g. Input: b'\xb5\xb5\xb5\xb5\r\n1' output: '\xb5\xb5\xb5\xb5\r\n1' I've tried iterating over the byte string, but that gives me a list of integers: my_bytestring = b'%PDF-1.4\n%\x93\x8c\x8b\x9e' my_string = "" my_list = [] for char in my_bytestring: my_list.append(char) my_string += str(char) print(my_list) # -&gt; list of ints print(my_string) # -&gt; string of converted ints I get: [37, 80, 68, 70, 45, 49, 46, 52, 10, 37, 147, 140, 139, 158] I want: ['%', 'P', 'D', 'F', '-', '1', '.', '4', '\\', 'n', '%', '\\', 'x', '9', '3', '\\', 'x', '8', 'c', '\\', 'x', '8', 'b', '\\', 'x', '9', 'e']
answer count: 3
accepted answer: http://stackoverflow.com/a/50040688
has comment: http://stackoverflow.com/comment/87097351
possible better answer: http://stackoverflow.com/a/50040812
has comment: http://stackoverflow.com/comment/87097238
tagged with: python
linked to: http://stackoverflow.com/q/7262828
has comment: http://stackoverflow.com/comment/87096838
type: Question

http://stackoverflow.com/comment/87058630
comment on: http://stackoverflow.com/q/50006314
has text: OK... when you say *Python is still using the newer version*, which Python? Are you using it in an IDE and if so how have you ensured it's using the Python interpreter from the right env?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50015458
tagged with: post-processing
tagged with: python
has body: I am working on 3-D numpy array in python and want to do post-processing on CNN output of Brain Tumor Segmentation images. We get a 3-D (208x208x155) numpy array with values as 0/1/2/4 for each pixel. I want to remove the connected components with a threshold less than 1000 for better results. I tried erosion-dilation but don't get good results. Can anyone help me?
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has title: Remove connected components below a threshold in a 3-d array
answer count: 1
favorite count: 0
type: Question
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/50016182
accepted answer: http://stackoverflow.com/a/50016182

http://stackoverflow.com/q/49953345
has comment: http://stackoverflow.com/comment/86923591
answer count: 0
has comment: http://stackoverflow.com/comment/86923184
has comment: http://stackoverflow.com/comment/86936997
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86963339
tagged with: python
has body: I load a Candide3D model self.drawFace(vertices) and load a hat 3D model glCallList(obj.gl_list), but when I change the z position of the hat, it never stay on the Candidie3 model. I also changed the gluPerspective(50,self.w/float(self.h), 1 , 250.0) camera matrix but, in almost every case the hat render in front of Candide3 model. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() setOrtho(self.w, self.h) glEnable(GL_DEPTH_TEST) glEnable(GL_TEXTURE_2D) glDepthMask(GL_FALSE) self.drawFace(vertices) glDepthMask( GL_TRUE ) ######## render next model ########## glLightfv(GL_LIGHT0, GL_POSITION, (-40, 50, 100, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (0.2, 0.2, 0.2, 1.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.5, 0.5, 0.5, 1.0)) glEnable(GL_LIGHT0) glEnable(GL_LIGHTING) glEnable(GL_COLOR_MATERIAL) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(50,self.w/float(self.h), 1 , 250.0) glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glBindTexture(GL_TEXTURE_2D, self.texture_image2) glTranslate(self.tx,self.ty,-40) self.tx,self.ty=self.track(shape2D) glRotate(ry, 1, 0, 0) glPushMatrix() glCallList(obj.gl_list) glPopMatrix() glEnable(GL_TEXTURE_2D)
score: 0
has title: How to render two object in same z position in Open Gl?
tagged with: opengl
has comment: http://stackoverflow.com/comment/86967033
has comment: http://stackoverflow.com/comment/86937476
has comment: http://stackoverflow.com/comment/86924413
has comment: http://stackoverflow.com/comment/86931664
type: Question

http://stackoverflow.com/a/50053050
accepted answer of: http://stackoverflow.com/q/50052940
type: Answer
has comment: http://stackoverflow.com/comment/87122554
has comment: http://stackoverflow.com/comment/87122572
answers question: http://stackoverflow.com/q/50052940
has comment: http://stackoverflow.com/comment/87122534
score: 0
type: AcceptedAnswer
has body: This is what you can do to simplify your logic: import pandas as pd df = pd.DataFrame({'Date': ['2012-10-30', '2012-10-30', '2012-10-30', '2012-10-31', '2017-10-31'], 'Home': ['Toronto Raptors', 'Los Angeles Lakers', 'Miami Heat', 'Sacramento Kings', 'Sacramento Kings']}) df['Date'] = pd.to_datetime(df['Date']) d = {'Toronto Raptors': 'Air Canada Centre', 'Los Angeles Lakers': 'Staples Center', 'Miami Heat': 'American Airlines Arena'} # general criteria df['Arena'] = df['Home'].map(d) # custom criteria df.loc[(df['Home'] == 'Sacramento Kings') &amp; (df['Date'].dt.year &lt; 2016), 'Arena'] = 'Sleep Train Arena' df.loc[(df['Home'] == 'Sacramento Kings') &amp; (df['Date'].dt.year &gt;= 2016), 'Arena'] = 'Golden 1 Center' print(df) Date Home Arena 0 2012-10-30 Toronto Raptors Air Canada Centre 1 2012-10-30 Los Angeles Lakers Staples Center 2 2012-10-30 Miami Heat American Airlines Arena 3 2012-10-31 Sacramento Kings Sleep Train Arena 4 2017-10-31 Sacramento Kings Golden 1 Center
has comment: http://stackoverflow.com/comment/87123487

http://stackoverflow.com/comment/86862803
has text: Why are you making a graphQL query from a inside Django view?
score: 0
comment on: http://stackoverflow.com/q/49918978
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49956316
answers question: http://stackoverflow.com/q/49956302
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: I think need left join in merge: df = df1.merge(df2,how='left', left_on='Username', right_on=0) print (df) Username User_trim 0 1 2 0 Maria M Maria Maria M Maria female 1 FakeName NaN NaN NaN NaN 2 Achim B Achim Achim B Achim male 3 FlashMaster11 NaN NaN NaN NaN 4 Fakename2 NaN NaN NaN NaN 5 Gustav W Gustav Gustav W Gustav male Solution if need append new column(s) by merge without remove unnecessary columns is first rename at least one column use for join (here Username in both DataFrames) and then select all necessary columns (always join column + all another new columns): df22 = df2.rename(columns={0:'Username', 2:'Gender'})'Username', 'Gender' print (df22) Username Gender 0 Maria M female 1 Achim B male 2 Gustav W male df = df1.merge(df22,how='left', on='Username') print (df) Username User_trim Gender 0 Maria M Maria female 1 FakeName NaN NaN 2 Achim B Achim male 3 FlashMaster11 NaN NaN 4 Fakename2 NaN NaN 5 Gustav W Gustav male If need add only one new column use map by Series created by set_index: df1['Gender'] = df1['Username'].map(df2.set_index(0)[2]) print (df1) Username User_trim Gender 0 Maria M Maria female 1 FakeName NaN NaN 2 Achim B Achim male 3 FlashMaster11 NaN NaN 4 Fakename2 NaN NaN 5 Gustav W Gustav male

http://stackoverflow.com/q/50003959
answer count: 1
has comment: http://stackoverflow.com/comment/87024321
has comment: http://stackoverflow.com/comment/87024401
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50004101
score: 0
has body: I want to get particular value of a key such as agentName in below json format in python. How can this be done? { "metaData": { "fields": [ "id", "path", "time", "userid", "type", "size", "lastProcessed", "numProcessed" ], "queueStatus": { "agentId": "publish-xxxxx", "agentName": "publish-xxxxx", "isBlocked": false, "isPaused": false, "lastProcessTime": -1, "nextRetryPeriod": -1524578525793, "processingSince": -1, "time": 1524578525792 }, "root": "queue" }, "queue": [] }
tagged with: http://stackoverflow.com/tag/json
has title: How to get particular value of a key in below json format in python
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87024456
has answer: http://stackoverflow.com/a/50004101

http://stackoverflow.com/q/50038442
has body: import time import os import math import string from random import * def hasNumbers(inputString): return any(char.isdigit() for char in inputString) print("Password checker") password = input("Enter password: ") if len(password) &gt; 8: if password[0].isupper(): if hasNumbers(password): print("Password is secure!") else: print("Password not strong enough!") If I put "BobBob123" it sais "Password is secure!" which is fine. If I put bob it goes to the else. If I put "Bob123" it doesn't show anything.
accepted answer: http://stackoverflow.com/a/50038506
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50038506
answer count: 2
downvote count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/50038526
has comment: http://stackoverflow.com/comment/87093051
favorite count: 0
has answer: http://stackoverflow.com/a/50038526
type: Question
tagged with: python
score: -2
has title: Python how can I make all if's lead to the else

http://stackoverflow.com/comment/87161670
has text: have you checked the path of top.html and the directories you've listed in the settings.py file to look for templates?
score: 0
comment on: http://stackoverflow.com/q/50072475
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49925067
has comment: http://stackoverflow.com/comment/86866588
has comment: http://stackoverflow.com/comment/86866516
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86866689
has comment: http://stackoverflow.com/comment/86866122
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86866735
has body: ("General Kenobi") Working with the tkinter module of python, I'm trying to recreate a quite complex graphical interface from something existing in VB. Everything was okay until I decided to make things a little more nice and clean with an initialization function including global variables. Since, every single PanedWindow won't show. This is my initialization function : def init(): Tk().withdraw() global DL_COM1_NAME DL_COM1_NAME = StringVar() And the main function with the graphical stuff : def frame_Menu(init): init() # graphical user interface (GUI) # main frame main_frame = Tk() ... DL_COM_Panel1 = PanedWindow(orient='horizontal') DL_COM1 = Label(DL_COM_Panel1,bg='light slate blue',fg='white',font=('Arial','10','bold'),text='first :',anchor='w',relief='sunken',width=8) DL_COM_Panel1.add(DL_COM1) DL_COM1_Choice = Entry(DL_COM_Panel1,textvariable=DL_COM1_NAME,width=90) DL_COM_Panel1.add(DL_COM1_Choice) DL_COM1_Select = Button(DL_COM_Panel1,text='Browse',command=set_COM1filename) DL_COM_Panel1.add(DL_COM1_Select) DL_COM_Panel1.grid(row=7,column=0,columnspan=4,sticky='we',padx=(15,15),pady=(2.5,2.5)) ... main_frame.mainloop() The set_COM1filename function I'm using in "command" asks for a file by askopenfilename. The PanedWindow I defined here won't open, and it's the same for every other ones, while everything was working with local variables. Furthermore, when I use the command prompt to run this, the process doesn’t stop when I click the quit button of my interface. Do you have any idea of the reason ? Thank you very much
score: 0
has comment: http://stackoverflow.com/comment/86866438
answer count: 0
has title: PanedWindow and global variables
has comment: http://stackoverflow.com/comment/86886005
type: Question

http://stackoverflow.com/q/50066704
score: 0
has body: I was working on a program testing the .pack_forget() command in TKinter, but encountered a problem. I had a time.sleep() command in my code, and the TKinter window will not open until the time.sleep() command has been executed in IDLE. Here is my code: from tkinter import * import time main = Tk() main.title("Test") myLabel = Label(main, text="I'm a Label", fg="black") myLabel.pack() time.sleep(3) myLabel.pack_forget() If you know why this issue is occurring, please answer.
answer count: 1
type: Question
tagged with: python-3.x
has title: Python 3 TKinter Window will not open until command has been executed
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87150139
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87150195
has answer: http://stackoverflow.com/a/50067151

http://stackoverflow.com/q/50073293
tagged with: django-views
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/50127190
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50073516
has answer: http://stackoverflow.com/a/50073516
has body: I am trying to play with an open fda API. So far everything works well. Issue is coming for nested JSON data. Here is my Json data: { "seriousnessother": "1", "reportduplicate": { "duplicatenumb": "US-BRISTOL-MYERS SQUIBB COMPANY-BMS-2017-086135", "duplicatesource": "BRISTOL MYERS SQUIBB" }, "safetyreportversion": "1", "receiptdate": "20170927", "duplicate": "1", "seriousnessdeath": "1", "receivedate": "20170927", "patient": { "reaction": [ { "reactionmeddrapt": "Death", "reactionmeddraversionpt": "20.1", "reactionoutcome": "5" }, { "reactionmeddrapt": "Product use in unapproved indication", "reactionmeddraversionpt": "20.1", "reactionoutcome": "6" } ], "patientsex": "1", "drug": [ { "drugstartdateformat": "102", "medicinalproduct": "OPDIVO", "drugindication": "COLORECTAL CANCER", "drugcharacterization": "1", "drugadministrationroute": "065", "drugenddateformat": "102", "drugseparatedosagenumb": "1", "drugstructuredosageunit": "032", "openfda": { "manufacturer_name": [ "E.R. Squibb & Sons, L.L.C." ], "unii": [ "31YO63LBSN" ], "product_type": [ "HUMAN PRESCRIPTION DRUG" ], "spl_set_id": [ "f570b9c4-6846-4de2-abfa-4d0a4ae4e394" ], "route": [ "INTRAVENOUS" ], "generic_name": [ "NIVOLUMAB" ], "brand_name": [ "OPDIVO" ], "product_ndc": [ "0003-3772", "0003-3734", "0003-3774" ], "pharm_class_epc": [ "Programmed Death Receptor-1 Blocking Antibody [EPC]" ], "substance_name": [ "NIVOLUMAB" ], "spl_id": [ "2d33126d-5115-459e-bcaf-d0ace4fbe94e" ], "pharm_class_moa": [ "Programmed Death Receptor-1-directed Antibody Interactions [MoA]" ], "application_number": [ "BLA125554" ], "nui": [ "N0000191259", "N0000191260" ], "package_ndc": [ "0003-3734-13", "0003-3772-11", "0003-3774-12" ] }, "drugstructuredosagenumb": "1", "drugintervaldosageunitnumb": "2", "drugstartdate": "20160907", "actiondrug": "5", "activesubstance": { "activesubstancename": "NIVOLUMAB" }, "drugintervaldosagedefinition": "803", "drugauthorizationnumb": "125554", "drugrecurreadministration": "3", "drugdosagetext":…
has title: Django get value from JSON data
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50127190
type: AnsweredQuestion
score: 2
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/q/49929833
favorite count: 0
type: Question
tagged with: ajax
tagged with: python
has answer: http://stackoverflow.com/a/49930003
accepted answer: http://stackoverflow.com/a/49930003
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
has title: How can I update one element from a flask app on a button click?
tagged with: javascript
tagged with: flask
tagged with: jinja2
has body: In my app.py I have a list of strings, eg: list = ['item 1', 'item 2', 'item 3'] I would like to be able to be shown a string at random and display it on a page after clicking a 'refresh' button, but each item should only be shown once. ie. once the items have all been shown in random order I can show a message 'finished'. I have looked into refreshing the page (shown below) but this means the items can appear one after the other and I can always keep refreshing. This is my work-in-progress code at the moment, but I feel as if it's not close to what I want. items_list = ['A', 'B', 'C', 'D', 'E'] @app.route("/") def index(): return render_template("index.html") @app.route("/items", methods=['GET', 'POST']) def items(): item = random.choice(items_list) if request.method == "POST": return render_template("scales.html", item=item) else: return render_template("scales.html") items.html: {{ item }} Refresh Perhaps I could do this with AJAX? But would I need a database? Or something along the lines of app.jinja_env.globals.update() At a bit of a loss and any suggestions or pointers in the right direction would be much appreciated thanks.

http://stackoverflow.com/comment/87067424
type: QuestionComment
comment on: http://stackoverflow.com/q/50023985
score: 0
has text: @VincentNguyen Oh yeah, I missed that. What's the output of `pip3 --version`? Have you installed python 3.6 through `yum install python36` like in [this answer](https://stackoverflow.com/a/47544610/4796844)?
type: Comment

http://stackoverflow.com/q/50048911
type: Question
has title: Exclude Django Installed Apps while execute custom django command
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87114090
tagged with: django
tagged with: python
tagged with: django-commands
has comment: http://stackoverflow.com/comment/87114028
has comment: http://stackoverflow.com/comment/87114313
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87114063
has comment: http://stackoverflow.com/comment/87114168
has body: I have "xxx" in installed apps (settings.INSTALLED_APPS) Inside this applications, I check on existing schema in Postgresql If schema not exists I throw the exception. I request a user to execute Django custom command (for create schema) python manage.py create_schema .... But this command can't execute because of django.setup() Django runs xxx app, which run exception about absent schema I wanna temporarily exclude xxx app from Django while execute my custom command, or maybe You have any suggestion
has comment: http://stackoverflow.com/comment/87114242

http://stackoverflow.com/a/50009059
has body: Album.object does not exist; you should've written Album.objects. class IndexView (generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): # return Album.object.all() &lt;-- Remove this return Album.objects.all() As a side note, reserved words cannot be python attributes. This is by design, because disallowing these words makes parsing substantially easier. Why can&#39;t attribute names be Python keywords?
downvote count: 0
answers question: http://stackoverflow.com/q/50008899
accepted answer of: http://stackoverflow.com/q/50008899
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer

join
type: Tag
tags question: http://stackoverflow.com/q/50042441
tags question: http://stackoverflow.com/q/49979917
tag name: join
tags question: http://stackoverflow.com/q/50048484
tags question: http://stackoverflow.com/q/49948476

http://stackoverflow.com/a/50005187
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Solved it. I had to delete the checkpoint file in among the model.ckpt files. Checklist for next time I want to do transfer learning with TensorFlow after changing architecture: Use inspect_checkpoint.py to verify that your model.ckpt files have stored the right variables. Make sure you read the right model.ckpt file. Make sure you exclude the right scopes when restoring. Delete checkpoint if necessary.
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49998364
answers question: http://stackoverflow.com/q/49998364

http://stackoverflow.com/comment/86912961
comment on: http://stackoverflow.com/a/49947352
type: Comment
type: AnswerComment
score: 0
has text: That works for me now. I had not heard of the 'xml.etree.ElementTree' before. Is it a more reliable way of web scrapping instead of Beautiful Soup alone or Beautiful Soup + Selenium? Thanks in advance.

http://stackoverflow.com/q/49941816
has title: How to add character to a string element in a tuple or list?
score: 1
downvote count: 0
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/49941920
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49942159
answer count: 5
has answer: http://stackoverflow.com/a/49942134
has answer: http://stackoverflow.com/a/49942159
possible better answer: http://stackoverflow.com/a/49941920
tagged with: python
tagged with: replace
has body: I have the following sentence: sentence = "&lt;s&gt; online auto body &lt;s&gt;" And I would like first to make words 3-grams out of it as: ('&lt;s&gt;', 'outline', 'auto') ('online', 'auto', 'body') ('auto', 'body', '&lt;s&gt;') To do so I used the following code: sentence = '&lt;s&gt; online auto body &lt;s&gt;' n = 3 word_3grams = ngrams(sentence.split(), n) for grams in word_3grams: print(grams) Now, I would like to get "#" at the beginning and at the end of every word, as follows: ('#&lt;s&gt;#','#outline#','#auto#') ('#online#', '#auto#', '#body#') ('#auto#', '#body#', '#&lt;s&gt;#') But I don't know what to do in order to get it. As a side note elements here are tuples but it wouldn't mind using lists.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49942010
has answer: http://stackoverflow.com/a/49941852

http://stackoverflow.com/a/50003132
accepted answer of: http://stackoverflow.com/q/50002053
answers question: http://stackoverflow.com/q/50002053
type: Answer
score: 1
upvote count: 1
has body: I try to repond to you but I can't understand one thing. How you retrieve your field name from data? In your code I see that you retrieve it from a list called header that is empty? I can't understand how you take this value.. Check my answer i don't know if i understand well from elasticsearch import Elasticsearch from elasticsearch import helpers index_name = "your_index_name" doc_type = "your_doc_type" esConnector = Elasticsearch(["http://192.168.1.1:9200/"]) # change your ip here count = 0 def generate_data(csv_file_object) with open(csv_file_object, "r") as f: for line in f: line = line.split(",").rstrip() data_dict = {header[count]: line} obj={ '_op_type': 'index', '_index': index_name, '_type': doc_type, '_id': count+1, '_source': data_dict } count +=1 yield obj for success, info in helpers.parallel_bulk(client=esConnector, actions=generate_data(csv_file_object), thread_count=4): if not success: print 'Doc failed', info
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49983544
has body: I have multiples classes in my program. At the beguinning, i initiate a static class that contains an SQLite connexion : class Utils : dbClient = None @staticmethod def initialize(settings): from storage.sqlite.SQLiteClient import SqliteClient Utils.dbClient = SqliteClient(settings) then my app.py start the class by calling the initilize static method. Utils.initialize(settings) app.py call 2 others classes in multiprocessing mode. I would like these 2 classes using the same connexion (from Utils). Utils.dbClient.insert(...) How to do that ? Thanks
has comment: http://stackoverflow.com/comment/86983480
has comment: http://stackoverflow.com/comment/86983576
tagged with: python
has comment: http://stackoverflow.com/comment/86984036
type: Question
has title: Share static class in python
answer count: 0
has comment: http://stackoverflow.com/comment/86985709
type: UnansweredQuestion
score: 0
tagged with: sqlite

http://stackoverflow.com/comment/86922078
comment on: http://stackoverflow.com/q/49943882
score: 0
type: Comment
type: QuestionComment
has text: I want to keep lets say 2 records. But if I have a record with the same MMSI I want to keep both records as one. I want the joined data to be distinct. The join query as you can see returns for the same MMSI again the values.

http://stackoverflow.com/comment/86912692
score: 0
type: AnswerComment
has text: Ah, the loop elements were enclosed by `['` and `']` Not very elegantly, I removed these characters `curr_symbol=str(stocks).replace('[','').replace(']','').replace('\'','')` and now I can use curr_symbol in the lingregress-call. Thanks!
comment on: http://stackoverflow.com/a/49947342
type: Comment

http://stackoverflow.com/a/50019697
answers question: http://stackoverflow.com/q/50019210
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50019210
type: AcceptedAnswer
downvote count: 0
has body: No, it is not overkill. In this situation, pandas can add flexibility rather than restrictions. For example, you can allow users to upload any of: excel, csv, csv.gz. Since pandas has a library of methods to handle various formats you can write a function to select the appropriate method and convert to a dataframe. Once in a dataframe, conversion to dictionary is trivial. Here's an example of a function I use for this purpose: import os, pandas as pd def read_file(filename, **kwargs): """Read file with **kwargs; files supported: xls, xlsx, csv, csv.gz, pkl""" read_map = {'xls': pd.read_excel, 'xlsx': pd.read_excel, 'csv': pd.read_csv, 'gz': pd.read_csv, 'pkl': pd.read_pickle} ext = os.path.splitext(filename)[1].lower()[1:] assert ext in read_map, "Input file not in correct format, must be xls, xlsx, csv, csv.gz, pkl; current format '{0}'".format(ext) assert os.path.isfile(filename), "File Not Found Exception '{0}'.".format(filename) return read_map[ext](filename, **kwargs) Then simply call it as follows: df = read_file('file.xlsx') # or 'file.csv', 'file.csv.gz', etc
score: 6
type: Answer

multidimensional-array
tags question: http://stackoverflow.com/q/50046134
tags question: http://stackoverflow.com/q/49977932
tags question: http://stackoverflow.com/q/49928429
tags question: http://stackoverflow.com/q/49930236
tags question: http://stackoverflow.com/q/50047749
tags question: http://stackoverflow.com/q/49932795
type: Tag
tags question: http://stackoverflow.com/q/50033282
tags question: http://stackoverflow.com/q/49949052
tags question: http://stackoverflow.com/q/49980814
tag name: multidimensional-array

http://stackoverflow.com/q/50019288
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I have a question regarding the formatting of various text objects within a graph. While trying to make my plots look good (for example for publishing purposes) I have encountered the issue that text elements seem to have quite different requirements when it comes to formatting. For example formatting the title of a graph is done by pw.setTitle('test', **{'color': '#FFF', 'size': '14pt'}) while formatting a label is done with pw.setLabel('test', **{'color': '#FFF', 'font-size': '14pt'}) Then when it comes to formatting the text of ticks I have to create a QFont and manipulates it's properties, for example tickFont = QtGui.QFont() tickFont.setPointSize(14) pw.getAxis('left').tickFont = tickFont Therefore I wonder if it's just me who has an improper understanding of the classes or if it really is that different for each label. I understand of course that there are subtle differences in which kinds of objects are involved and how they are controlled. However it makes me wonder if some kind of unified interface would be desireable, especially to produce publishable graphs. Greets, Fabian.
tagged with: python
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/87067856
tagged with: text
has comment: http://stackoverflow.com/comment/87075839
has title: Pyqtgraph Setting Label Styles
has answer: http://stackoverflow.com/a/63652406
upvote count: 2
score: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/a/50021509
accepted answer of: http://stackoverflow.com/q/50021381
has body: import string # string.ascii_letters = 'abcde...ABCDE...' def mine(s, x): return s * x # fixed your code so it multiplies by x, not 4 def theirs(s, x): # renamed but the same as codebat res = '' for _ in range(x): res += s return res We can see they give the same results mine(string.ascii_letters, 10) == theirs(string.ascii_letters, 10) # --&gt; True We can test the time efficiency of these functions however %timeit mine(string.ascii_letters, 1000) 2.27 µs ± 9.69 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit theirs(string.ascii_letters, 1000) 202 µs ± 4.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) As you can see mine is almost 100 times more efficient because under the hood python pre-allocates the memory needed for the new string. In theirs it has to keep reallocating memory each time the string length is increased.
answers question: http://stackoverflow.com/q/50021381
type: Answer
has comment: http://stackoverflow.com/comment/87062097
downvote count: 0
type: AcceptedAnswer
upvote count: 6
score: 6

http://stackoverflow.com/q/50026785
accepted answer: http://stackoverflow.com/a/50028210
has comment: http://stackoverflow.com/comment/87070275
upvote count: 1
has answer: http://stackoverflow.com/a/50028210
has body: I need to download a package using pip. I ran pip install &lt;package&gt; but got the following error: [user@server ~]$ pip install sistr_cmd Collecting sistr_cmd Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection. VerifiedHTTPSConnection object at 0x7f518ee0cd90&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection. VerifiedHTTPSConnection object at 0x7f518ee0c290&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection. VerifiedHTTPSConnection object at 0x7f518ee0c510&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection. VerifiedHTTPSConnection object at 0x7f518ee0cf10&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection. VerifiedHTTPSConnection object at 0x7f518ee0c190&gt;: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/ Could not find a version that satisfies the requirement sistr_cmd (from versions: ) No matching distribution found for sistr_cmd I verified that the source of the problem is the network blocking most sites because I am working behind a proxy …
has title: Which repositories are pip packages installed from?
possible better answer: http://stackoverflow.com/a/50027471
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87070207
answer count: 2
has answer: http://stackoverflow.com/a/50027471
has comment: http://stackoverflow.com/comment/87070352
downvote count: 0
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/87070490
has comment: http://stackoverflow.com/comment/87070423
has comment: http://stackoverflow.com/comment/87070110
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87070727
has comment: http://stackoverflow.com/comment/87069985
score: 1

http://stackoverflow.com/a/49918472
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49917999
has body: else clause only applies to the last if and is executed when the if condition not met if body == "Atrium": print("Brad's dead body lies in the middle of the floor") identifier = ei else: identifier = ei In this snippet, else gets executed when body != "Atrium" - indeed, ingoring all your previous if clauses. Solution: elif if murderer.location == "Atrium": print(murderer.name, "is stood in here, waiting") identifier = murderer elif innocent1.location == "Atrium": print(innocent1.name, "is stood in here, waiting") identifier = innocent1 ... else: identifier = ei Another alternative is to set identifier to the default value first, only overwriting it in if clauses when the conditions are met. This only works as long as you're not using identifier value in the comparisons, of course. identifier = ei if murderer.location == "Atrium": ... Also, as @Mitch Wheat mentioned, you should really read about lists and arrays. It's so much easier and cleaner to examine all lists members (especially if you need to add another innocent person later) for innocent in innocents: if innocent.location == 'Atrium': print(innocent.name, "is stood in here, waiting") identifier = innocent
accepted answer of: http://stackoverflow.com/q/49917999
type: Answer
score: 2

http://stackoverflow.com/a/49936484
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49922920
score: 2
downvote count: 0
has body: You cannot use python-firebase to access analytics data since there is no REST API for Firebase Analytics. In order to work with the data you have to link your Firebase project to BigQuery. https://cloud.google.com/solutions/mobile/mobile-firebase-analytics-big-query

http://stackoverflow.com/comment/86965776
comment on: http://stackoverflow.com/q/49974923
score: 0
has text: `speaker_id, sex, subset, minutes, speaker_name = line.split(' | ', 4)`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50061716
tagged with: odoo-10
possible better answer: http://stackoverflow.com/a/51764034
has answer: http://stackoverflow.com/a/65866579
has answer: http://stackoverflow.com/a/51764034
tagged with: python
accepted answer: http://stackoverflow.com/a/51766810
has body: I am trying to create multiple sale order based on a input field (product_quantity) in crm.lead. @api.multi def create_sale(self): values = { 'opportunity_id': self.id, 'state': 'draft', 'date_order': datetime.now(), 'partner_id': self.partner_id.id } for i in range(0, self.product_quantity): res = self.env['sale.order'].create(values) I am receiving the following error as pop up Error, a partner cannot follow twice the same object.
type: AnsweredQuestion
has title: Create multiple saleorder
downvote count: 0
answer count: 3
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51766810
type: Question

http://stackoverflow.com/comment/86913601
type: AnswerComment
has text: Yes, i will put that into the question, the samples must be uniformly distributed.
type: Comment
comment on: http://stackoverflow.com/a/49948229
score: 0

http://stackoverflow.com/comment/86949847
has text: @Kasramvd Not my downvote but FWIW I really don't think this "violates SO's rule of downvoting". You can downvote whatever you please. And when the OP's question's first line is "I have 2 huge NumPy arrays" your solution doesn't look promising.
type: Comment
comment on: http://stackoverflow.com/a/49964970
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86984786
type: QuestionComment
comment on: http://stackoverflow.com/q/49984197
type: Comment
has text: Your argument is `num` but you're passing `x` as the kwarg?
score: 0

http://stackoverflow.com/comment/87263669
score: 0
has text: @cowlinator When using xlsxwriter as writer you just have one shot of getting your data into the worksheet, there is no altering already present worksheets. The user tries to apply formatting onto a worksheet before dumping the dataframe into it. This approach will likely not work. You just notice on save though.
type: Comment
comment on: http://stackoverflow.com/q/49941005
type: QuestionComment

http://stackoverflow.com/q/49953132
has body: def partitions(set_): if not set_: yield [] return for i in range(2**len(set_)//2): parts = [set(), set()] for item in set_: parts[i&amp;1].add(item) i &gt;&gt;= 1 for b in partitions(parts[1]): yield [parts[0]]+b def get_partitions(set_): for partition in partitions(set_): yield [list(elt) for elt in partition] I'm trying to understand what "i >>= 1" does in this code. Can someone explain this to me? Edit: Can someone explain what "parts[i&amp;1]" does as well?
has comment: http://stackoverflow.com/comment/86940052
score: 1
has title: >>= operator in Python3
tagged with: python
has comment: http://stackoverflow.com/comment/86922765
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49953151
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86940194
answer count: 1
downvote count: 0
upvote count: 1

amazon-web-services
tags question: http://stackoverflow.com/q/50006409
tags question: http://stackoverflow.com/q/49989794
tags question: http://stackoverflow.com/q/50053347
tags question: http://stackoverflow.com/q/50061634
tags question: http://stackoverflow.com/q/49953271
tags question: http://stackoverflow.com/q/49930030
tags question: http://stackoverflow.com/q/50044759
tags question: http://stackoverflow.com/q/50063668
tags question: http://stackoverflow.com/q/49973504
tags question: http://stackoverflow.com/q/49992886
tags question: http://stackoverflow.com/q/49954268
tags question: http://stackoverflow.com/q/49979677
tags question: http://stackoverflow.com/q/50072547
tags question: http://stackoverflow.com/q/49933952
tags question: http://stackoverflow.com/q/49989510
tags question: http://stackoverflow.com/q/49948563
tags question: http://stackoverflow.com/q/50010833
tags question: http://stackoverflow.com/q/50023985
tags question: http://stackoverflow.com/q/50006657
type: Tag
tags question: http://stackoverflow.com/q/49955157
tags question: http://stackoverflow.com/q/49989604
tags question: http://stackoverflow.com/q/49990358
tags question: http://stackoverflow.com/q/50071304
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/50018760
tags question: http://stackoverflow.com/q/50054671
tags question: http://stackoverflow.com/q/50073489
tags question: http://stackoverflow.com/q/49938509
tags question: http://stackoverflow.com/q/50012261
tags question: http://stackoverflow.com/q/49985422

http://stackoverflow.com/a/50022147
score: 0
answers question: http://stackoverflow.com/q/50020118
has body: It seems like you never add id to your context in your view index. So the template does not have that variable available. You need to add that id to your context. Just like @Alasdair pointed out in the comments.
type: Answer

http://stackoverflow.com/q/50012174
tagged with: java
has comment: http://stackoverflow.com/comment/87070495
linked to: http://stackoverflow.com/q/46246104
downvote count: 0
has comment: http://stackoverflow.com/comment/87078765
favorite count: 0
has title: SpringBoot org.springframework.beans.factory.UnsatisfiedDependencyException
type: Question
tagged with: spring-boot
has comment: http://stackoverflow.com/comment/87073760
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78571446
has comment: http://stackoverflow.com/comment/87072790
has comment: http://stackoverflow.com/comment/87040794
tagged with: python
has comment: http://stackoverflow.com/comment/87070762
tagged with: spring
has comment: http://stackoverflow.com/comment/87073776
has answer: http://stackoverflow.com/a/51396830
score: 2
upvote count: 2
has body: I am very new to SpringBoot. I have written a sample service which accepts project details and stores them in a postgres db. However, I am unable to launch my application and not sure what is wrong. I did check the package hierarchy and everything seems to be fine. Any help is appreciated. I haven't created a table in the database, I am doing this via the JPA, when I send POST request. ProjectPocApiApplication.java package com.poc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProjectPocApiApplication { public static void main(String[] args) { SpringApplication.run(ProjectPocApiApplication.class, args); } } Project.java package com.poc.project; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Project { @Id @GeneratedValue(strategy = GenerationType.AUTO) private String id; @Id private String name; private String status; private String priority; private String manager; private String comments; public Project() {} public Project(String id, String name, String status, String priority, String manager, String comments) { super(); this.id = id; this.name = name; this.status = status; this.priority = priority; this.manager = manager; this.comments = comments; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comme…
tagged with: spring-data-jpa
has comment: http://stackoverflow.com/comment/87076584
answer count: 2
has comment: http://stackoverflow.com/comment/87079801

http://stackoverflow.com/a/50051242
score: 1
accepted answer of: http://stackoverflow.com/q/50040056
type: Answer
answers question: http://stackoverflow.com/q/50040056
upvote count: 1
type: AcceptedAnswer
has body: The main issue here is theoretical. You're trying to minimize doutput_tensor/dx + d2output_tensor/d2x. Your network just linearly combines the input x-s, however, with relu and softplus activations. Well, softplus adds a bit of twist to it, but that also has a monotonously increasing derivative. Therefore for the derivative to be as small as possible, the network will just scale the input up as much as possible with negative weights, to make the derivative as small as possible (that is, a really large negative number), at some point reaching NaN. I've reduced the first layer to 5 neurons and ran the model for 2 epochs, and the weights became: ('dense_1', [array([[ 1.0536456 , -0.32706773, 0.0072904 , 0.01986691, 0.9854533 ], [-0.3242108 , -0.56753945, 0.8098554 , -0.7545874 , 0.2716419 ]], dtype=float32), array([ 0.01207507, 0.09927677, -0.01768671, -0.12874101, 0.0210707 ], dtype=float32)]) ('dense_2', [array([[-0.4332278 ], [ 0.6621602 ], [-0.07802075], [-0.5798264 ], [-0.40561703]], dtype=float32), array([0.11167384], dtype=float32)]) You can see that the second layer keeps a negative sign where the first has a positive, and vice versa. (Biases don't get any gradient because they don't contribute to the derivative. Well, not exactly true because of the softplus but more or less.) So you have to come up with a loss function that is not divergent towards extreme parameter values because this will not be trainable, it will just increase the values of weights until they NaN. This was the version I ran: import tensorflow as tf from keras.models import * from keras.layers import * from keras import backend as K def grad(f, x): return Lambda(lambda u: K.gradients(u[0], u[1]), output_shape=[2])([f, x]) def ngrad(f, x, n): if 0 == n: return f else: return Lambda(lambda u: K.gradients(u[0], u[1]), output_shape=[2])([ngrad( f, x, n - 1 ), x]) def custom_loss(input_tensor,output_tensor): def loss(y_true, y_pred): _df1 = grad(output_tensor,input_tensor) df1 = tf.Print( _df1, …
downvote count: 0

databricks
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/49947820

http://stackoverflow.com/comment/133052296
score: 1
type: Comment
type: AnswerComment
has text: Quick and easy, perfect for my use case. Thanks!
comment on: http://stackoverflow.com/a/62956658

http://stackoverflow.com/comment/87155171
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50048877
has text: I think that's how quantified capture groups work in all regexp engines.
type: Comment

http://stackoverflow.com/comment/86950110
comment on: http://stackoverflow.com/a/49967084
type: Comment
type: AnswerComment
has text: I was just wondering if there was a way to cancel it (I did write why it happened in the question).
score: 0

http://stackoverflow.com/q/49996123
has title: Python interpolate throws no errors - but also does nothing
has comment: http://stackoverflow.com/comment/87009935
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87008840
type: Question
tagged with: interpolation
has body: I am trying some DataFrame manipulation in Pandas that I have learnt. The dataset that I am playing with is from the EY Data Science Challenge. This first part may be irrelevant but just for context - I have gone through and set some indexes: import pandas as pd import numpy as np # loading the main dataset df_main = pd.read_csv(filename) '''Sorting Indexes''' # getting rid of the id column del df_main['id'] # sorting values by LOCATION and GENDER columns # setting index to LOCATION (1st tier) then GENDER (2nd tier) and then re- #sorting df_main = df_main.sort_values(['LOCATION','TIME']) df_main = df_main.set_index(['LOCATION','TIME']).sort_index() The problem I have is with the missing values - I have decided that columns 7 ~ 18 can be interpolate because a lot of the data is very consistent year by year. So I made a simple function to take in a list of columns and apply the interpolate function for each column. '''Missing Values''' x = df_main.groupby("LOCATION") def interpolate_columns(list_of_column_names): for column in list_of_column_names: df_main[column] = x[column].apply(lambda x: x.interpolate(how = 'linear')) interpolate_columns( list(df_main.columns[7:18]) ) However, the problem I am getting is one of the columns (Access to electricity (% of urban population with access) [1.3_ACCESS.ELECTRICITY.URBAN]) seems to not be interpolating when all the other columns are interpolated successfully. I get no errors thrown when I run the function, and it is not trying to interpolate backwards either. Any ideas regarding why this problem is occurring? EDIT: I should also mention that the column in question was missing the same number of values - and in the same rows - as many of the other columns that interpolated successfully.
score: 0
has answer: http://stackoverflow.com/a/50014850
tagged with: pandas
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87043547
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50013571
type: AnswerComment
has text: Sir, I'm in production. Deleting the instances won't be a good idea :(

http://stackoverflow.com/comment/86989825
has text: @jpp My real data contains length of 420091 array and each array has 256 elements inside. Is that causing the problem?
comment on: http://stackoverflow.com/q/49986647
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87019545
type: QuestionComment
has text: Do you think you can build an alternation with 200k items?
comment on: http://stackoverflow.com/q/50001328
score: 0
type: Comment

http://stackoverflow.com/a/50051463
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50050847
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50050847
has body: When a button is pressed it becomes active, which is different from its ordinary state, so you need to specify the parameter activebackground: Button(r, image=i, bg="#ff73c8", activebackground="#ff73c8") See more on button states here.

http://stackoverflow.com/q/49932098
tagged with: python
has body: How would I multiply and obtain the sum of the lists in the following lists WITHOUT the use of numpy? pattern = [40, 30, 20, 10] data_list =[[-1, 2, -2, 3], [2, -2, 3, 41], [-2, 3, 41, 38], \ [3, 41, 38, 22], [41, 38, 22, 10], [38, 22, 10, -1], [22, 10, -1, 3]] I want to multiply each element in the data_list by the pattern and obtain the following result. expected_answer = [10, 490, 1210, 2330, 3320, 2370, 1190] I've tried: sum([i*j for i,j in zip(data_list, pattern)]) yet I keep getting this error: TypeError: unsupported operand type(s) for +: 'int' and 'list'
score: 0
tagged with: list
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86881585
has title: element list multiply sum
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49932129

http://stackoverflow.com/a/50010860
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50009504
downvote count: 0
score: 1
type: Answer
has body: Try this regex solution: s.replace('-(?=[0-9])','_', regex=True).replace('_(?=2w|baseline|RT)','-', regex=True) Explanation: We use regex to find - before a number [0-9] and replace with _ We use regex again to find _ before 2w or baseline or RT and replace with - Exemplified: import pandas as pd s = pd.Series(['mitra_baseline_310808-1', 'mitra_baseline_310808-2', 'mitra_baseline_310808-3', 'mitra_baseline_310808-4', 'mitra_baseline_310907-1', 'mitra_baseline_310907-2', 'mitra_baseline_310907-3', 'mitra_baseline_310907-4', 'mitra_baseline_311090-1', 'mitra_baseline_311090-2', 'mitra_baseline_311090-3', 'mitra_baseline_311090-4', 'mitra_baseline_311091-1', 'mitra_baseline_311091-2', 'mitra_baseline_311091-3', 'mitra_baseline_311091-4', 'mitra_baseline_311123-1', 'mitra_baseline_311123-2', 'mitra_baseline_311123-3', 'mitra_baseline_311123-4', 'frozen_2w_310808-1', 'frozen-2w_310808-2', 'frozen-2w_310907-1', 'frozen-2w_310907-2', 'frozen-2w_311090-1', 'frozen-2w_311090-2', 'frozen-2w_311091-1', 'frozen-2w_311091-2', 'frozen-2w_311123-1', 'frozen-2w_311123-2', 'RT-2w_310808-1', 'RT-2w_310808-2', 'RT-2w_310907-1', 'RT-2w_310907-2', 'RT-2w_311090-1', 'RT-2w_311090-2', 'RT-2w_311091-1', 'RT-2w_311091-2', 'RT-2w_311123-1', 'RT-2w_311123-2', 'LT_RT_310808_1', 'LT_RT_310808_2', 'LT_RT_310907_1', 'LT_RT_310907_2', 'LT_RT_311090_1', 'LT_RT_311090_2', 'LT_RT_311091_1', 'LT_RT_311091_2', 'LT_RT_311123_1', 'LT_RT_311123_2', 'LT-frozen_310808_1', 'LT-frozen_310808_2', 'LT-frozen_310907_1', 'LT-frozen_310907_2', 'LT-frozen_311090_1', 'LT-frozen_311090_2', 'LT-frozen_311091_1', 'LT-frozen_311091_2', 'LT-frozen_311123_1', 'LT-frozen_311123_2']) print(s.replace('-(?=[0-9])','_', regex=True).replace('_(?=2w|baseline|RT)','-', regex=True))
accepted answer of: http://stackoverflow.com/q/50009504

http://stackoverflow.com/comment/86986702
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49960575
has text: Hi @wim, thank for your answer. at the s1 = o"this is a string" line I get a SyntaxError: invalid syntax. Do you know what may have caused this?
score: 0

django-serializer
tags question: http://stackoverflow.com/q/49926710
type: Tag
tag name: django-serializer
tags question: http://stackoverflow.com/q/50018463
tags question: http://stackoverflow.com/q/50019009
tags question: http://stackoverflow.com/q/49936194

http://stackoverflow.com/a/49959468
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49959311
has body: Try making use of exec statement. Of course, this can cause several problems in a real case scenario, since you are trying to execute random lines off a file, but it works for simple lines of code (like the ones you supplied in your example code_lines.py). from random import randint with open('code_lines.py') as file: line = file.readline() count = 0 code =[] while line: code += [line] line = file.readline() count += 1 exec(code[randint(0,count-1)])
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49959311

http://stackoverflow.com/comment/86963179
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49973613
has text: what do you mean by reference exactly? In what ways can i use references?

http://stackoverflow.com/q/50071148
tagged with: python
has comment: http://stackoverflow.com/comment/124584518
has comment: http://stackoverflow.com/comment/87165503
favorite count: 0
tagged with: python-3.x
answer count: 0
has title: ValueError: Too many values to unpack in recursive graph search
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87159418
has comment: http://stackoverflow.com/comment/87159254
has comment: http://stackoverflow.com/comment/87159066
has body: Problem As part of a uni assignment im building a program to find a shortest path from one road to another. I'm using an algorithm called recursive best-first search to do so, and im getting the ValueError as the recursion unwinds and tries to unpack the solution (Stored as a list of nodes, from goal node to root node). The recursive call is stored in the variables 'result' and 'best.f' as seen in the second last line in the search algorithm. Code Included below is the main algorithm and the relevant (but not all) methods Search algorithm: (Based on this pseudocode) def find_path_from_to(problem): return RBFS_Road(problem,Node(problem.start,None,None,0,problem),math.inf) def RBFS_Road(problem,node,f_limit): if problem.goaltest(node): return solution(node) successors = [] for action in problem.actions(node): successors.append(Node(action.current_pos,node, [node.current_pos,action],node.g+1,problem)) if not successors: return "failure",math.inf for s in successors: s.f = max(s.g+s.h,node.f) while True: best = min_node(successors) if best.f &gt; f_limit: return "failure",best.f alternative = alt(successors) result,best.f = RBFS_Road(problem,best,min(f_limit,alternative)) if result != "failure": return result The function that returns the solution list and the Node and Problem class def solution(node): solution_list = [node.current_pos] current_node = node while current_node.parent is not None: solution_list.append(current_node.parent.current_pos) current_node = current_node.parent return [solution_list,None] | class Problem(): def __init__(self,start,goal,city_data): self.start = start self.goal = goal self.city_data = city_data def goaltest(self,node): return node.current_pos.split(' ',1)[0] == self.goal.split(' ',1)[0] def actions(self,node): return find_neighbors(node,self.city_data) class Node(): def __init__(self,current_pos,parent,action,steps,problem): self.current_pos = current_pos self.parent = parent self.action = action self.problem = problem self.g = steps …
type: Question
has comment: http://stackoverflow.com/comment/87159489
score: 0
downvote count: 1

firebase-analytics
type: Tag
tags question: http://stackoverflow.com/q/49922920
tag name: firebase-analytics

http://stackoverflow.com/comment/87071902
type: QuestionComment
has text: Let Python do the path escape for you, e.g. `subprocess.call(["C:\\Program Files\\ArcGIS\\Pro\bin\\Python\\envs\\arcgispro-py3\\python.exe", "D:\\inetpud_backup_17_04_2018\\Gurminder\\Cases\\02104091\\test.py"])` if you want to use a specific `python.exe`.
comment on: http://stackoverflow.com/q/50027778
type: Comment
score: 1

http://stackoverflow.com/q/49953624
possible better answer: http://stackoverflow.com/a/49953930
favorite count: 0
has answer: http://stackoverflow.com/a/49954050
has answer: http://stackoverflow.com/a/49953930
type: Question
has answer: http://stackoverflow.com/a/49953712
tagged with: python
score: -2
tagged with: date
has title: Python Function running on a random date
has body: #first and last day of every month s_january, e_january = ("1/1/2017"), ("1/31/2017") s_february, e_february = ("2/1/2017"), ("2/28/2017") s_march, e_march = ("3/1/2017"), ("3/31/2017") s_april, e_april = ("4/1/2017"), ("4/30/2017") s_may, e_may = ("5/1/2017"), ("5/31/2017") s_june, e_june = ("6/1/2017"), ("6/30/2017") s_july, e_july = ("7/1/2017"), ("7/31/2017") s_august, e_august = ("8/1/2017"), ("8/31/2017") s_September, e_September = ("9/1/2017"), ("9/30/2017") s_october, e_october = ("10/1/2017"), ("10/31/2017") s_november, e_november = ("11/1/2017"), ("11/30/2017") s_december, e_december = ("12/1/2017"), ("12/31/2017") def foo(s_date, e_date): does stuff foo(s_january, e_january) foo(s_february, e_february) foo(s_march, e_march) foo(s_april, e_april) foo(s_may, e_may) foo(s_june, e_june) foo(s_july, e_july) foo(s_august, e_august) foo(s_september, e_september) foo(s_october, e_october) foo(s_november, e_november) foo(s_december, e_december) I have a function that on a random date does stuff, but I have to call the function for every month, if I put the range for year I don't get the result that I want. Is there any better way to avoid running it 12 times?
tagged with: random
type: AnsweredQuestion
tagged with: time
upvote count: 0
downvote count: 2
answer count: 3
accepted answer: http://stackoverflow.com/a/49954050

http://stackoverflow.com/comment/87146876
comment on: http://stackoverflow.com/a/50065003
score: 0
type: AnswerComment
has text: good catch, give me a min to edit
type: Comment

http://stackoverflow.com/q/50019825
accepted answer: http://stackoverflow.com/a/50019840
has body: Assume we have data, and columnNames e.g. dataExample = [1,2] columnNames = ['a','b'] we want to create a python dataframe like: a b 0 1 2 Surprsingly, writting df = pd.DataFrame( dataExample , columns = columnNames ) gives error, since data (i.e. [1,2]) is shaped like (2,1) and columns requires shape (1,2) So the way round can be df = pd.DataFrame( np.array([1,2]).reshape(1,-1) , columns = ['a','b'] ) It works, but, it seems not quite "nice"/"one-line" as I naively expect the answer should be. Question: is there some "nice"/"shorter" way ? Another way to do the same, but still not "nice"/"one line" df = pd.DataFrame( columns = ['a','b'], index = [0] ) df.loc[0] = [1,2] But again it does not look like "nice"/"short" as I would expect There is related question: python create a data frame with one row by a list But it does not answer my question
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has title: python create a data frame with one row by a list (Nice way without "reshape" )
tagged with: pandas
score: 1
answer count: 1
linked to: http://stackoverflow.com/q/29079408
downvote count: 0
has answer: http://stackoverflow.com/a/50019840
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49968362
type: Answer
answers question: http://stackoverflow.com/q/49968248
score: 1
downvote count: 0
upvote count: 1
has body: You can configure the Oracle Net layer used by cx_Oracle by creating a sqlnet.ora configuration file with various timeout parameters such as SQLNET.INBOUND_CONNECT_TIMEOUT, SQLNET.RECV_TIMEOUT and SQLNET.SEND_TIMEOUT etc. You can read the documentation here and there's more details in this answer.
has comment: http://stackoverflow.com/comment/86953123

http://stackoverflow.com/q/49958256
has body: I've been studying algorithm, and just came across this bucket sort. Although it can only be used for few cases, it just looks too efficient to be not implemented in standard library, since it can sort a list in O(n) time. so my question is, why isn't there a given library that supports bucket sort, or any other counting-sort-like algorithm such as radix sort in most of the languages? I've checked java, python, and c++ library, but it doesn't look like it supports any sorting algorithm other then sorting algorithms based on comparing. Although implementing such algorithm requires list to have integer in specific range, it doesn't seem impossible to implement such method. Java, for example, can have a interface similar to Comparator() which returns integer in given range that would be used as index for sorting. So what is the reason that makes O(n) sorting algorithms not used? Or is there a library that actually uses bucket sort that I just missed? Sorry if it was a silly question, I just thought there must be a reason that makes O(n) algorithm unused.
tagged with: python
accepted answer: http://stackoverflow.com/a/49959952
has answer: http://stackoverflow.com/a/66737806
possible better answer: http://stackoverflow.com/a/74255267
favorite count: 0
type: Question
tagged with: c++
has answer: http://stackoverflow.com/a/74255267
downvote count: 0
upvote count: 1
tagged with: sorting
has comment: http://stackoverflow.com/comment/86936237
has answer: http://stackoverflow.com/a/49959952
type: AnsweredQuestion
answer count: 3
tagged with: algorithm
has title: Why isn't there a bucket sort library(or is there?)
score: 1
tagged with: java

http://stackoverflow.com/comment/87173606
has text: Yes, a `for` loop
type: Comment
comment on: http://stackoverflow.com/a/50067632
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87033342
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50008120
has text: x_train.shape (5, 129) and transformed_review.shape (1, 129)

http://stackoverflow.com/q/49918742
type: UnansweredQuestion
has title: Python-Imap: retrieve MIMEMultipart's mails and get the body with HTML tags
has comment: http://stackoverflow.com/comment/87109637
tagged with: imap
has comment: http://stackoverflow.com/comment/86866761
has comment: http://stackoverflow.com/comment/87065403
type: Question
score: 0
has body: Here my situation: I am currently retrieving all my outlook (2016) mails from my Inbox, and more specificcaly I am retrieving a table: ¦ Product ¦ Currency ¦ Tenor (months) ¦ Code 1 ¦ ¦ MyItem ¦ USD ¦ 12 ¦ AAA01 ¦ My goal is to catch the body of each of them to then store them in a MsSQL Server. I had difficulties to understand the 'Multipart' term, now with couples of (long) hours it's more clear. So for now my process is: going through all my mails in the Inbox Creating a list of mails' Id For all the Id I have in this list, I am checking if the mail is a Multipart one. If Yes -> I retrieve the body with body = part.get_payload(decode=True) If No -> I retrieve the body with body = b.get_payload(decode=True) So in both case I use the get_payload(decode=True). When my mail is "Multipart", it appears in my debugger as a simple text: Product Currency Tenor (months) Code 1 MyItem USD 12 AAA01 When my mail isn't a Multipart, it appears in my debugger with HTML tags: Product Currency Tenor (months) Code 1 MyItem USD 12 AAA01 How can I retrieve body of Multipart's mails with HTML tag also and not as simple text ? I need HTML tag to identify each header and its corresponding value to use Beautiful Soup and Insert all those data into my MSSQL Server ? Thanks for your help to let me understand better MIMEMultipart ! Here my (messy) python code: @app.route('/ps_rfq_imap', methods=['GET', 'POST']) def ps_rfq_imap(): #Connection to IMAP/OULTLOOK url = 'outlook.mycompayny.com' mailbox = imaplib.IMAP4_SSL(url,993) user,password = ('mymail@mycompany.com','mypassword') mailbox.login(user,password) mailbox.list() # Lists all labels in GMail mailbox.select('INBOX') # Connected to inbox. #giving list id, not outlook ones, but uid ones typ, data = mailbox.search(None,'ALL') #Get all the uid outlook of all emails #typ, data = mailbox.uid('search', None,'ALL') ids = data[0] id_list = ids.split() print id_list #get the most recent email id latest_email_id = int( id_list[-1] ) for i in ran…
tagged with: tags
tagged with: http://stackoverflow.com/tag/html
tagged with: email
tagged with: python
has comment: http://stackoverflow.com/comment/87065178
answer count: 0

http://stackoverflow.com/q/49919252
upvote count: 1
tagged with: multi-index
has answer: http://stackoverflow.com/a/49932579
possible better answer: http://stackoverflow.com/a/49932579
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49919621
has title: How to select this kind of data from this pandas multi-index dataframe
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49919621
has body: I'm working with futures market data, here is an example multi-index dataframe: date_index = pd.date_range('2018-03-20', periods = 10) contract = ['ZN1805', 'ZN1806', 'ZN1807'] price = ['open', 'close'] columns = pd.MultiIndex.from_product([contract, price], names=['contract', 'price']) df1 = pd.DataFrame(data=np.random.randint(100, 150, (10, columns.shape[0])), index=date_index, columns=columns) df2 = pd.DataFrame(columns=['contract', 'close'], index=df1.index) # Set the data in contract column randomly here for illustration df2.contract = np.random.choice(contract, 10) Here is what df1 looks like, df1 Out[357]: contract ZN1805 ZN1806 ZN1807 price open close open close open close 2018-03-20 145 144 116 127 107 128 2018-03-21 116 143 114 103 114 148 2018-03-22 101 135 143 125 140 129 2018-03-23 106 139 100 127 116 100 2018-03-24 104 101 148 132 102 140 2018-03-25 125 141 106 136 128 134 2018-03-26 148 146 142 143 108 137 2018-03-27 110 123 128 128 124 127 2018-03-28 144 143 117 116 112 140 2018-03-29 143 114 115 105 124 118 and df2 would be: df2 Out[364]: contract close 2018-03-20 ZN1805 NaN 2018-03-21 ZN1807 NaN 2018-03-22 ZN1806 NaN 2018-03-23 ZN1807 NaN 2018-03-24 ZN1807 NaN 2018-03-25 ZN1806 NaN 2018-03-26 ZN1807 NaN 2018-03-27 ZN1806 NaN 2018-03-28 ZN1805 NaN 2018-03-29 ZN1807 NaN My problem is how do I 'pythonically' fill in the close column of df2 from df1 that has the same date index and contract value? I tried this: from pandas import IndexSlice as idx df2['close'] = df1.loc[df2.index, idx[df2.contract.values.tolist(), 'close']] However I got an error: UnsortedIndexError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)' I understand I could do an iterated way to filter each row, but any pythonic way to do it?
answer count: 2
tagged with: pandas
score: 1
downvote count: 0

http://stackoverflow.com/comment/87046681
comment on: http://stackoverflow.com/q/49975013
type: Comment
type: QuestionComment
has text: @lenz: but the error code tell us that file found `0xb1` byte (in an invalid position for utf-8). Possibly that char is in an incorrect position (e.g. in tag name). And recover was not about the lazy html syntax (POV xml). OTOH 1 in 8000 is probably an exception (so I think a subtle bug). @claudiogugliotta: could you retrieve the page with problem (and maybe reduce it). I think it is worth to investigate further (and probably for a bug report)
score: 0

fractions
tags question: http://stackoverflow.com/q/49981286
type: Tag
tag name: fractions

http://stackoverflow.com/comment/86903530
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49935778
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169451/discussion-between-lucas-farias-and-peter-szoldan).

http://stackoverflow.com/a/50086901
answers question: http://stackoverflow.com/q/49964550
has comment: http://stackoverflow.com/comment/87267216
has comment: http://stackoverflow.com/comment/87265833
downvote count: 0
upvote count: 1
has body: Edit: a more simple WSGI config is given in my question of Python WSGI handler directly in Apache .htaccess, not in VirtualHost Based on Evhz's answer, I made a simple test to check that the processes are still running: Apache config: ServerName example.com AllowOverride All Require all granted WSGIScriptAlias / /home/www/wsgi_test/app.wsgi WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5 display-name=testwsgi app.wsgi file: import os, time from bottle import route, template, default_app os.chdir(os.path.dirname(__file__)) @route('/hello/<name>') def index(name): global i i += 1 return template('Hello {{name}}! request={{i}}, pid={{pid}}', name=name, i=i, pid=os.getpid()) i = 0 time.sleep(3) # wait 3 seconds to make the client notice we launch a new process! application = default_app() Now access http://www.example.com/hello/you many times: The initial time.sleep(3) will help, from the client browser, to see exactly when a new process is started, and the request counter i will allow to see how many requests have been served by each process. The PIDs will correspond to those present in ps aux | grep testwsgi: Also the time.sleep(3) will happen maximum 5 times (at the startup of each of the 5 processes), then the processes should run forever, until we restart/stop the server or modify the app.wsgi file (modifying it triggers a restart of the 5 processes, you can see new PIDs). [I'll check that by letting my test run now, and access http://www.example.com/hello/you in 2 days to see if it's still a previously-launched process or a new one!] Edit: the next day, the same processes were still up and running. Now, two days after, when reloading the same URL, I noticed new processes were created... (Is there a time after which a process with no request dies?)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87266421

http://stackoverflow.com/comment/86935875
comment on: http://stackoverflow.com/a/49959687
type: Comment
type: AnswerComment
has text: Good observation! I hope it helps OP +1
score: 1

http://stackoverflow.com/q/50008592
type: Question
has title: regex runtime diff between create a new rule and using "|", python
answer count: 2
downvote count: 0
upvote count: 1
has body: I am using python3. I have one rule: (re.compile(r'a b', re.IGNORECASE), "A") and later I found 'a c' should also be a match. Which way is more efficient to add this rule? (re.compile(r'a (b|c)', re.IGNORECASE), "A") or simply add another rule (re.compile(r'a c', re.IGNORECASE), "A"). I did 'timeit', yet no significant difference. I am wondering my conclusion is right or not, the reason behind it and if it applies to multi-case, such as 'a (b|c|d|e)' and three extra rules.
tagged with: python
has comment: http://stackoverflow.com/comment/87034565
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50011219
accepted answer: http://stackoverflow.com/a/50011219
score: 1
tagged with: regex
has comment: http://stackoverflow.com/comment/87033666
has answer: http://stackoverflow.com/a/50008682
possible better answer: http://stackoverflow.com/a/50008682
linked to: http://stackoverflow.com/q/29217346

linux
tags question: http://stackoverflow.com/q/49988706
tags question: http://stackoverflow.com/q/49962067
tags question: http://stackoverflow.com/q/49997382
tags question: http://stackoverflow.com/q/49924853
tags question: http://stackoverflow.com/q/50049724
tag name: linux
tags question: http://stackoverflow.com/q/50051146
tags question: http://stackoverflow.com/q/49986119
tags question: http://stackoverflow.com/q/50015167
tags question: http://stackoverflow.com/q/50025219
tags question: http://stackoverflow.com/q/49920444
tags question: http://stackoverflow.com/q/49956272
tags question: http://stackoverflow.com/q/50033136
tags question: http://stackoverflow.com/q/49936845
type: Tag
tags question: http://stackoverflow.com/q/49943206
tags question: http://stackoverflow.com/q/49983862
tags question: http://stackoverflow.com/q/49986774
tags question: http://stackoverflow.com/q/49974542
tags question: http://stackoverflow.com/q/50028447
tags question: http://stackoverflow.com/q/49919133
tags question: http://stackoverflow.com/q/49921214
tags question: http://stackoverflow.com/q/50010997

http://stackoverflow.com/comment/87011136
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49997258
has text: The `abc` module _uses_ a metaclass to do its magic, but that doesn't mean it turns your class into a functioning metaclass.

http://stackoverflow.com/q/49991426
has answer: http://stackoverflow.com/a/49991460
tagged with: python-3.x
linked to: http://stackoverflow.com/q/240178
tagged with: python
accepted answer: http://stackoverflow.com/a/49991460
has body: In the function "enText" changes its value even though I don't modify it. e = 5 and n = 6. enText is an array of ints. I modify the values in the array after passing it to changeTxt. I then return changeTxt but for some reason enText ends up being modified as well. No idea why. #Function for encryption def encrypt(e, n, enText): #e=5 &amp; n=6 changeTxt = enText print(enText) #prints [18, 15, 2, 9, 14] for x in range(0, len(changeTxt)): #problem here!!!!!!!! tmp = changeTxt[x]**e tmp = tmp % n changeTxt[x] = tmp print(enText) #prints [0, 3, 2, 3, 2] return changeTxt
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86999511
upvote count: 3
answer count: 1
has title: Weird python bug. Variable changes value without any modification
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87014083
type: Comment
comment on: http://stackoverflow.com/q/49998456
type: QuestionComment
has text: Also for both models share the `summary()` output.
score: 0

http://stackoverflow.com/comment/87035741
score: 0
has text: @GiacomoCatenazzi The `recover` flag is `True` by default for HTML. I think it has nothing to do with encoding; it's about broken HTML syntax-wise.
type: Comment
comment on: http://stackoverflow.com/q/49975013
type: QuestionComment

http://stackoverflow.com/comment/87145339
type: Comment
comment on: http://stackoverflow.com/a/50064213
type: AnswerComment
score: 0
has text: This is one time hassle or you can use a powerful IDE such as PyCharm and setup your virtual environment, once done, click on any file and it will ask you to install all dependencies for you. No Hassle.

http://stackoverflow.com/comment/87134310
type: QuestionComment
score: 0
has text: You will need to come up with a better algorithm. Your current strategy _can_ work sometimes, if you're lucky with the random numbers, but generally it will get stuck before it completes the square because there won't _be_ a number that works. Take a look at the code I linked earlier, but also see https://en.wikipedia.org/wiki/Backtracking
comment on: http://stackoverflow.com/q/50058425
type: Comment

http://stackoverflow.com/a/50265426
has body: When this happens, I check by using the test functionality in AWS IoT. You can listen to the '$aws/things/TestMichael/shadow/update' topic and see if it is getting data published when the lambda updates the shadow.
score: 0
answers question: http://stackoverflow.com/q/50053347
type: Answer

http://stackoverflow.com/a/49995685
has body: Normally it would be: r = requests.get("url"); from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, 'html.parser') soup.find_all("cite") You can look at the website's source code (ctrl+U, or dev-tools/Inspector and find the tags/class/id where your data is. I see e.g.: &lt;cite class="iUh30"&gt;link...) Now the problem is here, if you look at, the output of: print(soup.prettify()) Then you see, they do not just give you back plain-text, but generate it with JS. You could have a look at other search engines responses Dig deeper into Js code execution from python (maybe other libs etc?) Please, also think about, that some would not consider parsing out data from other websites programatically and in big amount without permission legit. But I have no idea what google's policy is regarding this. requests advanced usage bs4 ======= EDIT: @Rahul's link is the fastest solution to OP. https://www.geeksforgeeks.org/performing-google-search-using-python-code/
answers question: http://stackoverflow.com/q/49994727
type: Answer
score: 0

http://stackoverflow.com/comment/86881432
score: 1
type: Comment
type: QuestionComment
has text: also note that you are using random uniform weights in Keras and random normal weights in Tf
comment on: http://stackoverflow.com/q/49932756

http://stackoverflow.com/comment/87071441
comment on: http://stackoverflow.com/q/50027512
type: QuestionComment
type: Comment
score: 0
has text: @Jacobr365: I guess that's just for equality comparison right?

http://stackoverflow.com/comment/87023271
score: 0
type: QuestionComment
has text: Are you reading the file inside a Python function? Because then the variable `file` will be local to that function, and its lifetime ends when the function end, making your pointer to the data invalid.
type: Comment
comment on: http://stackoverflow.com/q/50002896

http://stackoverflow.com/q/49981686
tagged with: database
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/86979635
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49982352
has answer: http://stackoverflow.com/a/49982272
type: Question
has answer: http://stackoverflow.com/a/49982352
answer count: 2
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86980005
has comment: http://stackoverflow.com/comment/86980862
possible better answer: http://stackoverflow.com/a/49982272
has title: Database with Sqlite3
tagged with: pandas
type: AnsweredQuestion
has body: I am creating a stock price database with Sqlite3 python library. But my code is taking ages to run, not sure why it is slow. Any idea how I can speed it up? Am I doing something wrong? I am using Python 3.x, Anaconda import pandas as pd from googlefinance.client import get_price_data, get_prices_data, get_prices_time_data import sqlite3 db = sqlite3.connect('database.db') c = db.cursor() param = {'q':'MMM', 'i':"86400",'x':"NYSE",'p':"25Y"} end_of_day = pd.DataFrame(get_price_data(param)) end_of_day['Time']=end_of_day.index count= len(end_of_day['Time']) c.execute('CREATE TABLE IF NOT EXISTS MMM(date,open,high,low,close,volume)') for i in range(0,count): c.execute('INSERT INTO MMM(date,open,high,low,close,volume) VALUES(?,?,?,?,?,?)', (str(end_of_day.iloc[i][5]),str(end_of_day.iloc[i][0]),str(end_of_day.iloc[i][1]), str(end_of_day.iloc[i][2]),str(end_of_day.iloc[i][3]),str(end_of_day.iloc[i][4]))) db.commit() c.close() db.close()

http://stackoverflow.com/q/50071280
has answer: http://stackoverflow.com/a/50071401
possible better answer: http://stackoverflow.com/a/50071401
has answer: http://stackoverflow.com/a/50071443
accepted answer: http://stackoverflow.com/a/50071443
has comment: http://stackoverflow.com/comment/87159341
downvote count: 0
has title: Comparing the difference of integers in a list with a given value
has comment: http://stackoverflow.com/comment/87159362
has body: My Python is a bit rusty and I'm really having trouble with this super simple algorithm. I'm trying to write a function that takes two parameters (target, values) to find which number in the values is closest to the target number; if there happens to be a tie, then select the lower number. Here's my progress, but I've only ever selected the lower number without actually comparing the difference of the values in the list in comparison to the relative distance of the target. So, in essence, my function hasn't actually completed the challenge correctly at all because 47 is actually closer to 46 than 31 is; however, if the numbers contained in the list were hypothetically 45 and 47, then they would be equally distant from my target number and so 45 should be printed and not 47. I'd prefer answers that use simple for/if/while loops so that I can really practice my skills. Other more advanced answers are also welcome with a detailed explanation. EDIT A few really good answers from you guys, much appreciated; I'm testing them as we speak and will choose the one most fitting to my style and use the rest as references, even if you have the best one-liner answer. target = 46 values = [1, 22, 31, 47, 87, 99] def closest_to_target(target, values): lower = [] for number in values: if number &lt; target: lower.append(number) if lower: lowest = sorted(lower, reverse=True)[0] return lowest else: return "Error handling array" print closest_to_target(target, values)
linked to: http://stackoverflow.com/q/12141150
has answer: http://stackoverflow.com/a/50071316
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3
has comment: http://stackoverflow.com/comment/87159352
tagged with: algorithm
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50071448
has answer: http://stackoverflow.com/a/50071436
has comment: http://stackoverflow.com/comment/87159396
type: Question

http://stackoverflow.com/comment/87145471
has text: thanks, thanks, and thanks .... can I put all the values in parentheses () For example S1 to S (1)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50064076

http://stackoverflow.com/a/50047327
accepted answer of: http://stackoverflow.com/q/50047174
has comment: http://stackoverflow.com/comment/87110848
has comment: http://stackoverflow.com/comment/87111153
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/87111338
upvote count: 6
has comment: http://stackoverflow.com/comment/87110930
has comment: http://stackoverflow.com/comment/87110905
has body: The problem is due to accuracy of np.float32 vs np.float64. Use np.float64 and you will not see a problem: import numpy as np arr = np.array([3.1415927], dtype=np.float64) print((arr &gt; np.pi)[0]) # True print(arr[0] &gt; np.pi) # True As @WarrenWeckesser comments: It involves how numpy decides to cast the arguments of its operations. Apparently, with arr &gt; scalar, the scalar is converted to the same type as the array arr, which in this case is np.float32. On the other hand, with something like arr &gt; arr2, with both arguments nonscalar arrays, they will use a common data type. That's why (arr &gt; np.array([np.pi]))[3154950] returns True. Related github issue
answers question: http://stackoverflow.com/q/50047174
has comment: http://stackoverflow.com/comment/87111036
has comment: http://stackoverflow.com/comment/87110997
has comment: http://stackoverflow.com/comment/87111486
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87111636

http://stackoverflow.com/comment/87136454
has text: @GrayRidley If you don't mind decimals in your output (e.g., `12.31564` min), sure. Otherwise, use `//` and you will be at max +- a min off.
type: AnswerComment
comment on: http://stackoverflow.com/a/50059928
score: 0
type: Comment

http://stackoverflow.com/comment/86969020
type: Comment
has text: I solved it but problem is that my region is too large so when i am regridding it at 50km scale from 200km scale so python is taking too much time and while i m saving this data into csv so the file size is too much in GBs. How to make process fast and how can i do compression while saving data
comment on: http://stackoverflow.com/a/49974471
score: 0
type: AnswerComment

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/49991704

http://stackoverflow.com/comment/87165715
comment on: http://stackoverflow.com/q/50074446
score: 0
has text: I understand 'equivalent' as identical input and output. Input is the two identical ranges [0,1,2,3,4]
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90211061
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50039223
score: 0
has text: @tobias_k *At least it's simpler than the thread-based approaches* For the record, the approaches in my answer are not thread-based, at least not all of them. They're still complex, though, but that's probably unavoidable without loss of generality.

http://stackoverflow.com/comment/110456495
score: 6
has text: @demongolem if you want each cell, use `df.applymap(type)`
comment on: http://stackoverflow.com/a/49927321
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49956507
type: Question
has body: I have a problem with sympy simplification. See the code below. When I substitute expression under sqrt with something, it becomes "unbreakable". For example, in the last line of code I multiplied expression by f0 and simplified the result. f0 in numerator and sqrt(f0**2) in denominator did not get simplified out even though f0 is declared as nonnegative. What did I do wrong and how do I substitute expressions without having this effect? Code (pretty version with rendered equations): &gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; from sympy import * &gt;&gt;&gt; from sympy.abc import pi &gt;&gt;&gt; init_printing(use_unicode=True) &gt;&gt;&gt; L0, Csum0, f0 = symbols("L0 C_{{\\Sigma}0} f0", nonnegative=True) &gt;&gt;&gt; equation = sqrt(L0) &gt;&gt;&gt; equation ____ ╲╱ L₀ &gt;&gt;&gt; substitute = solve(Eq(1/(2*pi*sqrt(L0)*sqrt(Csum0)), f0), L0, dict=1)[0] &gt;&gt;&gt; substitute ⎧ 1 ⎫ ⎪L₀: ──────────────────────⎪ ⎨ 2 2⎬ ⎪ 4⋅C_{{\Sigma}0}⋅f₀ ⋅π ⎪ ⎩ ⎭ &gt;&gt;&gt; equation = equation.subs(substitute) &gt;&gt;&gt; equation ______________________ ╱ 1 ╱ ──────────────────── ╱ 2 2 ╲╱ C_{{\Sigma}0}⋅f₀ ⋅π ─────────────────────────── 2 &gt;&gt;&gt; simplify(equation*f0) ______________________ ╱ 1 f₀⋅ ╱ ──────────────────── ╱ 2 2 ╲╱ C_{{\Sigma}0}⋅f₀ ⋅π ────────────────────────────── 2
tagged with: sympy
downvote count: 0
has answer: http://stackoverflow.com/a/49968481
accepted answer: http://stackoverflow.com/a/49968481
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Sympy does not simplify an expression with a symbol divided by the square root of its square
tagged with: symbolic-math
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/87063691
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50021660
has text: Thank you Noor, where do i pass the database information and user credentials , is it with in `cur = db.connection.cursor()` ?
type: AnswerComment

http://stackoverflow.com/comment/97455989
has text: you can also use conversion by `pd.to_numeric(...)` https://stackoverflow.com/a/28648923/4521646
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50938359
type: AnswerComment

http://stackoverflow.com/a/50076849
answers question: http://stackoverflow.com/q/50072357
score: 0
type: Answer
has body: Try this:- app.secret_key = "define secret key of your own choice" I hope this works for you

http://stackoverflow.com/q/49922674
tagged with: tensorflow
favorite count: 0
type: Question
has body: Actually, I'm doing the homework "Art Generation with Neural Style Transfer" of deeplearning.ai on coursera. In the function compute_layer_style_cost(a_S, a_G): a_S = tf.reshape(a_S, [n_H*n_W, n_C]) a_G = tf.reshape(a_G, [n_H*n_W, n_C]) GS = gram_matrix(tf.transpose(a_S)) GG = gram_matrix(tf.transpose(a_G)) Why does this code give the right answer, however, the following doesn't: a_S = tf.reshape(a_S, [n_C, n_H*n_W]) a_G = tf.reshape(a_G, [n_C, n_H*n_W]) GS = gram_matrix(a_S) GG = gram_matrix(a_G)
tagged with: python
accepted answer: http://stackoverflow.com/a/49923087
upvote count: 6
has answer: http://stackoverflow.com/a/49923087
tagged with: numpy
type: AnsweredQuestion
has title: Difference between `tf.reshape(a, [m, n])` and `tf.transpose(tf.reshape(a, [n, m]))`?
tagged with: deep-learning
tagged with: matrix
downvote count: 0
answer count: 1
score: 6

http://stackoverflow.com/q/50053757
has comment: http://stackoverflow.com/comment/87124765
score: 1
accepted answer: http://stackoverflow.com/a/50053847
tagged with: python
has answer: http://stackoverflow.com/a/50053847
has comment: http://stackoverflow.com/comment/87124552
upvote count: 2
answer count: 1
downvote count: 1
favorite count: 0
has title: How to get the whole word starting at an index in a string in Python
type: Question
has body: I have something like: import re text = 'hi this is john my name is john im bad boy' target = 'is john' target = target.replace(' ', '[\s\n]*') target = re.compile(r'\b%s' % target, flags=re.I | re.X) indices = [m.start() for m in re.finditer(target, text)] And I want to then find the word after and before each occurrence in indices (ie. 'this', 'my' and 'name', 'im'). However, I want to avoid using regex to find the words outright because it is too slow when searching bigger files and if I want to find n > 1 word on each side of each occurrence of target. So I have the indices, and I want to get the words before and after the word at the index.
type: AnsweredQuestion

http://stackoverflow.com/comment/136810030
has text: Isn't the code line, `train_data = shuffle(train_data)` broke the sequence of input signal?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50055502

string
tags question: http://stackoverflow.com/q/49959715
tags question: http://stackoverflow.com/q/50064596
type: Tag
tags question: http://stackoverflow.com/q/50005856
tags question: http://stackoverflow.com/q/50066306
tags question: http://stackoverflow.com/q/49928375
tags question: http://stackoverflow.com/q/49959119
tags question: http://stackoverflow.com/q/50024431
tags question: http://stackoverflow.com/q/50037992
tags question: http://stackoverflow.com/q/50031488
tags question: http://stackoverflow.com/q/50023635
tags question: http://stackoverflow.com/q/49918693
tags question: http://stackoverflow.com/q/49991360
tags question: http://stackoverflow.com/q/49923488
tags question: http://stackoverflow.com/q/50022491
tags question: http://stackoverflow.com/q/49975644
tags question: http://stackoverflow.com/q/50033030
tags question: http://stackoverflow.com/q/49936175
tags question: http://stackoverflow.com/q/50037871
tags question: http://stackoverflow.com/q/49927030
tags question: http://stackoverflow.com/q/49969539
tags question: http://stackoverflow.com/q/50057457
tags question: http://stackoverflow.com/q/49921980
tags question: http://stackoverflow.com/q/49945812
tags question: http://stackoverflow.com/q/50037194
tags question: http://stackoverflow.com/q/49930459
tags question: http://stackoverflow.com/q/49936559
tags question: http://stackoverflow.com/q/50033898
tags question: http://stackoverflow.com/q/49966479
tags question: http://stackoverflow.com/q/50017054
tags question: http://stackoverflow.com/q/49994020
tags question: http://stackoverflow.com/q/49923934
tags question: http://stackoverflow.com/q/50068837
tags question: http://stackoverflow.com/q/49921601
tags question: http://stackoverflow.com/q/50074439
tags question: http://stackoverflow.com/q/49987329
tags question: http://stackoverflow.com/q/50033608
tags question: http://stackoverflow.com/q/49998198
tags question: http://stackoverflow.com/q/49929647
tags question: http://stackoverflow.com/q/49933970
tags question: http://stackoverflow.com/q/50018857
tags question: http://stackoverflow.com/q/49946165
tags question: http://stackoverflow.com/q/49919272
tags question: http://stackoverflow.com/q/49917743
tags question: http://stackoverflow.com/q/49931629
tags question: http://stackoverflow.com/q/49976858
tags question: http://stackoverflow.com/q/49984905
tags question: http://stackoverflow.com/q/49960871
tags question: http://stackoverflow.com/q/50026954
tags question: http://stackoverflow.com/q/49941816
tags question: http://stackoverflow.com/q/50066830
tags question: http://stackoverflow.com/q/49925292
tags question: http://stackoverflow.com/q/50018955
tags question: http://stackoverflow.com/q/49941052
tags question: http://stackoverflow.com/q/49968074
tags question: http://stackoverflow.com/q/50042403
tags question: http://stackoverflow.com/q/49958177
tags question: http://stackoverflow.com/q/49976576
tags question: http://stackoverflow.com/q/49999369
tags question: http://stackoverflow.com/q/49976676
tags question: http://stackoverflow.com/q/49923479
tags question: http://stackoverflow.com/q/50037369
tags question: http://stackoverflow.com/q/49964227
tag name: string
tags question: http://stackoverflow.com/q/50022764
tags question: http://stackoverflow.com/q/50072900
tags question: http://stackoverflow.com/q/50027104
tags question: http://stackoverflow.com/q/49953285
tags question: http://stackoverflow.com/q/50056859
tags question: http://stackoverflow.com/q/50051440
tags question: http://stackoverflow.com/q/50001328
tags question: http://stackoverflow.com/q/49950926
tags question: http://stackoverflow.com/q/50007292
tags question: http://stackoverflow.com/q/49951647
tags question: http://stackoverflow.com/q/49979749
tags question: http://stackoverflow.com/q/49924922
tags question: http://stackoverflow.com/q/50030731
tags question: http://stackoverflow.com/q/49958976
tags question: http://stackoverflow.com/q/49961508

http://stackoverflow.com/comment/86873821
comment on: http://stackoverflow.com/q/49928609
has text: If you didn't count the repetitions, you could potentially do some arithmetic like `((myList[-1] - a)/d) + 1` but this only works if the last element is part of the sequence. I am not sure it's possible in less than `O(N)`.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49987072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86990604
has answer: http://stackoverflow.com/a/75389576
has title: Controller Support in PyGame
has body: Is it possible to add a purely python code to python, more specifically in the pygame module, so that it can take direct input from a Controller (XBox One, PS4, etc.)? I have attempted to use the following code with no luck; win.onkey() win.use(sys())
downvote count: 0
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/87072972
tagged with: pygame
has answer: http://stackoverflow.com/a/71983026
favorite count: 0
has comment: http://stackoverflow.com/comment/86997587
type: Question
answer count: 2
upvote count: 2

http://stackoverflow.com/q/49925555
has comment: http://stackoverflow.com/comment/87981668
tagged with: jupyter-notebook
type: Question
has answer: http://stackoverflow.com/a/50897718
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: virtualenv
has body: I have been following along the Hands-On Machine Learning with Scikit-Learn and TensorFlow book. I have followed all commands but every time I try to run $jupyter notebook I receive the following error: "Error executing Jupyter command 'notebook': [Errno 2] No such file or directory" Here is a list of all the commands I have run so far: $sudo apt-get install python-setuptools $sudo easy_install pip==9.0.1 $sudo pip install virtualenv $pip3 install --user --upgrade virtualenv $source env/bin/activate $pip3 install --upgrade jupyter matplotlib numpy pandas scipy scikit-learn $sudo pip install jupyter $pip3 install --upgrade --force-reinstall --no-cache-dir jupyter $pip install notebook As you can see, I have tried a lot and it still won't work. I am using windows 10 with an ubuntu shell (bash). I have also installed anaconda but it is in my D: drive, not the C: drive. Could that be it? Any help would be appreciated. Thanks. EDIT: I have reinstalled anaconda on my C drive and restarted my computer but it still won't work.
score: 0
has title: Jupyter notebook command returns Error executing Jupyter command 'notebook': [Errno 2] No such file or directory
answer count: 1
tagged with: jupyter

http://stackoverflow.com/q/49920035
answer count: 1
has body: I have realized that in a corpus XML file many sentences are missing the sentence ID which are important to navigate through them. I would like now to iterate through all &lt;sentence/&gt; tags and add an attribute with an enumerating value such as: &lt;sentence id="1"&gt;, and the next &lt;sentence id="2"&gt; and so on. In BeautifulSoup one can add attributes: soup.find('sentence')['id'] = '1' that returns &lt;sentence id="1"&gt;in the tree. Now, how can I increment that number continously? (Suggestions for Elementtree are also very welcome)
favorite count: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/49920455
accepted answer: http://stackoverflow.com/a/49920455
tagged with: python
has title: How to modify and enumerate XML tags in python
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86922568
comment on: http://stackoverflow.com/q/49952760
type: Comment
has text: You do not seem to describe what does not work in what you implemented, so it's difficult to try and help you...
score: 0
type: QuestionComment

http://stackoverflow.com/a/64638229
has comment: http://stackoverflow.com/comment/114291947
downvote count: 0
upvote count: 1
has body: Here's a simple way to do this using NumPy. It is somewhat similar to the OP's idea of indexing instead of looping again inside the main loop, but without the division check, only slicing. It is also similar to user2357112 supports Monica answer, but this one only considers odd numbers, which makes it faster. This is a typical odd only sieve: https://stackoverflow.com/a/20248491/8094047. Create a bool array of size n. Loop through odd numbers up to square root of n. Note: numbers are used interchangeably as indices Mark composite (multiples of primes) numbers as false. In the end we have a bool array that we can use to check if a number below n is prime (except even numbers, you can check for them without the array, using &amp; 1 or so) Avg. time for n = 20000000: 0.1063s import numpy as np n = 20000000 isprime = np.ones(n, dtype=np.bool) # odd only sieve i = 3 while (i * i &lt; n): if isprime[i]: isprime[i * i:n:2 * i] = False i += 2 # test print(isprime[97]) # should be True
answers question: http://stackoverflow.com/q/49936222
score: 1
has comment: http://stackoverflow.com/comment/138515324
type: Answer

http://stackoverflow.com/comment/87016489
score: 0
comment on: http://stackoverflow.com/q/49999636
has text: Thanks for that. Next clarification. It looks like you are wanting one type of stacked bar chart with two applications. 1) that places Cat_1 on the X-axis with the height being the total count of strings contained within each corresponding Cat_2. And then your second use case is just using it the opposite way: with sums of "P", "E" and "R" chunked for each "Apples", "Pears" and Cats" on the x-axis. I am reading this correctly?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49918307
tagged with: python
tagged with: qlineedit
score: 0
tagged with: pyqt
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37270376
answer count: 1
has body: I have the following PyQT code: self.datestartbox = QLineEdit(self) # Create a textbox self.dateendbox = QLineEdit(self) # Create a textbox How can I get the user input as soon there is text in the fields? At the moment I can only get it when user clicks a button and then use self.datestartbox.text() Cheers!
tagged with: pyqt5
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/37270376
has answer: http://stackoverflow.com/a/49919451
has title: Retrieving information from QLineEdit as soon as there is input?

http://stackoverflow.com/comment/86936612
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49959656
type: Comment
has text: The problem seems to be related to `None`. `Union[Type[BaseException],None]` fails also.

http://stackoverflow.com/q/49995728
has answer: http://stackoverflow.com/a/49995842
favorite count: 0
has body: I am having following CSV "name","isTrue","ID" "ashok",True, 12 When I read it using dictRead values are appended with single quotes. For example, output would be: ["name" : 'ashok', "isTrue":'True', "ID":'12'] I don't want it to add quotes for True and 12 value since I didn't have quotes in my CSV. I tried using regular file read, but again splitting the line yields list of string. Can any one help me on this?
type: Question
has comment: http://stackoverflow.com/comment/87007966
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49995881
answer count: 3
type: UnansweredQuestion
score: 1
has title: Python CSV reading unnecessary adding quotes
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49996046

http://stackoverflow.com/q/49968647
has body: I am working on a simple python script to test mpi4py. Specifically, I want to broadcast a scalar and an array from a given processor (say rank 0), so that all other processors have access to the values of the broadcasted scalar and the array in subsequent steps. This is what I have done till now: from __future__ import division from mpi4py import MPI import numpy as np comm = MPI.COMM_WORLD nproc = comm.Get_size() rank = comm.Get_rank() if rank==0: scal = 55.0 mat = np.array([[1,2,3],[4,5,6],[7,8,9]]) arr = np.ones(5) result = 2*arr comm.bcast([ result , MPI.DOUBLE], root=0) comm.bcast( scal, root=0) comm.bcast([ mat , MPI.DOUBLE], root=0) for proc in range(1, 3): if (rank == proc): print "Rank: ", rank, ". Array is: ", result print "Rank: ", rank, ". Scalar is: ", scal print "Rank: ", rank, ". Matrix is: ", mat But, I get the following errors: NameError: name 'mat' is not defined print "Rank: ", rank, ". Matrix is: ", mat Also, in my output (print "Rank: ", rank, ". Scalar is: ", scal and print "Rank: ", rank, ". Array is: ", arr), I do not see the values of scal and array. What am I missing here? I will really appreciate any help.
answer count: 1
tagged with: cluster-computing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86973382
has title: mpi4py | comm.bcast does not work
has comment: http://stackoverflow.com/comment/86995405
tagged with: mpi
tagged with: hpc
tagged with: python
tagged with: mpi4py
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49970737
accepted answer: http://stackoverflow.com/a/49970737
downvote count: 0

http://stackoverflow.com/comment/86982477
has text: Is the below answer is your expected output?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49976047
type: Comment

http://stackoverflow.com/comment/86971624
has text: Yes that's is the issue, I don't know how to force my code to read variable path instead of exact path... Do you understand? I don't want to use exact path but I want to use path in variable and part of path as I mentioned Components\xxx\etc\static-data\myfile.xml
comment on: http://stackoverflow.com/q/49977495
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87113920
type: QuestionComment
has text: looks like you need `str.join`?
comment on: http://stackoverflow.com/q/50048877
score: 0
type: Comment

iterable-unpacking
type: Tag
tags question: http://stackoverflow.com/q/49931186
tag name: iterable-unpacking
tags question: http://stackoverflow.com/q/50054003

http://stackoverflow.com/comment/86949164
type: Comment
has text: Well, unless you also removed the `pass` in except and replaced it with something useful (start with `raise`) then you can't be sure you did the same thing.
comment on: http://stackoverflow.com/a/49966720
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86882559
has text: Can I use asyncio? I think it is similar to aiohttp. I am not sure how to use that.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49932737

http://stackoverflow.com/comment/86907020
comment on: http://stackoverflow.com/a/49943548
type: Comment
has text: see my latest edit. I do not know if I can help you much more with this, as you seem to have requirements I do not quite understand. This code starts asset loading and stays in the while loop until done, no matter how long it takes. Only when the thread exits, the while loop exits as well.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49948541
accepted answer of: http://stackoverflow.com/q/49948412
has comment: http://stackoverflow.com/comment/86913703
has comment: http://stackoverflow.com/comment/86913813
type: Answer
answers question: http://stackoverflow.com/q/49948412
has comment: http://stackoverflow.com/comment/86914171
has body: You can be explicit and concise: def __eq__(self, other): fetcher = operator.attrgetter("a", "b", "c", "d") try: return self is other or fetcher(self) == fetcher(other) except AttributeError: return False Just comparing the __dict__ attribute (which might not exist if __slots__ is used) leaves you open to the risk that an unexpected attribute exists on the object: class A: def __init__(self, a): self.a = a def __eq__(self, other): return self.__dict__ == other.__dict__ a1 = A(5) a2 = A(5) a1.b = 3 assert a1 == a2 # Fails
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/86999206
type: Comment
has text: using python 'extend' is an option for you --> https://www.tutorialspoint.com/python/list_extend.htm
comment on: http://stackoverflow.com/q/49991273
score: 0
type: QuestionComment

http://stackoverflow.com/q/49934177
type: Question
upvote count: 2
tagged with: server
has answer: http://stackoverflow.com/a/49934848
type: UnansweredQuestion
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/50198799
score: 2
has body: Hi I have a Python (version 3.6) script which I developed in my laptop. But I would need to run the script from another server. I have installed the same version of Python on the server but not the modules which are imported in my script. These modules are installed on my laptop though. Is it possible to run the python script from the server without installing the imported modules in the server? Thanks Shanto
answer count: 3
downvote count: 0
has title: Is it possible to run python script from another machine without installing imported modules?
has comment: http://stackoverflow.com/comment/86884014
tagged with: libraries
favorite count: 0
has answer: http://stackoverflow.com/a/49935434

http://stackoverflow.com/comment/87095195
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50039505
has text: Just print stuff to see what you are working on. Do not suppose it should work.
score: 0

http://stackoverflow.com/comment/87048408
comment on: http://stackoverflow.com/a/50016046
score: 0
type: Comment
has text: Yes, logging is good idea, which I will use in next processings. But this particular is already running.
type: AnswerComment

http://stackoverflow.com/q/50051776
has comment: http://stackoverflow.com/comment/87120171
has answer: http://stackoverflow.com/a/50065844
type: Question
tagged with: plotnine
has comment: http://stackoverflow.com/comment/87123450
has comment: http://stackoverflow.com/comment/87119966
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50065844
tagged with: inspection
has body: New to python, I'm trying to fine tuning the plotnine graph, and explore what can be done in the theme() function. I'm just wondering what is the general way to find out what else is available for me to play with. theme(plot_title = element_text(size=10, text='tile'), axis_title_y = element_text(size=7, text='tlab'), axis_title_x = element_text(size=7,text='xlab'))
type: AnsweredQuestion
has title: How to find what can be tuned in theme()
tagged with: python

http://stackoverflow.com/q/49922460
has answer: http://stackoverflow.com/a/49922520
has answer: http://stackoverflow.com/a/52469364
tagged with: python
upvote count: 15
tagged with: image
score: 15
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/49922520
possible better answer: http://stackoverflow.com/a/52469364
downvote count: 0
has comment: http://stackoverflow.com/comment/86860696
favorite count: 0
has title: Scale a numpy array with from -0.1 - 0.2 to 0-255
type: AnsweredQuestion
has body: I have an numpy array in python that represent an image its size is 28x28x3 while the max value of it is 0.2 and the min is -0.1. I want to scale that image between 0-255. How can I do so?
linked to: http://stackoverflow.com/q/21030391

http://stackoverflow.com/a/56750453
upvote count: 21
has comment: http://stackoverflow.com/comment/120024791
has comment: http://stackoverflow.com/comment/119206478
has body: This problem is mainly caused due to different versions. The tensorflow.keras version may not be same as the keras. Thus causing the error as mentioned by @Priyanka. For me, whenever this error arises, I pass in the name of the optimizer as a string, and the backend figures it out. For example instead of tf.keras.optimizers.Adam or keras.optimizers.Adam I do model.compile(optimizer= 'adam' , loss= keras.losses.binary_crossentropy, metrics=['accuracy'])
score: 21
answers question: http://stackoverflow.com/q/50056356
type: Answer
has comment: http://stackoverflow.com/comment/114602795
has comment: http://stackoverflow.com/comment/138947869
downvote count: 0

http://stackoverflow.com/q/49946616
has body: I am trying to write a plugin environment where I need to do multiple inheritances on an unknown number of classes. Therefore, I have opted to use the type class creation: class A(object): def __init__(self,s): self.a="a" def testA(self,x): print(x) class B(object): def __init__(self,s): self.b="b" def testA(self,x): print(x) C = type('C', (A,B), {}) x= C("test") print x.b When I run the above code, I get the error: AttributeError: 'C' object has no attribute 'b' This is because only the init for class A is being run when the instance for class C is initialized. My question is how can I get the class C to have both the init for class A as well as the init for class B to run when an instance of class C is initialized. I do realize that if I had class C like the following it would work: class C(A,B): def __init__(self,s): A.__init__(self,s) B.__init__(self,s) However, given that I need to have a dynamic list of classes inherited this will not work.
has comment: http://stackoverflow.com/comment/86909719
tagged with: python
accepted answer: http://stackoverflow.com/a/49946788
tagged with: class
has answer: http://stackoverflow.com/a/49946788
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: multiple-inheritance
has title: python dynamic multiple inheritance __init__
type: Question

http://stackoverflow.com/a/50049740
has comment: http://stackoverflow.com/comment/87118529
downvote count: 0
answers question: http://stackoverflow.com/q/50049069
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87119019
has comment: http://stackoverflow.com/comment/87117574
has body: It turns out that I overestimated the difference between Python and numpy, and while the Python code I put in the question is quite slow, it can be made much faster using a preallocated array: def python_parse(arr): result = np.empty(shape=(len(arr),), dtype=int) for i, x in enumerate(arr): try: result[i] = x except ValueError: raise Exception(f'Failed at: {i}') return result This produces errors correctly and is almost as fast as simply np.array(strings, dtype=int) (which seriously surprised me).
type: Answer
has comment: http://stackoverflow.com/comment/87115912
accepted answer of: http://stackoverflow.com/q/50049069
has comment: http://stackoverflow.com/comment/87118929

http://stackoverflow.com/q/49987236
type: Question
tagged with: python-3.x
downvote count: 0
tagged with: python
has title: Using complex mysql query python is not returning correct values
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49987303
has body: I am trying to get results from mysql database using python3 and having some issues retrieving the values. MySQL table: Stock Date Price GOOG 2012-05-20 402 GOOG 2012-05-21 432 APPL 2012-05-20 553 APPL 2012-05-21 590 FB 2012-05-20 40 FB 2012-05-21 34 Following is the expected result in MySQL Stock Date Price Change GOOG 2012-05-21 30 APPL 2012-05-21 37 FB 2012-05-21 -6 I am using following MySQL to get results mentioned in expected results above: SELECT t1.stock, t1.date AS CurrentDate, oldDate.date AS OldDate, ( t1.price - oldDate.price ) AS PriceChange FROM mp_stocktable t1 JOIN (SELECT t2.stock, t2.date AS date1, (SELECT Max(t3.date) FROM mp_stocktable t3 WHERE t3.date &lt; t2.date AND t3.stock = t2.stock GROUP BY t3.stock) AS date2 FROM mp_stocktable t2) AS StockDates ON StockDates.stock = t1.stock AND StockDates.date1 = t1.date JOIN mp_stocktable oldDate ON oldDate.stock = t1.stock AND oldDate.date = StockDates.date2 I have following python function which is running query mentioned above with where clause def checkStockSold(db,stock): print("*************checkStockSold*************") try: curs = db.cursor() query = (" SELECT t1.stock, t1.date AS CurrentDate, oldDate.date AS OldDate, ( t1.price - oldDate.price ) AS PriceChange FROM mp_stocktable t1 JOIN (SELECT t2.stock, t2.date AS date1, (SELECT Max(t3.date) FROM mp_stocktable t3 WHERE t3.date &lt; t2.date AND t3.stock = t2.stock GROUP BY t3.stock) AS date2 FROM mp_stocktable t2) AS StockDates ON StockDates.stock = t1.stock AND StockDates.date1 = t1.date JOIN mp_stocktable oldDate ON oldDate.stock = t1.stock AND oldDate.date = StockDates.date2" "WHERE t1.stock = %s",(Stock,)) print(query) curs.execute(query) for calcStockBalance in curs: pprint.pprint(calcStockBalance) return calcStockBalance except TypeError as e: print(e) I am getting following when I do pprint or print on calcStockBalance a bytes-like object is required, not 'tuple' What I am doing wrong here ? I have also tried the for loop like this for st…
has answer: http://stackoverflow.com/a/49987303
has comment: http://stackoverflow.com/comment/86990826
answer count: 1
has comment: http://stackoverflow.com/comment/86990808
tagged with: mysql
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86990812
has comment: http://stackoverflow.com/comment/86990729
favorite count: 0

http://stackoverflow.com/comment/86986905
comment on: http://stackoverflow.com/a/49976002
has text: I'm still confused about how to use the data that is gathered with the script I have above. How will the code in the comment you gave me live inside of the script I already have. Can you show me how you would merge them together so that they function as one program, please?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87099280
type: Comment
has text: OP only has an input statement and is not doing anything with it. Question is not clear if he needs help with finalizing what he has, or that he needs a complete new approach. In case of a new approach more info is needed on "how to select" the said algorithms, what type of input this has, and if there is something in the data which can be used to select which code to run. If that is the case you can do classes or consider other approaches.
comment on: http://stackoverflow.com/a/50041590
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86930181
type: Comment
comment on: http://stackoverflow.com/a/49956832
score: 0
type: AnswerComment
has text: @KonstantinNikitin `array.array` is probably the most underrated Python standard library module, and was so even before it was made somewhat obsolete by `numpy`. Interestingly, in PyPy `array.array('i', (0,)) * 10**8` is instantaneous because PyPy recognizes and special-cases construction of an array consisting of all zeros.

http://stackoverflow.com/q/49923598
has comment: http://stackoverflow.com/comment/86863903
has comment: http://stackoverflow.com/comment/86863087
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: pyqt5
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/86864088
favorite count: 0
has title: pyQt5 program with multiple windows
has comment: http://stackoverflow.com/comment/86898933
has answer: http://stackoverflow.com/a/49924214
has comment: http://stackoverflow.com/comment/86863232
score: 1
has body: I'am trying to make a program with multiple windows so that next window will open after clicking a pushbutton. Now i'm at this point where the first window works just fine and the second window opens BUT pushbuttons doesn't work. Edit:The button in the second window does nothing when the window is opened from the first one but when the class "Second" is called by its own and not from the first window, it works. Here is the important parts from the class for the first window: class Aloitus(QMainWindow): def __init__(self): super().__init__() self.InitAloitus() def InitAloitus(self): self.button=QPushButton("Ok",self) self.button.move(200,200) self.button.clicked.connect(self.continue) self.setGeometry(600,200,500,300) self.show() def continue(self): self.close() next=Second() next.__init__() And here is the class for second window: class Second(QMainWindow): def __init__(self): super().__init__() self.title="Alkutiedot" self.top=600 self.left=200 self.width=500 self.height=500 self.initWindow() def initWindow(self): self.button=QPushButton("Ok", self) self.button.move(100,400) self.button.clicked.connect(self.ok) self.setWindowTitle(self.title) self.setGeometry(self.top, self.left, self.width, self.height) self.show() def ok(self): self.close()
type: Question

http://stackoverflow.com/q/50049567
accepted answer: http://stackoverflow.com/a/50049608
has body: I have been trying to run a program using keyboard input to decide whether or not to run the program and the if statement is ignoring the input and always defaults to the else statement. Here is my code. import random import time import sys print("Do you want to run the program? Yes/No") ans = sys.stdin.readline() time.sleep(1) if ans == "Yes" or ans == "yes": '''Body of IF statement''' else: print("Alright, have a great day!")
has answer: http://stackoverflow.com/a/50049608
type: Question
tagged with: stdin
has comment: http://stackoverflow.com/comment/87115304
tagged with: if-statement
has comment: http://stackoverflow.com/comment/87115270
tagged with: python
has title: IF statement ignoring keyboard input
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/a/49965411
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86964177
has comment: http://stackoverflow.com/comment/86966258
has body: Full code: import requests from bs4 import BeautifulSoup urls = ['http://www.lyricsfreak.com/e/ed+sheeran/shape+of+you_21113143.html/', 'http://www.lyricsfreak.com/e/ed+sheeran/thinking+out+loud_21083784.html', 'http://www.lyricsfreak.com/e/ed+sheeran/photograph_21058341.html'] for url in urls: page = requests.get(url) page.encoding = 'utf-8' soup = BeautifulSoup(page.text, 'html.parser') div = soup.select_one('#content_h') for e in div.find_all('br'): e.replace_with('\n') lyrics = div.text print(lyrics) Notice that sometimes the wrong encoding is used: I may be crazy donât mind me That's why I set it manually: page.encoding = 'utf-8'. Fragment of the requests docs mentioning this situation: The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.
accepted answer of: http://stackoverflow.com/q/49962350
type: Answer
answers question: http://stackoverflow.com/q/49962350
score: 0
has comment: http://stackoverflow.com/comment/86984249

http://stackoverflow.com/comment/87143995
score: 0
type: AnswerComment
has text: yes the items in a table for example
type: Comment
comment on: http://stackoverflow.com/a/50063006

http://stackoverflow.com/comment/86953850
type: AnswerComment
comment on: http://stackoverflow.com/a/49959383
has text: Sure! For i=1,...,len(t)-1, you are checking the elements that aren't at either end. For i=0, t[i-1]=t[-1] fetches the last element of the array so you are checking the first element. For i=len(t), i % len(t) = 0, so you have looped back round and got the first element, while checking for the last. You're right that I didn't need len(t)+1, thanks @Jasper
score: 0
type: Comment

http://stackoverflow.com/comment/87106695
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50037645
has text: Looks like you are trying to import Python3 modules into Jython, which is still at Python2. I don't think that is going to work.

http://stackoverflow.com/comment/87092083
comment on: http://stackoverflow.com/a/50037501
type: AnswerComment
has text: I've added instructions for finding it in the Control Panel.
score: 0
type: Comment

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/49927538
type: Tag

http://stackoverflow.com/comment/86876539
score: 0
comment on: http://stackoverflow.com/a/49930086
type: AnswerComment
type: Comment
has text: @ASGM I hadn't thought of that. Thanks!

http://stackoverflow.com/comment/87090826
type: Comment
comment on: http://stackoverflow.com/q/50037109
type: QuestionComment
has text: Looks like you found a pandas bug
score: 0

http://stackoverflow.com/comment/87092687
type: Comment
has text: In the generator example the inner `()` are implicit and not needed (as long as the generator is the sole argument).
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/50038021

http://stackoverflow.com/a/49966116
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49966058
score: 1
type: Answer
has body: Try this: d = {k:[i[0] for i in v] for k,v in p.items()} &gt; d {'a': [0, 0]}

http://stackoverflow.com/comment/86869992
comment on: http://stackoverflow.com/q/49926263
type: Comment
type: QuestionComment
score: 0
has text: Also, its not clear what the functions `rand_name_giving_func()` and `rand_value()` do. Its quite likely that the errors are appearing when these values are being updated to the temp dictionary.

http://stackoverflow.com/q/49938071
linked to: http://stackoverflow.com/q/7974849
tagged with: python
possible better answer: http://stackoverflow.com/a/49938155
has comment: http://stackoverflow.com/comment/86895111
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86899586
tagged with: spyder
answer count: 3
tagged with: user-interface
has comment: http://stackoverflow.com/comment/86895629
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/86900577
has comment: http://stackoverflow.com/comment/86896591
has title: Run script from GUI
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49941780
has answer: http://stackoverflow.com/a/49944896
has answer: http://stackoverflow.com/a/49938155
type: Question
has answer: http://stackoverflow.com/a/49941780
has body: I wrote a script (test.py) for Data Analysis. Now I'm doing a GUI in PyQt. What I want is when I press a button 'Run', the script test.py will run and show the results (plots). I tried subprocess.call('test1.py') and subprocess.Popen('test1.py') but it only opens the script and don't run it. I also tried os.system, doesn't work either. The script below is not complete (there are more buttons and functions associated but is not relevant and aren't connect to the problem described). I'm using Python 3.6 on Spyder and PyQt5. Is there any other function or module that can do what I want? class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50, 50, 500, 300) self.setWindowTitle("TEMP FILE") self.home() def home (self): btn_run = QPushButton("Run", self) btn_run.clicked.connect(self.execute) self.show() def execute(self): subprocess.Popen('test1.py', shell=True) subprocess.call(["python", "test1.py"]) if not QtWidgets.QApplication.instance(): app = QtWidgets.QApplication(sys.argv) else: app = QtWidgets.QApplication.instance() GUI = Window() app.exec_()

http://stackoverflow.com/comment/87147594
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/50065484
type: Comment
has text: Possible duplicate of [How to calculate precision and recall in Keras](https://stackoverflow.com/questions/43076609/how-to-calculate-precision-and-recall-in-keras)

http://stackoverflow.com/q/50070820
tagged with: python
linked to: http://stackoverflow.com/q/14010551
has comment: http://stackoverflow.com/comment/87158235
has comment: http://stackoverflow.com/comment/87177811
score: 2
duplicate of: http://stackoverflow.com/q/14010551
tagged with: python-2.7
has title: Inconsistent `str(b"")` return values between python versions
linked to: http://stackoverflow.com/q/49681951
has comment: http://stackoverflow.com/comment/87158580
answer count: 0
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87158697
favorite count: 0
has body: Python 2.7.13 &gt;&gt;&gt; str(b'') "" &gt;&gt;&gt; bool(str(b'')) False Python 3.6.0 &gt;&gt;&gt; str(b'') "b''" &gt;&gt;&gt; bool(str(b'')) True My question is two-fold: Why does this happen? What is the best way to get an empty string from an empty byte string in Python 3.6.0?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87158328
has comment: http://stackoverflow.com/comment/87158401
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/49681951

http://stackoverflow.com/q/49969966
tagged with: python-3.x
has title: How to convert a "YYYY:MM:DD" that xlrd reads as a float to a date in python
type: UnansweredQuestion
tagged with: python
tagged with: date
tagged with: excel
has comment: http://stackoverflow.com/comment/86956178
has comment: http://stackoverflow.com/comment/90146812
answer count: 0
tagged with: xlrd
has comment: http://stackoverflow.com/comment/86956329
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86955955
score: 1
has comment: http://stackoverflow.com/comment/86955891
has body: If you have an excel with dates stored in a format "YYYY/MM/DD" there is no much problem, excel stores it as an integer and you can make it a date by using: x = work_sheet.cell(1,4).value #in excel this cell is "2006/02/04" dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(x) - 2) print(dt) which will return 2006-02-04 00:00:00 However there is other dates in the excel stored in a different format "YYYY:MM:DD" if you try the same code in this cells with dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(x) - 2) it will allways return 1900-03-23 00:00:00 and if you try dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + x - 2) it says it expected a float and gives an error. So I used : x = work_sheet.cell_value(rowx=1, colx=0) # in excel this cell is "2006:02:04" print(xlrd.xldate_as_tuple(x, 1)) and the output was: (1904, 3, 24, 14, 2, 4) Is there a form to make it a normal date? I think is kind of making it like if it was a smaller time since 1900-03-23 00:00:00, and making it a lot of hours, but I don't really get it. EDIT WITH SOULTION Thanks for your help, this is the code that solves the problem! def floatHourToTime(x): t1 = datetime(1904,1,1,0,0) too = xlrd.xldate_as_tuple(x, 1) t2 = datetime(too[0],too[1],too[2],too[3],too[4]) too = t2-t1 year = too.days*24 + int(too.seconds/3600) month = int(too.seconds/60-int(too.seconds/3600)*60) day = 24*3600 *(x- (year/24)- (month/(24*60)) ) return datetime(year,month, round(day) )
favorite count: 0
type: Question

http://stackoverflow.com/q/50049660
tagged with: python
has comment: http://stackoverflow.com/comment/87115622
has body: I have a table like this: key1 | key2 --------------- 0 | a, b, c --------------- 1 | d, e, f --------------- I would like to convert it to like: key1 | key2 ------------ 0 | a ------------ 0 | b ------------ 0 | c ------------ 1 | d ------------ 1 | e ------------ 1 | f ------------ Any simple way in Pandas? Thanks a lot!
has comment: http://stackoverflow.com/comment/87115598
duplicate of: http://stackoverflow.com/q/12680754
has title: Multiple index in pandas series in pandas
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/12680754

http://stackoverflow.com/comment/87395533
type: AnswerComment
has text: I gave +1 for your answer, because it hinted about the usage of mock.patch.object, which I did not previously know, but the problem with that solution is that if you need to mock something that is used in __init__() it will not work. I have added the solution down below
comment on: http://stackoverflow.com/a/50081850
type: Comment
score: 0

http://stackoverflow.com/comment/87007884
has text: Meanwhile: is there a reason you're daemonizing the threads? Also, have you considered using a threadpool (like [`futures`](https://pypi.org/project/futures/) or [`multiprocessing.dummy`](https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy)) instead of building one yourself with a queue and a list of threads? (Normally, you don't actually want as many threads as tasks—or, when you do, you don't want a queue of tasks.)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49994975
type: QuestionComment

http://stackoverflow.com/comment/87112088
comment on: http://stackoverflow.com/a/50025959
type: Comment
has text: Yes indeed, "F and S are the same for the three plots". So I have applied all your recommendations and the time fell down from 150-170ms to 50-70ms. Almost 3 times faster!! I appreciate your answer and your effort :)
type: AnswerComment
score: 1

http://stackoverflow.com/q/50029795
has answer: http://stackoverflow.com/a/50029934
tagged with: sqlite
tagged with: django-models
type: Question
has body: Im using Django 2.0. My task is to write a large dataset that after being analized it'll be dropped every day. I've decided to write that data in SQLite using database routers that generates the file automatically but it does not create the model table and throws an OperationalError cause the table does not exist. Which (if someone had a similar situation) should be a nice solution for this? Thanks in advance!
answer count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87075693
has title: How to create sqlite table in Django automatically?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50029934
score: 0

http://stackoverflow.com/a/49930123
has comment: http://stackoverflow.com/comment/86877501
type: Answer
answers question: http://stackoverflow.com/q/49929821
has body: In short: you're passing one too many arguments to .select(); you must pass a single CSS selector as a string. Looking at the stack trace: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/InvestopediaApi/ita.py", line 240, in trade prev_form = prev_page.soup.select("form", {"name": "simTradePreview"}) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/bs4/element.py", line 1532, in select for candidate in _use_candidate_generator(tag): TypeError: 'dict' object is not callable It appears that what you pass as the second argument to .select() is a dict ({"name": "simTradePreview"}). Apparently it's not expected. From the stacktrace it appears that the soup in question is BeautifulSoup 4 (bs4); its select does not seem to accept a second argument. But the source does have more undocumented arguments with default vlues, in particular, _candidate_generator, which you clobber.
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86876502

http://stackoverflow.com/a/56346986
has body: Here I've simplified answer using ternary operator. May it will be helpful and better. def fib(n): a, b = 0, 1 while a &lt; n: endstatement = '-' if (b &lt; n) else '' print(a, end=endstatement) a, b = b, a+b print() # Now call the function: fib(1000) Result: 0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49949638

http://stackoverflow.com/comment/86853158
score: 0
comment on: http://stackoverflow.com/a/49918524
type: Comment
type: AnswerComment
has text: Nope, it becomes "0.000"

http://stackoverflow.com/a/61732830
has body: Thanks for you contribution. I had to modify your code a little just to correct some missing stuff and to adapt to python3. Main changes were import string (it was missing) change dictionary.iteritems to dictionary.items (python3) convert all print "..." to print("...") (python3) the variable group_names was missing force the GroupName to be a str in the group_name loop sort the final dictionary into dict2 Your original data is in a csv file now named input2.csv ,group1,group2,meandiff,lower,upper,reject 0,101,102,0.2917,-0.0425,0.6259,False 1,101,103,0.1571,-0.1649,0.4792,False 2,101,104,-0.1333,-0.4675,0.2009,False 3,101,105,0.0833,-0.2509,0.4175,False 4,101,106,-0.0500,-0.3626,0.2626,False 5,102,103,-0.1345,-0.4566,0.1875,False 6,102,104,-0.4250,-0.7592,-0.0908,True 7,102,105,-0.2083,-0.5425,0.1259,False 8,102,106,-0.3417,-0.6543,-0.0290,True 9,103,104,-0.2905,-0.6125,0.0316,False 10,103,105,-0.0738,-0.3959,0.2482,False 11,103,106,-0.2071,-0.5067,0.0924,False 12,104,105,0.2167,-0.1175,0.5509,False 13,104,106,0.0833,-0.2293,0.3960,False 14,105,106,-0.1333,-0.4460,0.1793,False import pandas as pd import numpy as np import math import itertools import string df = pd.read_csv('input2.csv', index_col=0) df_True = df.loc[df.reject==True,:] letters = list(string.ascii_lowercase) n = 0 group1_list = df_True.group1.tolist() #get the groups from the df with only True (True df) to a list group2_list = df_True.group2.tolist() group3 = group1_list+group2_list #concat both lists group4 = list(set(group3)) #get unique items from the list group5 = [str(i) for i in group4 ] #convert unicode to a str group5.sort() #sort the list gen = ((i, 0) for i in group5) #create dict with 0 so the dict won't be empty when starts dictionary = dict(gen) group6 = [(group5[i],group5[j]) for i in range(len(group5)) for j in range(i+1, len(group5))] #get all combination pairs for pairs in group6: #check for each combination if it is present in df_True print(n) print(dictionary) try: a = df_True.loc…
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49963138
type: Answer
upvote count: 3

http://stackoverflow.com/a/50059676
has body: As you said, fetchall() is a bad idea in this case, as it loads all the data into the memory. In order to avoid that you can iterate over cursor object itself: cur.execute("SELECT * FROM test") for row in cur: # iterate over result set row by row do_stuff_with_row(row) cur.close()
has comment: http://stackoverflow.com/comment/87136764
has comment: http://stackoverflow.com/comment/87137639
has comment: http://stackoverflow.com/comment/87137026
score: 0
has comment: http://stackoverflow.com/comment/87136948
has comment: http://stackoverflow.com/comment/87242557
has comment: http://stackoverflow.com/comment/87135741
answers question: http://stackoverflow.com/q/50059415
has comment: http://stackoverflow.com/comment/87137260
type: Answer

http://stackoverflow.com/a/50055159
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50055085
has comment: http://stackoverflow.com/comment/87126819
has comment: http://stackoverflow.com/comment/87127059
has comment: http://stackoverflow.com/comment/87127315
type: Answer
has comment: http://stackoverflow.com/comment/87127268
has comment: http://stackoverflow.com/comment/87127276
has comment: http://stackoverflow.com/comment/87127267
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50055085
has comment: http://stackoverflow.com/comment/87127333
has comment: http://stackoverflow.com/comment/87127172
downvote count: 0
has body: You can convert your data to datetime objects : import datetime as dt df['reg_date'] = pd.to_datetime(df['reg_date'], errors='coerce') And then you can extract the month as below: df['month'] = df['reg_date'].dt.month Output: time month 0 2013-06-10 6 1 2014-09-30 9 2 2014-09-30 9 3 2014-09-30 9 4 2014-10-01 10 Here are the docs.

http://stackoverflow.com/q/49932344
tagged with: opencv
has comment: http://stackoverflow.com/comment/86880547
score: 0
has comment: http://stackoverflow.com/comment/86884923
has answer: http://stackoverflow.com/a/49932416
tagged with: pyautogui
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86880461
type: UnansweredQuestion
has body: The code I currently have is: import pyautogui location_button = pyautogui.locateOnScreen('Button.png') x, y = pyautogui.center(location_button) pyautogui.click(x, y) The code tries to find a exact image of Button.png on the screen, get the coordinate, and click the coordinate. The problem is that the Button changes color gradually, so sometimes location_button returns None. What is the best way to get a positive match all the time even if the button color changes? Greyscale doesn't because there are particles flying around sometimes get in the Button. Would binary image work? Thanks
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86885322
has comment: http://stackoverflow.com/comment/86880396
has title: best way to locate a color changing button

http://stackoverflow.com/comment/86862343
comment on: http://stackoverflow.com/q/49922915
score: 0
type: QuestionComment
type: Comment
has text: I would suggest trying inserting a row of `[np.nan, np.nan]` at the 0th position (https://stackoverflow.com/questions/24284342/insert-a-row-to-pandas-dataframe)

http://stackoverflow.com/a/49951265
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49935778
has comment: http://stackoverflow.com/comment/86925922
score: 9
has body: In order for a K.gradients() layer to work like that, you have to enclose it in a Lambda() layer, because otherwise a full Keras layer is not created, and you can't chain it or train through it. So this code will work (tested): import keras from keras.models import * from keras.layers import * from keras import backend as K import tensorflow as tf def grad( y, x ): return Lambda( lambda z: K.gradients( z[ 0 ], z[ 1 ] ), output_shape = [1] )( [ y, x ] ) def network( i, d ): m = Add()( [ i, d ] ) a = Lambda(lambda x: K.log( x ) )( m ) return a fixed_input = Input(tensor=tf.constant( [ 1.0 ] ) ) double = Input(tensor=tf.constant( [ 2.0 ] ) ) a = network( fixed_input, double ) b = grad( a, fixed_input ) c = grad( b, fixed_input ) d = grad( c, fixed_input ) e = grad( d, fixed_input ) model = Model( inputs = [ fixed_input, double ], outputs = [ a, b, c, d, e ] ) print( model.predict( x=None, steps = 1 ) ) def network models f( x ) = log( x + 2 ) at x = 1. def grad is where the gradient calculation is done. This code outputs: [array([1.0986123], dtype=float32), array([0.33333334], dtype=float32), array([-0.11111112], dtype=float32), array([0.07407408], dtype=float32), array([-0.07407409], dtype=float32)] which are the correct values for log( 3 ), &#8531;, -1 / 32, 2 / 33, -6 / 34. Reference TensorFlow code For reference, the same code in plain TensorFlow (used for testing): import tensorflow as tf a = tf.constant( 1.0 ) a2 = tf.constant( 2.0 ) b = tf.log( a + a2 ) c = tf.gradients( b, a ) d = tf.gradients( c, a ) e = tf.gradients( d, a ) f = tf.gradients( e, a ) with tf.Session() as sess: print( sess.run( [ b, c, d, e, f ] ) ) outputs the same values: [1.0986123, [0.33333334], [-0.11111112], [0.07407408], [-0.07407409]] Hessians tf.hessians() does return the second derivative, that's a shorthand for chaining two tf.gradients(). The Keras backend doesn't have hessians though, so you do have to chain the two K.gradients(). Numerical approximation If for some reason none of t…
upvote count: 9
has comment: http://stackoverflow.com/comment/86921211
answers question: http://stackoverflow.com/q/49935778
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/86972664
score: 0
type: QuestionComment
has text: Sure, i will take a look! thank you etene
comment on: http://stackoverflow.com/q/49977257
type: Comment

http://stackoverflow.com/comment/86898858
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49940813
type: QuestionComment
has text: Make sure that `/usr/local/lib/pythonX.X/site-packages` precedes `/usr/lib/pythonX.X/site-packages` in your `$PATH`.

http://stackoverflow.com/comment/132538249
has text: Please, add description of what is done.
comment on: http://stackoverflow.com/a/75074833
score: 0
type: Comment
type: AnswerComment

unit-testing
tags question: http://stackoverflow.com/q/50018700
type: Tag
tags question: http://stackoverflow.com/q/50003048
tags question: http://stackoverflow.com/q/50010485
tags question: http://stackoverflow.com/q/50039515
tag name: unit-testing
tags question: http://stackoverflow.com/q/49957212
tags question: http://stackoverflow.com/q/50025707
tags question: http://stackoverflow.com/q/50033692
tags question: http://stackoverflow.com/q/50073846
tags question: http://stackoverflow.com/q/49989673
tags question: http://stackoverflow.com/q/49945576
tags question: http://stackoverflow.com/q/49972376

http://stackoverflow.com/a/49968636
has body: This line of code in editRoster() teamRoster[oldName] = (playerName, playerPhoneNumber, playerJersyNumber) is replacing the Roster() object teamRoster with a 3-tuple. This is creating the problem later when you call displayRoster on that tuple. You need to modify the Roster() object in place: teamRoster[oldName].playerName = playerName teamRoster[oldName].platerPhoneNumber = playerPhoneNumber teamRoster[oldName].platerJersyNumber = playerJersyNumber Then you keep the same object and everything will work correctly with updated values.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49968581

http://stackoverflow.com/q/50060435
has comment: http://stackoverflow.com/comment/87213947
tagged with: python
tagged with: parameterization
has comment: http://stackoverflow.com/comment/87145748
answer count: 0
tagged with: ros
has title: Populating a Numpy array from CSV file in Ros
score: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has body: I have a script that uses np.loadtext to populate a numpy array. This process is only done on init and basically acts like a look up table from there on. I want to implement this in Ros Kinetic. I have created a ROS node that performs the task and now I am wondering what is the best way to populate this array on init? Is there an analog to np.loadtext I can use? Do I need to convert it to something like a roslaunch xml or rosbag. I'm relatively new to ROS so not so familiar with parameter server etc. I'd like to be able to change the files every now and then for different test scenarios and have the values picked up on init and the file is fairly large ~7Mb. Thanks in advance.
type: UnansweredQuestion

http://stackoverflow.com/comment/86849811
has text: Please add the error that you are getting after using `data.show`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49917008
score: 2

http://stackoverflow.com/q/49959907
score: 0
tagged with: machine-learning
tagged with: keras
answer count: 1
has answer: http://stackoverflow.com/a/49963489
tagged with: video
type: Question
tagged with: python
type: UnansweredQuestion
has body: I have this Conv3D model in Keras: model = Sequential( Conv3D(32, (3,3,3), activation='relu', input_shape=self.input_shape), MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2)), Conv3D(64, (3,3,3), activation='relu'), MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2)), Conv3D(128, (3,3,3), activation='relu'), Conv3D(128, (3,3,3), activation='relu'), MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2)), Conv3D(256, (2,2,2), activation='relu'), Conv3D(256, (2,2,2), activation='relu'), MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2)), Flatten(), Dense(1024)), Dropout(0.5), Dense(1024), Dropout(0.5)), Dense(self.nb_classes, activation='softmax') ) This model is based on this article https://arxiv.org/pdf/1412.0767.pdf Which is the best way to preprocess video data to be predicted using this Conv3D? I wrote this function to extract frames from each video of the UCF-101: def frame_writer(pathIn, pathOut, class_name): """ This function will read videos and write frames in a new dataset args: pathIn -&gt; base dataset of videos pathOut -&gt; destination folder for the frames ('data/path') """ #creating output path if it not exists try: if not os.path.exists(pathOut + '/' + class_name): os.makedirs(pathOut + '/' + class_name) else: pass except: print('Invalid path!') #getting the list containing all files from the directory pathIn_files = glob.glob(pathIn + '\\' + class_name + '\\' + '*.avi') video_limit = len(pathIn_files) #iterating over all files for i, j in zip(pathIn_files, range(len(pathIn_files))): #getting the names from file paths base_name = os.path.basename(pathIn_files[j]) file_name = base_name[0:-4] #taking only the file name (without extension) #getting the frames vidcap = cv2.VideoCapture(i) success,image = vidcap.read() count = 0 success = True while success: success,image = vidcap.read() print ('Read a new frame: ', success) cv2.imwrite(pathOut + '\\' + class_name + "\\%s_frame%d.jpg" % (file_name, count), image) count += 1 print('Done!') Now i have m…
tagged with: artificial-intelligence
has title: How to preprocess videos for a Conv3D Model

http://stackoverflow.com/a/50016813
answers question: http://stackoverflow.com/q/50011028
has comment: http://stackoverflow.com/comment/87061827
has body: Your final example dose not look like a heatmap, but treemap. Maybe you could try this: library(treemapify) product &lt;- c('Credit') startdate &lt;- c('12/30/2018','12/30/2018','12/30/2018','12/31/2018','12/31/2018') reporting_amount &lt;- c(29918501.83,50000000,40000000,13766666.67,75000000) mydata &lt;- data.frame(product, startdate, reporting_amount) mydata$product &lt;- as.character(product) The reporting_amount used to define areas or color(fill) should be numeric but not character, so I deleted the quotes. And the label (here I used Product) should be character. ggplot(mydata,aes(area = reporting_amount,fill = reporting_amount,subgroup = startdate,label = product)) + geom_treemap() + geom_treemap_subgroup_border(size = 10)+ geom_treemap_text(color = 'white',grow = T,place = 'center') + geom_treemap_subgroup_text() Then I got this picture: I'm not sure whether this is what you're looking for, just that the area and color can change by some value looks quite similar to your final example. Maybe when you have more dimensions in the dataset, more features can be defined by the treemap.
accepted answer of: http://stackoverflow.com/q/50011028
downvote count: 0
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50059845
has title: Select dataframe columns based on conditions
has answer: http://stackoverflow.com/a/50060303
tagged with: pandas
has comment: http://stackoverflow.com/comment/87136453
has body: Input DataFrame : a b c d e f g j k l m n o p q r s t 2 33 17 0 418 -5 -81 NaN 14336 81 1 462 -24 NaN 81 1 462 -24 NaN 5 33 17 0 415 -5 -116 NaN 14336 81 0 487 -5 116 81 1 462 -24 NaN 7 33 17 0 413 -5 -116 NaN 14336 81 1 462 -24 NaN 81 1 462 -24 -111 Check the value of column c if it's equal to 0: insert the values of d e f into x1 x2 x3 Check the value of column l if it's equal to 0: insert the values of m n o into y1 y2 y3 if he value of column l is equal to 1 : check columns o and t : the first that contains a value, insert m n o, or r s t into columns z1 z2 z3 Output DataFrame: x1 x2 x3 y1 y2 y3 z1 z2 z3 2 418 -5 -81 NaN NaN NaN 462 -24 NaN 5 415 -5 -116 487 -5 116 462 -24 NaN 7 413 -5 -81 NaN NaN NaN 462 -24 -111
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87136121
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87273791
tagged with: dataframe
tagged with: python
score: -1

http://stackoverflow.com/comment/86969090
type: QuestionComment
has text: you are right. It should be 'auto.offset.reset': 'latest'.
comment on: http://stackoverflow.com/q/49968377
score: 0
type: Comment

http://stackoverflow.com/q/49969862
tagged with: nltk
tagged with: counter
tagged with: python
has body: I want to convert the output of my list. I used nltk to find bigraphs from tokens. This is the output I got after counter: [(('declaration', 'rights'), 8), (('rights', 'freedoms'), 8), (('peoples', 'nations'), 3)] Desired output: ['declaration rights', 'rights freedoms', 'peoples nations'] Is there a fix for this issue?
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49969952
favorite count: 0
accepted answer: http://stackoverflow.com/a/49969952
type: Question
has title: convert counter list in python of nltk bigraph

http://stackoverflow.com/q/50035681
score: 12
has answer: http://stackoverflow.com/a/75973396
has answer: http://stackoverflow.com/a/50035728
has body: What is INTERNAL_IPS and ALLOWED_HOSTS in django settings.Why we are using it,what happen if we not use it.
has title: INTERNAL_IPS and ALLOWED_HOSTS in django settings
favorite count: 0
upvote count: 17
type: Question
has comment: http://stackoverflow.com/comment/132642947
answer count: 2
type: UnansweredQuestion
tagged with: django
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/87090954

http://stackoverflow.com/comment/86916638
type: Comment
type: QuestionComment
has text: https://docs.python.org/3/reference/expressions.html#membership-test-operations
score: 1
comment on: http://stackoverflow.com/q/49949874

http://stackoverflow.com/comment/87132084
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50057695
has text: btw is the user you want to run the script as really called `eval` ? That could cause some confusion :)
score: 0

http://stackoverflow.com/comment/87147213
type: QuestionComment
has text: You can just `re.search(r'A|B|AB', sample_str)`, but if you want to find substrings matching that the problem is kind of ill-posed, giving `"AB"` could be interpreted as two matches, `A` and `B`, or one match `AB`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50065138

http://stackoverflow.com/q/49934878
has answer: http://stackoverflow.com/a/49935533
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49935533
has body: I am trying to extract the gallery link of the first result on an imgur search. theurl = "https://imgur.com/search?q=" +text thepage = urlopen(theurl) soup = BeautifulSoup(thepage,"html.parser") link = soup.findAll('a',{"class":"image-list-link"})[0].decode_contents() Here is what is being displayed for link: I am mainly trying to get the href value from only this section (the first result for the search) Here is what the inspect element looks like:
tagged with: python-3.x
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has title: How to extract the link of the first gallery on imgur using BS4 and urllib
answer count: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/a/50056517
answers question: http://stackoverflow.com/q/50056461
downvote count: 0
type: Answer
has body: Try using join: print(reply_noun[0] + "is related to " + ' '.join(feed)) [EDIT] If you want it to work for any list (not just list of strings), and even if you don't, this could be an even better alternative: print(reply_noun[0] + "is related to" , *feed)
has comment: http://stackoverflow.com/comment/87199551
upvote count: 1
has comment: http://stackoverflow.com/comment/87129451
has comment: http://stackoverflow.com/comment/87129589
has comment: http://stackoverflow.com/comment/87129636
score: 1
has comment: http://stackoverflow.com/comment/87199737
has comment: http://stackoverflow.com/comment/87129488

http://stackoverflow.com/comment/87013575
type: AnswerComment
has text: I don't understand your question. You already use the `pk` in the `item_category` view: `item_category = get_object_or_404(Categories, pk=pk)`.
comment on: http://stackoverflow.com/a/49998585
score: 0
type: Comment

http://stackoverflow.com/q/50008120
has answer: http://stackoverflow.com/a/50014956
has comment: http://stackoverflow.com/comment/87033120
type: Question
has comment: http://stackoverflow.com/comment/87033579
has comment: http://stackoverflow.com/comment/87284826
tagged with: naivebayes
has comment: http://stackoverflow.com/comment/87033026
tagged with: python
answer count: 1
has title: Getting dimension mismatch error when i try to predict with naive bayes / Python
has comment: http://stackoverflow.com/comment/87033219
tagged with: sklearn-pandas
has comment: http://stackoverflow.com/comment/87034257
has comment: http://stackoverflow.com/comment/87033342
has comment: http://stackoverflow.com/comment/87033861
has body: I've created a sentiment script and use Naive Bayes to classify the reviews. I trained and tested my model and saved it in a Pickle object. Now I would like to perform on a new dataset my prediction but I always get following error message raise ValueError('dimension mismatch') ValueError: dimension mismatch It pops up on this line: preds = nb.predict(transformed_review)[0] Can anyone tell me if I'm doing something wrong? I do not understand the error. This is my Skript: sno = SnowballStemmer("german") stopwords = [word.decode('utf-8-sig') for word in stopwords.words('german')] ta_review_files = glob.glob('C:/users/Documents/review?*.CSV') review_akt_doc = max(ta_review_files, key=os.path.getctime ta_review = pd.read_csv(review_akt_doc) sentiment_de_class= ta_review x = sentiment_de_class['REV'] y = sentiment_de_class['SENTIMENT'] def text_process(text): nopunc = [char for char in text.decode('utf8') if char not in string.punctuation] nopunc = ''.join(nopunc) noDig = ''.join(filter(lambda x: not x.isdigit(), nopunc)) ## stemming stemmi = u''.join(sno.stem(unicode(x)) for x in noDig) stop = [word for word in stemmi.split() if word.lower() not in stopwords] stop = ' '.join(stop) return [word for word in stemmi.split() if word.lower() not in stopwords] ###################### # Matrix ###################### bow_transformer = CountVectorizer(analyzer=text_process).fit(x) x = bow_transformer.transform(x) ###################### # Train and test data ###################### x_train, x_test, y_train, y_test = train_test_split(x,y, random_state=101) print 'starting training ..' ###################### ## first use ###################### #nb = MultinomialNB().fit(x_train,y_train) #file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'wb') ## dump information to that file #pickle.dump(nb, file) ###################### ## after train ###################### file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'rb') nb = pickle.load(file) predis = [] #############…
linked to: http://stackoverflow.com/q/15463387
type: AnsweredQuestion
score: 0
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87033169
accepted answer: http://stackoverflow.com/a/50014956
downvote count: 1
has comment: http://stackoverflow.com/comment/87281476
favorite count: 0

http://stackoverflow.com/comment/87039598
has text: I am currently working to incorporate and test @PatrickArtner 's script... I understand the basis of buffers and memory, and why this task can get tricky throwing in a `.read()` to a million+ line file, but would you elaborate on how the buffer comes into play in your script above? or hyperlink me a site or other stack question you think covers the information? Thanks for the help too!
comment on: http://stackoverflow.com/a/50011499
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49931732
upvote count: 1
tagged with: polymorphism
tagged with: inheritance
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49931798
type: Question
tagged with: python-3.x
tagged with: oop
has comment: http://stackoverflow.com/comment/86887003
has comment: http://stackoverflow.com/comment/86885835
tagged with: python
has body: I'm using python 3.6. My goal is to make a base class that would be able to somehow access through polymorphism - one of the child class variables. I know it sounds somewhat 'not oop', so if what im describing can't be done with python - I would like to know what is the best practice for this case. Following wikipedia's example: class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr. Mistoffelees'), Dog('Lassie')] for animal in animals: print animal.name + ': ' + animal.talk() Prints the following: Missy: Meow! Mr. Mistoffelees: Meow! Lassie: Woof! Woof! I would like to achieve the exactly same output - using variable overloading (is that a thing?) instead of method overloading. The reason is that in the programm im working on - dog, cat, and every other kind of animal will talk exactly the same way - influenced only by the data member, such as: class Animal: def __init__(self, name): # Constructor of the class self.name = name self.vocabulary = [] # so called abstract data member def talk(self): # Non Abstract method, all animals would talk for word in self.vocabulary: print (word) class Cat(Animal): vocabulary = ["Meow", "Muuuew", "Maow"] class Dog(Animal): vocabulary = ["Woof", "Waf", "Haw"] animals = [Cat('Missy'), Cat('Mr. Mistoffelees'), Dog('Lassie')] for animal in animals: print animal.name + ': ' + animal.talk() Prints the following: Missy: Meow Muuuew Maow Mr. Mistoffelees: Meow Muuuew Maow Lassie: Woof Waf Haw Clearly, this won't work since vocabulary will be empty, as it is in the base class. I tried to find a solution using super, e.g: class Cat(Animal): vocabulary = ["Meow", "Muuuew", "Maow"] def talk(self): super(Animal,Cat).talk() But the result would be At…
answer count: 2
score: 0
type: UnansweredQuestion
has title: Base class accessing super class variables
has answer: http://stackoverflow.com/a/49931822
has comment: http://stackoverflow.com/comment/86879227

http://stackoverflow.com/a/50066777
downvote count: 0
type: Answer
score: 3
has body: You need to implement your own custom on_message method to be able to get the websocket information: import time import gdax import pandas as pd results = [] class myWebsocketClient(gdax.WebsocketClient): def on_open(self): self.url = "wss://ws-feed.gdax.com/" self.products = ["LTC-USD"] def on_message(self, msg): if 'price' in msg and 'type' in msg: results.append(msg['price']) wsClient = myWebsocketClient() wsClient.start() time.sleep(5) df = pd.DataFrame(results, columns = ["Price"]) print(df.head()) wsClient.close() This will run for 5 seconds, and outputs: Price 0 153.13000000 1 151.14000000 2 140.52000000 3 140.52000000 4 152.62000000 -- Socket Closed --
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50066428
answers question: http://stackoverflow.com/q/50066428

http://stackoverflow.com/comment/86889870
type: Comment
comment on: http://stackoverflow.com/q/49936379
type: QuestionComment
score: 0
has text: What do you mean a different array? Y_true and the probabilities are of the same length.

http://stackoverflow.com/q/49989924
has comment: http://stackoverflow.com/comment/86996674
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/12572362
has comment: http://stackoverflow.com/comment/86996376
has answer: http://stackoverflow.com/a/49990364
has comment: http://stackoverflow.com/comment/87022203
score: 0
has title: Grabbing characters after a certain value
tagged with: pandas
has comment: http://stackoverflow.com/comment/86996404
answer count: 1
tagged with: python
has body: Below is the dataframe. PIC_1 and Wgt are strings and p.lgth and p_lgth are integers. If p_lgth is not equal to 30, I want to find 42 in PIC_1 and grab 42 and the 15 digits that come after it. PIC_1 Wgt p.lgth p_lgth **PARTIAL-DECODE***P / 42011721930018984390078... 112 53 53 So the output from above should be 42011721930018984 My code that does not work follows: def pic_mod(row): if row['p_lgth'] !=30: PIC_loc = row['PIC_1'].find('42') PIC_2 = row['PIC_1'].str[PIC_loc:PIC_loc + 15] elif row['p_lgth']==30: PIC_2=PIC_1 return PIC_2 row_1 is just a row from the larger df that is identical to the example row given above row_1 = df71[2:3] pic_mod(row_1) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool (), a.item(), a.any() or a.all(). I did type() on the variables and got type(df71['PIC_1']) = pandas.core.series.Series type(df71['p_lgth']) = pandas.core.series.Series type(df71['Wgt']) = pandas.core.series.Series I'm fairly new to Python. Should these data types come back as int and str? df71 is a df.
type: Question
has comment: http://stackoverflow.com/comment/86996631
has comment: http://stackoverflow.com/comment/86996644

http://stackoverflow.com/comment/87018891
has text: As already said above: if you need one answer, and don't care about the solution, then implement the deterministic algorithm that finds the first solution. But then you should delete the "random" from the name of `gen_random_matrix`. Otherwise you would have to specify what you mean by "random".
comment on: http://stackoverflow.com/q/50000574
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50036737
upvote count: 3
tagged with: multiple-inheritance
accepted answer: http://stackoverflow.com/a/50036860
downvote count: 1
favorite count: 0
type: Question
has body: I am trying to understand python's class inheritance methods and I have some troubles figuring out how to do the following: How can I inherit a method from a class conditional on the child's input? I have tried the following code below without much success. class A(object): def __init__(self, path): self.path = path def something(self): print("Function %s" % self.path) class B(object): def __init__(self, path): self.path = path self.c = 'something' def something(self): print('%s function with %s' % (self.path, self.c)) class C(A, B): def __init__(self, path): # super(C, self).__init__(path) if path=='A': A.__init__(self, path) if path=='B': B.__init__(self, path) print('class: %s' % self.path) if __name__ == '__main__': C('A') out = C('B') out.something() I get the following output: class: A class: B Function B While I would like to see: class: A class: B B function with something I guess the reason why A.something() is used (instead of B.something()) has to do with the python's MRO.
has answer: http://stackoverflow.com/a/50038256
has answer: http://stackoverflow.com/a/50037827
tagged with: python
possible better answer: http://stackoverflow.com/a/50038256
has comment: http://stackoverflow.com/comment/87089641
has answer: http://stackoverflow.com/a/50036860
type: AnsweredQuestion
has title: multiple python class inheritance
answer count: 3
score: 2

http://stackoverflow.com/comment/87050737
score: 1
type: Comment
type: QuestionComment
has text: Will you get the same error if you do a `select [TEMP CELCIUS] from [db].[username].[mytable]`? Also I strongly advise against whitespaced column names.
comment on: http://stackoverflow.com/q/50015509

http://stackoverflow.com/comment/87113784
comment on: http://stackoverflow.com/q/50048804
score: 1
type: QuestionComment
has text: You should read about [how scoping works in python](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules). You define `age` in the `askAge()` function, but once you leave that function the variable will not be available in `main()`.
type: Comment

http://stackoverflow.com/comment/86979393
has text: Can you tell me how you did that? Can you show me your code? Is it similar to mine?
comment on: http://stackoverflow.com/a/49976245
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86907909
type: Comment
comment on: http://stackoverflow.com/q/49930401
type: QuestionComment
has text: The question is too broad (imho) as @AlexHall suggested this could be accomplished with [Pandas](http://pandas.pydata.org/) and your example data would fit neatly into many of the examples in documentation. Then again there are a number of ways to filter items in a dictionary using loops and conditional statements then operate on the resultant item values. *cont'd*
score: 0

http://stackoverflow.com/q/49967179
tagged with: tweepy
favorite count: 0
tagged with: urllib
type: Question
has title: Getting additional image urls (i.e. not just first) from tweet with tweepy and python
has comment: http://stackoverflow.com/comment/86984228
upvote count: 1
tagged with: python
has body: I am making a script to download the images from the user's timeline (from each tweet/status) and have got it working well, but only for retrieving and downloading the first image, it will not get the image urls for additional images (i.e. 2nd, 3rd, 4th etc.) in each tweet/status. My (badly written) code: timeline = tweepy.Cursor(api.user_timeline, tweet_mode='extended').items() for tweet in timeline: imagesfiles = [] # this is the list I want the image urls to go into if 'media' in tweet.entities: for image in tweet.entities['media']: file_location = str(image['media_url']) imagesfiles.append(file_location) file_location = "data/images/" + file_location.rsplit('/', 1)[-1] urllib.urlretrieve(image['media_url'], file_location) else: imagesfiles = "noimages" print "no images" print imagesfiles # this should be a list of the urls for media in the tweet/status, but it only ever returns one url (the first image url) and never the rest in the status (i.e. 2nd, 3rd, 4th images etc). Can anyone see any obvious reason why this would only get the first media_url in Twitter's returned data for status with extra media entities? The JSON from Twitter looks something as follows: u'extended_entities': { u'media': [ { u'expanded_url': u'https://twitter.com/someone/status/84848343434888484/photo/1', u'display_url': u'pic.twitter.com/Dbasasasdamh6W', u'url': u'SHORT_URL_FROM_TWITTER', u'media_url_https': u'https://pbs.twimg.com/media/Dbasasasdamh6W.jpg', u'id_str': u'84848343434888484', u'sizes': { u'large': { u'h': 800, u'resize': u'fit', u'w': 800 }, u'small': { u'h': 680, u'resize': u'fit', u'w': 680 }, u'medium': { u'h': 800, u'resize': u'fit', u'w': 800 }, u'thumb': { u'h': 150, u'resize': u'crop', u'w': 150 } }, u'indices': [ 55, 78 ], u'type': u'photo', u'id': 84848343434888484, u'media_url': u'https://pbs.twimg.com/media/Dbasasasdamh6W.jpg' }, { u'expanded_url': u'https://twitter.com/someone/status/435345345345345345/photo/1', u'display_url': u'pic.twitter.com/otasws6y36', u'…
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/49984189
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/49984189
answer count: 1
tagged with: twitter

http://stackoverflow.com/comment/87050080
comment on: http://stackoverflow.com/q/50016875
type: QuestionComment
has text: Can you send an example row?
score: 0
type: Comment

http://stackoverflow.com/q/49987686
has title: Why my output from preprocessing methods in sklearn.pipeline does not align?
favorite count: 0
type: Question
has body: I am learning the book "Hands On Machine Learning" and writing some code of transformation pipelines to clean up my data and find the output of the same pipeline method varies according to the size of the dataframe I chose to input. Here is the code: from sklearn.base import BaseEstimator,TransformerMixin class DataFrameSelector(BaseEstimator, TransformerMixin): def __init__(self, attribute_names): self.attribute_names =attribute_names def fit(self,X,y=None): return self def transform(self,X): return X[self.attribute_names].values from sklearn.pipeline import FeatureUnion class CustomLabelBinarizer(BaseEstimator, TransformerMixin): def __init__(self, sparse_output=False): self.sparse_output = sparse_output def fit(self, X, y=None): return self def transform(self, X, y=None): enc = LabelBinarizer(sparse_output=self.sparse_output) return enc.fit_transform(X) num_attribs = list(housing_num) cat_attribs = ['ocean_proximity'] num_pipeline = Pipeline([ ('selector', DataFrameSelector(num_attribs)), ('imputer', Imputer(strategy='median')), ('attribs_adder', CombinedAttributesAdder()), ('std_scalar', StandardScaler()) ]) cat_pipeline = Pipeline([ ('selector', DataFrameSelector(cat_attribs)), ('label_binarizer', CustomLabelBinarizer()) ]) full_pipeline = FeatureUnion(transformer_list=[ ('num_pipeline', num_pipeline), ('cat_pipeline', cat_pipeline) ]) housing_prepared = full_pipeline.fit_transform(housing) data_prepared = full_pipeline.transform(housing.iloc[:5]) data_prepared1 = full_pipeline.transform(housing.iloc[:1000]) data_prepared2 = full_pipeline.transform(housing.iloc[:10000]) print(data_prepared.shape) print(data_prepared1.shape) print(data_prepared2.shape) The output of these three print will be (5, 14) (1000, 15) (10000, 16) Could anyone help me explain this？
downvote count: 0
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/49993974
has answer: http://stackoverflow.com/a/49993974
type: AnsweredQuestion
score: 1
answer count: 1
upvote count: 1
tagged with: scikit-learn

http://stackoverflow.com/q/50028823
type: Question
has answer: http://stackoverflow.com/a/77048372
has body: I am currently coding a program, with the library 'keyboard' in python 3 on Debian. So if i hold down a Key. The keyboard-library gets multiple KeyDownEvents instead of one at KeyPress but I only want the first event. Is there anyway to suppress the auto-repeat? I have already tried multiple terminal commands in python which should stop the keyboard auto-repeat but that mostly only works for printable Chars but I also need only 1 event if for example shift is pressed My conclusion is that the terminal commands don't effect the keyboard library at all. Any ideas? Best regards
type: UnansweredQuestion
tagged with: python
has title: How to avoid key auto repeat if key is held down?
tagged with: autorepeat
answer count: 2
tagged with: keyup
has answer: http://stackoverflow.com/a/76964024
downvote count: 0
tagged with: keydown
score: 1
upvote count: 1
tagged with: keyboard
favorite count: 0

http://stackoverflow.com/q/49951472
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/41296313
tagged with: bar-chart
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/41296313
score: 0
tagged with: pandas
has body: I have plotted stacked bar chart and want to add text indicating its proportion on the bar but do not know how I can add those labels on. My codes are, tps = df3[df3['Action Type_new']!='NA'].pivot_table(values=['Column'], index='year', columns='Action Type_new', aggfunc='sum') tps = tps.div(tps.sum(1), axis=0) tps.plot(kind='bar', stacked=True) and my tps looks like, (it is pivot table so, it has multi index) MultiIndex(levels=[['Column'], ['Less Severe', 'Severe']], labels=[[0, 0], [0, 1]], names=[None, 'Action Type_new']) Column Action Type_new Less Severe Severe year 1990 0.208409 0.791591 1991 0.276577 0.723423 1992 0.281479 0.718521 1993 0.402501 0.597499 1994 0.430871 0.569129 1995 0.445519 0.554481 1996 0.509341 0.490659 1997 0.604371 0.395629 1998 0.716450 0.283550 1999 0.578597 0.421403 My current bar chart is like below.
tagged with: matplotlib
has title: how to add proportion label on the stacked bar chart in python bar chart
has answer: http://stackoverflow.com/a/49952248
type: Question
linked to: http://stackoverflow.com/q/39279404
tagged with: pivot

http://stackoverflow.com/comment/86960521
type: Comment
has text: Why are you using the "None" as a string?
type: AnswerComment
comment on: http://stackoverflow.com/a/49972272
score: 1

http://stackoverflow.com/comment/87022963
type: QuestionComment
comment on: http://stackoverflow.com/q/50003227
score: 0
has text: what is your intent on using `null=True` in 'supplier' attribute of ServiceArea model?
type: Comment

http://stackoverflow.com/comment/87047684
type: AnswerComment
has text: Do I pickle the Vector in a seperate file or do I do this in sentiment_MNB_model.pickle ?
comment on: http://stackoverflow.com/a/50014956
type: Comment
score: 0

http://stackoverflow.com/a/49988449
answers question: http://stackoverflow.com/q/49988110
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/86995114
downvote count: 0
has body: Just for the sake of more options, you can also groupby and mean in pandas import pandas as pd df = pd.DataFrame(s) meaned_df = df.groupby(0).mean() 1 0 (a, b) 3 (b, c) 2 then just format using to_dict() : &gt;&gt;&gt; meaned_df.to_dict()[1] [{('a', 'b'): 3}, {('b', 'c'): 2}] Of course you can make it a one-liner :) &gt;&gt; pd.DataFrame(s).groupby(0).mean().to_dict()[1] outputs [{('a', 'b'): 3}, {('b', 'c'): 2}]

http://stackoverflow.com/a/50069656
answers question: http://stackoverflow.com/q/50048141
type: Answer
has body: Your approach to recursion is all wrong. You can't use absolute positioning in your recursion: square.goto(0,0) ... pattern(length/4.4, depth -1, 1.5,1.5) Everything has to be relative to where you are. Also, to make a recursive drawing like this work, your recursive function should leave the turtle in the same state (position and heading) as it was when you entered the recursive function, so the caller knows where it stands. For this design, you can't simply draw a square and then recurse, you need to be recursing at each corner of the square as you're drawing. As a simpler, initial exercise, let's just draw the lines of this shape and ignore the fill. This may not lead directly to a solution but will demonstrate the above principals: from turtle import Turtle, Screen def pattern(length, depth): if depth &lt; 1: return # assume we're at the center of square, move to corner turtle.penup() turtle.backward(length / 2) turtle.left(90) turtle.backward(length / 2) turtle.right(90) turtle.pendown() for _ in range(4): pattern(length / 2.2, depth - 1) # recurse at each corner turtle.forward(length) turtle.left(90) # return to center of square for the benefit of caller turtle.penup() turtle.forward(length / 2) turtle.left(90) turtle.forward(length / 2) turtle.right(90) turtle.pendown() screen = Screen() turtle = Turtle() turtle.speed('fastest') pattern(100, 4) turtle.hideturtle() screen.exitonclick() OUTPUT Now comes the problem of both filling these squares and making sure the upper right square in the pattern is always "tucked under".
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50008296
favorite count: 0
has title: Facebook JSON badly encoded
linked to: http://stackoverflow.com/q/5396560
has comment: http://stackoverflow.com/comment/87034266
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66207608
has answer: http://stackoverflow.com/a/78035878
has comment: http://stackoverflow.com/comment/117272473
score: 55
has comment: http://stackoverflow.com/comment/87040615
upvote count: 57
possible better answer: http://stackoverflow.com/a/63768513
answer count: 10
has answer: http://stackoverflow.com/a/70133429
has comment: http://stackoverflow.com/comment/105736574
accepted answer: http://stackoverflow.com/a/50011987
linked to: http://stackoverflow.com/q/19161501
has answer: http://stackoverflow.com/a/69926351
has comment: http://stackoverflow.com/comment/87033391
linked to: http://stackoverflow.com/q/50799187
has answer: http://stackoverflow.com/a/50011987
type: Question
linked to: http://stackoverflow.com/q/20045268
tagged with: python-3.x
has body: I downloaded my Facebook messenger data (in your Facebook account, go to settings, then to Your Facebook information, then Download your information, then create a file with at least the Messages box checked) to do some cool statistics However there is a small problem with encoding. I'm not sure, but it looks like Facebook used bad encoding for this data. When I open it with text editor I see something like this: Rados\u00c5\u0082aw. When I try to open it with python (UTF-8) I get RadosÅ\x82aw. However I should get: Radosław. My python script: text = open(os.path.join(subdir, file), encoding='utf-8') conversations.append(json.load(text)) I tried a few most common encodings. Example data is: { "sender_name": "Rados\u00c5\u0082aw", "timestamp": 1524558089, "content": "No to trzeba ostatnie treningi zrobi\u00c4\u0087 xD", "type": "Generic" }
has comment: http://stackoverflow.com/comment/87033602
has comment: http://stackoverflow.com/comment/87034095
has answer: http://stackoverflow.com/a/57867459
downvote count: 2
has answer: http://stackoverflow.com/a/63768513
has answer: http://stackoverflow.com/a/62160255
tagged with: python
has answer: http://stackoverflow.com/a/52494169
tagged with: mojibake
tagged with: unicode
has answer: http://stackoverflow.com/a/69305125

http://stackoverflow.com/comment/87108583
score: 1
has text: If you hope to get any useful answer, please post a MCVE.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50046101

http://stackoverflow.com/a/50051005
answers question: http://stackoverflow.com/q/50050862
downvote count: 0
has comment: http://stackoverflow.com/comment/110853186
type: Answer
has comment: http://stackoverflow.com/comment/108717717
upvote count: 15
has comment: http://stackoverflow.com/comment/87224045
has comment: http://stackoverflow.com/comment/87301135
has body: The answer to your question, "Is there a way I can call the overridden method only on create?" is this: def save(self, *args, **kwargs): if not self.id: # Object is a new instance return super(Model, self).save(*args, **kwargs) But there are other issues here. Your model shouldn't be named "Model", for example.
has comment: http://stackoverflow.com/comment/87119581
score: 15

http://stackoverflow.com/comment/87122195
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50051627
has text: Thanks everyone , as @diek said, problem was using regex with path function. After deleting regular expressions problem is solved.
score: 1

http://stackoverflow.com/a/49994415
score: 0
has comment: http://stackoverflow.com/comment/87005262
has comment: http://stackoverflow.com/comment/87005105
answers question: http://stackoverflow.com/q/49994379
has comment: http://stackoverflow.com/comment/87005519
has comment: http://stackoverflow.com/comment/87005148
has comment: http://stackoverflow.com/comment/87005044
has body: You can use pandas to load your .csv as a DataFrame. This is a highly recommended datastructure due to its versatility. import pandas as pd df = pd.read_csv(filename)
has comment: http://stackoverflow.com/comment/87005583
has comment: http://stackoverflow.com/comment/87005228
type: Answer
has comment: http://stackoverflow.com/comment/87005104

http://stackoverflow.com/comment/86951263
score: 0
comment on: http://stackoverflow.com/q/49967763
has text: @Bn.F76 - What return `print (a.columns.tolist())` ? If no csv header need `a = pd.read_csv("/Users/usr/Images.csv", header=None)`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50012848
has comment: http://stackoverflow.com/comment/87042544
has comment: http://stackoverflow.com/comment/87042160
has comment: http://stackoverflow.com/comment/87042234
has title: No module named 'bankdate'(How to import just .py??)
has answer: http://stackoverflow.com/a/50012931
tagged with: python
has body: Sorry that I have no idea how to describe this situation. The bigger package I like to install is "finance" (http://pydoc.net/finance/0.2502/finance.bankdate/). I downloaded it and unzipped to install using python setup.py install. However, I cannot resolve importing another sub-module bankdate(.py) When I use finance module, there comes the error message, "ImportError: No module named 'bankdate'.(It is required in "__init__.py" under finance.) bankdate.py seems to be file under finance folder. How could I install "bankdate"?? Does anybody help me with this?? Thank you~! cf) pip install bankdate, easy_install bankdate don't work in this case.
has comment: http://stackoverflow.com/comment/87042436
type: Question
has comment: http://stackoverflow.com/comment/87042517
tagged with: python-import
has comment: http://stackoverflow.com/comment/87042413
answer count: 2
has comment: http://stackoverflow.com/comment/87042144
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87042206
has comment: http://stackoverflow.com/comment/87042366
has answer: http://stackoverflow.com/a/50012969
upvote count: 1
has comment: http://stackoverflow.com/comment/87042209
downvote count: 1
has comment: http://stackoverflow.com/comment/87042543
favorite count: 0
has comment: http://stackoverflow.com/comment/87042524
has comment: http://stackoverflow.com/comment/87042498
has comment: http://stackoverflow.com/comment/87042178

python-curses
tag name: python-curses
type: Tag
tags question: http://stackoverflow.com/q/50008700

http://stackoverflow.com/comment/86885809
comment on: http://stackoverflow.com/q/49935141
type: QuestionComment
has text: I recommend first go to python.org - read some docs of python types etc.
score: 0
type: Comment

http://stackoverflow.com/q/49942452
tagged with: performance
has comment: http://stackoverflow.com/comment/86945495
answer count: 1
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49953210
favorite count: 0
tagged with: knn
has answer: http://stackoverflow.com/a/49953210
type: Question
has comment: http://stackoverflow.com/comment/86901642
upvote count: 2
has title: How to train up a (k-NN) model on additional data (for the sake of plotting a learning curve)
has body: I am playing with MNIST database for which I would like to plot a learning curve for a various learning algorithms. For the sake of this question let us consider k-NN algorithm. I imported the data using mnist package and I transformed it to the numpy.ndarray objects. import numpy as np import matplotlib.pyplot as plt from mnist import MNIST mndata = MNIST('./data') images_train, labels_train = mndata.load_training() images_test, labels_test = mndata.load_testing() labels_train = labels_train.tolist() labels_test = labels_test.tolist() X_train = np.array(images_train) y_train = np.array(labels_train) X_test = np.array(images_test) y_test = np.array(labels_test) However, it contains 60.000 examples in training set so it too much for my computer. I want to plot the learning curve to find out if further training makes any sense. import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier start_time = time.time() training_range = range(500, 1500, 100) test_size = 1000 training_accuracy = [] test_accuracy = [] for train_size in training_range: X_train_small = X_train[:train_size] y_train_small = y_train[:train_size] X_test_small = X_test[:test_size] y_test_small = y_test[:test_size] clf = KNeighborsClassifier(n_neighbors=3) clf.fit(X_train_small, y_train_small) training_accuracy.append(clf.score(X_train_small, y_train_small)) test_accuracy.append(clf.score(X_test_small, y_test_small)) plt.plot(training_range, training_accuracy, label="training accuracy") plt.plot(training_range, test_accuracy, label="test accuracy") plt.ylabel("Accuracy") plt.xlabel("Training size") plt.title("Learning curve") plt.legend() plt.show() Output: It takes over a minute to plot this simple graph, which at its best shows accuracy from training just on 1500 elements. The main problem is that the program runs clf.fit(X_train_small, y_train_small) multiple times and recalculates everything from scratch every time. Question. Is there a way to preserve already learned data and…
tagged with: machine-learning
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/62709868
score: 0
downvote count: 1
type: Answer
has body: If you are confused with driver version you can use below code username=&lt;username&gt; password=&lt;password&gt; server=&lt;servername&gt; | &lt;host:port&gt; database=&lt;database&gt; #below code is with authentication engine = create_engine('mssql+pyodbc://'+username+':'+password+'@' + server + '/' + database + '?driver=SQL+Server') query = '''select * from &lt;table&gt;''' result = engine.execute(query) #below code is without authentication engine = create_engine('mssql+pyodbc://@' + server + '/' + database + '?driver=SQL+Server') query = '''select * from &lt;table&gt;''' result = engine.execute(query)
upvote count: 1
answers question: http://stackoverflow.com/q/49947098

http://stackoverflow.com/q/49961994
tagged with: logging
favorite count: 0
has title: Python mutual exlusive log messages depending on level
type: Question
tagged with: python-3.x
has body: I'm looking for recommendations/pattern for the following issue In my script I have situations where I would like to log only 1 of 2 messages depending on the logger level, so in my script I have something along these lines logger.info('AA') # Less detailed message logger.debug('AABB') # More detailed message When the logger level is set to DEBUG, both messages will be logged. The reason I don't want that is because the DEBUG message is a duplicate of the INFO level but with more details. Options I have considered 1-Check the logger level if logger.getEffectiveLevel() == logging.INFO: logger.info('AA') # Less Detailed Message elif logger.getEffectiveLevel() == logging.DEBUG: logger.debug('AABB') # More Detailed Message Doesn't feel like the right thing to be checking the level as this is basically the work the logging module should be doing on behalf of my script 2-Make the DEBUG message only log the extra level of detail that the INFO message doesn't log. The problem with this approach is that this is a multi-threaded script, and there is no guarantee that the DEBUG message will show up right after the INFO message in the script because messages of another thread might come in between, so that makes it very tricky to find both messages in the log to be able to get the full debug message logger.info('AA') logger.debug('BB') Anyone have any good ideas/suggestions? TIA
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49922799
tagged with: python
has comment: http://stackoverflow.com/comment/86861310
has comment: http://stackoverflow.com/comment/86861350
score: 0
tagged with: pandas
answer count: 0
has body: I am trying check which part costs the most memory for my python program. Using this post, http://practicalpython.blogspot.com/2017/03/monitoring-memory-usage-in-jupyter.html. The code is: import numpy as np import pandas as pd def show_mem_usage(): '''Displays memory usage from inspection of global variables in this notebook''' gl = sys._getframe(1).f_globals vars= {} for k,v in list(gl.items()): # for pandas dataframes if hasattr(v, 'memory_usage'): mem = v.memory_usage(deep=True) if not np.isscalar(mem): mem = mem.sum() vars.setdefault(id(v),[mem]).append(k) # work around for a bug elif isinstance(v,pd.Panel): v = v.values vars.setdefault(id(v),[sys.getsizeof(v)]).append(k) total = 0 for k,(value,*names) in vars.items(): if value&gt;1e6: print(names,"%.3fMB"%(value/1e6)) total += value print("%.3fMB"%(total/1e6)) However, I got the error File "&lt;ipython-input-437-c6c16f08fe15&gt;", line 1 for k,(value,*names) in vars.items(): ^ SyntaxError: invalid syntax Anyone knows what's happening? Thanks.
linked to: http://stackoverflow.com/q/34766677
type: Question
duplicate of: http://stackoverflow.com/q/34766677
has title: expanding does not work in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86861324

http://stackoverflow.com/comment/86916967
type: AnswerComment
has text: I thought simple list would be fine for your requirement, but what if there are lot of `primary` tasks which you wanna keep track of(look-up) , so this one is better. you can as many details as you want but primary id and child ids in dict is more than enough
comment on: http://stackoverflow.com/a/49949538
score: 0
type: Comment

http://stackoverflow.com/comment/86941224
has text: Yeah, it all depends what you want to do with it. You could even just make it into a `DataFrame` making it easy to just keep using all of the pandas methods with it. `corrdf = df.from_dict({'corr': corr_dict})`
type: AnswerComment
comment on: http://stackoverflow.com/a/49962510
score: 1
type: Comment

http://stackoverflow.com/a/50051280
type: Answer
has body: As an idea i would say, splitting the data column wise let's say four times, and use the id for each subset to perform the operations and then remerge
answers question: http://stackoverflow.com/q/50051210
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87118968

http://stackoverflow.com/q/49924164
tagged with: memory-management
tagged with: random
score: 0
has comment: http://stackoverflow.com/comment/86864451
answer count: 0
type: Question
has title: Generating a random array with additional constraints
type: UnansweredQuestion
tagged with: python
has body: I'm trying to generate a numpy array of random values, satisfying some additional constraints, and for a given fixed length N. Is it better to: Make a list (sampling once at a time), then convert it to a numpy array while len(list)&lt;N: num=np.random.rand(1) if num &lt;.5: list.append(np.random.rand(1)) x=np.array(list) Use vectorized code, and append to the array: x=np.array([]) while x.shape[0]&lt;N: x=np.append(x,np.random.rand(int(N/2)) x=x[x&lt;.5][:N] Overshoot the array length, then try until the masked version is long enough x=np.array([]) while x.shape[0]&lt;N: x=np.random.rand(4*N) x=x[x&lt;.5][:N]
tagged with: numpy
has comment: http://stackoverflow.com/comment/86864395

eval
tag name: eval
tags question: http://stackoverflow.com/q/50047602
type: Tag

http://stackoverflow.com/a/51659412
has body: For linux, cuda9.0, python3.6: pip3 install http://download.pytorch.org/whl/cu90/torch-0.3.1-cp36-cp36m-linux_x86_64.whl pip3 install torchvision For other cuda/python version: check website: https://ptorch.com/news/145.html
type: Answer
answers question: http://stackoverflow.com/q/49918479
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50004745
tagged with: augmented-reality
has answer: http://stackoverflow.com/a/50048390
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Augmented Reality with Python for smartphone
tagged with: python
tagged with: android-augmented-reality
has body: Are there tools available to build AR apps/games for Android/iOS with Python as a primary programming language? For smartphones according to my research most used combination is Unity/Vuforia ( C#), but I would really like to use Python?
has comment: http://stackoverflow.com/comment/87026554
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/77710745
upvote count: 2
downvote count: 2

http://stackoverflow.com/comment/86900705
has text: @ely Yes, Sorry. I saw that now. Thanks for correcting.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49931965

http://stackoverflow.com/a/68546179
upvote count: 45
has comment: http://stackoverflow.com/comment/125648103
answers question: http://stackoverflow.com/q/49992300
downvote count: 1
has comment: http://stackoverflow.com/comment/125628662
type: Answer
has comment: http://stackoverflow.com/comment/136843549
score: 44
has comment: http://stackoverflow.com/comment/137557563
has body: Instead of using a Jupyter notebook you can use Visual Studio Code in Interactive mode. It is similar to a notebook in many ways, as it splits your code into cells that can be run individually. One advantage over notebooks is that this remains a normal .py file. Spyder IDE also has this feature. You can split your code into cells using # %% as in this example. Running code this way, Visual Studio Code opens an Interactive pane that displays the plots inline. # %% import matplotlib.pylab as plt import numpy as np # %% plt.figure() plt.plot(np.sin(np.linspace(-np.pi, np.pi, 1001))) plt.show()

http://stackoverflow.com/q/50047265
downvote count: 0
tagged with: scipy
favorite count: 0
has title: Scipy ode integrate to unknown limit of t, based on the size of solution
tagged with: ode
type: Question
has answer: http://stackoverflow.com/a/50050273
tagged with: python
has body: I am modeling charged particles moving through an electromagnetic field and am using scipy ode. The code here is simplified, obviously, but works as an example. The problem I have is that I want to end the integration after a limit on r, not on t. So, integrate dx/dt up to the point where norm(x) > r. I don't want to just change the function to integrate over r, however, because the position is a function of t. Can I do a definite integral over an unrelated variable or something? import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint def RHS(state, t, Efield, q, mp): ds0 = state[3] ds1 = state[4] ds2 = state[5] ds3 = q/mp * Efield*state[0] ds4 = q/mp * Efield*state[1] ds5 = q/mp * Efield*state[2] r = np.linalg.norm((state[0], state[1], state[2])) # if r &gt; 30000 then do stop integration.....? # return the two state derivatives return [ds0, ds1, ds2, ds3, ds4, ds5] ts = np.arange(0.0, 10.0, 0.1) state0 = [1.0, 2.0, 3.0, 0.0, 0.0, 0.0] Efield=1.0 q=1.0 mp=1.0 stateFinal = odeint(RHS, state0, ts, args=(Efield, q, mp)) print(np.linalg.norm(stateFinal[-1,0:2]))
tagged with: numerical-integration
has comment: http://stackoverflow.com/comment/87113957
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/50050273
answer count: 1

http://stackoverflow.com/a/49952008
has body: This can be achieved very simply by reimplementing mimeData in your model: class MyModel(QStandardItemModel): ... def mimeData(self, indexes): mimedata = super(MyModel, self).mimeData(indexes) if indexes: mimedata.setText(indexes[0].data()) return mimedata That's all that's needed. You don't need to implement dragEnterEvent or dropEvent in the line-edit.
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49951628
downvote count: 0

http://stackoverflow.com/q/50049213
tagged with: django-models
tagged with: python
has body: I did some diagnosis and found that on htop: python save_to_db.py takes 86% of the CPU postgres: mydb mydb localhost idle in transaction takes 16% of the CPU. My code for save_to_db.py looks something like: import datetime import django import os import sys import json import itertools import cProfile # setting up standalone django environment ... from django.db import transaction from xxx.models import File INPUT_FILE = "xxx" with open("xxx", "r") as f: volume_name = f.read().strip() def todate(seconds): return datetime.datetime.fromtimestamp(seconds) @transaction.atomic def batch_save_files(files, volume_name): for jf in files: metadata = files[jf] f = File(xxx=jf, yyy=todate(metadata[0]), zzz=todate(metadata[1]), vvv=metadata[2], www=volume_name) f.save() with open(INPUT_FILE, "r") as f: dirdump = json.load(f) timestamp = dirdump["curtime"] files = {k : dirdump["files"][k] for k in list(dirdump["files"].keys())[:1000000]} cProfile.run('batch_save_files(files, volume_name)') And the respective cProfile dump(I only kept the ones with large cumtime): ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 881.336 881.336 &lt;string&gt;:1(&lt;module&gt;) 1000000 5.325 0.000 844.553 0.001 base.py:655(save) 1000000 14.574 0.000 834.125 0.001 base.py:732(save_base) 1000000 10.108 0.000 800.494 0.001 base.py:795(_save_table) 1000000 5.265 0.000 720.608 0.001 base.py:847(_do_update) 1000000 4.522 0.000 446.781 0.000 compiler.py:1038(execute_sql) 1000000 23.669 0.000 196.273 0.000 compiler.py:1314(as_sql) 1000000 7.473 0.000 458.064 0.000 compiler.py:1371(execute_sql) 1 0.000 0.000 881.336 881.336 contextlib.py:49(inner) 1000000 7.370 0.000 62.090 0.000 lookups.py:150(process_lhs) 1000000 3.907 0.000 81.685 0.000 lookups.py:159(as_sql) 1000000 3.251 0.000 44.679 0.000 lookups.py:74(process_lhs) 1000000 3.594 0.000 53.745 0.000 manager.py:81(manager_method) 1000000 19.855 0.000 106.487 0.000 query.py:1117(build_filter) 1000000 5.523 0.000 161.104 0.00…
type: AnsweredQuestion
tagged with: cprofile
score: 1
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
accepted answer: http://stackoverflow.com/a/50049471
favorite count: 0
type: Question
tagged with: postgresql
has answer: http://stackoverflow.com/a/50049471
has title: Django + PostgreSQL - 1000 inserts/sec, how to speed up?

text
tags question: http://stackoverflow.com/q/49925292
tags question: http://stackoverflow.com/q/49959094
tags question: http://stackoverflow.com/q/50035986
tags question: http://stackoverflow.com/q/49961589
tags question: http://stackoverflow.com/q/49951298
tags question: http://stackoverflow.com/q/50064426
tags question: http://stackoverflow.com/q/50026959
type: Tag
tags question: http://stackoverflow.com/q/49960024
tags question: http://stackoverflow.com/q/49997600
tags question: http://stackoverflow.com/q/50019288
tags question: http://stackoverflow.com/q/50038691
tags question: http://stackoverflow.com/q/49986858
tag name: text
tags question: http://stackoverflow.com/q/50040578
tags question: http://stackoverflow.com/q/50028067

http://stackoverflow.com/comment/86880411
type: Comment
type: QuestionComment
has text: Sorry it´s my first time here I can´t put in a code format. I have used %ch, just for try. I have also let as ch, only, but no success as well. In other languages, like vba, vb I know that is possible to combines variable into functions but I have not idea about Python. The problem I see is that the microbit argument is "radio.config(channel =7" - so I can´t find a way to break the function, removing the 7 and put a variable and the function still be valid
comment on: http://stackoverflow.com/q/49931962
score: 0

http://stackoverflow.com/comment/87070751
type: QuestionComment
comment on: http://stackoverflow.com/q/50020112
score: 0
type: Comment
has text: @CristiFati, yes, the C++ version works as expected, so does the swig wrapper.

http://stackoverflow.com/comment/86975298
type: AnswerComment
has text: yes i am pretty new to python, although the script simply opens and writes out stuff to console, its almost what i need :D i am going to try delete the "print line" and fit it to my script and see what happens.
comment on: http://stackoverflow.com/a/49979311
score: 1
type: Comment

http://stackoverflow.com/comment/86927986
comment on: http://stackoverflow.com/q/49955687
score: 0
has text: Please also read https://stackoverflow.com/help/mcve and https://stackoverflow.com/help/how-to-ask.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86970141
type: Comment
has text: Probably. Just read a bit more on regexes. See http://regexone.com - it is useful to learn the basics (as anchors and word boundaries). Use http://regex101.com to debug regex patterns (with PCRE option, it allows you to peek at what is going on behind the scenes).
comment on: http://stackoverflow.com/q/49976003
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86970835
has text: @JahKnows Please consider the actual question: `Why? What is the difference of this derivatives?`
type: QuestionComment
comment on: http://stackoverflow.com/q/49977063
score: 0
type: Comment

http://stackoverflow.com/q/50026554
has body: When someone says something else in replay() except for "no" or "yes" it starts the host's turn for some reason or even no. I'm still learning, this is my second project, any comments? I tried many things but it still doesn't work. # Blackjack game import random global playername, nameofplayer nameofplayer = input('Enter your name').capitalize() print ('Hello,', str(nameofplayer)) class Player(): def __init__(self, banktotal): self.banktotal = banktotal # adds an amount to the bank def addtobank(self, bankadd): self.banktotal += bankadd # removes an amount from the bank def subfrombank(self, subbank): self.banktotal -= subbank def rolldice(): global playerhand playerhand = 0 print('Your Current hand: ' + str(playerhand)) playerhand = 0 print ('...') print ('Rolling the dice for you') dice = list(range(1,7)) while playerhand &lt;= 21: rolled = random.choice(dice) print('Your Current hand: ' + str(playerhand)) hitstick = str(input('Hit or Stick?').capitalize()) if hitstick == 'Hit': print('You chose to hit!') playerhand += rolled elif hitstick == 'Stick': print('Your exit hand: ' + str(playerhand)) break elif hitstick != 'Hit' or 'Stick': print('Enter a valid argument') else: print('Your Current hand: ' + str(playerhand)) print ('Busted, Host Wins!') print('Reducing 100$ from your account') playername.banktotal -= 100 print('Your bank balance: ' + str(playername.banktotal)) replay() def hostchance(): hosthand = 0 print ('Current host hand: ' + str(hosthand)) dice = list(range(1, 7)) while hosthand &lt;= playerhand: rolled = random.choice(dice) hosthand += rolled print('Rolling the dice for the host') print ('Current host hand: ' + str(hosthand)) if hosthand &lt; playerhand: pass elif hosthand == playerhand: print ('Its a draw!') break elif hosthand &gt; playerhand and hosthand &lt; 22: print('Host Wins!') print('Reducing 100$ from your account') playername.banktotal -= 100 break if hosthand &lt; playerhand or hosthand &gt; 21: print (str(nameofplayer) + ' Wins!') prin…
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: blackjack
has comment: http://stackoverflow.com/comment/87073410
has comment: http://stackoverflow.com/comment/87073429
answer count: 1
has title: Blackjack python dice game fix?
score: -2
has answer: http://stackoverflow.com/a/50028588

http://stackoverflow.com/q/50054671
type: AnsweredQuestion
score: 0
has title: No module named app when running celery worker -A app in EB .ebextensions
has body: I'm setting up celeryd and redis on Elastic Beanstalk as a daemon, per How do you run a worker with AWS Elastic Beanstalk?. I think I'm almost there. Redis is running and accessible on elasticcache. But the .ebextesions file to setup celeryd is failing on a specific line. See entire script I'm running in .ebextensions further below. Line: command=/opt/python/run/venv/bin/celery worker -A myappname --loglevel=INFO. I've tried a few different variations of the command. Tried: command=/opt/python/run/venv/bin/celery worker -A /opt/python/current/app/app.py --loglevel=INFO (directory to my app.py) command=/opt/python/run/venv/bin/celery worker -A app.py --loglevel=INFO (name of my app.py) command=/opt/python/run/venv/bin/celery worker -A app --loglevel=INFO (name without extension) command=/opt/python/run/venv/bin/celery worker -A flask-celery-01 --loglevel=INFO (app name in elastic beanstalk) command=/opt/python/run/venv/bin/celery worker -A myappname --loglevel=INFO (original unedited) Traceback in celery logs: Traceback (most recent call last): File "/opt/python/run/venv/bin/celery", line 11, in &lt;module&gt; sys.exit(main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/__main__.py", line 30, in main main() File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 769, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 305, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 465, in setup_app_from_commandline self.app = self.find_app(app) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 485, in find_app return find…
tagged with: amazon-elastic-beanstalk
type: Question
has answer: http://stackoverflow.com/a/50103220
linked to: http://stackoverflow.com/q/14761468
accepted answer: http://stackoverflow.com/a/50103220
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/50046825
tagged with: amazon-web-services
tagged with: flask
tagged with: celery

python-sphinx
tags question: http://stackoverflow.com/q/50064314
tag name: python-sphinx
tags question: http://stackoverflow.com/q/49962436
tags question: http://stackoverflow.com/q/49932998
tags question: http://stackoverflow.com/q/50070864
type: Tag
tags question: http://stackoverflow.com/q/49967691

http://stackoverflow.com/a/49937318
type: Answer
has comment: http://stackoverflow.com/comment/89987411
accepted answer of: http://stackoverflow.com/q/49936557
has body: For improve performance is possible use numexpr: import numexpr np.random.seed(125) N = 40000000 df = pd.DataFrame({'A':np.random.randint(10, size=N)}) def ne(df): x = df.A.values return df[numexpr.evaluate('(x &gt; 5)')] print (ne(df)) In [138]: %timeit (ne(df)) 1 loop, best of 3: 494 ms per loop In [139]: %timeit df[df.A &gt; 5] 1 loop, best of 3: 536 ms per loop In [140]: %timeit df.query('A &gt; 5') 1 loop, best of 3: 781 ms per loop In [141]: %timeit df[df.eval('A &gt; 5')] 1 loop, best of 3: 770 ms per loop import numexpr np.random.seed(125) def ne(x): x = x.A.values return x[numexpr.evaluate('(x &gt; 5)')] def be(x): return x[x.A &gt; 5] def q(x): return x.query('A &gt; 5') def ev(x): return x[x.eval('A &gt; 5')] def make_df(n): df = pd.DataFrame(np.random.randint(10, size=n), columns=['A']) return df perfplot.show( setup=make_df, kernels=[ne, be, q, ev], n_range=[2**k for k in range(2, 25)], logx=True, logy=True, equality_check=False, xlabel='len(df)') Edit: Graph with modified ne and improved be: def ne(x): return x[numexpr.evaluate('(x &gt; 5)')] def bex(x): return x[x.A.values &gt; 5]
upvote count: 43
answers question: http://stackoverflow.com/q/49936557
type: AcceptedAnswer
score: 42
has comment: http://stackoverflow.com/comment/89987332
downvote count: 1
has comment: http://stackoverflow.com/comment/94567198
has comment: http://stackoverflow.com/comment/117336860

http://stackoverflow.com/q/49963138
has answer: http://stackoverflow.com/a/50041593
accepted answer: http://stackoverflow.com/a/50041593
tagged with: posthoc
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7982513
tagged with: tukey
answer count: 2
upvote count: 2
tagged with: classification
downvote count: 0
has title: Label groups from Tukey's test results according to significant
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61732830
possible better answer: http://stackoverflow.com/a/61732830
has body: I have a Tukey's test table resulted from pairwise_tukeyhsd from the python statsmodels.stats.multicomp. group1 group2 meandiff lower upper reject 0 101 102 0.2917 -0.0425 0.6259 False 1 101 103 0.1571 -0.1649 0.4792 False 2 101 104 -0.1333 -0.4675 0.2009 False 3 101 105 0.0833 -0.2509 0.4175 False 4 101 106 -0.0500 -0.3626 0.2626 False 5 102 103 -0.1345 -0.4566 0.1875 False 6 102 104 -0.4250 -0.7592 -0.0908 True 7 102 105 -0.2083 -0.5425 0.1259 False 8 102 106 -0.3417 -0.6543 -0.0290 True 9 103 104 -0.2905 -0.6125 0.0316 False 10 103 105 -0.0738 -0.3959 0.2482 False 11 103 106 -0.2071 -0.5067 0.0924 False 12 104 105 0.2167 -0.1175 0.5509 False 13 104 106 0.0833 -0.2293 0.3960 False 14 105 106 -0.1333 -0.4460 0.1793 False I have this table as pandas df. I would like to label (by letters) the groups (101-106) denoting statistical relationships. For this specific example the desired result would be: (I don't mind if the results will be df, a list, a dictionary) group label 101 ab 102 a 103 ab 104 b 105 ab 106 b As you can see, all groups that share similar letter have an equal mean (reject column = False), and groups that have different letters (reject column = True) have different mean. For example, the mean of group 101 is equal to all of the other groups' means because group 101 has the letter ab, and all of the other groups have either a or b or ab. On the other hand, group 106 only has the letter b which indicates that it is similar to all the groups except for group 102 that has only the letter a. I could not find an automatic python solution for that. I saw that R has a package for that called multcompLetters, is there something similar in python?
tagged with: python

http://stackoverflow.com/comment/87055212
type: Comment
comment on: http://stackoverflow.com/q/50019588
has text: Why do you even need `else` in the first place?
score: 1
type: QuestionComment

http://stackoverflow.com/a/49956542
type: AcceptedAnswer
downvote count: 0
has body: When you create sp2 you set the value to var1.get(), but to have it change with var1 you will have to give it a function which reacts to changes in sp1. As with buttons you can specify a callback function: sp1 = tk.Spinbox( ... , command=callback_function) Also, the spinbox does not seem to get it if I set both from_ and to to the same value, so I set it explicitly whenever var1.get() returns 1. Example code: import tkinter as tk mainWin = tk.Tk() def update_sp2(event=None): sp2.config(to=var1.get()) if var1.get() == 1: var2.set(1) # Needed to set spinbox value = 1 var1 = tk.IntVar() sp1 = tk.Spinbox(mainWin, from_=1, to=20, textvariable=var1, command=update_sp2) sp1.grid() var2 = tk.IntVar() sp2 = tk.Spinbox(mainWin, from_=1, to=1, textvariable=var2) sp2.grid() var2.set(1) # Needed to set spinbox value = 1 mainWin.mainloop()
accepted answer of: http://stackoverflow.com/q/49955470
score: 1
answers question: http://stackoverflow.com/q/49955470
type: Answer
upvote count: 1

http://stackoverflow.com/comment/87135207
type: Comment
has text: Are the modules you're trying to import in the same directory as the script you're calling ? Can you give an example value for `$2` in your shell script ?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50057695

http://stackoverflow.com/q/50013067
has comment: http://stackoverflow.com/comment/87124059
has comment: http://stackoverflow.com/comment/87082087
has comment: http://stackoverflow.com/comment/87124176
score: 1
has comment: http://stackoverflow.com/comment/87125910
has comment: http://stackoverflow.com/comment/87123823
tagged with: python
has comment: http://stackoverflow.com/comment/87153928
has title: Django + WSGI + Apache apps fail after idle time
has comment: http://stackoverflow.com/comment/87124035
has comment: http://stackoverflow.com/comment/87044260
has comment: http://stackoverflow.com/comment/87078274
type: Question
has comment: http://stackoverflow.com/comment/87124052
answer count: 0
has body: Using Django 1.11, Python 2.7, and mod_wsgi 4.6.4 in an Ubuntu and Apache environment. I'm pretty sure this is a configuration issue, and I'm happy to provide more information if this isn't enough. In my Apache configuration file I have: Include "/home/django/wsgi-aliases" WSGIApplicationGroup %{GLOBAL} In the WSGI aliases file indicated above, I have the aliases for my various Django apps written out, along with a specification for WSGI daemon mode. Example: WSGIScriptAlias /EmployeeDirectory /home/django/EmployeeDirectory/EmployeeDirectory/wsgi.py process-group=EmployeeDirectory WSGIDaemonProcess EmployeeDirectory display-name=WSGI_EmployeeDirectory Alias /static/EmployeeDirectory /home/django/EmployeeDirectory/EmployeeDirectoryApp/static This all works just fine unless the process stays idle, at which point the page in question breaks, and will not work again without an Apache graceful restart. One more piece of information: this problem occurs only with apps that utilize either LDAP, or the authentication API to our content resource provider. My apps that utilize neither of these have no issues. An example error message: {'info': 'Connection reset by peer', 'errno': 104, 'desc': "Can't contact LDAP server"} It occurs to me that both the LDAP and API connections, respectively, time out if they are not used. But this was never an issue when these apps ran in non-daemon mode (which I recognize is not recommended and is why we moved over to daemon mode). This impacts a fairly well trafficked production page and any help is appreciated. Thanks in advance.
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/87081705
has comment: http://stackoverflow.com/comment/87075549
has comment: http://stackoverflow.com/comment/87183076
type: UnansweredQuestion
tagged with: wsgi
tagged with: apache
downvote count: 0
has comment: http://stackoverflow.com/comment/87123515
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/87078216
has comment: http://stackoverflow.com/comment/87081662
favorite count: 0
has comment: http://stackoverflow.com/comment/87139095
has comment: http://stackoverflow.com/comment/87124368

http://stackoverflow.com/a/49946791
has body: One way you can do it using set and id. Note this solution also uses generators which means we can start using our flattened dict before the entire result is computed def recursive_flatten (mydict): def loop (seen, path, value): # if we've seen this value, skip it if id(value) in seen: return # if we haven't seen this value, now we have else: seen.add(id(value)) # if this value is a dict... if isinstance (value, dict): for (k, v) in value.items (): yield from loop(seen, path + [k], v) # base case else: yield (".".join(path), value) # init the loop yield from loop (set(), [], mydict) Program demo mydict = { 'first': { 'second': { 'third': { 'fourth': 'the end' } } } } for (k,v) in recursive_flatten (mydict): print (k, v) # first.second.third.fourth the end mydict['new_key'] = mydict for (k,v) in recursive_flatten (mydict): print (k, v) # first.second.third.fourth the end We can make a slight modification if you would like to see output for self-referential values # if we've seen this value, skip it if (id(value) in seen): # this is the new line yield (".".join(path), "*self-reference* %d" % id(value)) return Now the output of the program will be first.second.third.fourth the end first.second.third.fourth the end new_key *self-reference* 139700111853032
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49946398
score: 2
answers question: http://stackoverflow.com/q/49946398
type: Answer

http://stackoverflow.com/comment/87084458
type: Comment
has text: Possible duplicate of [Is it possible to show \`print\` output as LaTeX in jupyter notebook?](https://stackoverflow.com/questions/48422762/is-it-possible-to-show-print-output-as-latex-in-jupyter-notebook)
score: 0
comment on: http://stackoverflow.com/q/50033768
type: QuestionComment

http://stackoverflow.com/comment/87129675
type: Comment
has text: @AparnaAnanthasubramaniam Correct, `copy.deepcopy` also copies the lists inside that list, so references are replaced with copies.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50035916

http://stackoverflow.com/comment/87209674
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50023592
has text: @Matias Valdenegro Unfortunately I can´t provide the data, so you cannot run the code anyway. If the Class CRF is undefinded you have to install the CRF from Keras contribs package.

http://stackoverflow.com/q/49935190
answer count: 2
downvote count: 0
has title: Kivy: How to initialize the viewclass of the RecycleView dynamically?
has answer: http://stackoverflow.com/a/55110003
possible better answer: http://stackoverflow.com/a/55110003
linked to: http://stackoverflow.com/q/56245754
accepted answer: http://stackoverflow.com/a/49963257
favorite count: 0
type: Question
has body: Recently I have been struggling with using RecycleView in kivy. I have made quite many test and got a bit confused. My goal I want to create a Recycle view where each Row contains few Label (i.e. columns), but the number of columns is set dynamically (but is the same for all the rows of course). Typically, I have a database and I want to display the table but I want to dynamically change the columns that I display. There have been similar questions, but they all deal a fixed number of value to set. What works If the number of columns is fixed, the values can be linked using properties I can adding widget dynamically using add_widget What doesn't work If the cell are added dynamically, I cannot link the content of value in the kv widget to the python variable If the number of Label widget is fixed, I can updated things dynamically (like the examples) but it cannot be directly initialized. Here is an example with all the different possibilities that I have tried: from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.properties import StringProperty, ObjectProperty from kivy.uix.label import Label from kivy.uix.recycleview import RecycleView kv = """ &lt;Row&gt;: id: row canvas.before: Color: rgba: 0.5, 0.5, 0.5, 1 Rectangle: size: self.size pos: self.pos value1: '' value2: '' value3: '' value4: '' value5: '' Label: #Label 1 text: root.value1 &lt;Test&gt;: canvas: Color: rgba: 0.3, 0.3, 0.3, 1 Rectangle: size: self.size pos: self.pos orientation: 'vertical' GridLayout: cols: 3 rows: 2 size_hint_y: None height: dp(108) padding: dp(8) spacing: dp(16) Button: text: 'Update list' on_press: root.update() RecycleView: id: rvlist scroll_type: ['bars', 'content'] scroll_wheel_distance: dp(114) bar_width: dp(10) viewclass: 'Row' RecycleBoxLayout: default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' spacing: dp(2) """ Builder.load_string(kv) class Row(BoxLay…
score: 3
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/49963257
type: AnsweredQuestion
upvote count: 3
tagged with: kivy-language

http://stackoverflow.com/comment/106563409
type: Comment
comment on: http://stackoverflow.com/a/50595676
type: AnswerComment
has text: BeeWare does not seem to support Android (Java) at this stage in any event.
score: 3

http://stackoverflow.com/comment/86898816
type: AnswerComment
comment on: http://stackoverflow.com/a/49940731
score: 0
type: Comment
has text: I saw `isna` was bein introduced. Is it recommended in place of `isnull`?

http://stackoverflow.com/comment/86897884
comment on: http://stackoverflow.com/a/49939971
type: AnswerComment
has text: This returns just two columns as below: ['a', 'b'] But when I save the Dataframe and use it in the mail I see this extra column..
score: 0
type: Comment

http://stackoverflow.com/a/49954198
accepted answer of: http://stackoverflow.com/q/49954037
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49954037
score: 2
has body: In your case you have written len(set(list)) != 1 which only works if all elements in list are same if you have two elements repeats for thousand of time then it will return length of set as two because it will have two unique elements. So one way is that you check length of unique elements with original list if its same then function evaluates True otherwise False def all_distinct(lis): return len(set(lis)) == len(lis) set(lis) - creates set of element where all elements are unique (never repeated) len() - returns length of set or list or string passed as argument. In [8]: all_distinct(['a', 'a']) Out[8]: False In [9]: all_distinct(['a', 'a', 'x']) Out[9]: False In [11]: all_distinct(['a', 'b', 'x']) Out[11]: True You can also approach in different way as below (keeping record of occurances) def get_occurrence(lis): td = {} for i in lis: td[i] = td.setdefault(i, 0) + 1 return td def all_distinct(lis): dict_ = get_occurrence(lis) # this will return dict containing key as element and value of it's occurrence return all(i==1 for i in dict_.values())
has comment: http://stackoverflow.com/comment/86924904
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/50030447
has answer: http://stackoverflow.com/a/50038007
has body: I' like to have a small explanation about Flask, Something I don't understand. I'm looking to get DATA from Database by an ID. The ID is my route parameter. I've create my route, but I'm having an error, And I don't understand What they are requesting in fact ? An element from Database ? mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%(site_id)s' at line 1 My route code : #Construct app app = Flask(__name__) app.config.from_object('config') app.config.from_object('secret_config') #Database functions def connect_db () : g.mysql_connection = mysql.connector.connect( host = app.config['DATABASE_HOST'], user = app.config['DATABASE_USER'], password = app.config['DATABASE_PASSWORD'], database = app.config['DATABASE_NAME'] ) g.mysql_cursor = g.mysql_connection.cursor() return g.mysql_cursor def get_db () : if not hasattr(g, 'db') : g.db = connect_db() return g.db @app.teardown_appcontext def close_db (error) : if hasattr(g, 'db') : g.db.close() @app.route('/historique/<int:site_id>') def historique(site_id): db = get_db() db.execute('SELECT * FROM sites s JOIN historique h ON h.site_id WHERE `s.site_id = %(site_id)s', {'id': site_id}) entries = db.fetchall() return render_template('historique.html', entries = entries) And Here is my HTML Code {% extends 'layout.html' %} {% block titre %} Acceuil {% endblock %} {% block body %} Historique d'activité pour {{ entrie.0 }} {% for entrie in entries %} {% endfor %} {% endblock %} I only like to understand. Thanks a lot for your help.
has title: FLASK - You have an error in your SQL syntax near '%(site_id)s' at line 1
has comment: http://stackoverflow.com/comment/87077098
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87077613
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/87092235
score: 0
answer count: 1
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/87077279

http://stackoverflow.com/q/50043603
upvote count: 2
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87103524
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/87104086
has title: Why doesn't the pandas apply method have an axis=None option to apply a function to the whole dataframe?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/73668855
answer count: 1
tagged with: dataframe
has body: There seems to be a gap in the pandas API (IMHO/YMMV) in that there is no way to chain operations (in a fluent style) that operate on the whole dataframe. e.g. a.op1.op2.op3... The apply method takes a function and an axis argument and applies the function to either rows or columns accordingly. What I think is missing is an axis=None which would then mean that the function applies to the whole dataframe. This would then allow for operations, including structural modifications (e.g. dropping rows, columns, renaming, index changes etc) to be chained in such a fluent style. There is a hack to accomplish this. If a is a dataframe then... a.groupby(lambda _:0).apply(lambda x:... ... means that the x in the applied lambda is set to each group of the groupby successively but there is only one group created so a function applied to that one group effectively becomes a function applied to the whole dataframe. However this is a bit clunky and has a drawback is that sometimes the groupby creates a new level in the index (but sometimes it doesn't and that is hard to predict). Have I missed a method in the API or is there a less clunky way to achieve this?
has answer: http://stackoverflow.com/a/73668855
favorite count: 0
type: Question

http://stackoverflow.com/comment/87097637
type: QuestionComment
comment on: http://stackoverflow.com/q/50039500
has text: @JohnZwinck Thanks for your comment, I added some more code and clarified the use case :)
score: 0
type: Comment

http://stackoverflow.com/q/49998073
has body: I've been trying scraping Instagram posts for a certain hashtag for the keys: display_url, taken_at_timestamp, text, edge_liked_by. This goes perfect for some hundreds in the start, but then stops fetching 'text' keyword only. Other three fields are successfully fetched though. I am not sure why it's happening. I am parsing the JSON https://www.instagram.com/explore/tags/something/?__a=1. base_url = "https://www.instagram.com/explore/tags/salonedelmobile/?__a=1" url = "https://www.instagram.com/explore/tags/salonedelmobile/?__a=1" while True: response = url_req.urlopen(url) json_file = json.load(response) for i in json_file['graphql']['hashtag']['edge_hashtag_to_media']['edges']: try: post_text = i['node']['edge_media_to_caption']['edges'][0]['node']['text'] except IndexError as e: post_text = e try: display_url = i['node']['display_url'] except: display_url = e try: like_count = i['node']['edge_liked_by']['count'] except: like_count = e try: time_stamp = i['node']['taken_at_timestamp'] except: time_stamp = e output.append([display_url, like_count, time_stamp, post_text]) df = pd.DataFrame(output,columns=['URL', 'Like Count', 'Time', 'Text']) try: df.to_excel('instagram.xlsx') except: pass if json_file['graphql']['hashtag']['edge_hashtag_to_media']['page_info']['has_next_page'] == True: end_cursor = json_file['graphql']['hashtag']['edge_hashtag_to_media']['page_info']['end_cursor'] url = base_url + '&amp;max_id=' + end_cursor else: break
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87013480
has comment: http://stackoverflow.com/comment/87101329
tagged with: python
has title: Scraping Instagram with API ?__a=1
score: 0
answer count: 0
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/87335966
has comment: http://stackoverflow.com/comment/87013968
has comment: http://stackoverflow.com/comment/87025457
type: Question
has comment: http://stackoverflow.com/comment/87014102
tagged with: instagram-api

http://stackoverflow.com/comment/86996301
score: 0
has text: @abarnert I'll rephrase that, I don't know why I said it like that: The resulting IPs in the final file are not in the inputs from Column A. In other words, it's putting IPs in the final file that were not in Column A for the input -- they're false results.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49989455

http://stackoverflow.com/q/50016989
score: 0
linked to: http://stackoverflow.com/q/29173299
tagged with: pyqt
answer count: 1
linked to: http://stackoverflow.com/q/5033903
tagged with: pyqt5
tagged with: method-resolution-order
tagged with: multiple-inheritance
linked to: http://stackoverflow.com/q/3277367
has title: MRO in python when subclassing with multiple inheritance, using PyQt (QMainWindow)
type: Question
has comment: http://stackoverflow.com/comment/87076678
accepted answer: http://stackoverflow.com/a/50042974
duplicate of: http://stackoverflow.com/q/3277367
has body: I recently experienced a TypeError, that I didn't understood when I was subclassing a QMainWindow with PyQt5. When creating two classes: class Base (QMainWindow): def __init__(self): super(Base, self).__init__(None) class Base2 (object): def __init__(self, a, b): pass and then creating a Subclass of both, without any init arguments: class SubClass( Base, Base2 ): def __init__(self): Base.__init__(self) Base2.__init__(self, 0,0) I get a TypeError when creating an instance of the subclass: from PyQt5.QtWidgets import QApplication, QMainWindow app = QApplication([]) print( SubClass() ) output: Traceback (most recent call last): print(SubClass()) Base.__init__(self) super(Base, self).__init__(None) TypeError: __init__() missing 2 required positional arguments: 'a' and 'b' However, when changing the Order for the inheritance class SubClass( Base2, Base ): the code will run fine. I read the post in How does Python's super() work with multiple inheritance? and Method Resolution Order but didn't found an answer on this. (Also note that this is somewhat PyQt-specific, because I couldn't reproduce the problem with Base-classes entirely based on object) Could someone give a clear explanation for this behaiviour?
tagged with: python
has answer: http://stackoverflow.com/a/50042974
type: AnsweredQuestion

http://stackoverflow.com/comment/87003797
has text: Try beautifulsoup?
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/49993754
type: Comment

http://stackoverflow.com/q/49940813
favorite count: 0
has answer: http://stackoverflow.com/a/77183662
has body: I have a problem when I try to use pip in any way. I'm using Ubuntu 16.04.4 I should say that I've used it already, and I never had any problem, but starting today when I use any command I always get the same error (as an example using pip --upgrade). Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in <module> from pip._internal import main ImportError: No module named _internal I have tried doing sudo apt-get remove python-pip followed by sudo apt-get install python-pip but nothing changed.
has answer: http://stackoverflow.com/a/56318740
has comment: http://stackoverflow.com/comment/99245203
has answer: http://stackoverflow.com/a/50639340
has answer: http://stackoverflow.com/a/53561694
linked to: http://stackoverflow.com/q/122327
has answer: http://stackoverflow.com/a/56949381
has title: pip: no module named _internal
type: Question
has answer: http://stackoverflow.com/a/71645899
has answer: http://stackoverflow.com/a/50102939
has answer: http://stackoverflow.com/a/57819972
has answer: http://stackoverflow.com/a/56535132
has answer: http://stackoverflow.com/a/53280451
has answer: http://stackoverflow.com/a/51101241
has answer: http://stackoverflow.com/a/52162358
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/77990367
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59956037
has answer: http://stackoverflow.com/a/51629695
has answer: http://stackoverflow.com/a/73027932
has answer: http://stackoverflow.com/a/69704214
has comment: http://stackoverflow.com/comment/86909108
has answer: http://stackoverflow.com/a/77028970
answer count: 29
has answer: http://stackoverflow.com/a/76963747
has answer: http://stackoverflow.com/a/50737296
has answer: http://stackoverflow.com/a/51182092
has answer: http://stackoverflow.com/a/50444972
has answer: http://stackoverflow.com/a/62343176
has answer: http://stackoverflow.com/a/50067201
has answer: http://stackoverflow.com/a/53881970
has answer: http://stackoverflow.com/a/78479499
has comment: http://stackoverflow.com/comment/86911688
downvote count: 0
has answer: http://stackoverflow.com/a/74779255
has answer: http://stackoverflow.com/a/54851781
score: 213
upvote count: 213
has comment: http://stackoverflow.com/comment/91385688
has answer: http://stackoverflow.com/a/49997795
has comment: http://stackoverflow.com/comment/86898858

http://stackoverflow.com/q/50035992
tagged with: ftp
has comment: http://stackoverflow.com/comment/87097847
answer count: 0
tagged with: ftplib
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/12613797
has body: I have a script, that puts a number (in this case "9") into a var and saves it as a .txt file. Now i wanted to store that number automatically in a .txt file on my FTP server. connecting to FTP works and i managed to create the "lifetime_wins.txt" file. But it has nothing in it. I want to store the data of the "headers" variable in the txt. can anyone help here? I am not that good at python :x Code: import bs4 import time def main(): #----INPUT BASIC---- #import bs4 and url-grabbing-module from urllib.request import urlopen as uReq from urllib.request import Request, urlopen from bs4 import BeautifulSoup as soup #setting var "url" to the page url = 'https://fortnitetracker.com/profile/psn/Rehgum' #var req to uReq and setting Mozilla / decoding for https req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) #decoding web_byte = urlopen(req).read() webpage = web_byte.decode('utf-8') urlopen(req).close() #html parsing page_soup = soup(webpage, "html.parser") #----SORTING---- #selecting &lt;div&gt; lifetime lifetime = page_soup.findAll("div", {"class": "top-stats"}) #headers and file creation filename = "lifetime_wins.txt" f = open(filename, "w") #setting lifetime into another var (0) stats = lifetime[0] #selecting container with the right information stats.div.div #setting variable to put in the value value = stats.div.div #----OUTPUT---- output = value.text #----PRINTING OUTPUT---- print("Lifetime Siege: " + output) headers = ("#" + output + " ") f.write(headers) f.close() #---FTP CONNECTION--- from ftplib import FTP ftp = FTP('server.1and1-data.host') ftp.login('user','pw') ftp.cwd('/') #--WRITING HEADERS TO TXT ON FTP-- def placeFile(): filename = 'lifetime_wins.txt' ftp.storbinary('STOR '+filename, f.write(headers), open(filename, 'rb')) f.close() ftp.quit() #--------------------------------- #loop time.sleep(30) main() for i in range(1, 2): main() while i &lt; 1: print("Ende") Edit: Its working after changing the method from storing a var into the text to stor…
duplicate of: http://stackoverflow.com/q/2671118
duplicate of: http://stackoverflow.com/q/37043910
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87088170
score: 0
duplicate of: http://stackoverflow.com/q/12613797
has comment: http://stackoverflow.com/comment/87089519
has title: Writing number (var) into a .txt on FTP server with .ftplib with python
has comment: http://stackoverflow.com/comment/87089181
tagged with: python

http://stackoverflow.com/q/50008919
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87034439
type: AnsweredQuestion
has title: How can I convert dictionary to dataframe in pandas?
has answer: http://stackoverflow.com/a/50008988
accepted answer: http://stackoverflow.com/a/50008988
has body: I have a dictionary like this. The inside of dictionary is ... When I clicked the {top:'Dataframe',rising:'Dataframe'}, i accessed to two different Dataframes which are top and rising. My question is that How can i access these dataframes directly? I tried to use dict to dataframe examples. They did not work. Any help would be appreciated.
tagged with: python
score: -1
tagged with: dictionary
type: Question
upvote count: 0

http://stackoverflow.com/a/49977151
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49940550
answers question: http://stackoverflow.com/q/49940550
has body: I think, I have found the solution myself. Kinda. Referring to the chapter Schedule before frame in the docs, I thought a timeout of -1 was what I needed as I wanted to first calculate all positions and then have the app draw all widgets there. However, this does the above mentioned mess-up. I don't quite understand why this is causing the described callback loop. If anybody likes to explain :-) Anyway, what does work is a timeout of either 0or 1/60 (for a framerate of 60). self.layout_clock = Clock.schedule_interval(self._trigger_layout, 0) Now all my widgets move buttery smooth and there’s no more warnings.
score: 0

http://stackoverflow.com/comment/117874957
has text: In the case that the proxy has been set up, there will still be proxy error on win10. Lowering the pip version is a feasible solution.
comment on: http://stackoverflow.com/a/66672044
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86964232
score: 0
has text: Hi @JimyHendrixFalcónCárdenas here I added the model for adding data.
type: Comment
comment on: http://stackoverflow.com/q/49969040
type: QuestionComment

http://stackoverflow.com/q/49943543
answer count: 2
tagged with: arrays
downvote count: 0
possible better answer: http://stackoverflow.com/a/49943628
favorite count: 0
accepted answer: http://stackoverflow.com/a/49943684
has body: This is my below code and I would like to add jsondict value to parsedData list parsedData = [] userData = {} jsondict=[{u'Name': u'BILL', u'ID': u'1028', u'CARS': [u'BMW', u'AUDI']}, {u'Name ': u'TOM', u'ID': u'1029', u'CARS': [u'TOYOTA', u'FERRARI']}] for distro in jsondict: userData['Name'] = distro['Name'] userData['ID'] = distro['ID'] userData['CARS1'] = distro['CARS'][0] userData['CARS2'] = distro['CARS'][1] parsedData.append(userData) But from this code I am getting two times last dict which is not correct and expected output should be like this: [{u'Name': u'BILL', u'ID': u'1028', u'CARS1': u'BMW',u'CARS2': u'AUDI'}, {u'Name ': u'TOM', u'ID': u'1029', u'CARS1': u'TOYOTA', u'CARS2':u'FERRARI'}]
has answer: http://stackoverflow.com/a/49943684
type: Question
score: 3
has title: Adding two dictionaries to list by array
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/49943628
has comment: http://stackoverflow.com/comment/86903257
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/86950573
score: 0
type: Comment
type: QuestionComment
has text: show traceback please
comment on: http://stackoverflow.com/q/49967434

http://stackoverflow.com/a/50075270
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50071671
accepted answer of: http://stackoverflow.com/q/50071671
has body: The error was in the Edit/Preferences/Tools/Terminal field. I changed mate-terminal to mate-terminal -e "/bin/sh %c" Now all is well.
type: Answer

http://stackoverflow.com/a/49932169
answers question: http://stackoverflow.com/q/49932076
has body: You're calculation of y_hat is slightly incorrect. It's currently a 2D array of shape (100,1). This should help. It pulls the "zeroith" element from each of the rows: theta_ = [(theta[0]*(a**2) + theta[1]*a + theta[2]) for a in x] y_hat = np.array([t[0] for t in theta_])
score: 0
has comment: http://stackoverflow.com/comment/86922050
type: Answer

http://stackoverflow.com/q/49971443
type: AnsweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: ctypes
has title: Pass a string as a char pointer array using ctypes
tagged with: python
score: 4
has body: I have a C function of this signature: int fileopen(const char *fname, int flags) In Linux system, I want to pass the fname from Python using ctypes so I use ctypes.c_char_p("file1.dat") as the following: import ctypes as ctypes dll_name = "IO/pyaio.so" dllabspath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + dll_name pyaio = ctypes.CDLL(dllabspath) fd_w = pyaio.fileopen(ctypes.c_char_p("file1.dat"), 1) But I get this error: Traceback (most recent call last): File "test.py", line 21, in &lt;module&gt; fd_w = pyaio.fileopen(ctypes.c_char_p("file1.dat"), 1) # 0 read, 1 write TypeError: bytes or integer address expected instead of str instance I don't know another way to pass the string"file1.dat" than using ctypes.c_char_p. How to solve this problem? Thank you
has answer: http://stackoverflow.com/a/49971523
accepted answer: http://stackoverflow.com/a/49971523
upvote count: 4

google-vision
tags question: http://stackoverflow.com/q/49918950
tag name: google-vision
tags question: http://stackoverflow.com/q/49974375
type: Tag

http://stackoverflow.com/a/50021867
type: Answer
answers question: http://stackoverflow.com/q/50021797
upvote count: 2
has body: This is what Counter was created for: &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counts = Counter([5,5,7,7,7,7,9,10,12,14]) &gt;&gt;&gt; [counts[i] for i in sorted(counts.keys())] [2, 4, 1, 1, 1, 1] Alternatively, if you want to optimize for memory usage, here's a function that takes any iterable, even a generator that sources numbers from a file: def run_lengths(lst): previous_val = None num_vals = 0 for i in lst: if previous_val is None: previous_val = i if i == previous_val: num_vals += 1 continue yield num_vals previous_val = i num_vals = 1 if num_vals: yield num_vals print(list(run_lengths([5,5,7,7,7,7,9,10,12,14]))) # Returns [1, 2, 4, 1, 1, 1] def file_generator(file_path): with open(file_path, 'r') as f: for l in f: yield int(l.strip()) print(list(run_lengths(file_generator('my/huge/file.dat'))))
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/87059558
has comment: http://stackoverflow.com/comment/87059530
score: 1
accepted answer of: http://stackoverflow.com/q/50021797

http://stackoverflow.com/a/76863166
answers question: http://stackoverflow.com/q/50068856
type: Answer
has body: So far this is the solution that worked for me Which will give you URL for image for the first question and first option looking like like this /static/images/question1-0.png Why static: as of 2023 images are stored in /static/images/ subfield.id - so far this is the only one that worked. I've tried with subfield.label and it got me something like this: as URL: /static/%3Clabel%20for=%22question1-0%22%3EOften-Q1%3C/label%3E subfield.value gave me /static/.png but subfield.id seems to work, as is unique for each subfield, and so far you don't need to assign it, it's auto assigned by flask. Extraction of the code that may interest you: app.py from flask import Flask, render_template, request, redirect, url_for from flask_wtf import FlaskForm from wtforms import RadioField, SubmitField class SurveyForm(FlaskForm): # example = RadioField('Label', choices=[('value','subfield.label'),('value','subfield.label')]) question1 = RadioField('Question 1', choices=[('Often-A1', 'Often-Q1'), ('Sometimes-A1', 'Sometimes-Q1'), ('Never-A1', 'Never-Q1')]) survey.html {{ form.csrf_token }} {{ form.question1.label }}: {% for subfield in form.question1 %} {{ subfield(class="form-check-input") }} {{ subfield.label(class="form-check-label") }} {% endfor %} {{ form.submit }}
score: 0

http://stackoverflow.com/a/52809848
has comment: http://stackoverflow.com/comment/100162233
has comment: http://stackoverflow.com/comment/93060720
downvote count: 0
score: 13
has body: The easiest way to stream video via IP Camera ! I just edit your example. You must replace your IP and add /video on your link. And go ahead with your project import cv2 cap = cv2.VideoCapture('http://192.168.18.37:8090/video') while(True): ret, frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): cv2.destroyAllWindows() break
has comment: http://stackoverflow.com/comment/93229241
type: Answer
answers question: http://stackoverflow.com/q/49978705
upvote count: 13

http://stackoverflow.com/comment/86866121
type: Comment
type: QuestionComment
has text: Hi Peter, I believe so. The string will be identical other than the dynamic name field. Some strings won't have any dynamic fields and won't require any additional work.
comment on: http://stackoverflow.com/q/49924922
score: 0

http://stackoverflow.com/comment/87129039
has text: @jpmc26: Thanks for replying. I agree it is not the best way. But I am just trying my options out. If it works out, I will improve the return statements. This is not going to production environment for now. Thanks again!
comment on: http://stackoverflow.com/q/50040232
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/49920357
has answer: http://stackoverflow.com/a/49920649
has body: Fairly new to pandas so I'm struggling with this. I have a larger DataFrame with records indexed by a MultiIndex containing a DatetimeIndex, and a smaller DataFrame indexed with start and end dates, both of DatetimeIndex also. Here's what they look like: Larger DataFrame: Data PatId EntryDate Id 725 2005-01-03 1422 X 2005-01-04 1563 X 2005-01-05 1355 X 2005-01-06 118 X 2005-01-09 1400 X And the smaller one containing the date ranges: PatId EntryDate ExitDate 2005-01-15 2005-04-15 22407 2005-01-30 2005-04-30 95938 2005-02-07 2005-05-07 116812 2005-02-18 2005-05-18 12163 2005-02-21 2005-05-21 22908 I'd like an elegant and efficient way to filter the larger DataFrame to only include those records that fall within the date ranges defined in the smaller DataFrame.
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has title: Filter a larger DataFrame using date ranges from a smaller one
accepted answer: http://stackoverflow.com/a/49920649
tagged with: pandas
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49920499
possible better answer: http://stackoverflow.com/a/49920499
upvote count: 2

http://stackoverflow.com/comment/87974851
comment on: http://stackoverflow.com/q/49953620
has text: were you able to find any solution? I am facing same issue at the moment
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86952957
has text: Actually, looking at https://archive.ics.uci.edu/ml/machine-learning-databases/00327/Training%20Dataset.arff I see that they seem to be encoded as `(-1, 0, 1). So it looks like you might have to generate that encoding yourself with various tests (e.g. testing if the netloc is an ip or not). Unless the original authors have code to achieve that you can use. It also looks like they examine the behaviour of following the url as well as the url itself.
comment on: http://stackoverflow.com/a/49967449
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87123092
comment on: http://stackoverflow.com/a/50053152
type: Comment
score: 0
type: AnswerComment
has text: How so, like this? Still trying to fully understand the syntax sorry. -------return recursionNum(int(compGuess /2+1, magicNum)) @Christian.M

http://stackoverflow.com/comment/87060139
type: Comment
comment on: http://stackoverflow.com/q/50022098
type: QuestionComment
has text: In python we use `lowercase_with_underscores` for variables and `CapitalCase` for types. `Entity` should be `entity`, etc.. That threw me for a second.
score: 0

http://stackoverflow.com/comment/87153190
has text: Yeah i cant because i dont have enough rep it's not because i didnt know how thanks tho.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50068174

http://stackoverflow.com/comment/86870323
has text: Why aren't you using the `csv` module to write the output?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49927149

http://stackoverflow.com/comment/86932872
has text: Do you call main() anywhere?
score: 7
type: Comment
comment on: http://stackoverflow.com/q/49958308
type: QuestionComment

http://stackoverflow.com/comment/87040620
type: QuestionComment
has text: i found out my problem in my CLASS program i have my set's and get's as local.. all i had to do was backspace the def_set and def_get methods... thanks all.
score: 0
comment on: http://stackoverflow.com/q/49968873
type: Comment

http://stackoverflow.com/comment/87088070
comment on: http://stackoverflow.com/q/50035895
score: 0
type: Comment
type: QuestionComment
has text: find the intersection area between two rectangles and if it's bigger than a certain threshold then ignore any one of them maybe smaller one

http://stackoverflow.com/comment/86995118
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49980380
has text: You should edit your question to include a description of what a Gabriel graph is.
score: 0

http://stackoverflow.com/comment/86905694
score: 1
type: Comment
has text: You can hack around `pivot` @COLDSPEED @Mihai Alexandru-Ionut
comment on: http://stackoverflow.com/a/49944681
type: AnswerComment

http://stackoverflow.com/a/49959444
has comment: http://stackoverflow.com/comment/86935226
has comment: http://stackoverflow.com/comment/86935960
has comment: http://stackoverflow.com/comment/86935995
type: Answer
has body: Here, the ~ means $HOME (read here): which is why you end up with: /Users//Users/usernamehere/Desktop/Machine Learning/Lesson 5/ratings.csv' which is not a valid path.
answers question: http://stackoverflow.com/q/49959335
has comment: http://stackoverflow.com/comment/86935269
score: 0
has comment: http://stackoverflow.com/comment/86935252

http://stackoverflow.com/comment/86992908
has text: `os.listdir(dir_loc)` will give you the all the file NAMES. It does not give you the actual files to manipulate, read and write only their name. If you want to store the names you already have them in `list_of_dir` iterate through and write them to a csv or whatever your second choice is. @TheProfiler Please read your question, I'm sure you can't even understand it let alone others. Please make sure that you're getting the point across.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49988186

http://stackoverflow.com/comment/86906159
comment on: http://stackoverflow.com/a/49944852
score: 0
type: Comment
type: AnswerComment
has text: It's not about `self.x = x`, but the possible `if` in `compute`.

http://stackoverflow.com/q/49969006
tagged with: deep-learning
has answer: http://stackoverflow.com/a/59854096
has comment: http://stackoverflow.com/comment/87027005
has answer: http://stackoverflow.com/a/73718048
has answer: http://stackoverflow.com/a/50005651
accepted answer: http://stackoverflow.com/a/50005651
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/70522734
downvote count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/87027721
upvote count: 18
has title: save and load keras.callbacks.History
score: 18
tagged with: python
has answer: http://stackoverflow.com/a/61079810
possible better answer: http://stackoverflow.com/a/61079810
tagged with: keras
has comment: http://stackoverflow.com/comment/86955391
tagged with: generator
has body: I'm training a deep neural net using Keras and looking for a way to save and later load the history object which is of keras.callbacks.History type. Here's the setup: history_model_1 = model_1.fit_generator(train_generator, steps_per_epoch=100, epochs=20, validation_data=validation_generator, validation_steps=50) history_model_1 is the variable I want to be saved and loaded during another Python session.
type: AnsweredQuestion

http://stackoverflow.com/q/50010268
has comment: http://stackoverflow.com/comment/87038417
has title: Python import statement only recognizes packages from certain directories?
has comment: http://stackoverflow.com/comment/87038502
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87037395
has body: This is one of the weirder issues I've come across and I can't figure out what is causing it. I have a from x import x statement and it only works in certain file directories. for example, from my userroot directory C:\Users\admin&gt;where python C:\scoop\shims\python.exe C:\Users\admin&gt;python Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AM D64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from influxdb import InfluxDBClient &gt;&gt;&gt; ^Z I can import the package just fine - however when I go to the desktop (which is still apart of my user directory) C:\Users\admin&gt;cd Desktop C:\Users\admin\Desktop&gt;where python C:\scoop\shims\python.exe C:\Users\admin\Desktop&gt;python Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AM D64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from influxdb import InfluxDBClient Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\scoop\apps\python27\current\lib\site-packages\influxdb\__init__.py", line 9, in &lt;module&gt; from .client import InfluxDBClient File "C:\scoop\apps\python27\current\lib\site-packages\influxdb\client.py", li ne 14, in &lt;module&gt; import requests File "C:\scoop\apps\python27\current\lib\site-packages\requests\__init__.py", line 43, in &lt;module&gt; import urllib3 File "C:\scoop\apps\python27\current\lib\site-packages\urllib3\__init__.py", l ine 8, in &lt;module&gt; from .connectionpool import ( File "C:\scoop\apps\python27\current\lib\site-packages\urllib3\connectionpool. py", line 3, in &lt;module&gt; import logging File "logging.py", line 4, in &lt;module&gt; from influxdb import InfluxDBClient ImportError: cannot import name InfluxDBClient &gt;&gt;&gt; ^Z So going into my desktop directory, though still using the same python.exe, will not allow my to import the same package. What makes this more bizar…
answer count: 1
has answer: http://stackoverflow.com/a/75068258
has comment: http://stackoverflow.com/comment/87037307
type: Question
tagged with: python-3.x
tagged with: python-import
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49941646
downvote count: 1
has answer: http://stackoverflow.com/a/49941721
possible better answer: http://stackoverflow.com/a/49941721
has answer: http://stackoverflow.com/a/49941763
favorite count: 0
has title: Python Counter() function to count words in documents with more then one occurrence
type: AnsweredQuestion
score: 3
answer count: 3
tagged with: python-collections
tagged with: words
has comment: http://stackoverflow.com/comment/86899405
tagged with: python
upvote count: 4
has body: I am working on an NLP (Natural Language Processing) project where I used the Python Counter() function from collections library. I am getting the results in the following form: OUTPUT: Counter({'due': 23, 'support': 20, 'ATM': 16, 'come': 12, 'case': 11, 'Sallu': 10, 'tough,': 9, 'team': 8, 'evident': , 'likely': 6, 'rupee': 4, 'depreciated': 2, 'senior': 1, 'neutral': 1, 'told': 1, 'tour\n\nRussia’s': 1, 'Vladimir': 1, 'indeed,': 1, 'welcome,”': 1, 'player': 1, 'added': 1, 'Games,': 1, 'Russia': 1, 'arrest': 1, 'system.\nBut': 1, 'rate': 1, 'Tuesday': 1, 'February,': 1, 'idea': 1, 'ban': 1, 'data': 1, 'consecutive': 1, 'interbank': 1, 'man,': 1, 'involved': 1, 'aggressive': 1, 'took': 1, 'sure': 1, 'market': 1, 'custody': 1, 'gang.\nWithholding': 1, 'cricketer': 1}) The problem is, I want to extract the words having count more than 1. In other words, I am trying to get only those words whose count is greater than 1 or 2. I want to use the output to make a vocabulary list after reducing the words with low frequency. PS: I have more than 100 documents to test my data with almost 2000 distinct words. PPS: I have tried everything to get the results but unable to do so. I only need a logic and will be able to implement.
accepted answer: http://stackoverflow.com/a/49941763
tagged with: nlp
has answer: http://stackoverflow.com/a/78265620
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86899208

http://stackoverflow.com/comment/87021859
type: QuestionComment
has text: Yes, that's it. With a DSL you reach a greater level of freedom/flexibility, so you can generate valid Python code with as many information as you wish (things to help you with debugging etc) from an especialized language (you can make the syntax and the semantics of this DSL to be as rich for your usecase as you need it to be!). You'll have a lot more work (you have to create a parser and emit Python code from the generated AST) but I think it's worth it in your case. Long story short: Make a language to express the specific problem domain you're working on. Good luck!
type: Comment
comment on: http://stackoverflow.com/q/49941484
score: 1

http://stackoverflow.com/comment/87039678
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50011572
score: 0
has text: @merlin2011 3847 kb ; zwer I have used 2 files, one for reading, another for the writing

http://stackoverflow.com/comment/86932904
type: QuestionComment
comment on: http://stackoverflow.com/q/49958255
has text: A good question shows *exactly what error you get*, and ideally lets someone else see the problem for themselves and test if their proposed fix works, as described in the [mcve] definition. It seems unlikely that your classes are really on the default CLASSPATH on the remote machine in question.
score: 0
type: Comment

http://stackoverflow.com/q/49952373
score: 2
answer count: 1
has answer: http://stackoverflow.com/a/49952514
has body: I would like to be able to get info about what types will be created during SQLAlchemy's create_all(). Yes, they can be printed if I set up echo-ing of generated SQL, but how can i print it without actually hitting database? For example, I have a model: class MyModel(Base): id = Column(Integer, primary_key=True) indexed_field = Column(String(50)) enum_field = Column(Enum(MyEnum)) __table_args__ = ( Index("my_ix", indexed_field), ) where MyEnum is: class MyEnum(enum.Enum): A = 0 B = 1 I can get CREATE TABLE statement and all CREATE INDEX statements like this: from sqlalchemy.schema import CreateTable, CreateIndex print(str(CreateTable(MyModel.__table__).compile(postgres_engine))) for idx in MyModel.__table__.indexes: print(str(CreateIndex(idx)).compile(postgres_engine)) Result will be something like that: CREATE TABLE my_model ( id SERIAL NOT NULL, indexed_field VARCHAR(50), enum_field myenum, PRIMARY KEY (id) ) CREATE INDEX my_ix ON my_model (indexed_field) Notice the line enum_field myenum. How can I get generated SQL for CREATE TYPE myenum... statement?
tagged with: sqlalchemy
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has title: SQLAlchemy + Postgres (print created types, e.g. enum types)
downvote count: 0
tagged with: python
tagged with: postgresql

http://stackoverflow.com/comment/87127118
type: QuestionComment
comment on: http://stackoverflow.com/q/50055307
score: 0
has text: can you be please more specific on what you are trying to achieve
type: Comment

http://stackoverflow.com/q/49926279
favorite count: 0
type: Question
has title: Pandas GroupBy on column names
has answer: http://stackoverflow.com/a/56574082
has answer: http://stackoverflow.com/a/49926381
tagged with: python
type: AnsweredQuestion
score: 3
answer count: 3
has answer: http://stackoverflow.com/a/49926321
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/49926321
tagged with: pandas
upvote count: 3
possible better answer: http://stackoverflow.com/a/49926381
downvote count: 0
has body: I have a dataframe, we can proxy by df = pd.DataFrame({'a':[1,0,0], 'b':[0,1,0], 'c':[1,0,0], 'd':[2,3,4]}) and a category series category = pd.Series(['A', 'B', 'B', 'A'], ['a', 'b', 'c', 'd']) I'd like to get a sum of df's columns grouped into the categories 'A', 'B'. Maybe something like: result = df.groupby(??, axis=1).sum() returning result = pd.DataFrame({'A':[3,3,4], 'B':[1,1,0]})

http://stackoverflow.com/comment/86857857
type: Comment
has text: I cannot change the header content as the post request is uneditable.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49920557

http://stackoverflow.com/comment/86911717
type: QuestionComment
has text: I believe the best route is to go with regular expressions and grab the first 5 results, if I am understanding correctly.
score: 0
comment on: http://stackoverflow.com/q/49947416
type: Comment

http://stackoverflow.com/q/49971340
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49971448
possible better answer: http://stackoverflow.com/a/49971351
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49971351
upvote count: 2
has answer: http://stackoverflow.com/a/49971395
has title: Python: short syntax for accessing multiple properties
tagged with: python
accepted answer: http://stackoverflow.com/a/49971448
has comment: http://stackoverflow.com/comment/86958812
has comment: http://stackoverflow.com/comment/86958619
has comment: http://stackoverflow.com/comment/87261736
type: AnsweredQuestion
answer count: 3
tagged with: syntax
has comment: http://stackoverflow.com/comment/86958610
score: 1
has body: I have a Python object with a lot of properties (say, twenty). I want to put about half of them in a tuple. I'll write: # Sample property names myTuple = (myObj['one'], myObj['five'], myObj['six'], myObj['seven'], myObj['nine'], myObj['ten'], myObj['eleven'], myObj['fifteen'], myObj['twenty']) Problem is, I have to repeat the name of the source object numerous times. Is there a more terse syntax? I would love something similar to this: # Sample property names myTuple = myObj[('one', 'five', 'six', 'seven', 'nine', 'ten', 'eleven', 'fifteen', 'twenty')]
has comment: http://stackoverflow.com/comment/86958718

http://stackoverflow.com/a/50023433
answers question: http://stackoverflow.com/q/50018315
score: 0
has body: I did found a solution. python 3.6 has changed something. I did create directory as views and added scheduler_view.py and from .views import scheduler_view as view app_name = 'scheduler' urlpatterns = [ re_path(r'^service/(?P&lt;status&gt;\w+)', view.SchedulerView.as_view(), name='schedule-service') ] it doesn't occur error and runserver as well. plus I did error occur again in another file. it's for older python. scheduler_view.py from scheduler import Scheduler -&gt; from scheduler.scheduler import Scheduler I did change it. http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html I wish it's helpful.
type: Answer

http://stackoverflow.com/a/50048728
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50048595
has body: You could set the values of rtol and atol in the set_integrator call, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html. The default values provide a medium accuracy that is good enough for graphics, but may not be enough for other purposes.
type: Answer

http://stackoverflow.com/a/49988401
has comment: http://stackoverflow.com/comment/86993742
has comment: http://stackoverflow.com/comment/86993987
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49988186
type: AcceptedAnswer
has body: We list the current directory and print the contents you can do some other action with the read file, i.e. manipulate import os dir_loc = os.getcwd() list_of_dir = os.listdir(dir_loc) for file in list_of_dir: with open(file, 'rb') as f: temp_file = f.read() # Do somethin with the file, it's currently stored in a variable print(temp_file) # I used print With Pymongo: import os import pymongo import gridfs dir_loc = os.getcwd() list_of_dir = os.listdir(dir_loc) # Pymongo connection = pymongo.Connection("localhost", 27017) db = connection.yourdatabase # Create a GridFS object using a reference to the database in which to # store the file(s). gridFs = gridfs.GridFS(db) for file in list_of_dir: with open(file, 'rb') as f: file_id = gridFs.put(f.read(), filename="my_file_name")
answers question: http://stackoverflow.com/q/49988186
has comment: http://stackoverflow.com/comment/86993821
type: Answer

http://stackoverflow.com/q/50001328
downvote count: 0
has comment: http://stackoverflow.com/comment/87019895
answer count: 1
has comment: http://stackoverflow.com/comment/87020186
has comment: http://stackoverflow.com/comment/87019520
tagged with: python
has comment: http://stackoverflow.com/comment/87019709
tagged with: string
has comment: http://stackoverflow.com/comment/87020123
favorite count: 0
has comment: http://stackoverflow.com/comment/87019785
has comment: http://stackoverflow.com/comment/87019810
has comment: http://stackoverflow.com/comment/87019545
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87020737
upvote count: 8
has comment: http://stackoverflow.com/comment/87019547
has title: Get regex group with fuzziness
has comment: http://stackoverflow.com/comment/87020315
tagged with: regex
has comment: http://stackoverflow.com/comment/87019860
has body: I have a very big list of words (around 200k): ["cat", "the dog", "elephant", "the angry tiger"] I created this regex, with fuzziness : regex = "(cat){e&lt;3}|(the dog){e&lt;3}|(elephant){e&lt;3}|(the angry tiger){e&lt;3}" I have input sentences : sentence1 = "The doog is running in the field" sentence2 = "The elephent and the kat" ... What I want to get is this : res1 = ["the dog"] res2 = ["elephant", "cat"] I tried this for example: re.findall(regex, sentence2, flags=re.IGNORECASE|re.UNICODE) But this outputs me : ["elephent", "kat"] Any idea how to get the right answer with corrected words ? What I want is to get the regex capturing group for each match but I struggle to do so. Maybe I'm not doing this right and maybe the regex way is not the good one but the if item in list with a for loop is way too long to execute.
score: 8
has answer: http://stackoverflow.com/a/50001999
type: Question
has comment: http://stackoverflow.com/comment/87019577
accepted answer: http://stackoverflow.com/a/50001999
has comment: http://stackoverflow.com/comment/87019420
has comment: http://stackoverflow.com/comment/87019498
tagged with: fuzzy-search

http://stackoverflow.com/q/50066194
has comment: http://stackoverflow.com/comment/87149495
tagged with: python
has title: Why is this script so slow in Python?
tagged with: matlab
tagged with: optimization
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/87149588
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50067990
accepted answer: http://stackoverflow.com/a/50067990
has comment: http://stackoverflow.com/comment/87149858
has comment: http://stackoverflow.com/comment/87149350
has comment: http://stackoverflow.com/comment/87149589
has answer: http://stackoverflow.com/a/50066702
possible better answer: http://stackoverflow.com/a/50066702
downvote count: 0
has body: I have written a script that trains a 1D Kohonen network in MATLAB and it works as a charm. I then tried to translate it to Python 2.7, a language in which I'm pretty new, and the script is taking forever to run. I'll explain what I'm doing to see if someone here can throw some light on the matter. I have a given dataset in the matrix y and I want to train different SOMs with it. The SOM is one-dimensional (a line), and its number of neurons varies. I train a SOM of size N=2 at first, and N=NMax at last, giving a total of NMax-2+1 SOMs. For each SOM, I want to store the weights once the training is over before moving on to the next SOM. In MATLAB, for NMax = 5 and iterMax = 50, it takes 9.74 seconds. In Python, 54.04 seconds. This difference is huge, and the actual datasets, number of SOMs and number of iterations is even greater, so the Python code takes forever to end. My current code is the following: import numpy as np import time y = np.random.rand(2500,3) # Create random dataset to test def A(d,s): # Neighborhood function return np.exp(-d**2 / (2*s**2)) sigma_0 = float(5) # Initial standard deviation for A eta_0 = float(1) # Initial learning rate iterMax = 250 # Maximum number of iterations NMax = 10 # Maximum number of neurons w = range(NMax - 1) # Initialize the size of the weight matrix (it will store NMax-2+1 sets of weights, each of varying size depending on the value of N) #%% KOHONEN 1D t = time.time() # Start time for N in np.arange(2,NMax + 1): # Size of the network w[N - 2] = np.random.uniform(0,1,(N,np.size(y,axis=1))) - 0.5 # Initial weights iterCount = 1; # Iteration counter while iterCount &lt; iterMax: # Mix the datapoints to choose them in random order mixInputs = y[np.random.permutation(np.size(y,axis = 0)),:] # Decrease the value of the variance and the learning rate sigma = sigma_0 - (sigma_0/(iterMax + 1)) * iterCount eta = eta_0 - (eta_0/(iterMax + 1)) * iterCount for kk in range(np.size(mixInputs,axis = 0)): # Picking one datapoint at a t…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87149418
has comment: http://stackoverflow.com/comment/87149385
has comment: http://stackoverflow.com/comment/87150890
has comment: http://stackoverflow.com/comment/87149785

http://stackoverflow.com/comment/87038212
score: 0
type: AnswerComment
has text: Ahhh didn't even think to reload the page, does scrapy have a specific method for reloading pages? I have been doing some digging as to why it only shows up sometimes and have come up empty so far.
type: Comment
comment on: http://stackoverflow.com/a/49932877

http://stackoverflow.com/q/49984510
type: Question
tagged with: python-3.x
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Pandas - plot cumulative proportion of column
answer count: 1
accepted answer: http://stackoverflow.com/a/49985059
has body: I have a dataframe column that is either 0, 1, or 2. I want to plot the relative proportions over time in a stacked bar chart. E.g. if the values are: 0 1 2 2 0 0 1 Then the 0 - % value would be (rounded to 1.d.p): 100 50 33 25 40 50 42 And the 1 - % value would be (again rounded to 1.d.p): 0 50 33 25 20 33 I would want the 0, 1 and 2 proportions to all be stacked in a single bar, showing how the relative proportion changes over time.
has answer: http://stackoverflow.com/a/49985059

http://stackoverflow.com/q/49991840
type: AnsweredQuestion
score: 2
tagged with: product
accepted answer: http://stackoverflow.com/a/49992789
has answer: http://stackoverflow.com/a/49992789
tagged with: python
possible better answer: http://stackoverflow.com/a/49991994
tagged with: dictionary
tagged with: loops
linked to: http://stackoverflow.com/q/6967632
has body: I'm not sure how verbose I should go so please ask for elaboration if this is too terse. Is there a way to pack the for a,b,c in product(d['a'],d['b'],d['c']): in some syntactical sugar so I would only need to type mute variables a,b,c only once for this loop itself? Something like this may be? my_for_loop('a','b','c'): API_Call1(a) API_Call2(b,c) instead of for a,b,c in product(d['a'],d['b'],d['c']): API_Call1(a) API_Call2(b,c) How could my_for_loop look like? I am a bit lost at how to approach this conceptually. More detail: I have an API that requires calling it for each cell of a cartesian product of some lists. I am using the product function to avoid nested loops. Let's say we have a list1 and a list2 it can be done in a following way from itertools import product for a,b in product(list1,list2): API_Call(a,b) I have created a dictionary_of_lists={'a':list1,'b':list2,'c':list3...} to be able to write it like this for a,b in product(dictionary_of_lists['a'],dictionary_of_lists['b']): API_Call(a,b) for c,b in product(dictionary_of_lists['c'],dictionary_of_lists['b']): API_Call(c,b) for e,f,g,h in product(dictionary_of_lists['e'],dictionary_of_lists['f'],dictionary_of_lists['g'],dictionary_of_lists['h'],): API_Call1(e,f,g,h) API_Call2(e,h) ... So basically the variables that the loop creates are used in that API calls and they are mute otherwise, their name doesn't matter. There are many of these calls and there is some convoluted logic around them. So I would like to keep the loop itself simple and should I need to change the variables I won't have to to change them at three places for each such loop. my_for_loop('a','b'): API_Call(a,b) my_for_loop('b','c'): API_Call(c,b) my_for_loop('e','f','g','h'): API_Call1(e,f,g,h) API_Call2(e,h) ... ADDITION: I have simplified a few things but was taken by surprise where exactly ambiguity was lurking :-) Thanks for all the answers so far! It's a good suggestion to have the dproduct wrapper. I have one indeed, just did not …
has comment: http://stackoverflow.com/comment/87010854
tagged with: syntactic-sugar
favorite count: 0
type: Question
answer count: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87000501
has answer: http://stackoverflow.com/a/49991994
has title: A pythonic way of packing loops into a function to mute variables?

http://stackoverflow.com/q/49936414
has answer: http://stackoverflow.com/a/49936615
has title: Remove file in the ascending order
has comment: http://stackoverflow.com/comment/86888495
has body: In a folder containing , say 5 zip files say we have the following files 123_456_2018_01_01.zip 123_456_2018_01_02.zip 789_456_2018_11_02.zip 789_456_2018_11_12.zip 889_456_2018_11_02.zip I want to remove the oldest file, i.e 123_456_2018_01_01.zip then 789_456_2018_11_02.zip how would I accomplish this in Python ? Any help would be appreciated
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/168409
has answer: http://stackoverflow.com/a/49936550
has comment: http://stackoverflow.com/comment/86893444
answer count: 2
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1

http://stackoverflow.com/comment/86984857
comment on: http://stackoverflow.com/a/49976718
type: Comment
score: 0
type: AnswerComment
has text: Yep it works! Thank you. Just want to test, what approach is faster!

http://stackoverflow.com/comment/87032647
has text: The error is pretty straightforward. The format you passed in (the second argument) doesn't work for the string you are parsing (the first argument). Why did you expect that format string to work? Please share your research. Did you read the documentation on how `datetime.strptime()` works?
comment on: http://stackoverflow.com/q/50008025
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50024296
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87064670
tagged with: multithreading
favorite count: 0
has title: Closing thread is Mandatory?
downvote count: 0
has comment: http://stackoverflow.com/comment/87064868
score: 1
tagged with: python
type: Question
has body: I am using multiple threads in my python application and I am not closing any thread. If I run my code for multiple times, once in a while I am getting core dump issue. Is it necessary to close every thread I used in my code? Is it causing the core dump issue?
has comment: http://stackoverflow.com/comment/87064639
answer count: 0

http://stackoverflow.com/q/49931352
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/49931462
has answer: http://stackoverflow.com/a/49931443
type: Question
has comment: http://stackoverflow.com/comment/86878622
has answer: http://stackoverflow.com/a/49931428
score: 0
has answer: http://stackoverflow.com/a/49931410
has answer: http://stackoverflow.com/a/72574871
type: UnansweredQuestion
has body: I'm having trouble converting a string to data format. I'm using the time module to convert a string to the YYYY-MM-DD format. The code below is what I've tried but I get the following error. sre_constants.error: redefinition of group name 'Y' as group 5; was group 3 Here is the code import time review_date = "April 18, 2018" review_date = time.strptime(review_date, '%m %d %Y %I:%Y%m%d')
answer count: 5
has title: Converting string in python to date format

http://stackoverflow.com/q/49940115
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/86895909
score: 1
has comment: http://stackoverflow.com/comment/86896192
downvote count: 0
has comment: http://stackoverflow.com/comment/86896194
possible better answer: http://stackoverflow.com/a/49940244
accepted answer: http://stackoverflow.com/a/49940161
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49940161
has title: pandas apply lambda on column values and select those whose set size is > 1
has body: I am trying to select the rows in a df, that within each row, the set size of a column value is > 1; df = pd.DataFrame({'col': [1, 2, 3], 'a': [41, 4, 5], 'b': [3, 13, 6]}) df['concat'] = (df['a'].astype(str) + df['b'].astype(str)) df.groupby('concat')['col'].apply(set).to_dict() but this only applies set to each column ('col') value. python prevent me from df.groupby('concat')['col'].apply(lambda x: set(x) if len(set(x)) &gt; 1).to_dict()
upvote count: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86896149
has comment: http://stackoverflow.com/comment/86897215
has comment: http://stackoverflow.com/comment/86895941
has comment: http://stackoverflow.com/comment/86896049
has answer: http://stackoverflow.com/a/49940261
has comment: http://stackoverflow.com/comment/86896073
has answer: http://stackoverflow.com/a/49940244

http://stackoverflow.com/q/49959656
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49959723
has comment: http://stackoverflow.com/comment/86935756
upvote count: 10
tagged with: python-typing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86935730
tagged with: mypy
has comment: http://stackoverflow.com/comment/86936479
type: UnansweredQuestion
has title: Typing __exit__ in 3.5 fails on runtime, but typechecks
tagged with: contextmanager
linked to: http://stackoverflow.com/q/44651115
has comment: http://stackoverflow.com/comment/86936522
downvote count: 0
has body: What is the proper type signature for __exit__? I have the following: from types import TracebackType from typing import Optional, Type class Foo: def __enter__(self) -> 'Foo': return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> bool: return False On recent mypy (0.560) this typechecks with --strict (and I have moderate faith in this signature, because I stole it from the innards of the typeshed). When this script is run with python 3.6, as expected nothing happens. But when run with 3.5.2, we get an exception: Traceback (most recent call last): File "/home/student/mypy_test/test.py", line 4, in <module> class Foo: #(ContextManager['Foo']): File "/home/student/mypy_test/test.py", line 8, in Foo def __exit__(self, exc_type: Optional[Type[BaseException]], File "/usr/lib/python3.5/typing.py", line 649, in __getitem__ return Union[arg, type(None)] File "/usr/lib/python3.5/typing.py", line 552, in __getitem__ dict(self.__dict__), parameters, _root=True) File "/usr/lib/python3.5/typing.py", line 512, in __new__ for t2 in all_params - {t1} if not isinstance(t2, TypeVar)): File "/usr/lib/python3.5/typing.py", line 512, in <genexpr> for t2 in all_params - {t1} if not isinstance(t2, TypeVar)): File "/usr/lib/python3.5/typing.py", line 1077, in __subclasscheck__ if super().__subclasscheck__(cls): File "/home/student/.local/share/virtualenvs/sf_cs328-crowdsourced-QAuuIxFA/lib/python3.5/abc.py", line 225, in __subclasscheck__ for scls in cls.__subclasses__(): TypeError: descriptor '__subclasses__' of 'type' object needs an argument If you remove parameters until the exception disappears, we find that the problem type is the first: exc_type: Optional[Type[BaseException]]. Note: To get it to complain if the type signature does not match (when run with mypy), you need to change class Foo: to class Foo(ContextManager['Foo']). I didn't do this in the snippet, because typing in Python 3.5.2 …
has comment: http://stackoverflow.com/comment/86936592
has comment: http://stackoverflow.com/comment/86936612
has comment: http://stackoverflow.com/comment/86936569
score: 10

http://stackoverflow.com/comment/86926593
type: AnswerComment
score: 0
type: Comment
has text: Sorry I did have the wrong iteration of 1000 in the Python code, it should be 2. I updated it above -- with updated DerivedBytes. I found the PowerShell example for using PasswordDeriveBytes so that is why the function is being passed as an argument.
comment on: http://stackoverflow.com/a/49933258

http://stackoverflow.com/q/49983047
tagged with: python
has comment: http://stackoverflow.com/comment/86982450
type: Question
has title: Flask: api call downloads excel sheet, need to store in folder
has answer: http://stackoverflow.com/a/49983415
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86983338
answer count: 1
downvote count: 0
tagged with: file
upvote count: 1
tagged with: python-requests
favorite count: 0
has body: The following url downloads an excel spreadsheet http://www.bocsar.nsw.gov.au/Documents/RCS-Annual/bluemountainslga.xlsx via flask code I want to call that url, and save the spreadsheet to a folder So far I have r = requests.get('http://www.bocsar.nsw.gov.au/Documents/RCS-Annual/bluemountainslga.xlsx') But need help moving the spread sheet to a downloads folder inside the project. The folder structure is. App +static +templates main.py +downloads |__ move file here
score: 1

odo
tag name: odo
type: Tag
tags question: http://stackoverflow.com/q/49985657

http://stackoverflow.com/q/49959119
has comment: http://stackoverflow.com/comment/86934657
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
has title: Applying a dictionary to a string sentence
possible better answer: http://stackoverflow.com/a/49959167
has body: Is there a fast way to apply a dictionary defined for a given number of letters to a string formatted word that contains more than one of them? e.g. def decode(code): key = {"a":1,"b":2,"c":3,"d":4,"e":5} return key[code] print decode("eddcab") and get back from this 544312 I am aware it doesn't work this simply but is there like some trick or easy way to go around this or I need to define the operations separately from the indices [1:2] and then from [2:3] until I get to the end of the string? I am using python 2.7 I appreciate any hints or advice related to this.
has answer: http://stackoverflow.com/a/49959167
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49959155
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49959155
tagged with: python-2.7
score: 0
answer count: 2

http://stackoverflow.com/comment/87029541
comment on: http://stackoverflow.com/q/50004158
type: Comment
type: QuestionComment
has text: When I perform the computations in the way you describe, I get `v_tmp[1,1] = 5e-4`, and not `0.941` like you indicated above in `v^1`. Could you verify that the value of the 2nd row, 2nd column of `v^1` is correct? Otherwise there is a flaw in your explanation, or in my interpretation of that...
score: 0

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/50034214

http://stackoverflow.com/q/49970594
has answer: http://stackoverflow.com/a/49970752
answer count: 1
downvote count: 0
upvote count: 1
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
type: Question
has body: I'm new to Tensorflow. I worked in Caffe previously. I'm trying to implement http://cvlab.cse.msu.edu/pdfs/Tai_Yang_Liu_CVPR2017.pdf in Tensorflow. I'm having trouble with variables in Tensorflow, despite having them initialized. I tried using tf.get_variable instead of tf.Variable, but this didn't work. And setting initializer=tf.contrib.layers.xavier_initializer() did nothing. My code: import tensorflow as tf import sys, os import numpy as np global xseed def get_model(inp, train): #create architecture #db input, 128 batch size with tf.name_scope('input'): inl = tf.reshape(inp, [-1, 31, 31, 1]) with tf.name_scope('batchnorm_scale_relu'): #batchnorm,scale,relu normed = tf.contrib.layers.batch_norm(inl, is_training=train) alpha = tf.Variable(tf.truncated_normal((1,), stddev=0.1), trainable=True, name="alpha") beta = tf.Variable(tf.truncated_normal((1,), stddev=0.1), trainable=True, name="beta") scaled = alpha * normed + beta relud = tf.nn.relu(scaled, name="relu1") with tf.name_scope('conv1'): #??? padding ??? is correct padded_input = tf.pad(relud, [[0, 0], [1, 1], [1, 1], [0, 0]], "CONSTANT") #weight initializer msra convolved = tf.layers.conv2d(inputs=padded_input, filters=128, kernel_size=(3, 3), strides=(1, 1), padding="VALID", kernel_initializer=tf.contrib.layers.variance_scaling_initializer(seed=xseed)) with tf.name_scope('batchnorm_scale_relu_1a'): #batchnorm,scale,relu normed_1a = tf.contrib.layers.batch_norm(convolved, is_training=train) alpha_1a = tf.Variable(tf.truncated_normal((1,), stddev=0.1), trainable=True, name="alpha_1a") beta_1a = tf.Variable(tf.truncated_normal((1,), stddev=0.1), trainable=True, name="beta_1a") scaled_1a = alpha_1a * normed_1a + beta_1a relud_1a = tf.nn.relu(scaled_1a, name="relu1_1a") with tf.name_scope('conv1_1a'): padded_input_1a = tf.pad(relud_1a, [[0, 0], [1, 1], [1, 1], [0, 0]], "CONSTANT") #weight initializer msra convolved_1a = tf.layers.conv2d(inputs=padded_input_1a, filters=128, kernel_size=(3, 3), strides=(1, 1), padd…
tagged with: python
tagged with: variables
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49970752
tagged with: deep-learning
has title: Tensorflow, uninitialized variables despite running global_variable_initializer
score: 1

http://stackoverflow.com/a/49927073
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86870684
has comment: http://stackoverflow.com/comment/86870779
has comment: http://stackoverflow.com/comment/86871025
accepted answer of: http://stackoverflow.com/q/49926867
type: Answer
answers question: http://stackoverflow.com/q/49926867
has body: I don't know what the values for the columns are but have you tried something like this? patients['new_patient_id'] = patients.apply(lambda x: x['patient_id'] + x['patient_sex'] + x['patient_dob'],axis=1) This should create a new column and you can then use groupby with the new_patient_id

http://stackoverflow.com/comment/86889952
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49936845
has text: `print` will use `stdout` so it will never print (you closed the file). You should copy stdout and restore at the end. But it is really better not to tamper it (like other comments)
score: 0

http://stackoverflow.com/q/49960060
type: Question
has comment: http://stackoverflow.com/comment/86936615
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86937166
has answer: http://stackoverflow.com/a/50712210
has title: "ModuleNotFoundError: No module named 'PyQt5'" after pip install
type: UnansweredQuestion
answer count: 1
tagged with: pyqt5
tagged with: pip
has body: I'm trying to run a python script from the command window, but every time I try to run it I get this error. C:\Users\TJ\Downloads\bovada-hand-history-converter-master\bovada-hand-history-converter-master&gt;python app.py Traceback (most recent call last): File "app.py", line 25, in &lt;module&gt; from gui import * File "C:\Users\TJ\Downloads\bovada-hand-history-converter-master\bovada-hand-history-converter-master\gui.py", line 9, in &lt;module&gt; from PyQt5 import QtCore, QtGui, QtWidgets ModuleNotFoundError: No module named 'PyQt5' I have no idea why I'm getting this, because when I check Python36\Lib\site-packages\, PyQt5 is right there. I installed it using pip from the command window. I did the same thing with pytz and I'm not having any problems with that. If anyone thinks they know what's going on, let me know! Thanks.

http://stackoverflow.com/q/50051988
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/121863261
type: UnansweredQuestion
has title: add actions in the contextual chatbot
tagged with: neural-network
tagged with: python
tagged with: chatbot
answer count: 0
downvote count: 0
has body: I am developing a contextual chatbot (Python, bag of words, tensorflow) based on a tutorial, https://chatbotsmagazine.com/contextual-chat-bots-with-tensorflow-4391749d0077 Here is the JSON file that defines the intent, {"intents": [ {"tag": "greeting", "patterns": ["Hi", "How are you", "Is anyone there?", "Hello", "Good day"], "responses": ["Hello, thanks for visiting", "Good to see you again", "Hi there, how can I help?"], "context_set": "" }, {"tag": "goodbye", "patterns": ["Bye", "See you later", "Goodbye"], "responses": ["See you later, thanks for visiting", "Have a nice day", "Bye! Come back again soon."] }, {"tag": "thanks", "patterns": ["Thanks", "Thank you", "That's helpful"], "responses": ["Happy to help!", "Any time!", "My pleasure"] }, {"tag": "hours", "patterns": ["What hours are you open?", "What are your hours?", "When are you open?" ], "responses": ["We're open every day 9am-9pm", "Our hours are 9am-9pm every day"] }, {"tag": "mopeds", "patterns": ["Which mopeds do you have?", "What kinds of mopeds are there?", "What do you rent?" ], "responses": ["We rent Yamaha, Piaggio and Vespa mopeds", "We have Piaggio, Vespa and Yamaha mopeds"] }, {"tag": "payments", "patterns": ["Do you take credit cards?", "Do you accept Mastercard?", "Are you cash only?" ], "responses": ["We accept VISA, Mastercard and AMEX", "We accept most major credit cards"] }, {"tag": "opentoday", "patterns": ["Are you open today?", "When do you open today?", "What are your hours today?"], "responses": ["We're open every day from 9am-9pm", "Our hours are 9am-9pm every day"] }, {"tag": "rental", "patterns": ["Can we rent a moped?", "I'd like to rent a moped", "How does this work?" ], "responses": ["Are you looking to rent today or later this week?"], "context_set": "rentalday" }, {"tag": "today", "patterns": ["today"], "responses": ["For rentals today please call 1-800-MYMOPED", "Same-day rentals please call 1-800-MYMOPED"], "context_filter": "rentalday" } ] Now I am adding another intent…

http://stackoverflow.com/q/49987780
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
has body: How can I log the file attributes such as file name, file size, modification time in any database table at the time of file uploading also I need to keep track in database table which files have been cancelled and paused while uploading using Resumable.js. How can I implement this at server side. I am using python flask on server side.
tagged with: javascript
tagged with: flask
has comment: http://stackoverflow.com/comment/86992530
has comment: http://stackoverflow.com/comment/87001390
has title: Log the files in database when using resumable.js
score: 0

http://stackoverflow.com/a/49983682
type: Answer
score: -1
has body: If you are looking for a way to execute code from a string (which is not recommended, you might be better off going through the whole process of setup.py to make your library installable) you can use the exec statement as follows exec(mymod) This will parse the string as it would normal Python source and execute it, leaving you with it's side effects (such as defining functions and variables). This will work in both Python 2.7 and 3.x. See the documentation here and here for more details. Alternatively, in Python 2.7 only, execfile does the same thing as exec but for a text file execfile("path/to/my/mod") The documentation explains what it does and doesn't do.
answers question: http://stackoverflow.com/q/49982968
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/86976975
comment on: http://stackoverflow.com/a/49979969
score: 1
type: Comment
has text: @AnnaRG, I expect a `numpy` solution to be fastest. But you should test this with your data.
type: AnswerComment

http://stackoverflow.com/a/49961775
accepted answer of: http://stackoverflow.com/q/49958098
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49958098
score: 0
type: Answer
has body: Can you show us the error message? Otherwise it is difficult to guess where causes the error. But I guess input shape may be different. When you use the chainer built-in function to get dataset, train, test = chainer.datasets.get_mnist() These dataset image shape is (minibatch, channel, height, width). but it seems you are constructing input x as the shape (minibatch, height * width =28*28=784) which is the different shape?? You can also refer some tutorial for chainer, chainer handson deep learning tutorial with chainer MNIST inference code

http://stackoverflow.com/a/49926321
accepted answer of: http://stackoverflow.com/q/49926279
type: Answer
answers question: http://stackoverflow.com/q/49926279
downvote count: 0
type: AcceptedAnswer
has body: Use groupby + sum on the columns (the axis=1 is important here): df.groupby(df.columns.map(category.get), axis=1).sum() A B 0 3 1 1 3 1 2 4 0
score: 5
upvote count: 5

http://stackoverflow.com/a/49921412
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/108332639
type: Answer
has body: Qt widgets are drawn from parent to children. That means that MyWidget paints itself (by calling paintEvent()) before the QPushButton paints itself. One possible solution is to create a widget to draw the rectangle and make it a sibling of QPushButton (i.e child of MyWidget). You can then decide of the rendering order of QPushButton and RectangleWidget by using QWidget::stackUnder(), QWidget::raise() or QWidget::lower().
downvote count: 0
answers question: http://stackoverflow.com/q/49920532

http://stackoverflow.com/comment/118500262
score: 5
has text: The package hasn't been updated since May, 2020, and the specified source repo, https://github.com/dotnet/corefxlab, has been archived.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59369715

http://stackoverflow.com/comment/87145655
type: QuestionComment
comment on: http://stackoverflow.com/q/50064456
has text: Note: `raw_input` is *Python2* specific.
type: Comment
score: 2

http://stackoverflow.com/comment/87133561
type: Comment
has text: Examples are important to understand the question, but a detailed specification of the logic is essential. Your current problem is not Python coding but writing down a specification in English (or whatever) language. IMHO the current question is *unclear* because of that.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50058414

http://stackoverflow.com/comment/87071327
comment on: http://stackoverflow.com/a/50026601
type: Comment
has text: Exactly, batch means N lines, where N is dynamic and will be calculated depending on line sizes.But I assume that it will block receiving new lines, right? The app needs to be pretty highload, so it must serve at least 300 records per second.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86937226
has text: Something else to consider: how bad is it, really, if the generator repeats a number? If you can get away with an occasional repeated number (possibly with some changes in another part of your code), that opens up a bunch more possibilities, and if `num` is really large, the chance that happens might be vanishingly small anyway.
type: QuestionComment
comment on: http://stackoverflow.com/q/49956883
score: 0
type: Comment

http://stackoverflow.com/q/49922992
has title: celery start causes TypeError("unhashable type: 'list'",)
score: 0
has comment: http://stackoverflow.com/comment/86911305
tagged with: flask-socketio
has answer: http://stackoverflow.com/a/54223463
tagged with: python
has body: I am following the documentation for http://flask.pocoo.org/docs/0.12/patterns/celery/ and am getting the following error. $ python ./venv/bin/celery -A app.ctasks worker -c 8 -l INFO [2018-04-19 08:45:03,623: ERROR/MainProcess] Unrecoverable error: TypeError("unhashable type: 'list'",) Traceback (most recent call last): File "/Users/andy.terhune/PycharmProjects/flask_socketio_saml/venv/lib/python3.6/site-packages/kombu/utils/__init__.py", line 323, in __get__ return obj.__dict__[self.__name__] KeyError: 'backend' I have checked make_celery's line and backend and broker are strings with the correct data. celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL']) My celery setup is the following: cinit.py from celery import Celery def make_celery(app): celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) taskbase = celery.Task class ContextTask(taskbase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return taskbase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery __init__.py from flask import Flask, from flask_socketio import SocketIO async_mode = None app = Flask(__name__) app.config.from_object('config') socketio = SocketIO(app, async_mode=async_mode) ... from app import views, socks, saml, helper, cinit celery = cinit.make_celery(app) from app import ctasks I have tried to start celery several different ways to no avail. python ./venv/bin/celery -A app.ctasks worker -c 8 -l INFO causes: Unrecoverable error: TypeError("unhashable type: 'list'",) python ./venv/bin/celery -A app worker -c 8 -l INFO causes: AttributeError: 'Flask' object has no attribute 'user_options' which I found a similar article here: AttributeError: 'Flask' object has no attribute 'user_options' and python ./venv/bin/celery -A app.cinit worker -c 8 -l INFO causes: AttributeError: module 'a…
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25884951
answer count: 1
tagged with: flask
tagged with: celery
type: Question

http://stackoverflow.com/comment/87044873
type: QuestionComment
has text: @ShivamSingh fixed
comment on: http://stackoverflow.com/q/50014265
score: 0
type: Comment

http://stackoverflow.com/q/50005589
has title: Django doesn't send password rest email
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87033124
has comment: http://stackoverflow.com/comment/87027709
tagged with: django
tagged with: python
tagged with: forgot-password
has comment: http://stackoverflow.com/comment/87027899
answer count: 0
score: 0
type: Question
has body: I'm trying to make a password reset form and I added next urls: path('reset-password/', password_reset, name='reset_password'), path('reset-password/done/', password_reset_done, name='password_reset_done'), url(r'^reset-password/confirm/(?P&lt;uidb64&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$', password_reset_confirm, name='password_reset_confirm'), Also I added next lines to my settings.py file: EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'my_gmail_email@gmail.com' SERVER_EMAIL = 'my_gmail_email@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_gmail_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_gmail_password' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I get all forms correctly and when I type in email of a user it shows that email with reset password link was sent but it doesn't.

http://stackoverflow.com/a/63434738
has comment: http://stackoverflow.com/comment/115973835
score: 2
answers question: http://stackoverflow.com/q/49934932
upvote count: 2
downvote count: 0
type: Answer
has body: Although a bit late, but I will try to give a generic and useful answer. @Giacomo Catenazzi's answer is a good one but some part of it is factually incorrect. API requests (or other form of web requests) are served from an already running process. The creation of this 'already running' process is handled by some webserver like gunicorn which on startup creates specified number of processes that are running the code in your web application continuously waiting to serve any incoming request. Needless to say, each of these processes are limited by the GIL to only run one thread at a time. But one process in its lifetime handles more than one (normally many) request. Here it would be better if we could understand the flow of a request. We will take an example of flask but this is applicable to most web frameworks. When a request comes from Nginx, it is handed over to gunicorn which interacts with your web application via wsgi. When the request reaches to the framework, an app context is created and some variables are pushed into the app-context. Then it follows the normal route that mostly people are familiar with: routing, db calls, response creation and so on. The response is then handed back to the gunicorn via wsgi again. At the time of handing over the response, the app context is teared down. So it's the app context, not the process that is created on every new request. Also, I have talked only about the sync worker in gunicorn but it also has an option of async worker which can handle multiple requests in parallel through coroutines. But thats a separate topic. So answering your question: Nginx (Capable of handling multiple requests at a time) Gunicorn creates a pool of n number of processes at the start and also manages the pool in the sense that if a process exits or gets stuck, it kills/recreates ans adds that to the pool. Each process handling 1 request at a time. Read more about gunicorn's design and how it can be used to help you achieve your requirements. …

http://stackoverflow.com/a/50011453
has body: You can use the urllib2 unquote function: import urllib2 print urllib2.unquote("3D%20Printing%20Blueprints%20%5BeBook%5D.pdf") #3D Printing Blueprints.pdf
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50011356
score: 1

http://stackoverflow.com/a/49949880
has comment: http://stackoverflow.com/comment/86923114
has comment: http://stackoverflow.com/comment/86942183
type: Answer
answers question: http://stackoverflow.com/q/49948821
has body: If you want the connecting line to go from left to right then you have to sort your data points in order of increasing x: s = np.argsort(x0) plt.plot(x0[s], y0[s], 'ko-')
score: 0
has comment: http://stackoverflow.com/comment/86924320

http://stackoverflow.com/q/49968526
has comment: http://stackoverflow.com/comment/86953206
score: 0
has title: too many values to unpack with quiver
has comment: http://stackoverflow.com/comment/86952846
answer count: 1
has comment: http://stackoverflow.com/comment/86952863
has body: I am trying to use the quiver function to draw the vector field of a dynamic system. I have 2 lists X and V. I need to build 2 lists UE and VE containing respectively the first and second value returned by f, but I have the following error: too many values to unpack. This is my code. import numpy as np import scipy # donne acces aux librairies scipy, scipy.linalg et scipy.integrate import scipy.linalg import scipy.integrate import matplotlib.pyplot as plt import math %matplotlib inline def f(x,v,t): return v,-(float(g)/l)*np.sin(x) t0=0 x0=1 v0=0 T=20 l=1 g=9.81 UE, VE = np.array([f(x,v,0) for x,v in zip(X,V)]) plt.quiver(X, Y, UE, VE) Any help is much appreciated. Thanks.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86953057
has comment: http://stackoverflow.com/comment/86952913
accepted answer: http://stackoverflow.com/a/49968567
has answer: http://stackoverflow.com/a/49968567
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/53561694
has comment: http://stackoverflow.com/comment/106888094
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/49940813
type: Answer
upvote count: 6
has body: I just encountered the same problem and in my case, it turns out this is a conflict between the python installation in my virtualenv and the site-wide python (Ubuntu). What solves it for me is to run pip in this way, to force usage of the correct python installation (in my vortualenv): python3 -m pip install PACKAGE instead of pip3 install PACKAGE I realised this when I tried to follow some of the answers here that suggest re-installing pip and the error output I got was pointing to an existing site-wide python library path although I had activated my virtualenv. Worth trying before deleting and re-installing stuff.

http://stackoverflow.com/comment/86882767
type: QuestionComment
has text: Precise terminology is important. Particularly in this case, where yours is completely off.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49933481

http://stackoverflow.com/a/50055689
type: Answer
answers question: http://stackoverflow.com/q/50055640
score: 8
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50055640
upvote count: 8
has body: You can only inspect Python source this way. Builtin modules, and extension modules written with the C API, do not have any source in them, so there's no way to inspect it. (When you compile C code, the result may have some debugging information, including the local pathnames of the files used to build it, but it doesn't include the actual source text.) Notice that directly above the function you linked in the docs, getsourcefile says: This will fail with a TypeError if the object is a built-in module, class, or function. And, as you can probably guess (or can verify by looking at inspect.py, linked from the docs), getsource uses getsourcefile under the hood. If you built Python locally on your machine, and left the source code there after building, there is a project that can find the C sources used to build each module, but I can't find it (I think it was on a now-long-dead Berlios or Sourceforge), and I don't think it was ever updated beyond around the 2.4 days. It probably wouldn't be too hard to write your own module to look up the source in the github repo—or, maybe better, in your own local clone of the github repo. (Which would be far better than relying on a locally-built Python…) You could maybe even extend it to use setuptools information to find source for pip-installed extension modules that follow certain common patterns. But, as far as I know, nobody's published such a module. If you want to build something like this yourself, see this quick&amp;dirty proof of concept. Although you'd probably want to use either git or the Github API instead of scraping, and you'd want to be able to search a local repo (maybe cloning it if not found) and/or cache things between runs, and so on, this shows both how easy it is and how much special-casing it requires. So, the best option is to clone the repo and look things up manually, or browse directly on github.

http://stackoverflow.com/comment/86959562
has text: Thank you for the assistance! When applying the recommended update, I now get the above error.
comment on: http://stackoverflow.com/a/49971547
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87004968
type: QuestionComment
comment on: http://stackoverflow.com/q/49994260
has text: The immediate error is that Python 2.6 doesn't have set comprehensions. The top-level error is that you're using Python 2.6, and Django no longer supports Python 2.6, so you need to use 2.7 (or, better, 3.6 or 3.7).
score: 1
type: Comment

http://stackoverflow.com/comment/86971854
score: 0
has text: https://docs.python.org/3/library/os.html#os.environ
type: Comment
comment on: http://stackoverflow.com/q/49977495
type: QuestionComment

http://stackoverflow.com/comment/87005815
has text: @rtindru Performance isn't that important for my scenario, as I will only see integers ranging from 0 to 15 most likely, and the tuples represent multiple unique ways in which you can pick two numbers from that range.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49993936
type: Comment

http://stackoverflow.com/comment/87006251
comment on: http://stackoverflow.com/q/49994816
has text: Try this link, i think it will be a help for you. https://dzone.com/articles/restful-web-services-with-python-flask
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49972502
answer count: 1
has body: I have a Django app and am trying to make some specific model information changeable while the site is loaded. For example, I'd like to be able to change certain images on pages (banners and such) based on changes I make on the admin panel of Django. Additionally, I'd like to create a list of prepopulated migrations for my social media links that can be editable in a django admin page. My specific instance of this is for all of my social media links. I'd like to put my social media link in a model 'Facebook Url" = 'www.facebook.com/mypage. I would then like to put these links throughout the page using dot notation {{ project_settings.facebook.url }} for example. What is the easiest way to do this. I don't think I want to put the context in all of the views because I would have to do that for every page I want this to be available. In the case of my footer it is on every page. The background images are also on several different pages.
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: django-models
has answer: http://stackoverflow.com/a/49972733
tagged with: python
has title: Create Django Application Settings Page
score: 0

http://stackoverflow.com/comment/87137540
comment on: http://stackoverflow.com/a/50024036
type: Comment
has text: @AriannaSorrentino, did you make any progress on your problem?
type: AnswerComment
score: 0

http://stackoverflow.com/q/50000536
has body: I'm new to python and i have a list of objects like this. Sample code &gt;&gt;&gt; for val in las.version: ... print(val.mnemonic) ... print(val.unit) ... print(val.value) ... print(val.descr) ... VERS 1.2 some description WRAP NO another description &gt;&gt;&gt; I wanted to convert this as JSON array. { "versionInformation":[ { "mnemonic":"VERS", "unit":"", "value":"2.0", "description":"some description" }, { "mnemonic":"WRAP", "unit":"", "value":"NO", "description":"another description" } ] }
accepted answer: http://stackoverflow.com/a/50000785
has comment: http://stackoverflow.com/comment/87017014
possible better answer: http://stackoverflow.com/a/50000725
has comment: http://stackoverflow.com/comment/87017075
type: AnsweredQuestion
score: 2
upvote count: 3
linked to: http://stackoverflow.com/q/12309269
has answer: http://stackoverflow.com/a/50000725
answer count: 2
has comment: http://stackoverflow.com/comment/87017219
has comment: http://stackoverflow.com/comment/87017091
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50000785
has comment: http://stackoverflow.com/comment/87017265
has title: convert list of objects to Json array
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: python

http://stackoverflow.com/comment/87196049
has text: Do you know how I can transform the second index to show only the time instead of date and time?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50018219
score: 0

http://stackoverflow.com/a/49973838
downvote count: 0
has body: You can compare by 0 and isna if only NaNs and 0 and then fillna: if ((s == 0) | (s.isna())).all(): s = pd.Series(0, index=s.index) Or compare unique values: if pd.Series(s.unique()).fillna(0).eq(0).all(): s = pd.Series(0, index=s.index) @cᴏʟᴅsᴘᴇᴇᴅ solution, thank you - compare Series without NaNs with dropna: if s.dropna().eq(0).all(): s = pd.Series(0, index=s.index) Solution from question - need convert to strings, because problem with compare with NaNs: if set(s.unique().astype(str)).issubset(['0.0','nan']): s = pd.Series(0, index=s.index) Timings: s = pd.Series(np.random.choice([0,np.nan], size=10000)) In [68]: %timeit ((s == 0) | (s.isna())).all() The slowest run took 4.85 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 574 µs per loop In [69]: %timeit pd.Series(s.unique()).fillna(0).eq(0).all() 1000 loops, best of 3: 587 µs per loop In [70]: %timeit s.dropna().eq(0).all() The slowest run took 4.65 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 774 µs per loop In [71]: %timeit set(s.unique().astype(str)).issubset(['0.0','nan']) The slowest run took 5.78 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 157 µs per loop
has comment: http://stackoverflow.com/comment/86963740
type: AcceptedAnswer
upvote count: 8
has comment: http://stackoverflow.com/comment/86963693
has comment: http://stackoverflow.com/comment/86963728
answers question: http://stackoverflow.com/q/49973811
type: Answer
has comment: http://stackoverflow.com/comment/86963772
accepted answer of: http://stackoverflow.com/q/49973811
score: 8

http://stackoverflow.com/q/50017118
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87058765
tagged with: report
tagged with: odoo-10
tagged with: pivot
answer count: 1
accepted answer: http://stackoverflow.com/a/50021108
type: Question
has body: In Sales -&gt; Reports -&gt; Pipeline I would like to allow to filter by res.partner.category. In Odoo res.partner has a field category_id category_id = fields.Many2many('res.partner.category', column1='partner_id', column2='category_id', string='Tags', default=_default_category) I tried copying category_id = fields.Many2many('res.partner.category', column1='partner_id', column2='category_id', string='Tags', default=_default_category)` to my crm_opportunity_report (that has inherited crm.opportunity.report) but I get errors. Tried adding field category_ids = fields.Many2many(comodel_name='res.partner.category', relation="res_partner_res_partner_category_rel", column1='category_id', column2='partner_id') and this failed too. How to add category name as a filter to crm_opportunity_report? What can be done to allow filtering by category?
has title: Odoo sales reports pipeline filter by res partner category
tagged with: odoo
tagged with: python
has answer: http://stackoverflow.com/a/50021108
has comment: http://stackoverflow.com/comment/87055364
has comment: http://stackoverflow.com/comment/87053070
has comment: http://stackoverflow.com/comment/87055063
has comment: http://stackoverflow.com/comment/87055917

http://stackoverflow.com/q/50034728
has body: I have a similar problem to this simplified version: The experiment result is saved in the excel sheet, and I processed the data using Python Pandas and converted them to DataFrames. Two tables given below: Table_Race save in DataFrame race Table_standard save in DataFrame std &gt;&gt;&gt; data = [["Gold+",1,30,35],["Silver+",1,25,30],["Bronze+",1,20,25],["Gold",2,20,25],["Silver",2,15,20],["Bronze",2,10,15]] &gt;&gt;&gt; std = pd.DataFrame(data,columns=['Title','League','Start','End']) &gt;&gt;&gt; std Title League Start End 0 Gold+ 1 30 35 1 Silver+ 1 25 30 2 Bronze+ 1 20 25 3 Gold 2 20 25 4 Silver 2 15 20 5 Bronze 2 10 15 &gt;&gt;&gt; data = [["John",1,26],["Ryan",1,33],["Mike",1,9],["Jo",2,15],["Riko",2,21],["Kiven",2,13]] &gt;&gt;&gt; race = pd.DataFrame(data,columns=['Name','League','Distance']) &gt;&gt;&gt; race Name League Distance 0 John 1 26 1 Ryan 1 33 2 Mike 1 9 3 Jo 2 21 4 Riko 2 15 5 Kiven 2 13 &gt;&gt;&gt; I would like to check the distance for each player and get their title according to the standards: Title &lt;= distance in [start, end) and need to match league For example: Jo from league 2 and has distance 15 which is in between [15,20). Note that it's not [10,15), hence he get title 'Silver' The expected result as follows: Name League Distance Title John 1 26 Silver+ Ryan 1 33 Gold+ Mike 1 9 N/A Jo 2 21 Gold Riko 2 15 Silver Kiven 2 13 Bronze I can achieved this using two loops which basically get each distance from Table_race and search for (l, d) from each row of race's (League, Distance) Looking for condition: l == League &amp;&amp; d &gt;= Start &amp;&amp; d &lt; End But this method is O(N^2) which is too slow, as my data can easily go over 100,000 which takes hours to finish. Any better solutions?
type: AnsweredQuestion
tagged with: pandas
has title: Join two tables with a range criteria using Python Pandas
linked to: http://stackoverflow.com/q/31410356
score: 1
has comment: http://stackoverflow.com/comment/87086596
has answer: http://stackoverflow.com/a/50035263
accepted answer: http://stackoverflow.com/a/50035263
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87086433
tagged with: bigdata
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87151733
type: Comment
type: QuestionComment
score: 0
has text: That does not depend on `pickle` at all. Why are you not using something like hadoop or spark?
comment on: http://stackoverflow.com/q/50067583

http://stackoverflow.com/comment/86870786
has text: Thank you @Daniel Roseman, It's that the problem. there is no way to pass multiple instances to Response ?
comment on: http://stackoverflow.com/a/49926817
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/69681003
answers question: http://stackoverflow.com/q/50026264
type: Answer
score: 0
has body: The adjacent answer combines only text tags, without preserving nested tags, such as . The following code does this. For example, for this html: Abcd1, abcd2 abcd3 ab cd4 absd5 abcd6 the result will be: Abcd1, abcd2 abcd3 ab cd4 absd5 abcd6 In the ignoring_tags_names variable, you can set which tags are considered nested and ignored when merging. Any other tags will break the merging chain. In the re_symbols_ignore variable, you can set text characters between the same tags to be ignored when concatenating. Any other characters will break the merging chain. You can also specify a check for the identity of tag attributes. But their order is not checked. {class: ['a', 'b']} and {class: ['b', 'a']} are considered different and tags are not combined. import re from bs4 import BeautifulSoup, NavigableString def find_and_combine_tags(soup, init_tag_name: str, init_tag_attrs: dict = None or {}): def combine_tags(tag, tags: list): # appending the tag chain to the first tag for t in tags: tag.append(t) # unwrapping them for t in tag.find_all(init_tag_name): if t.name == init_tag_name and t.attrs == init_tag_attrs: t.unwrap() def fill_next_siblings(tag, init_tag_name: str, ignoring_tags_names: list) -> list: next_siblings = [] for t in tag.next_siblings: if isinstance(t, NavigableString) and not re_symbols_ignore.match(t): next_siblings.append(t) elif isinstance(t, NavigableString) and re_symbols_ignore.match(t): next_siblings.append(t) elif t.name in ignoring_tags_names and t.attrs == init_tag_attrs: # also checking the tag attrs next_siblings.append(t) else: # filling `next_siblings` until another tag met break has_other_tag_met = False for t in next_siblings: if t.name == init_tag_name and t.attrs == init_tag_attrs: has_other_tag_met = True break # removing unwanted tags on the tail of `next_siblings` if has_other_tag_met: while True: last_tag = next_siblings[-1] if isinstance(last_tag, NavigableString): next_siblings.pop() elif last_tag.name != init_tag_name and last_tag.…

http://stackoverflow.com/comment/87142296
type: QuestionComment
comment on: http://stackoverflow.com/q/50062663
has text: @SeanFrancisN.Ballais Updated, this one is i used.
score: 0
type: Comment

http://stackoverflow.com/q/49994942
favorite count: 0
type: Question
has title: how to convert a set of values in tensorflow using tf.case ?
has body: I have the following code: conversion_dictionary = {1: 2, 2: 5, 3: 4, 4: 4} converted_vals= [conversion_dictionary[label] for label in labels] It converts the labels from one set of values to another. I want to do the same thing using tensors but I know that tesnors are not iterable , so I get the not iterable error for the following code labels = tf.constant([1, 1, 2, 4, 3, 1]) conversion_dictionary = {1: 2, 2: 5, 3: 4, 4: 4} converted_vals = [conversion_dictionary[label] for label in labels] print(tf.eval(converted_vals)) I found the tf.case function that might be suitable here but I couldn't figure out how to use it. So my question is - how to convert between sets of values in tensorflow?
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49998103
has answer: http://stackoverflow.com/a/49998103
type: AnsweredQuestion
score: 1
tagged with: tensorflow

http://stackoverflow.com/a/54825928
upvote count: 3
downvote count: 0
score: 3
has body: Try to upgrade pip: python -m pip install --upgrade pip Then upgrade the Google packages: pip install --upgrade google-api-python-client pip install --upgrade google-cloud
type: Answer
answers question: http://stackoverflow.com/q/50072510

http://stackoverflow.com/comment/87035383
score: 3
type: Comment
type: QuestionComment
has text: If you have questions, provide your code as a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
comment on: http://stackoverflow.com/q/50009351

http://stackoverflow.com/a/50014458
type: Answer
has body: You can simply concatenate the columns df['new_col'] = df[df.columns[3]].astype(str) + ':' + df[df.columns[2]].astype(str) This will output a new column in your df named new_col. Now you can either delete the unnecessary columns.
answers question: http://stackoverflow.com/q/50014314
has comment: http://stackoverflow.com/comment/87045215
score: 0
has comment: http://stackoverflow.com/comment/87045170

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/49974855

http://stackoverflow.com/comment/86971662
type: QuestionComment
comment on: http://stackoverflow.com/q/49977495
score: 0
has text: Something like this %a_home%\components\xxx\etc......myfile.xml
type: Comment

http://stackoverflow.com/comment/86997616
comment on: http://stackoverflow.com/a/49990489
type: AnswerComment
score: 0
has text: This results works in a way! But one of the main reason i want it in a loop is that I am trying to convert the datetime.datetime too using datetime.fromtimestamp(int(result[1][x])).strftime('%Y-%m-%d %H:%M:%S'). How can I do this using your method.
type: Comment

http://stackoverflow.com/a/50057307
score: 0
has comment: http://stackoverflow.com/comment/87130983
type: Answer
answers question: http://stackoverflow.com/q/50056601
has body: A CSV file is a text file that simply consists of rows separated by linebreaks. An Excel file is a binary file using a proprietary Microsoft format. For a CSV file the notion of "lines" makes sense. It is nonsensical for an Excel file. If you want to count the rows in an Excel file you will have to use a library that can parse such a file. Just using .readlines() on the HTTP response body of an Excel file will not work.

http://stackoverflow.com/q/50012852
type: Question
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50014179
has body: Please help....i am trying use solr, pysolr and haystack on my django site search. I have edited the haystack build_solr_schema script to use BaseCommand.add_argument(), removing the default options_list. Below are my versions used; Python 3.5.2 Django 1.11.11 solr-7.3.0 django-haystack 2.4.0 pysolr 3.7.0 # encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import sys from optparse import make_option from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.template import Context, loader from haystack import constants from haystack.backends.solr_backend import SolrSearchBackend class Command(BaseCommand): help = "Generates a Solr schema that reflects the indexes." def add_arguments(self, parser): # positional arguments parser.add_argument("-f", "--filename", action="store", type="string", dest="filename", help='If provided, directs output to a file instead of stdout.',), # optional positional arguments parser.add_argument("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.') """ base_options = ( make_option("-f", "--filename", action="store", type="string", dest="filename", help='If provided, directs output to a file instead of stdout.'), make_option("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.'), ) option_list = BaseCommand.option_list + base_options """ def handle(self, **options): """Generates a Solr schema that reflects the indexes.""" using = options.get('using') schema_xml = self.build_template(using=using) if options.get('filename'): self.write_file(options.get('filename'), schema_xml) else: self.print_stdout(schema_xml) def build_context(self, using): from haystack import connections, connection_router backend = connections[using].get_backend() if not …
has title: python,django, solr, haystack: arg_parse error when editing solr_build_schema BaseCommand.add_argument()
has answer: http://stackoverflow.com/a/50014179
type: AnsweredQuestion
score: 0
tagged with: solr
tagged with: django-haystack
answer count: 1

http://stackoverflow.com/q/50009034
answer count: 1
has comment: http://stackoverflow.com/comment/87034724
has comment: http://stackoverflow.com/comment/87037687
type: Question
has title: Error during use of ffmpeg for the joining of images to form a video file
tagged with: ffmpeg
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/13590976
has comment: http://stackoverflow.com/comment/87036202
has comment: http://stackoverflow.com/comment/87034894
has comment: http://stackoverflow.com/comment/87037538
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/72680684
has body: I am trying to join a sequence of images (*.png) using ffmpeg. The filenames of the images are in the following format: recon_0001.png, recon_0002.png, ... , recon_0100.png. I would like to join the images sequentially (i.e. recon_0001.png being the first frame, recon_0002.png the second frame and so on.) After looking at the following link: Python: Make a video using several .png images , I tried to implement my task using the following code: from __future__ import division import cv2 import os import matplotlib.pyplot as plt from pylab import pcolor, show, colorbar, xticks, yticks import numpy as np if(1): ffmpeg -f image2 -r 1/5 -i /Users/Username/Folder/recon_%04d.png -vcodec mpeg4 -y movie.mp4 But, I get the following error: ffmpeg -f image2 -r 1/5 -i /Users/Username/Folder/recon_%04d.png -vcodec mpeg4 -y movie.mp4 ^ SyntaxError: invalid syntax What am I missing here? I am new to the use of ffmpeg and I will really appreciate any help.

http://stackoverflow.com/comment/86989310
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49986466
type: QuestionComment
has text: do you have numlock on? it works fine with my kivy app (my numpad i mean)

http://stackoverflow.com/comment/87108375
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50046077
has text: They are drastically different. Have you tried to see what your implementation does?

http://stackoverflow.com/q/50061577
answer count: 1
linked to: http://stackoverflow.com/q/34803855
has body: I have a following DataFrame: +-----------+----------+----------+ | some_id | one_col | other_col| +-----------+----------+----------+ | xx1 | 11| 177| | xx2 | 1613| 2000| | xx4 | 0| 12473| +-----------+----------+----------+ I need to add a new column which is based on some calculations done on the first and second column, namely, for example, for col1_value=1 and col2_value=10 would need to produce a percentage of col1 that is included in col2, so col3_value= (1/10)*100=10%: +-----------+----------+----------+--------------+ | some_id | one_col | other_col| percentage | +-----------+----------+----------+--------------+ | xx1 | 11| 177| 6.2 | | xx3 | 1| 10 | 10 | | xx2 | 1613| 2000| 80.6 | | xx4 | 0| 12473| 0 | +-----------+----------+----------+--------------+ I know I would need to use a udf for this, but how do I directly add a new column value based on the outcome? Some pseudo-code: import pyspark from pyspark.sql.functions import udf df = load_my_df def my_udf(val1, val2): return (val1/val2)*100 udf_percentage = udf(my_udf, FloatType()) df = df.withColumn('percentage', udf_percentage(# how?)) Thank you!
downvote count: 1
favorite count: 0
type: Question
tagged with: apache-spark-sql
accepted answer: http://stackoverflow.com/a/50061636
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/87139458
tagged with: pyspark
has answer: http://stackoverflow.com/a/50061636
tagged with: python
type: AnsweredQuestion
upvote count: 2
has title: How to create a new column based on calculations made in other columns in PySpark
score: 1

http://stackoverflow.com/comment/87073349
has text: Thank you simon after some little research I got it to work. Your help was really awesome
comment on: http://stackoverflow.com/a/50022313
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50045203
has title: Installing web3 for Ethereum error
favorite count: 0
type: Question
has body: I'm using MacOS and is trying to install web3. I'm getting this error response message which I'm not sure how to resolve. I have other code editors installed in my mac, and currently I'm learning how to do some blockchain development. Would be really helpful if someone could assist me in this. Thanks! npm WARN deprecated fs-promise@2.0.3: Use mz or fs-extra^3.0 with Promise Support npm WARN deprecated tar.gz@1.0.7: ⚠️ WARNING ⚠️ tar.gz module has been deprecated and your application is vulnerable. Please use tar module instead: https://npmjs.com/tar &gt; scrypt@6.0.3 preinstall /Users/HTT/inbox/node_modules/scrypt &gt; node node-scrypt-preinstall.js &gt; scrypt@6.0.3 install /Users/HTT/inbox/node_modules/scrypt &gt; node-gyp rebuild gyp ERR! configure error gyp ERR! stack Error: Python executable "/anaconda3/bin/python" is v3.6.4, which is not supported by gyp. gyp ERR! stack You can pass the --python switch to point to Python &gt;= v2.5.0 &amp; &lt; 3.0.0. gyp ERR! stack at PythonFinder.failPythonVersion (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:492:19) gyp ERR! stack at PythonFinder.&lt;anonymous&gt; (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:474:14) gyp ERR! stack at ChildProcess.exithandler (child_process.js:267:7) gyp ERR! stack at emitTwo (events.js:126:13) gyp ERR! stack at ChildProcess.emit (events.js:214:7) gyp ERR! stack at maybeClose (internal/child_process.js:925:16) gyp ERR! stack at Socket.stream.socket.on (internal/child_process.js:346:11) gyp ERR! stack at emitOne (events.js:116:13) gyp ERR! stack at Socket.emit (events.js:211:7) gyp ERR! stack at Pipe._handle.close [as _onclose] (net.js:567:12) gyp ERR! System Darwin 17.5.0 gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /Users/HTT/inbox/node_modules/scrypt gyp ERR! node -v v8.11.1 gyp ERR! node-gyp -v v3.6.2 gyp ERR! not ok npm WARN inbox@1.0.0 No descript…
has answer: http://stackoverflow.com/a/50072548
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: blockchain
tagged with: ethereum
answer count: 2
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has answer: http://stackoverflow.com/a/51574539
score: 1
upvote count: 1

http://stackoverflow.com/q/50062577
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50062685
upvote count: 2
downvote count: 0
tagged with: python
has title: Offsetting the index in pandas dataframe (keep content intact)
type: AnsweredQuestion
score: 2
tagged with: pandas
answer count: 1
tagged with: dataframe
has body: Scenario: I have 2 dataframes, one has data for period X and the other has the data for period X-1 (could be day or month). Data example: DF1 (time X): Item 1 Item 2 2018-01-02 0.431 0.656 2018-01-03 0.439 0.668 2018-01-04 0.447 0.680 2018-01-05 0.455 0.692 2018-01-08 0.479 0.729 2018-01-09 0.487 0.741 2018-01-10 0.495 0.753 DF1 (time X-1): Item 1 Item 2 2018-01-02 0.429 0.651 2018-01-03 0.431 0.656 2018-01-04 0.439 0.668 2018-01-05 0.447 0.680 2018-01-08 0.455 0.692 2018-01-09 0.479 0.729 2018-01-10 0.487 0.741 I want my resuling dataframe to be: X Final: Item 1 Item 2 2018-01-01 0.429 0.651 2018-01-02 0.431 0.656 2018-01-03 0.439 0.668 2018-01-04 0.447 0.680 2018-01-05 0.455 0.692 2018-01-08 0.479 0.729 2018-01-09 0.487 0.741 2018-01-10 0.495 0.753 What I already tried: I was initially trying to merge the last column of X array with x-1 array, and offset the index, but in doing that, I also offset the data, which is not what I want: df_xfinal = df_x1.iloc[:] df_xlastrow = df_x.iloc[-1:] df_xfinal = df_xfinal.append(df_xlastrow) df_xfinal = df_xfinal.shift(periods=-1, axis=0) Question: Can this be done in a straightforward way, without having through loop across all the array items?
accepted answer: http://stackoverflow.com/a/50062685

http://stackoverflow.com/q/49991677
has comment: http://stackoverflow.com/comment/87025703
accepted answer: http://stackoverflow.com/a/50011483
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87012066
tagged with: random-forest
upvote count: 6
score: 6
has body: I'm using a RandomForestClassifier to classify samples with a binary outcome ("does not have the thing" vs "has the thing"). From the result of RandomForestClassifier.decision_path, how do I determine which samples contributed to the classification decision? The documentation says: Returns: indicator : sparse csr array, shape = [n_samples, n_nodes] Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. n_nodes_ptr : array of size (n_estimators + 1, ) The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. Unfortunately, these terms are opaque to me. indicator[x:y] on a matrix of dimension [n_samples, n_nodes] seems like it is a mistake (shouldn't it be indicator[sample, n_nodes_ptr[i]:n_nodes_ptr[i+1]]?), but even then, I'm not sure what to do to take a "node indicator" and find what feature the node refers to. I can find examples using decision_path for DecisionTreeClassifier, but not for RandomForestClassifier.
has title: Using RandomForestClassifier.decision_path, how do I tell which samples the classifier used to make a decision?
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/87031224
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87033396
downvote count: 0
has answer: http://stackoverflow.com/a/50011483

http://stackoverflow.com/a/50045626
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: It depends what you want to do. If you just want to first row, you could access it with iloc do the following: d.iloc[0]['a'] If you want to filter the dataframe for example by the year, you could do: d.loc[d.index.year == 2018, 'a']
answers question: http://stackoverflow.com/q/50045182

http://stackoverflow.com/a/49959272
score: 0
type: AcceptedAnswer
has body: You should try to change your image source. This is what you have: &lt;img src="pic.jpg" alt="Smiley face" height="200" width="420"&gt; Try this: &lt;img src="{% static "exapp/pic.jpg" %}" alt="Smiley face" height="200" width="420"&gt; This worked for me! Good luck!
answers question: http://stackoverflow.com/q/49959206
type: Answer
accepted answer of: http://stackoverflow.com/q/49959206

http://stackoverflow.com/q/49994548
tagged with: python
has comment: http://stackoverflow.com/comment/87005626
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49994669
accepted answer: http://stackoverflow.com/a/49994669
has comment: http://stackoverflow.com/comment/87005543
has comment: http://stackoverflow.com/comment/87005399
answer count: 1
downvote count: 0
has body: I have a problem with multiprocessing in Python 3.11 on Windows. Here is the script: from multiprocessing import Process import os import time def info(title): print(title) print('module name:', __name__) if hasattr(os, 'getppid'): # only available on Unix print('parent process:', os.getppid()) print('process id:', os.getpid()) def f(name): info('function f') print('--- hello', name) time.sleep(5) print('--- bye', name) def some_func(): print('Running some_func function') def another_func(): print('Running another_func function') def main(): print('Running main function of try_multi.py') print('-------------------------------------') some_func() if __name__ == '__main__': info('main line') p1 = Process(target=f, args=('bob',)) p2 = Process(target=f, args=('larry',)) p1.start() p2.start() p1.join() p2.join() another_func() main() Here is it's output: C:\Scripts&gt; c:\Python31\python.exe try_multi.py Running main function of try_multi.py ------------------------------------- Running some_func function main line module name: __main__ process id: 12696 Running main function of try_multi.py ------------------------------------- Running some_func function Running another_func function function f module name: __main__ process id: 14568 --- hello bob Running main function of try_multi.py ------------------------------------- Running some_func function Running another_func function function f module name: __main__ process id: 9336 --- hello larry --- bye bob --- bye larry Running another_func function The problem is that I expect only function "f" to run in the new processes but it looks like the whole new instance of the parent script is started - both "some_fun" and "another_func" run. On Linux with Python 2.7.5 it works as expected: $ python try_multi.py Running main function of try_multi.py ------------------------------------- Running some_func function main line ('module name:', '__main__') ('parent process:', 1137) ('process id:', 1167) function f ('module name:', '_…
upvote count: 1
tagged with: multiprocessing
type: AnsweredQuestion
has title: Invocation of multiprocessing in Python 3.11 on Windows
score: 1
tagged with: windows

http://stackoverflow.com/comment/87089580
type: QuestionComment
comment on: http://stackoverflow.com/q/50034940
has text: https://stackoverflow.com/questions/10561923/unicodedecodeerror-ascii-codec-cant-decode-byte-0xef-in-position-1
score: 0
type: Comment

spss-modeler
type: Tag
tag name: spss-modeler
tags question: http://stackoverflow.com/q/49981833

http://stackoverflow.com/q/49969215
has body: I have two multi-dimensional arrays and I would like to evaluate and assign values for those matching and non-matching values. array_1 = array([[1,2,2], [1,2,3],[1,2,1]]) array_2 = array([[1,1,2], [2,2,3],[3,1,1]]) The idea is that for each member of array 1, if the value is the same, I want to assign 0 and it doesn't, I want to assign a different value. The logic is something like this. (array_1 ==1 and array_2 ==1) = 0 (array_1 ==1 and array_2 ==2) = 10 (array_1 ==1 and array_2 ==3) = 15 (array_1 ==2 and array_2 ==1) = 5 (array_1 ==2 and array_2 ==2) = 0 (array_1 ==2 and array_2 ==3) = 15 (array_1 ==3 and array_2 ==1) = 5 (array_1 ==3 and array_2 ==2) = 10 (array_1 ==3 and array_3 ==3) = 0 The over all goal is to detect a change. A brief description of this methodology is available on https://www.e-education.psu.edu/geog883/node/496
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49969526
accepted answer: http://stackoverflow.com/a/49969526
possible better answer: http://stackoverflow.com/a/49969468
tagged with: classification
has title: Evaluate arrays and assign values in Python
tagged with: arrays
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49969468
downvote count: 1

http://stackoverflow.com/q/49972988
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/87045494
has title: Running VBA code from Python: macros may be disabled
has comment: http://stackoverflow.com/comment/87020508
answer count: 1
downvote count: 0
tagged with: vba
has comment: http://stackoverflow.com/comment/86965848
has answer: http://stackoverflow.com/a/74513314
favorite count: 0
type: Question
has body: Trying to run an Excel macro via Python I get the following error: Traceback (most recent call last): File ".\test.py", line 17, in &lt;module&gt; xlApp.Application.Run(MACRO) File "&lt;COMObject &lt;unknown&gt;&gt;", line 14, in Run File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None) I tried many of the fixes suggested in other questions. I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'. Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public. As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine. I am running Python 3.6.5 on a 64 bit system, Windows 10. Python: import win32com.client import os import traceback DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\' FILE = 'test.xlsb' MACRO = 'test' path = os.path.join(DIRECTORY, FILE) if os.path.exists(path): try: xlApp = win32com.client.Dispatch('Excel.Application') xlApp.DisplayAlerts = False xlApp.Visible = True wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1) xlApp.Application.Run(MACRO) wb.Close(SaveChanges=1) xlApp.Application.Quit() print('Code ran successfully.') except: print('An error was encountered; see traceback.') print(traceback.format_exc()) xlApp.Quit() VBA: Public Sub test() MsgBox "Hello World!" End Sub
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33385259
tagged with: win32com
has comment: http://stackoverflow.com/comment/87045549
tagged with: python
tagged with: excel

http://stackoverflow.com/comment/87040323
has text: You are welcome. :). In order to use the function above you just need to provide a list of the chunk sizes you want. In the example it means first five lines, following two lines and following 3 lines. So in your case instead of calculating `packs` as the total count of lines make it as a list of chunk sizes and pass it to `split_list`. Something like: `packs = ([pack10] * 10) + ([pack25] * 25) + ([pack50] * 50) + ([pack100] * 100)`. I am assuming you want the chunks of size `10` to come before the ones of size `25` and so on.
type: AnswerComment
comment on: http://stackoverflow.com/a/49967780
score: 0
type: Comment

http://stackoverflow.com/comment/86887850
type: Comment
has text: Well, the issue is because of the program not being optimized
type: QuestionComment
comment on: http://stackoverflow.com/q/49930418
score: 0

http://stackoverflow.com/comment/86997227
has text: No, I put .recv within a while loop on the server side.
comment on: http://stackoverflow.com/q/49990229
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50035932
tagged with: datetime
tagged with: python
score: 2
has title: Pandas to_datetime not formatting as expected
tagged with: pandas
has body: I have a data frame with a column 'Date' with data type datetime64. The values are in YYYY-MM-DD format. How can I convert it to YYYY-MM format and use it as a datetime64 object itself. I tried converting my datetime object to a string in YYYY-MM format and then back to datetime object in YYYY-MM format but it didn't work. Original data = 1988-01-01. Converting datatime object to string in YY-MM format df['Date']=df['Date'].dt.strftime('%Y-%m') This worked as expected, my column value became 1988-01 Converting the string back to datetime object in Y-m format df['Date']=pd.to_datetime(df['Date'],format= '%Y-%m') I was expecting the Date column in YYYY-MM format but it became YYYY-MM-DD format. 1988-01-01 Can you please let me know if I am missing something. Thanks
answer count: 1
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50035958

http://stackoverflow.com/a/50064804
has body: WebSockets are for bi-directional communication, which you don't need. Use server-sent events instead. On the client, you'll do something like this: const metaEventSource = new EventSource('/metadata'); metaEventSource.addEventListener('message', (e) =&gt; { console.log(e.data); }); Server-side, there are many abstractions available depending on which stack you ultimately choose. It's a simple text-base response format: event: metadata data: Your new metadata goes here
type: Answer
answers question: http://stackoverflow.com/q/50040481
score: 0

http://stackoverflow.com/q/50003397
tagged with: dynet
type: Question
has title: How to read back the "random-seed" from a saved model of Dynet
has body: I have a model already trained by dynet library. But i forget the --dynet-seed parameter when training this model. Does anyone know how to read back this parameter from the saved model? Thank you in advance for any feedback.
tagged with: python
accepted answer: http://stackoverflow.com/a/50051554
tagged with: lstm
has answer: http://stackoverflow.com/a/50051554
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/q/50062125
has body: list1=['f','l','a','m','e','s'] #This is the predefined list list2=['e','e','f','a','s','a'] #This is the list with repitition x=list(set(list2)) # I want to remove duplicates print(x) Here I want the variable x to retain the order which list1 has. For example, if at one instance set(list2) produces the output as ['e','f','a','s'], I want it to produce ['f','a','e','s'] (Just by following the order of list1). Can anyone help me with this?
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50063147
downvote count: 0
has title: How to arrange the output of set based on predefined list
has answer: http://stackoverflow.com/a/50062256
has comment: http://stackoverflow.com/comment/87140873
favorite count: 0
has answer: http://stackoverflow.com/a/50062308
tagged with: list
linked to: http://stackoverflow.com/q/480214
has answer: http://stackoverflow.com/a/50062292
tagged with: python
answer count: 4
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49944574
has comment: http://stackoverflow.com/comment/86906120
has comment: http://stackoverflow.com/comment/86905751
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86905795
accepted answer of: http://stackoverflow.com/q/49944501
type: Answer
answers question: http://stackoverflow.com/q/49944501
has comment: http://stackoverflow.com/comment/86919621
has body: Option 1 pd.concat with a groupby should do it. pd.concat([ pd.Series(v.values, name=k) for k, v in df1.groupby('Name')['Value'] ], axis=1 ) classe code series 0 12 10 B 1 1 12 C 2 18 16 A Option 2 pivot Flaky pivot hack, don't count on it! This solution assumes values inside Name alternate regularly - code, classe, series, code, classe, series, ... and so on. Won't work otherwise. df1.assign(Index=df1.index // 3).pivot('Index', 'Name', 'Value') Name classe code series Index 0 12 10 B 1 1 12 C 2 18 16 A
downvote count: 0
has comment: http://stackoverflow.com/comment/86905545
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86905776

http://stackoverflow.com/q/49969960
tagged with: python
tagged with: data-science
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has title: Correct Calculation of BIC to determine K for K means
has body: I am trying to calculate BIC in python. In python, there is no inbuilt library for computing BIC. I referenced the following link to compute variance and BIC further:- https://stats.stackexchange.com/questions/90769/using-bic-to-estimate-the-number-of-k-in-kmeans?utm_medium=organic&amp;utm_source=google_rich_qa&amp;utm_campaign=google_rich_qa The variance formula given in the highest voted answer is not working for my code design as centers is a two-dimensional array and in my case it's a single dimensional array. So I converted the variance formula given in the link to calculate but I learned it's not the correct way. Here is my python code:- def compute_variance_grayscale(self, clusters, centroids, gImage, k): # compute variance variance = 0 for i in range(len(clusters)): #iterate over the available clusters cluster = clusters[i] sum = 0; centroid = centroids[i] for j in cluster: #for each data point in cluster j compute the sum sum += (gImage.getImageValueAt(j[0], j[1]) - centroid) ** 2 variance += sum / (len(cluster) - k); #add the sum to the given variance return variance def compute_variance_rgb(self, clusters, centroids, cImage, k): # compute variance variance = 0 for i in range(len(clusters)): cluster = clusters[i] sum = 0; centroid = centroids[i] for j in cluster: b,g,r = cImage.getImageValueAt(j[0], j[1]) b_e = (b - centroid[0]) ** 2 g_e = (g - centroid[1]) ** 2 r_e = (r - centroid[2]) ** 2 sum += (b_e + g_e + r_e) variance += sum / (len(cluster) - k); return variance Can anyone please point to the right way to calculate variance? Also, it would be great if someone could explain to me the computation of BIC and use of const terms as mentioned in the highest voted answer in the above link:- np.sum([n[i] * np.log(n[i]) - n[i] * np.log(N) - ((n[i] * d) / 2) * np.log(2*np.pi*cl_var) - ((n[i] - 1) * d/ 2) for i in range(m)]) - const_term
type: UnansweredQuestion
tagged with: k-means
tagged with: bayesian

http://stackoverflow.com/q/49923921
has title: Submit a python job to spark
type: UnansweredQuestion
tagged with: pyspark
has body: I'm trying to submit a job written in python to spark. First I'm going to explain my setup, I installed a single node of spark 2.3.0 on a performing windows server (40 cores and 1TB or RAM), of course the goal will be later to create a cluster of less powerfull nodes, but for now I'm testing everything there :) My first test consists on taking a set of tabular CSV files (40-100GB each), split them and then save the splitted result somewhere else. I've been making my prototype on a jupyter notebook using pyspark (which creates automatically a sparkContext. Now, I want to create a spark_test.py script, containing the body of my prototype in the main, which I'm planning to send to the spark-submit. The thing is that seems like the processing part of my script is not working at all. Here you have the body of my script: from pyspark import SparkContext, SparkConf def main(): # Create spark context spark_conf = SparkConf().setAppName('GMK_SPLIT_TEST') print('\nspark configuration: \n%s\n' % spark_conf.toDebugString()) sc = SparkContext(conf=spark_conf) # Variables definition partitionings_number = 40 file_1 = r'D:\path\to\my\csv\file.csv' output_path = r'D:\output\path' # Processing 1 rdd = sc.parallelize(range(1000)) print(rdd.mean()) # Processing 2 sdf = spark.read.option('header','true').csv(file_1, sep=';', encoding='utf-8') sdf_2 = sdf.repartition(partitionings_number, 'Zone[3-2]') sdf_2.write.saveAsTable('CSVBuckets', format='csv', sep=';', mode='overwrite', path=output_path, header='True') if __name__ == '__main__': main() Now here is where I have more doubts. Does spark-submit will try to connect to an already running instance of spark or it will initialize one by itself? I tried: spark-submit --master local[20] --driver-memory 30g The above command seems to work if for the Processing 1, but no for the Processing 2 spark-submit --master spark:\\127.0.0.1:7077 --driver-memory 30g The above command raises an exception of spark contex initialization. Is it because I …
tagged with: spark-submit
tagged with: apache-spark
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86887548
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86866344
answer count: 0

http://stackoverflow.com/comment/87077366
type: Comment
has text: How did you install Spyder?
comment on: http://stackoverflow.com/a/50030280
type: AnswerComment
score: 0

string-to-datetime
tag name: string-to-datetime
type: Tag
tags question: http://stackoverflow.com/q/50033145

http://stackoverflow.com/comment/87031029
score: 0
has text: I want to be able to keep count of the number of times a user clicks on the poke button and print that on the table.
comment on: http://stackoverflow.com/q/50006621
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49936583
answers question: http://stackoverflow.com/q/49936127
type: Answer
has body: The only thing that worked was h1 a:not(span)::text. Thanks.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49936127
score: 1

http://stackoverflow.com/comment/87084501
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50034041
type: Comment
has text: Hm, interesting. I was not aware of that functionality in numpy. Also, I think you mean `p_2D`.

http://stackoverflow.com/comment/86994000
type: AnswerComment
has text: I think this solves my issue, I can have a huge string following the mentioned pattern, so I didn't want to split and than iterate over it because I think it would take too much time, I (think) this is quicker because the second iteration is over a much smaller set
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49988737

http://stackoverflow.com/q/50028214
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50028356
has comment: http://stackoverflow.com/comment/87073393
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87072651
has body: In my application, I need a fast look up of attributes. Attributes are in this case a composition of a string and a list of dictionaries. These attributes are stored in a wrapper class. Let's call this wrapper class Plane: class Plane(object): def __init__(self, name, properties): self.name = name self.properties = properties @classmethod def from_idx(cls, idx): if idx == 0: return cls("PaperPlane", [{"canFly": True}, {"isWaterProof": False}]) if idx == 1: return cls("AirbusA380", [{"canFly": True}, {"isWaterProof": True}, {"hasPassengers": True}]) To better play with this class, I added a simple classmethod to construct instances by providing and integer. So now in my application I have many Planes, of the order of 10,000,000. Each of these planes can be accessed by a universal unique id (uuid). What I need is a fast lookup: given an uuid, what is the Plane. The natural solution is a dict. A simple class to generate planes with uuids in a dict and to store this dict in a file may look like this: class PlaneLookup(object): def __init__(self): self.plane_dict = {} def generate(self, n_planes): for i in range(n_planes): plane_id = uuid.uuid4().hex self.plane_dict[plane_id] = Plane.from_idx(np.random.randint(0, 2)) def save(self, filename): with gzip.open(filename, 'wb') as f: pickle.dump(self.plane_dict, f, pickle.HIGHEST_PROTOCOL) @classmethod def from_disk(cls, filename): pl = cls() with gzip.open(filename, 'rb') as f: pl.plane_dict = pickle.load(f) return pl So now what happens is that if I generate some planes? pl = PlaneLookup() pl.generate(1000000) What happens is, that lots of memory gets consumed! If I check the size of my pl object with the getsize() method from this question, I get on my 64bit machine a value of 1,087,286,831 bytes. Looking at htop, my memory demand seems to be even higher (around 2GB). In this question, it is explained quite well, why python dictionaries need much memory. However, I think this does not have to be the case in my application.…
answer count: 1
has comment: http://stackoverflow.com/comment/87072568
has title: How to decrease the memory footprint of dictionary?
has answer: http://stackoverflow.com/a/50028356
has comment: http://stackoverflow.com/comment/87073447
linked to: http://stackoverflow.com/q/10264874
type: Question
linked to: http://stackoverflow.com/q/449560
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87072889
has comment: http://stackoverflow.com/comment/87072943
has comment: http://stackoverflow.com/comment/87072632
has comment: http://stackoverflow.com/comment/87073869
tagged with: python

http://stackoverflow.com/q/50030000
tagged with: python
has body: Trying to drop certain row from pivot table. However, whenever I try to drop the row I get a key error. I've looked into reshaping pivot tables and multi-indexing, but I'm having trouble grasping the concepts. Are they even necessary for this situation? If so, can you please explain? If not, what's the most efficient way to fix the issue? ps_total = ps.pivot_table(index="CountyName",columns="Year",values=["Number of Private Schools"],aggfunc=np.sum) ps_total.columns = pd.MultiIndex.from_tuples(ps_total.columns) ps_total = ps_total[(ps_total["CountyName"]==1).any(axis=1)] # error here ps_total = ps_total.fillna(0) print(ps_total.to_string()) 2010 2011 2012 2013 2014 2015 CountyName 1 0.0 0.0 0.0 0.0 0.0 3.0 Alameda 156.0 144.0 148.0 145.0 141.0 136.0 Alpine 0.0 0.0 1.0 1.0 0.0 0.0 Amador 2.0 2.0 1.0 1.0 1.0 0.0 Butte 21.0 21.0 22.0 21.0 19.0 16.0 Key Error: "CountyName"
tagged with: pandas
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: pivot-table
has title: Key Error pivot table pandas
has answer: http://stackoverflow.com/a/50030154

http://stackoverflow.com/comment/87043649
has text: @PanosKal; you can post your own answer too in this thread. I'd like to see other way around.
comment on: http://stackoverflow.com/a/49994055
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49931936
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86879677
has comment: http://stackoverflow.com/comment/87632931
downvote count: 2
has answer: http://stackoverflow.com/a/49932011
possible better answer: http://stackoverflow.com/a/49932160
has comment: http://stackoverflow.com/comment/86879657
has comment: http://stackoverflow.com/comment/86879622
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86879707
has answer: http://stackoverflow.com/a/49932188
has answer: http://stackoverflow.com/a/72902423
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/86879717
has body: I'm a novice working on a practice script of which I have 90% figured out but am stumped on one portion. I'm doing the mocking spongebob "challenge" on dmoj which asks you to make every other character of a given string upper case, but demands symbols and spaces to be ignored and only letters to be counted. I and am able to make every other character upper case or lower case, but I am not sure how to ignore symbols and spaces? I'll drop what I have so far for critique. Thank you for your time. meme1 = "I don't even know her like that" meme2 = "You can't just make a new meme from a different Spongebob clip every couple of months" meme3 = "I must have listened to that latest Ed Sheeran song 10000 times!" memeFIN1 = [""] * len(meme1) memeFIN2 = [""] * len(meme2) memeFIN3 = [""] * len(meme3) memeFIN1[1::2] = meme1[1::2].upper() memeFIN2[1::2] = meme2[1::2].upper() memeFIN3[1::2] = meme3[1::2].upper() memeFIN1[::2] = meme1[::2].lower() memeFIN2[::2] = meme2[::2].lower() memeFIN3[::2] = meme3[::2].lower() memeFIN1 = "".join(memeFIN1) memeFIN2 = "".join(memeFIN2) memeFIN3 = "".join(memeFIN3) print(memeFIN1) print(memeFIN2) print(memeFIN3) EDIT: All of the following solutions in the answers helped me come to my own, but none of them seemed to work entirely on their own. In cheesits solution, changing counter to start at 1 works, but not realizing that (as an utter noob) I did counters differently, essentially doing the same thing. This is the solution that worked for me: meme1 = "I don't even know her like that" meme2 = "You can't just make a new meme from a different Spongebob clip every couple of months" meme3 = "I must have listened to that latest Ed Sheeran song 10000 times!" def spongebobify(meme): count = 0 char = [] for ch in meme: if ch.isalpha() and count % 2 == 1: char.append(ch.upper()) count += 1 elif ch.isalpha(): char.append(ch.lower()) count += 1 else: char.append(ch) return ''.join(char) m1 = spongebobify(meme1) m2 = spongebobify(meme2) m3 = spongebobify(mem…
linked to: http://stackoverflow.com/q/49928375
answer count: 5
has comment: http://stackoverflow.com/comment/86879887
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/49932027
has answer: http://stackoverflow.com/a/49932160
has title: Upper case characters every other character but ignoring symbols and spaces
accepted answer: http://stackoverflow.com/a/49932011
has comment: http://stackoverflow.com/comment/87632603

http://stackoverflow.com/a/49974184
type: Answer
answers question: http://stackoverflow.com/q/49969284
has comment: http://stackoverflow.com/comment/101797095
has comment: http://stackoverflow.com/comment/86968786
downvote count: 0
upvote count: 1
has body: Do you want to get the link('https://lrc-nct.nixcdn.com/2018/02/21/f/b/1/1/1519207822262.lrc')? you can convert the xml content to string and use regular expression to extract the link. re= re.findall('&lt;lyric&gt;&lt;!\[CDATA\[(.*)\]\]&gt;&lt;/lyric&gt;',XMLstring)
score: 1

http://stackoverflow.com/comment/87000097
has text: I am also new to pygame and stackoverflow, so if you have any tips of how I should reformat or reword the question or code to be clearer that would be helpful for future questions. Thank you.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49991443

http://stackoverflow.com/comment/87101552
type: Comment
has text: @DeepSpace Hey nice I like it :). Only works if `p(c)` returns a Boolean type though (True/False)
type: AnswerComment
comment on: http://stackoverflow.com/a/50042680
score: 0

http://stackoverflow.com/q/49998426
answer count: 1
tagged with: maya
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50001477
tagged with: python
accepted answer: http://stackoverflow.com/a/50001477
has title: Instancing maya objects with a sequential suffix, object name string not seen by cmds.instance
has body: I have a question about string usage in lists in python for Maya. I am writing a script meant to take a selected object, then instance it 100 times with random translate, scale, and orient attributes. The script itself works and does what it's meant to, however I'm not being able to decipher how to instance the objects with the original object name, and then add a suffix that ends with "_instance#", where # assigns 1, 2, 3, etc. in order to the copies of the original mesh. This is where I'm at so far: #Capture selected objects, sort into list thing = MC.ls(sl=True) print thing #Create instances of objects instanceObj = MC.instance(thing, name='thing' + '_instance#') This returns a result that looks like "thing_instance1, thing_instance2". Following this, I figured the single quote around the string for the object was causing it to just name it "thing", so I attempted to write it as follows MC.instance(thing, name=thing + '_instance1' I guess because instance uses a list, it's not accepting the second usage of the string as valid and returns a concatenate error. I've tried rewriting this a few times and the closest I get is with instanceObj = MC.instance(thing) which results in a list of (pCube1,2,3,4), but is lacking the suffix. I'm not sure where to go from here to end up with a result where the instanced objects are named with the convention "pCube1_instance1, pCube1_instance2" etc. Any assistance would be appreciated.

http://stackoverflow.com/q/50067437
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50102721
tagged with: peewee
answer count: 1
has title: How to get values from `ForeignKeyField` using peewee in join query?
tagged with: python
type: Question
tagged with: python-3.x
tagged with: database
has body: I have models like this (peewee 2.10): class LegalAct(Model): start_date = DateField() expiration_date = DateField() class SomeModel(Model): name = CharField() legal_act = ForeignKeyField(LegalAct) class OtherModel(Model): name = Charfield() some_model = ForeignKeyField(SomeModel) starting_legal_act = ForeignKeyField(LegalAct) closing_legal_act = ForeignKeyField(LegalAct) class ExtraModel(Model): value = IntegerField() other_model = ForeignKeyField(OtherModel) starting_legal_act = ForeignKeyField(LegalAct) closing_legal_act = ForeignKeyField(LegalAct) Given list of SomeModle.ids and a date (to filter LegalAct) I want to get following data: SomeModel.name OtherModel.name OtherModel.starting_legal_act.start_date ExtraModel.starting_legal_act.start_date ExtraModel.value The issue is that I'm can't figure out how to traverse to OtherModel.starting_legal_act.start_date and ExtraModel.starting_legal_act.start_date - I only able to get id of the corresponding models and fetch the data in consequence queries. My current code is like this: other_model_legal_act = get_other_legal_act(date) # a query extra_model_legal_act = get_extra_legal_act(date) # a query data = OtherModel.select( SomeModel.name OtherModel.name OtherModel.starting_legal_act.alias('date_1') # I get `id`, but want date ExtraModel.starting_legal_act.alias('date_2') # I get `id`, but want date ExtraModel.value ).join(SomeModel).switch(OtherModel).join(ExtraModel).where( (OtherModel.legal_act == other_model_legal_act) &amp; (ExtraModel.legal_act == extra_model_legal_act) &amp; (SomeModel.id.in_(id_list)) ) I need to replace these lines with code that will return actual dates instead of record ids: OtherModel.starting_legal_act.alias('date_1') # I get `id`, but want date ExtraModel.starting_legal_act.alias('date_2') # I get `id`, but want date
accepted answer: http://stackoverflow.com/a/50102721

http://stackoverflow.com/q/49946536
upvote count: 1
has body: Was doing something this morning and thought this was weird. Why am I able to do this? I would think this should bounce back saying there is no rank attribute. class EmployeeClass(object): __status = None def __init__(self, status): self.__status = status def get_status(self): return self.__status def set_status(self, status): self.__status = status John_Smith = EmployeeClass("Employed") John_Smith.rank = 'Director' print(John_Smith.rank) This actually runs and returns "Director" to me. I don't quite understand that, this line should fail shouldn't it? John_Smith.rank = 'Director'
favorite count: 0
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/12569018
tagged with: oop
has title: Python3 set nonexistent attribute
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/12569018
downvote count: 0

http://stackoverflow.com/q/50002974
score: 2
has answer: http://stackoverflow.com/a/50016051
has title: discord.py remove_roles isn't working
has body: I have a bot for auto permissions for Fortnite KD Ranking. It works like; If user have 1+ KD bot will assign the user "Bronz" perm. If user have 1.5+ KD bot will assign the user "Gümüş" perm. If user have 2+ KD bot will assign the user "Altın" perm. and it works like a charm. BUT. Bot must be remove the old role when it ranking up the next perm. So I mean, if a user rank up the "Altın" perm. The old perm "Gümüş" must be removed but remove.roles is not working. Here is bunch of codes for those lines: for list in LISTE: roles = discord.utils.get(message.server.roles, name=list) await client.remove_roles(message.author, role) await client.add_roles(message.author, role) elif ratio &gt;= BRONZE_B and ratio &lt;= BRONZE_E: role = discord.utils.get(message.server.roles, name=LISTE[2]) embed=discord.Embed(color=0xcd8032) embed.add_field(name="Oyuncu", value=username, inline=True) embed.add_field(name="KD", value=str(ratio), inline=True) embed.add_field(name="Lig", value=LISTE[2], inline=True) await client.send_message(message.channel, embed = embed) embed2=discord.Embed(color=0x727272) embed2.add_field(name="Sonraki Lig", value=LISTE[3], inline=True) embed2.add_field(name="Hedef KD", value=str(SILVER_B), inline=True) embed2.set_footer(text="Lig verileriniz Fortnite KD değerlerinize göre güncellendi.") await client.send_message(message.channel, embed = embed2) for list in LISTE: roles = discord.utils.get(message.server.roles, name=list) await client.remove_roles(message.author, role) await client.add_roles(message.author, role) elif ratio &gt;= SILVER_B and ratio &lt;= SILVER_E: role = discord.utils.get(message.server.roles, name=LISTE[3]) embed=discord.Embed(color=0x727272) embed.add_field(name="Oyuncu", value=username, inline=True) embed.add_field(name="KD", value=str(ratio), inline=True) embed.add_field(name="Lig", value=LISTE[3], inline=True) await client.send_message(message.channel, embed = embed) embed2=discord.Embed(color=0xcfb223) embed2.add_field(name="Sonraki Lig…
has answer: http://stackoverflow.com/a/69174572
tagged with: discord
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: discord.py
type: UnansweredQuestion
upvote count: 3
tagged with: python
tagged with: python-requests
downvote count: 1

http://stackoverflow.com/a/50051765
has body: The log shows you do not have proper permissions to access the file. try changing the permissions first
type: Answer
answers question: http://stackoverflow.com/q/50051606
score: 0

http://stackoverflow.com/comment/86873021
type: QuestionComment
has text: Do your training iterations have a sequential relationship with one another, like in a recurrent network? If so, you should use that type of model explicitly and evaluate a loss function on a sequence of output. If not, then this seems strictly worse than standard momentum-based optimization methods, which update gradients in a way that takes into account previously computed gradients from previous examples. Your method would arbitrarily bundle groups of training instances for purposes of the loss. Perhaps you can elaborate on why that is appropriate in your model?
score: 1
comment on: http://stackoverflow.com/q/49928337
type: Comment

http://stackoverflow.com/q/50023869
type: Question
has answer: http://stackoverflow.com/a/50033027
has title: Script directory not included in sys.path when a ._pth is in use
score: 9
upvote count: 9
has answer: http://stackoverflow.com/a/65333056
linked to: http://stackoverflow.com/q/8663076
tagged with: python
type: AnsweredQuestion
answer count: 3
has body: I am attempting to solve a weird issue related to importing modules in a Python script I have written. The file that implements the module is in the same directory as the main Python script. The Python script works perfectly when I use ActivePython. However, when I use the Embedded Distribution I get the following error. ModuleNotFoundError: No module named 'pyWhich' I have traced the difference in behavior to the way the sys.path veritable is set in the Embedded Distribution. In ActivePython, the environment in which my script works, the first entry in sys.path is the directory containing the script. In the Embedded Distribution, there is no entry for the directory containing the script. The Embedded Distribution uses a _pth file to set the sys.path. I am using the default ._pth file, which I have included below for your convenience. python36.zip . # Uncomment to run site.main() automatically #import site My question is, what magical incantation do I need to add to my _pth file to tell Python to please put the directory containing any script I run in sys.path so my scripts will work with the Embedded Distribution. The documentation on path configuration files does not seem to contain this information.
downvote count: 0
tagged with: pth
possible better answer: http://stackoverflow.com/a/50024385
accepted answer: http://stackoverflow.com/a/50033027
has answer: http://stackoverflow.com/a/50024385
favorite count: 0

http://stackoverflow.com/q/50074446
has title: Functional programming vs list comprehension
downvote count: 0
has comment: http://stackoverflow.com/comment/87165364
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50074980
tagged with: python-itertools
has answer: http://stackoverflow.com/a/55303230
tagged with: python
has comment: http://stackoverflow.com/comment/87165715
score: 4
has answer: http://stackoverflow.com/a/50075341
has body: Mark Lutz in his book "Learning Python" gives an example: &gt;&gt;&gt; [(x,y) for x in range(5) if x%2==0 for y in range(5) if y%2==1] [(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)] &gt;&gt;&gt; a bit later he remarks that 'a map and filter equivalent' of this is possible though complex and nested. The closest one I ended up with is the following: &gt;&gt;&gt; list(map(lambda x:list(map(lambda y:(y,x),filter(lambda x:x%2==0,range(5)))), filter(lambda x:x%2==1,range(5)))) [[(0, 1), (2, 1), (4, 1)], [(0, 3), (2, 3), (4, 3)]] &gt;&gt;&gt; The order of tuples is different and nested list had to be introduced. I'm curious what would be the equivalent.
answer count: 4
possible better answer: http://stackoverflow.com/a/50074980
accepted answer: http://stackoverflow.com/a/50074832
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/50074832
tagged with: list
tagged with: functools

http://stackoverflow.com/comment/87018937
score: 3
comment on: http://stackoverflow.com/q/50001446
type: Comment
type: QuestionComment
has text: have you tried `import bs4`?

http://stackoverflow.com/q/49930114
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49930420
upvote count: 5
tagged with: qml
tagged with: python
has body: From PyQt5 i want to write values into qml. This values change dynamically. For example it in rectangle text value is filed from Pyqt5 Rectangle { width: 75 height: 75 text { values from PyQt5 } }
has title: How to set values in qml using PyQt5?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49930420
score: 5
downvote count: 0
tagged with: pyqt

http://stackoverflow.com/comment/86878911
type: Comment
type: QuestionComment
score: 0
has text: im meant to do a bar plot on probability for each alphabet character
comment on: http://stackoverflow.com/q/49931376

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/49955595
tags question: http://stackoverflow.com/q/49933952

http://stackoverflow.com/a/50125172
type: Answer
has body: I think it would help to see your current mock to edit. In general, this is how I would mock the pymongo collection.find() as a standalone function. test_dao.py import unittest import mock from mock import Mock import pymongo class Test_Dao(unittest.TestCase): """ Set up the mock """ @classmethod @mock.patch('pymongo.collection') def setUpClass(self, mock_mongo): a = Mock() a.find.side_effect = self.findResponse # Assign side effect for mocked method mock_mongo.return_value = a # Importing pymongo.collection returns the mock """ Response Data """ findResponse = 'some data' def test_my_call(): result = dao.my_call() assert result == list() ... In your case that is worth a try but might not work because you are calling collection.find() from a variable. You may need to mock the MongoClient() such that db_name has a side_effect to return a fake class. Then the fake class would need a collection.find() method you define. That would be a little longer and look a little bit like this: class FakeCollection: def find: return 'data' class FakeDatabase: def collection: return FakeCollection() ... @classmethod @mock.patch('pymongo.MongoClient') def setUpClass(self, mock_mongo): a = Mock() a.db_name.side_effect = self.dbResponse mock_mongo.return_value = a dbResponse = FakeDatabase()
score: 0
answers question: http://stackoverflow.com/q/50010742

http://stackoverflow.com/a/66926471
downvote count: 0
answers question: http://stackoverflow.com/q/49988848
type: Answer
upvote count: 2
score: 2
has body: I guess you are looking for: f, axarr = plt.subplots(2, 3, sharey='row') From the docs, pass these values to sharex or sharey: row: each subplot row will share an x- or y-axis. col: each subplot column will share an x- or y-axis.

http://stackoverflow.com/comment/87039534
type: AnswerComment
comment on: http://stackoverflow.com/a/49932877
score: 0
has text: I haven't really used scrapy myself, but I think you can use scrapy.request() to load a page. Just loop that until you find the element you need. Let me know if it works.
type: Comment

http://stackoverflow.com/comment/87082450
type: QuestionComment
has text: Why are you converting box_coord into a string? I'd have thought the original array would be better, because it should be serialized into a JSON array, and I guess that's what the API wants.
score: 0
comment on: http://stackoverflow.com/q/50032822
type: Comment

http://stackoverflow.com/comment/120087734
has text: Alternatively `conn.autocommit = True` before connection would do a job as well
score: 2
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50070904

http://stackoverflow.com/q/49959630
has body: Before reading, please read this question In the linked question I asked the fastest way to create a "list-like object" that contains a lot of variables of a simple datatype. The best answer told me to use the array module and it worked wonderfully! Here's a sample code of how it works: from array import array a = array('i', (0,)) * 10 ** 8 But now I have a problem ... I don't want to store just integers ... I want to store my own instances of a class I coded. The class can be a 'Point' class: class Point: def __init__(s, x, y): s.x = x s.y = y def dist_from_origin(s): return s.x ** 2 + s.y ** 2 What if I wanted to make an array object containing as default for each index Point(0, 0) ? Is that possible? If not, are there alternatives to the array object that are as fast as it? Please don't include in your answer the fact that I could do one array containing the 'x' values and another one containing the 'y' values since this is not a good practice... Here's how I tried to solve the problem: from ctypes import Structure, c_int class Point(Structure): _fields_ = [('x', c_int), ('y', c_int)] p_arr = (Point * 10 ** 8)() # takes 0.5 sec (slow) My solution may be simpler in code than a solution with the array module (if it exists) but it is VERY slow. Before answering remember that my goal is to have a FAST solution, and not a beautiful one. Also, I'm not allowed to use any external modules (modules that need to be installed), like numpy.
has comment: http://stackoverflow.com/comment/86936097
has comment: http://stackoverflow.com/comment/86936347
has comment: http://stackoverflow.com/comment/86935828
has comment: http://stackoverflow.com/comment/86935856
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86935624
has comment: http://stackoverflow.com/comment/86935928
has comment: http://stackoverflow.com/comment/86935615
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86935672
linked to: http://stackoverflow.com/q/49956644
tagged with: python
has comment: http://stackoverflow.com/comment/86935775
has comment: http://stackoverflow.com/comment/86936185
has comment: http://stackoverflow.com/comment/86935691
has title: Store your own objects in python
downvote count: 1
has comment: http://stackoverflow.com/comment/86935907

http://stackoverflow.com/a/50017153
type: Answer
has comment: http://stackoverflow.com/comment/87050685
type: AcceptedAnswer
has body: Can you set utf-8 encoding before this code ? it's working fine for me. # -*- coding: utf-8 -*-
accepted answer of: http://stackoverflow.com/q/50016752
score: 0
answers question: http://stackoverflow.com/q/50016752

http://stackoverflow.com/comment/87242110
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50070863
has text: oh ok! I see it now. It is a breadth first approach. I went for depth first.
score: 0

http://stackoverflow.com/a/50068924
has comment: http://stackoverflow.com/comment/87154337
has body: You can levarege list comprehensions, join and zip: te1 = "12345" te2 = "6789XYZ" print (''.join( ''.join(x) for x in zip(te1,te2)) + (te1[len(te2):] if len(te1)&gt;len(te2) else te2[len(te1):])) # ^^^^ this part adds the remainer of longer list to result output: 162738495XYZ https://docs.python.org/3/library/functions.html#zip https://docs.python.org/3/library/stdtypes.html#str.join Explanation: zip pairs up the characters by position, the rest makes the list of pairs back into a string. Zip only works for the shorter length string - you can switch to itertools.zip_longest (see JimDennis answer) or append the longer lists part (like I did here) itertools.zip_longest(*iterables, fillvalue=None)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50068837
upvote count: 2
has comment: http://stackoverflow.com/comment/87154318
has comment: http://stackoverflow.com/comment/87154329
has comment: http://stackoverflow.com/comment/87154268
downvote count: 0

http://stackoverflow.com/q/49974359
upvote count: 1
tagged with: django
favorite count: 0
tagged with: sockets
score: 1
has answer: http://stackoverflow.com/a/49976030
tagged with: python
has body: I am using python 3 and Django 1.9 and frontend is android. I have to provide 2 connections one is via API so that user can use UI and send the his/her details to backend; second, socket connection for receiving Hardware details, failure logs and sending updates to app. Below is my Socket server. import socket, ssl, json from threading import Thread, active_count from socketserver import ThreadingMixIn #from serializers import create_log_entry # Multithreaded Python server : TCP Server Socket Thread Pool class ClientThread(Thread): def __init__(self,ip,port,conn): Thread.__init__(self) self.ip = ip self.port = port self.conn = conn print ("[+] New server socket thread started for " + ip + ":" + str(port), active_count() ) def run(self): connstream = ssl.wrap_socket(self.conn, server_side=True, certfile="/home/ubuntu/workspace/logs/server.crt", keyfile="/home/ubuntu/workspace/logs/server.key") while True : data = connstream.read() print ("Server received data:", data) if data != b"" : data = json.loads(data.decode("utf-8")) else: print("Exiting loop") break print ("Server received data:", data) #create_log_entry(data) connstream.send("OK".encode("utf-8")) # echo # Multithreaded Python server : TCP Server Socket Program Stub TCP_IP = '0.0.0.0' TCP_PORT = 2005 BUFFER_SIZE = 20 # Usually 1024, but we need quick response def socket_server(): tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpServer.bind((TCP_IP, TCP_PORT)) threads = [] while True: tcpServer.listen(4) print ("Multithreaded Python server : Waiting for connections from TCP clients...") (conn, (ip,port)) = tcpServer.accept() newthread = ClientThread(ip,port,conn) newthread.start() threads.append(newthread) for t in threads: t.join() socket_server() But it is threaded and listen to particular port. I am calling socket_server() in a serializer file to start the server. This server use a method in serializer file which create entry in…
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Python Django - How to support Socket and APIs both

http://stackoverflow.com/comment/87066018
type: Comment
type: QuestionComment
has text: @pstatix well - you just do `rows.extend(r)` to consume the remainder of the file then `break` no ?
score: 0
comment on: http://stackoverflow.com/q/50024699

http://stackoverflow.com/comment/86881695
type: Comment
score: 0
has text: That's old API, no rml here, gonna take a look anyways, thanks
type: QuestionComment
comment on: http://stackoverflow.com/q/49931402

http://stackoverflow.com/comment/86891178
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49937749
type: Comment
has text: @Ev.Kounis Saw your comment after my edit! I noticed that right after I wrote my answer as well.

http://stackoverflow.com/comment/86875410
type: Comment
has text: Have you analyzed the cases that it gets wrong? Going through the error cases by hand in detail will often reveal issues in the data that you weren't aware of. It may also give you direction in which path to take towards improvement.
type: QuestionComment
comment on: http://stackoverflow.com/q/49927619
score: 0

http://stackoverflow.com/a/49928660
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/86873760
answers question: http://stackoverflow.com/q/49928463
upvote count: 3
has comment: http://stackoverflow.com/comment/86873582
downvote count: 0
has body: You can use pd.Series.where on the result of left-joining df1 and df2 merged = df1.merge(df2, on=['Code', 'Name'], how='left') df1.Value = merged.Value_y.where(~merged.Value_y.isnull(), df1.Value) &gt;&gt;&gt; df1 Code Name Value 0 1 Company1 200.0 1 2 Company2 1000.0 2 3 Company3 400.0 You can change the line to df1.Value = merged.Value_y.where(~merged.Value_y.isnull(), df1.Value).astype(int) in order to return the value to be an integer.

http://stackoverflow.com/comment/86962148
has text: what did you name the script that you saved? `'main.py': [Errno 2] No such file or directory'` suggests your script is not named `main.py`, so whatever the script name, replace `main.py` with the name of your python script
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49972413

http://stackoverflow.com/a/50043969
has comment: http://stackoverflow.com/comment/87157995
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87130629
accepted answer of: http://stackoverflow.com/q/50026260
answers question: http://stackoverflow.com/q/50026260
type: Answer
score: 0
has body: to see a description in WinPython Control Panel, add it manually in your ...\python-3.6.5.amd64\Lib\site-packages\winpython\data\packages.ini file. there is now official/mandatory description included in an installed package, the closest workaround would be to do "pip search your_package" to get the description of "your_package" from pypi see https://pip.pypa.io/en/stable/reference/pip_search/ ... maybe pip show is even better: C:&gt;pip show winpython Name: winpython Version: 1.10.20180404 Summary: WinPython distribution tools, including WPPM Home-page: http://winpython.github.io/ Author: Pierre Raybaut Author-email: pierre.raybaut@gmail.com License: MIT

http://stackoverflow.com/a/50069648
score: 1
upvote count: 1
has body: I finally found something that worked: Keyboard This successfully sent keystrokes, including modifiers, to a Citrix application. To send CTRL-SPACE as described above is as easy as Keyboard.send('ctrl-space'). Hope this helps someone!
accepted answer of: http://stackoverflow.com/q/50029691
answers question: http://stackoverflow.com/q/50029691
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/127373935
downvote count: 0

http://stackoverflow.com/q/50042209
accepted answer: http://stackoverflow.com/a/50042264
downvote count: 1
tagged with: multi-index
possible better answer: http://stackoverflow.com/a/50042497
favorite count: 0
type: Question
has title: pandas: Selecting index and then columns on multiindex slice
has answer: http://stackoverflow.com/a/50042497
has body: I have a pandas dataframe with a multiindex of 2 levels, and four data columns, and I want to select, first some indices of both levels, and then certain columns. However, I do not find a way to do it. Let me illustrate with an example: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; a = pd.MultiIndex.from_arrays(np.array([np.repeat([1, 2], 6), np.tile(np.repeat(["a", "b", "c"], 2), 2)] ) ) &gt;&gt;&gt; df = pd.DataFrame(np.random.randn(12,4), index=a, columns=list('ABCD')) &gt;&gt;&gt; df A B C D 1 a 0.688481 -2.380630 1.586150 0.008736 a 0.481300 1.276254 -0.159889 0.568995 b -0.250297 -0.161532 -1.099416 0.362548 b -0.588712 0.403857 -0.573104 1.420252 c -1.026832 -1.297500 -0.084957 0.072306 c -0.262771 0.865048 -0.278121 -1.406952 2 a -0.873142 -0.871211 -1.790412 1.073330 a -2.252715 1.772763 1.784698 1.716706 b 1.108562 -0.622361 0.036408 1.170411 b -0.157282 -0.660653 -1.230480 -0.295144 c -0.241862 -0.471965 0.363945 0.125543 c -0.396109 0.245829 0.544339 -0.957016 So I am able to do this: &gt;&gt;&gt; df.loc["1","a"] A B C D 1 a 0.688481 -2.380630 1.586150 0.008736 a 0.481300 1.276254 -0.159889 0.568995 And this: &gt;&gt;&gt; df.loc[:,["A","B"]] A B 1 a 0.688481 -2.380630 a 0.481300 1.276254 b -0.250297 -0.161532 b -0.588712 0.403857 c -1.026832 -1.297500 c -0.262771 0.865048 2 a -0.873142 -0.871211 a -2.252715 1.772763 b 1.108562 -0.622361 b -0.157282 -0.660653 c -0.241862 -0.471965 c -0.396109 0.245829 And even this: &gt;&gt;&gt; df.loc["1","a"]["A"] 1 a 0.688481 a 0.481300 Name: A, dtype: float64 But when I do either of these: &gt;&gt;&gt; df.loc["1","a",["A","B"]] &gt;&gt;&gt; df.loc["1","a"]["A","B"] I get an error. What I want to obtain is this: A B 1 a 0.688481 -2.380630 a 0.481300 1.276254 I am new to pandas, and I am sure this is quite a basic question, but I cannot find an answer. Thanks!
has answer: http://stackoverflow.com/a/50042264
tagged with: python
tagged with: slice
tagged with: numpy
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas
upvote count: 1

http://stackoverflow.com/q/50057530
tagged with: python
score: -1
downvote count: 1
has body: I wanted to take some suggestion and learn the reason of getting "No module found error" for pyshark module. I installed it however I'm still getting error. You can see short record below. https://asciinema.org/a/MHAX4PeIg5yWSm40KcYqWQBDi Thanks in advance
tagged with: pyshark
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50057568
upvote count: 0
type: UnansweredQuestion
has title: What is the reason of "No module found error" for pyshark module?

http://stackoverflow.com/q/49958149
tagged with: for-loop
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86932558
tagged with: python
linked to: http://stackoverflow.com/q/1207406
has title: Python For loop not running each item?
answer count: 0
has body: If I run this code: a = ['bob','bob','bob','bob','bob','bob','bob'] b = ['bob'] for item in a: if item in b: a.remove(item) I expect all the 'bob's to be removed, but there are 3 'bob's left. I don't understand. Someone please enlighten me, I think I may be losing my mind.
score: 1
duplicate of: http://stackoverflow.com/q/1207406
has comment: http://stackoverflow.com/comment/86932824
upvote count: 1
has comment: http://stackoverflow.com/comment/86932843
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86932711

http://stackoverflow.com/q/50029347
has title: Plot with seaborn after groupby command in pandas
tagged with: python
has body: I have grouped a list using pandas and I'm trying to plot follwing table with seaborn: B A bar 3 foo 5 The code sns.countplot(x='A', data=df) does not work (ValueError: Could not interpret input 'A'). I could just use df.plot(kind='bar') but I would like to know if it is possible to plot with seaborn.
has answer: http://stackoverflow.com/a/50029606
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50029561
favorite count: 0
type: Question
tagged with: seaborn
type: UnansweredQuestion

http://stackoverflow.com/a/49996860
type: Answer
has body: Your code would work if your series contained strings. As such, they likely contain lists, in which case you need to extract the first element. I would also utilise pd.Series.map instead of using any row-wise logic. Below is a complete example: df = pd.DataFrame({'emailDomain': [['gmail'], ['gmail'], ['gmail'], ['aol'], ['yahoo'], ['yahoo'], ['else']]}) domains = {'gmail', 'aol', 'outlook', 'hotmail', 'yahoo'} df['validEmailDomain'] = df['emailDomain'].map(lambda x: x[0]).isin(domains)\ .astype(int) print(df) # emailDomain validEmailDomain # 0 [gmail] 1 # 1 [gmail] 1 # 2 [gmail] 1 # 3 [aol] 1 # 4 [yahoo] 1 # 5 [yahoo] 1 # 6 [else] 0
score: 0
answers question: http://stackoverflow.com/q/49996676
has comment: http://stackoverflow.com/comment/87013872
has comment: http://stackoverflow.com/comment/87014024

http://stackoverflow.com/q/50048494
score: 1
downvote count: 0
has body: I'm trying to match/index a string filled with gaps. Can this be done with regex? Below is my current solution: test = 'abcd---efghi-j-k-l---mnopq-r--st-uvw-x-yz' def match_gaps(match_string, match_target): ms = match_string.replace('-','').index(match_target)+1 for c in range(len(match_string)): if match_string[c] != '-': ms -= 1 if ms == 0: endp = ms while len(match_string[c:endp].replace('-','')) &lt; len(match_target): endp += 1 return(match_string[c:endp]) print(match_gaps(test, 'klmno')) output: k-l---mno It just feels messy...
has answer: http://stackoverflow.com/a/50049751
favorite count: 0
possible better answer: http://stackoverflow.com/a/50049751
type: Question
tagged with: python-3.x
has title: Matching/indexing string filled with random gaps
answer count: 2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50048589
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50048589

http://stackoverflow.com/q/50073601
type: AnsweredQuestion
tagged with: keras-layer
score: 0
has title: Minibatch Learning with Concatenated Layers in Keras?
answer count: 1
has body: I have a model like this: img_rows = 32 img_cols = 32 img_channels = 3 img_input = Input(shape=(img_rows, img_cols, img_channels)) layer1 = Conv2D(16, (2, 2), padding='same', activation='relu')(img_input) layer2 = Conv2D(16, (2, 2), padding='same', activation='relu')(layer1) layer3 = MaxPooling2D((2, 2), strides=(2, 2), padding='same')(layer2) layer4 = Flatten()(layer3) laser_input = Input(shape=(100,)) merge_input = keras.layers.concatenate([layer4, laser_input]) layer5 = Dense(300, activation='relu')(merge_input) layer6 = Dense(200, activation='relu')(layer5) layer7 = Dense(100, activation='relu')(layer6) output = Dense(21, activation='softmax')(layer7) model = Model(inputs=[img_input, laser_input], outputs=output) optimizer = optimizers.RMSprop(lr=learningRate, rho=0.9, epsilon=1e-06) model.compile(loss="mse", optimizer=optimizer) model.summary() So as far as I understand, my model takes a list of two numpy arrays as input. Now I want to train this model on minibatch (of size 64) like this: model.fit(X_batch, Y_batch, batch_size=64, ...) How can I create X_batch, and what is the type of Xbatch? I think it is an array of lists, am I correct?
type: Question
has comment: http://stackoverflow.com/comment/87163812
has comment: http://stackoverflow.com/comment/87172640
tagged with: python
has comment: http://stackoverflow.com/comment/87179359
has answer: http://stackoverflow.com/a/50093267
accepted answer: http://stackoverflow.com/a/50093267

http://stackoverflow.com/q/49940930
has comment: http://stackoverflow.com/comment/86918055
has comment: http://stackoverflow.com/comment/86964369
upvote count: 3
has comment: http://stackoverflow.com/comment/86963632
has comment: http://stackoverflow.com/comment/86964084
answer count: 1
downvote count: 0
tagged with: hdfs
has comment: http://stackoverflow.com/comment/86963721
has comment: http://stackoverflow.com/comment/86965602
favorite count: 0
type: Question
tagged with: model
has body: I am trying to store my model to hdfs using python. This code is by using pydoop library import pydoop.hdfs as hdfs from_path = prediction_model.fit(orginal_telecom_80p_train[features], orginal_telecom_80p_train["Churn"]) to_path ='hdfs://192.168.1.101:8020/user/volumata/python_models/churn_model.sav' hdfs.put(from_path, to_path) But, while using this, I am getting this error AttributeError: 'LogisticRegression' object has no attribute 'startswith' Then I tried using the pickle option import pickle with open('hdfs://192.168.1.101:8020/user/volumata/python_models/') as hdfs_loc: pickle.dump(prediction_model, hdfs_loc) Pickle option is working fine in local, when i tried to store the model in hdfs, this option is also not working for me. Can anyone please suggest how to proceed further for storing the models to hdfs by using python script?
has comment: http://stackoverflow.com/comment/86963584
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86963759
has answer: http://stackoverflow.com/a/50371810
tagged with: python
has comment: http://stackoverflow.com/comment/86963975
has comment: http://stackoverflow.com/comment/86963690
tagged with: hadoop
has title: How to store model to hdfs using python

http://stackoverflow.com/comment/87055967
comment on: http://stackoverflow.com/q/50019588
has text: Personally in this situation I would use continue as it seems appropriate to use seeing as it’s a for loop.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86894075
comment on: http://stackoverflow.com/a/49939020
has text: Could you maybe try as well: `contents = to_unicode_or_bust(fd.read()).replace(search, replace)`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87185358
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50068417
has text: You're welcome, happy to help. If you feel that this answer solved your problem, please [mark it as 'accepted' by clicking the green check mark](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235).

http://stackoverflow.com/q/50013316
type: UnansweredQuestion
tagged with: pearson-correlation
tagged with: python
tagged with: statistics
score: 0
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87045326
has title: How to compute correlation of a pandas dataframe with NaN in it
has comment: http://stackoverflow.com/comment/87044762
has body: I computed the correlation of a DataFrame in pandas but why does it give NaN for correlation between columns 1 and 2 and 1 and 4, when there is a common element between columns 1 and 4.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87045568

http://stackoverflow.com/q/50016320
tagged with: extract
type: UnansweredQuestion
tagged with: file
has answer: http://stackoverflow.com/a/73917484
tagged with: python
has title: .Thumbdata3 file extraction. TypeError: a bytes-like object is required, not 'str'
has answer: http://stackoverflow.com/a/55736204
has body: I'm aware there are similar threads and I've gone through them, but they didn't help my case: A while ago I saved two .thumbdata3 files that are about 500mb in size each. This stackexchange thread claimed I could extract small jpegs from the files using a python script: #!/usr/bin/python """extract files from Android thumbdata3 file""" f=open('thumbdata3.dat','rb') tdata = f.read() f.close() ss = '\xff\xd8' se = '\xff\xd9' count = 0 start = 0 while True: x1 = tdata.find(ss,start) if x1 &lt; 0: break x2 = tdata.find(se,x1) jpg = tdata[x1:x2+1] count += 1 fname = 'extracted%d03.jpg' % (count) fw = open(fname,'wb') fw.write(jpg) fw.close() start = x2+2 However it returned this error: Traceback (most recent call last): File "... extract.py", line 15, in &lt;module&gt; x1 = tdata.find(ss,start) TypeError: a bytes-like object is required, not 'str' After searching around I thought the error might be between using 2.7 and 3.5 methodology, and changed the 'rb' in the f.open function to 'r' only to get this error: Traceback (most recent call last): File "...\Thumbdata\thumbadata extract.py", line 6, in &lt;module&gt; tdata = f.read() File "...\Anaconda3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 277960004: character maps to &lt;undefined&gt; It's worth mentioning that the script and the file are both in the same folder. I'm using Atom with a Python run package, as well as Anaconda3. Any help is appreciated.
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/87025725
type: AnswerComment
has text: The file appears as output of `filelist = os.listdir(BASE_FOLDER)`. I then tried to do `BASE_NAME = filelist[2]`, but it gives me error again! What a mystery...
comment on: http://stackoverflow.com/a/50000911
type: Comment
score: 0

http://stackoverflow.com/comment/87209713
score: 0
comment on: http://stackoverflow.com/a/50018563
type: Comment
has text: Here is paypal screenshots, why is there no info on amount and why is it preapproved without recurring info ? https://imgur.com/a/Sp7JdVC, anyway I emailed to paypal on this as well
type: AnswerComment

http://stackoverflow.com/q/50009947
upvote count: 4
type: AnsweredQuestion
tagged with: oop
has title: Is there any built in lambda for is notNone in python
tagged with: typing
answer count: 1
accepted answer: http://stackoverflow.com/a/50010052
downvote count: 1
favorite count: 0
type: Question
has body: I see the following idiom repeated several times in python X = filter(lambda x: x is not None, X)) I was hoping there is a builtin function for is not None(in its standard library or something similar to apache-commons for java) in python. In my code I have organized it as def isNotNone(X: Any) -&gt; bool: return True if X is not None else False X = filter(isNotNone, X)
score: 3
has comment: http://stackoverflow.com/comment/87036623
has comment: http://stackoverflow.com/comment/87036545
tagged with: python
has comment: http://stackoverflow.com/comment/87036561
has answer: http://stackoverflow.com/a/50010052
has comment: http://stackoverflow.com/comment/87036662

http://stackoverflow.com/comment/86890728
has text: "I'am new to coding", then SO is not the place to ask for teaching, find some tutorials for beginners, SO is about helping peoples who tried but can't make it work for some reasons. One can't become a pro from one day to another, and surely not while skipping the basics.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49937480
type: Comment

http://stackoverflow.com/q/50038057
has title: How to get weekly data from beginning of month using date_range of Pandas?
type: AnsweredQuestion
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50038143
accepted answer: http://stackoverflow.com/a/50038143
answer count: 1
tagged with: date-range
favorite count: 0
type: Question
downvote count: 0
tagged with: python
has body: I want to divide the date range starting from 1st July to 1st August, in weekly basis. But I want it to start from 1st day of the month. I am using pd.date_range('2015-07-01', '2015-08-01', freq='W' ) But I am getting DatetimeIndex(['2015-07-05', '2015-07-12', '2015-07-19', '2015-07-26'], dtype='datetime64[ns]', freq='W-SUN') I want this to be done from 2015-07-01. I know I can use timedelta or find the start day of the month and use W-WED. But is there any other shortcut to do the same using date_range of pandas? I have checked http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases, but could not come up with anything useful. Any help is appreciated. Thanks in advance.

http://stackoverflow.com/comment/131630816
type: Comment
comment on: http://stackoverflow.com/a/56424881
type: AnswerComment
score: 0
has text: You can go in and upvote the issue on changing the default https://github.com/pandas-dev/pandas/issues/43999

http://stackoverflow.com/comment/86958708
score: 0
type: AnswerComment
has text: Thanks. Your explanation was straightforward, simple, and it worked. After reading your suggestion I'd rather get rid of all the rows that have NaN. How would you recommend going about that?
comment on: http://stackoverflow.com/a/49971168
type: Comment

http://stackoverflow.com/comment/86943168
type: AnswerComment
has text: @user3294779 - Yes, sure.
comment on: http://stackoverflow.com/a/49963450
score: 0
type: Comment

http://stackoverflow.com/q/50002315
has body: I define a dictionaire containing some paramters to optimize with RandomizedSearchCV as follow import numpy as np from time import time from scipy.stats import randint as sp_randint from sklearn.model_selection import GridSearchCV from sklearn.model_selection import RandomizedSearchCV from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier # get some data digits = load_digits() X, y = digits.data, digits.target # build a classifier clf = RandomForestClassifier(n_estimators=20) # specify parameters and distributions to sample from param_dist = {"max_depth": [3, None], "max_features": sp_randint(1, 11), "min_samples_split": sp_randint(1, 11), "min_samples_leaf": sp_randint(1, 11), "bootstrap": [True, False], "criterion": ["gini", "entropy"]} # run randomized search n_iter_search = 20 random_search = RandomizedSearchCV(clf, param_distributions=param_dist, n_iter=n_iter_search) Now I would like to put the same parameters in a json file...is it possible? I created a json file as the one below { "max_depth": [3, null], "max_features": ?, "min_samples_split": ?, "min_samples_leaf": ?, "bootstrap": [true, false], "criterion": ["gini", "entropy"] } but I don't know how pass the parameters wiht "?"
has comment: http://stackoverflow.com/comment/87020963
tagged with: http://stackoverflow.com/tag/json
tagged with: grid-search
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/75144407
has comment: http://stackoverflow.com/comment/87021085
score: 0
has comment: http://stackoverflow.com/comment/87021009
has comment: http://stackoverflow.com/comment/87020907
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87021696
answer count: 1
has title: craete json configuration file to optimize parameters in RandomizedSearchCV
tagged with: scikit-learn

http://stackoverflow.com/a/66672044
score: -2
has comment: http://stackoverflow.com/comment/117859599
type: Answer
downvote count: 5
upvote count: 3
has body: If your proxy configration is OK, It may be because your pip version is too high. Try to lower your pip version python -m pip install pip==19.3.1 Then restart your terminal. You can try this method to see if it works
answers question: http://stackoverflow.com/q/49979354
has comment: http://stackoverflow.com/comment/117874957
has comment: http://stackoverflow.com/comment/117875140
has comment: http://stackoverflow.com/comment/117875790

http://stackoverflow.com/comment/129457230
has text: I am getting this error: ```NameError: name 'detection_graph' is not defined``` at this point: ```output_dict = run_inference_for_single_image(image_np, detection_graph)```. What should I do?
comment on: http://stackoverflow.com/q/49939018
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87057959
type: QuestionComment
comment on: http://stackoverflow.com/q/50020949
has text: https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects Check this, the `__eq__` and `__lt__` functions could solve the issue without lambda.
score: 0
type: Comment

http://stackoverflow.com/comment/87751304
comment on: http://stackoverflow.com/q/50033236
type: Comment
score: 0
has text: Possible duplicate of https://stackoverflow.com/questions/6312627/windows-7-how-to-bring-a-window-to-the-front-no-matter-what-other-window-has-fo
type: QuestionComment

http://stackoverflow.com/q/49957024
answer count: 1
has answer: http://stackoverflow.com/a/49957048
type: Question
has body: Error : AttributeError: 'BookForm' object has no attribute 'get'. im unable to debug the problem.please be helping out.thanks in advance forms.py from django import forms from .models import Book class BookForm(forms.Form): class Meta: model = Book fields = ['title', 'sub_title', 'author', 'image', 'price', 'description', 'ISBN', 'number_of_pages','dimensions', 'interior_pages','binding','availability','genre'] urls.py from django.urls import path from . import views urlpatterns = [ path('',views.BookForm, name = 'bookform' ), ] views.py from django.shortcuts import render,redirect from .forms import BookForm def bookview(request): if request.method == 'POST': form = BookForm(request.post) if form.is_valid(): model_instance = form.save() model_instance.save() return redirect('/') else: form = BookForm() return render(request,'book.html',{'myform':form}) template edit {% csrf_token %} {{form.as_p}}
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: AttributeError: 'BookForm' object has no attribute 'get'
accepted answer: http://stackoverflow.com/a/49957048
score: 0

http://stackoverflow.com/comment/120581438
type: AnswerComment
type: Comment
has text: It looks like this can be dangerous if the data is untrusted since it can execute code, I read it is recommended to use `ast.literal_eval` instead: https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval
score: 2
comment on: http://stackoverflow.com/a/63780901

http://stackoverflow.com/q/49974936
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86985052
has comment: http://stackoverflow.com/comment/87018110
favorite count: 0
type: Question
tagged with: pyqt4
tagged with: python
has comment: http://stackoverflow.com/comment/86979243
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50001090
has title: Using filepath without getting utf5 error
has body: Following code line produces an SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 57-58: malformed \N character escape: self.le1 = QLineEdit('\\S24014\\file.xlsx', self) This is a filepath, that I Need to Keep. Spyder Shows that \\S24014 is the Problem. The file has # -*- coding: utf-8 -*- at the top. How to solve the Problem? I am using Spyder 2 with Python 3.5 and PyQt4
tagged with: pyqt
has answer: http://stackoverflow.com/a/50001090
tagged with: spyder
answer count: 1

http://stackoverflow.com/q/50008508
has comment: http://stackoverflow.com/comment/87033556
tagged with: oop
has comment: http://stackoverflow.com/comment/87033545
upvote count: 0
accepted answer: http://stackoverflow.com/a/50008544
has answer: http://stackoverflow.com/a/50008541
duplicate of: http://stackoverflow.com/q/1535327
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7784148
linked to: http://stackoverflow.com/q/1535327
has title: I'm trying to add objects to an array in python and then print the contents of the array
possible better answer: http://stackoverflow.com/a/50008541
has body: import employee def main(): print('This program will create employee objects and store their information') print() ledger = [] numOfEmployees = int(input("Enter the number of employee's to enter: ")) for count in range(numOfEmployees): name = input("Enter employee's name: ") id_number = input("Enter employee's ID number: ") department = input("Enter employee's department: ") job_title = input("Enter employee's job title: ") count = employee.Employee(name, id_number, department, job_title) ledger.append(count) print("This is the list of employee's:") for person in ledger: print(person) main() the following is my employee module. I know making the ledger inside the module would make more sense but it seems like I should probably figure out how to do it an easier way before I try implementing that. class Employee: def __init__(self, name, id_number, department, job_title): self.__name = name self.__id_number = id_number self.__department = department self.__job_title = job_title def set_name(self, name): self.__name = name def set_id_number(self, id_number): self.__id_number = id_number def set_department(self, department): self.__department = department def set_job_title(self, job_title): self.__job_title = job_title def get_name(self): return self.__name def get_id_number(self): return self.__id_number def get_department(self): return self.__department def get_job_title(self): return self.__job_title the following is the output. This program will create employee objects and store their information Enter the number of employee's to enter: 1 Enter employee's name: adf Enter employee's ID number: afd Enter employee's department: asdf Enter employee's job title: asdf This is the list of employee's: &lt;employee.Employee object at 0x000001A96A92FF98&gt; I want it to actually print out the values and not just its location in memory... How can I do this?
tagged with: arrays
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50008544
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/49927952
has comment: http://stackoverflow.com/comment/86873159
favorite count: 0
has title: grouped by rolling means pandas
type: Question
linked to: http://stackoverflow.com/q/32012012
tagged with: pandas
has body: I need to calculate a rolling mean across data which is grouped by day. ID BC_DT BB_3M_DEFAULT_PROB REGION AA 27-Mar-18 0 Chicago BB 27-Mar-18 0.000002 Chicago CC 27-Mar-18 0.000003 Chicago DD 27-Mar-18 0.000006 Chicago AA 28-Mar-18 0 Dallas BB 28-Mar-18 0 New York CC 28-Mar-18 0.000005 Chicago DD 28-Mar-18 0.000004 Kansas City AA 29-Mar-18 0.000002 Chicago BB 29-Mar-18 0.000002 Chicago CC 29-Mar-18 0.000002 Kansas City DD 29-Mar-18 0.000005 Chicago AA 30-Mar-18 0.000002 Kansas City BB 30-Mar-18 0.019309 New York CC 30-Mar-18 0.000004 Dallas DD 30-Mar-18 0.000007 Chicago AA 31-Mar-18 0.000002 Dallas BB 31-Mar-18 0.000003 Dallas #Set BC_DT to datetime format. df_0['BC_DT'] = pd.to_datetime(df_0['BC_DT']) #Set BC_DT to be index. df_1 = df_1.set_index('BC_DT') #Sort index so we're in chronological order. df_1 = df_1.sort_index(axis=0, ascending=True) #Calculate a daily mean grouping by day. df_1['3M_DailyMean'] = df_1.groupby(df_1.index)['BB_3M_DEFAULT_PROB'].mean() Here's where I get tripped up. df_1['3M_SMA'] = df_1.groupby(df_1.index)['BB_3M_DEFAULT_PROB'].rolling(10, center=False).mean().reset_index(0, drop=True) I'm trying to group by date, then create a rolling mean with a span of 10 days. Anyone see where I'm tripping up? I'm expecting to have the rolling mean operate over days, so each date should have the same 'mean.' 2017-01-01 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 NaN 2017-01-02 0.001851 2017-01-02 0.001592 2017-01-02 0.001592 2017-01-02 0.001593 2017-01-02 0.001592 2017-01-02 0.001592 2017-01-02 0.001592 2017-01-02 0.000003 2017-01-02 0.000005 2017-01-02 0.000005 2017-01-02 0.000005 2017-01-02 0.000004 2017-01-02 0.000004
tagged with: python
has comment: http://stackoverflow.com/comment/86872185
has answer: http://stackoverflow.com/a/49929917
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49952518
has title: Trying to extract the source link of the first image of a google search using beautifulsoup4
has answer: http://stackoverflow.com/a/49952537
has answer: http://stackoverflow.com/a/68879468
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86924536
tagged with: python
linked to: http://stackoverflow.com/q/52970970
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86922424
has comment: http://stackoverflow.com/comment/86921977
has answer: http://stackoverflow.com/a/49954608
has comment: http://stackoverflow.com/comment/86921824
has body: I am trying to have a program that returns the image link for the first image of a google search. The link I am trying to get is if you were click the first image, right clicking the image that appears and then opening the image. The current code I have is. r = requests.get(theurl) soup = BeautifulSoup(r.text,"lxml") link = soup.find('img', class_='irc_mi')['src'] return link However I get a type error that says "TypeError: 'NoneType' object is not subscriptable".
type: Question
tagged with: beautifulsoup
tagged with: python-3.x

http://stackoverflow.com/q/49918346
accepted answer: http://stackoverflow.com/a/49919131
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86852201
has title: Check Previous Values in Numpy Array
has comment: http://stackoverflow.com/comment/86852927
has body: I'm trying to check the previous 90 values in an array (or upto the start of the array) to determine if a value already exists. So far my code just checks the previous value: overt = np.array([]) if frame ==0: overt = np.append(overt,lachange) else: pframe = frame - 1 plachange = overt[pframe] if lachange ==0: overt = np.append(overt,lachange) elif lachange ==1: if plachange == lachange: overt = np.append(overt,0) lachange = 0 else: overt = np.append(overt,lachange) The value is 1 if the vehicle has changed lane and 0 if it hasn't but if the value is 1 multiple times in a 3 second period I want only the first one to be recorded and the following values to be 0.
answer count: 1
has answer: http://stackoverflow.com/a/49919131
type: Question
tagged with: numpy
tagged with: python

http://stackoverflow.com/comment/86890691
comment on: http://stackoverflow.com/q/49936714
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169415/discussion-between-cherif-and-juanpa-arrivillaga).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86861685
score: 0
has text: No, the buttons are instances of `tk.Button`. `"Bonjour"`, `"Lundi"`, etc. are strings, not buttons.
type: Comment
comment on: http://stackoverflow.com/q/49922781
type: QuestionComment

http://stackoverflow.com/comment/86953331
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49968672
has text: Sorry, forgot to change the `open()` flag. I've updated the code.
type: Comment

http://stackoverflow.com/a/49995901
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87009368
has comment: http://stackoverflow.com/comment/87049079
has comment: http://stackoverflow.com/comment/87048431
answers question: http://stackoverflow.com/q/49994216
type: Answer
has body: The simplest thing to do is something like In [17]: def logf(x, eps=1e-6): ...: if abs(x) &lt; eps: ...: return -0.5 - x/3. ...: else: ...: return (1. + log1p(-x)/x)/x and play a bit with the threshold eps. If you want a numpy-like, vectorized solution, replace an if with a np.where &gt;&gt;&gt; np.where(x &gt; eps, 1. + log1p(-x)/x) / x, -0.5 - x/3.)

http://stackoverflow.com/a/50069381
type: AcceptedAnswer
has body: You should move that last open outside of the loop. You have a couple of bugs so I did some tidying... import csv chunk = set() for result in source: chunk.append(result) if len(chunk &gt;= 1000): with open('file.csv', 'a') as csvfile: csv.writer(csvfile).writerows([element] for element in chunk) chunk = set() if chunk: with open('file.csv', 'a') as csvfile: csv.writer(csvfile).writerows([element] for element in chunk) chunk = set() If you don't like writing the save logic twice, you can use two loops import csv chunk = set() source_iter = iter(source) have_data = True while have_data: for result in source_iter: chunk.append(result) if len(chunk &gt;= 1000): break else: have_data = False with open('file.csv', 'a') as csvfile: csv.writer(csvfile).writerows([element] for element in chunk) chunk = set()
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50068987
downvote count: 0
answers question: http://stackoverflow.com/q/50068987

http://stackoverflow.com/comment/87076906
type: Comment
type: QuestionComment
has text: Can you show some working example code demonstrating the problem and showing what you hope to accomplish?
score: 3
comment on: http://stackoverflow.com/q/50030414

http://stackoverflow.com/a/49973658
downvote count: 0
upvote count: 1
has body: When you do b = a, you simply creating a reference to the variable a and this reference is named b. A reference is just another name for the same object. You are not creating a copy of the variable a. Therefore, if you modify b, it modifies a as well and vice versa. However, if you do b = a[:], you are creating a shallow copy of the variable a and assigning it to a new variable called b. Since b is a copy, modifying either one of them, won't change the other. That is precisely why you get two different answers when printing b at the end.
answers question: http://stackoverflow.com/q/49973613
type: Answer
score: 1

http://stackoverflow.com/comment/87098304
comment on: http://stackoverflow.com/q/50041035
score: 0
type: Comment
has text: @pyrish, can you check if you have those headers in dataframe by checking df.columns?
type: QuestionComment

http://stackoverflow.com/comment/88080636
type: QuestionComment
score: 1
has text: I have the same problem under Win 10, Python 3.6.5 and setuptools 39.0.1 I am using a sample project as shown [here][1] somehow, I am not able to automatically put a `__main__.py` at the top level of the egg. I put the `__main__.py` besides the `setup.py` but it ends up being moved to the package, so it's location inside the `.egg` is `example_pkg/__main__.py` [1]: https://packaging.python.org/tutorials/packaging-projects/
type: Comment
comment on: http://stackoverflow.com/q/50062168

http://stackoverflow.com/comment/87008853
comment on: http://stackoverflow.com/q/49996216
type: Comment
has text: Why just not use Rust to save in a database and Python to read from the database ?
score: 1
type: QuestionComment

http://stackoverflow.com/q/49929284
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/79511681
accepted answer: http://stackoverflow.com/a/49930019
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/79511681
has answer: http://stackoverflow.com/a/49930019
has body: Is it possible to read the current flags that the display has been given? So when one calls pygame.display.set_mode(resolution, FLAGS), I'd love to read them afterwards. For example I'd like to have an is_fullscreen() function.
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: display
tagged with: pygame
has title: Reading pygame display's current flags (FULLSCREEN etc.)
favorite count: 0

http://stackoverflow.com/q/50004159
tagged with: group-by
tagged with: python
tagged with: merge
has body: I have two dataframes df1 KO-ST 1_UID 2_Vloge 0 1976-_ 200106897 200106897.0 1 991-_ 200108737 200108737.0 2 2147--- 200109776 200109776.0 3 2048-_ 200300912 200300912.0 4 2194-_ 200301057 200301057.0 5 2386--- 200301312 200301312.0 6 2002-_ 200301315 200301315.0 7 1324-_ 200301573 200301573.0 8 1625-45 200301868 200301868.0 9 1625-_ 200301868 200301868.0 ... df2 a b SID KO-ST 10000002 851-601 288.0 288.0 10000003 851-1 68.0 68.0 10000328 853-103 64.5 64.5 10000583 861-25 30.1 30.1 10001002 2590-1 96.7 178.9 10001004 2593-2 349.2 349.2 10001005 2593-3 282.0 295.2 10001006 2593-4 121.5 121.5 10001008 2593-6 109.3 110.3 10001009 2593-7 9.9 9.9 ... There is more than 500.000 rows, where KO-ST is unique and SID can be repeated. I am trying to group them and repeat the values from columns a and b. Values from KO-ST are unique and in 10 % cases - not perfect and this cases (e.g. 1324-___) there will be no matches in df2. My initial code is REN_ES = pd.merge(df1, df2, left_index=True, on = 'KO-ST') But i get an error: KeyError: 'KO-ST' Where did I get it wrong? df1 is a result from importing 2 csv files and combining and merging some values. For easier data treatment, column KO-ST was added as a combination of two columns with function: DS_STA['KO-ST'] =DS_STA['KO_SIFKO'].map(str) + "-" + DS_STA['STEV'].map(str) KO-SIFKO and STEV are integers, hence the code. I added this beacuse I'm suspecting there's something wrong with the recognition of data types.
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50004261
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50004261
has comment: http://stackoverflow.com/comment/87025006
type: Question
has title: Pandas merge problems
has comment: http://stackoverflow.com/comment/87024751

http://stackoverflow.com/a/50371810
type: Answer
has comment: http://stackoverflow.com/comment/87792627
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87785313
has comment: http://stackoverflow.com/comment/87800841
has body: You have to use hdfs.open instead of open, and open the file for writing: import pickle import pydoop.hdfs as hdfs with hdfs.open(to_path, 'w') as f: pickle.dump(prediction_model, f)
answers question: http://stackoverflow.com/q/49940930
has comment: http://stackoverflow.com/comment/87794954
score: 1

http://stackoverflow.com/q/50045353
type: Question
has title: Python Pandas sort by Time and group by user ID
accepted answer: http://stackoverflow.com/a/50046511
score: 5
has answer: http://stackoverflow.com/a/50046511
tagged with: http://stackoverflow.com/tag/csv
upvote count: 5
possible better answer: http://stackoverflow.com/a/50045412
tagged with: python
has body: I am loading a CSV file with pandas. It has three columns: a column with date and time, a column with a user id, and another 'campaignID'. Example rows: date user_id campaign_id 2018-01-10 0:21:09 151312395 GOOGLE 2018-01-10 0:21:19 151312395 GOOGLE 2018-01-10 0:21:32 151312395 GOOGLE I want to group the data by the user id, and then for each user id group the rows by time and the campaign ID, it should look as follows. user_id date ad_campaign 151312395 2018-01-10 0:21:09 GOOGLE 2018-01-10 0:21:19 GOOGLE 2018-01-10 0:21:32 GOOGLE This is what I have made until now: import pandas as pd import numpy as np import datetime def dateparse(time_in_secs): return datetime.datetime.fromtimestamp(float(time_in_secs)) columnnames = ['date','user_id', 'ad_campaign'] columnnames, sep='\t' ,usecols=[0,1,3],index_col = 'date') df=pd.read_csv(r'C:\Users\L\Desktop\Data.csv' , sep='\t',names = columnnames, usecols=[0,1,3], parse_dates=True,date_parser=dateparse) df.date = pd.to_datetime(df.date) df = df.sort_values(by = 'date') g = df.groupby('user_id')['ad_campaign'] print(g) This gives the following output: &lt;pandas.core.groupby.SeriesGroupBy object at 0x04EF26F0&gt; [Finished in 0.6s] Why doesnt the print provide the sorted columns?
type: AnsweredQuestion
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50045412
favorite count: 0

http://stackoverflow.com/comment/87041925
type: QuestionComment
has text: Can you paste all your traceback information when you got ?
score: 0
comment on: http://stackoverflow.com/q/50012754
type: Comment

ctypes
tags question: http://stackoverflow.com/q/50026454
tags question: http://stackoverflow.com/q/50054334
tags question: http://stackoverflow.com/q/49932140
tags question: http://stackoverflow.com/q/50002896
tags question: http://stackoverflow.com/q/49971443
tags question: http://stackoverflow.com/q/50043861
tags question: http://stackoverflow.com/q/50016217
tags question: http://stackoverflow.com/q/50020112
tags question: http://stackoverflow.com/q/49996416
tags question: http://stackoverflow.com/q/50033276
tags question: http://stackoverflow.com/q/49972924
tag name: ctypes
tags question: http://stackoverflow.com/q/50012275
type: Tag
tags question: http://stackoverflow.com/q/50003760
tags question: http://stackoverflow.com/q/50049225
tags question: http://stackoverflow.com/q/49973060
tags question: http://stackoverflow.com/q/49962265

http://stackoverflow.com/comment/87061162
score: 0
type: AnswerComment
has text: That's better! It'd be interesting to see how it compares speed wise to a solution that uses zip to iterate over a pair of lists, rather than indexing. For small data that's easy enough by doing eg `zip(L, L[1:])` but that's not so good for big data, since it copies `L`. But I guess you could do it with `islice`.
comment on: http://stackoverflow.com/a/50021844
type: Comment

http://stackoverflow.com/q/49964702
type: Question
tagged with: numpy
type: UnansweredQuestion
upvote count: 6
has body: I want to solve this differential equation: y′′+2y′+2y=cos(2x) with initial conditions: y(1)=2,y′(2)=0.5 y′(1)=1,y′(2)=0.8 y(1)=0,y(2)=1 and it's code is: import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def dU_dx(U, x): return [U[1], -2*U[1] - 2*U[0] + np.cos(2*x)] U0 = [1,0] xs = np.linspace(0, 10, 200) Us = odeint(dU_dx, U0, xs) ys = Us[:,0] plt.xlabel("x") plt.ylabel("y") plt.title("Damped harmonic oscillator") plt.plot(xs,ys); how can I fulfill it?
score: 6
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/63555684
tagged with: differential-equations
has title: python: Initial condition in solving differential equation
downvote count: 0
has answer: http://stackoverflow.com/a/49964927
tagged with: scipy
favorite count: 0

http://stackoverflow.com/a/49962982
accepted answer of: http://stackoverflow.com/q/49962913
has comment: http://stackoverflow.com/comment/86942006
answers question: http://stackoverflow.com/q/49962913
score: 0
has comment: http://stackoverflow.com/comment/86942014
type: AcceptedAnswer
has body: You can try this. It takes the input and inserts it into a new array: original_list = ["http://www.firstSite.com", "http://secondSite.com", "http://thirdSite.com", "http://www.fourthSite.com"] new_array = input("Choose some sites from %s. Separate each website by a space " % (original_list)).split() for site in new_array: #Checking if the sites entered by user are in the original_list if site not in original_list: print ("Error!") You can also use the index of a site to ask the user for input. Like this: original_list = ["http://www.firstSite.com", "http://secondSite.com", "http://thirdSite.com", "http://www.fourthSite.com"] user_input = input("Enter the indices of the websites in %s you choose separated by a space " % (original_list)).split() new_array = [original_list[x] for x in user_input] for site in new_array: #Checking if the sites entered by user are in the original_list if site not in original_list: print ("Error!") Both of these will create a list containing the sites that the user selected. It's hard to give you a clear solution as you don't provide what you are trying to accomplish. So, let me know if this works for you and if it doesn't, I'm happy to delete my answer.
has comment: http://stackoverflow.com/comment/86941984
has comment: http://stackoverflow.com/comment/86942074
type: Answer

http://stackoverflow.com/q/49931055
has title: TensorFlow model gets zero loss
tagged with: cross-entropy
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/49931591
favorite count: 0
has answer: http://stackoverflow.com/a/49931591
type: Question
has body: import tensorflow as tf import numpy as np import os import re import PIL def read_image_label_list(img_directory, folder_name): # Input: # -Name of folder (test\\\\train) # Output: # -List of names of files in folder # -Label associated with each file cat_label = 1 dog_label = 0 filenames = [] labels = [] dir_list = os.listdir(os.path.join(img_directory, folder_name)) # List of all image names in 'folder_name' folder # Loop through all images in directory for i, d in enumerate(dir_list): if re.search("train", folder_name): if re.search("cat", d): # If image filename contains 'Cat', then true labels.append(cat_label) else: labels.append(dog_label) filenames.append(os.path.join(img_dir, folder_name, d)) return filenames, labels # Define convolutional layer def conv_layer(input, channels_in, channels_out): w_1 = tf.get_variable("weight_conv", [5,5, channels_in, channels_out], initializer=tf.contrib.layers.xavier_initializer()) b_1 = tf.get_variable("bias_conv", [channels_out], initializer=tf.zeros_initializer()) conv = tf.nn.conv2d(input, w_1, strides=[1,1,1,1], padding="SAME") activation = tf.nn.relu(conv + b_1) return activation # Define fully connected layer def fc_layer(input, channels_in, channels_out): w_2 = tf.get_variable("weight_fc", [channels_in, channels_out], initializer=tf.contrib.layers.xavier_initializer()) b_2 = tf.get_variable("bias_fc", [channels_out], initializer=tf.zeros_initializer()) activation = tf.nn.relu(tf.matmul(input, w_2) + b_2) return activation # Define parse function to make input data to decode image into def _parse_function(img_path, label): img_file = tf.read_file(img_path) img_decoded = tf.image.decode_image(img_file, channels=3) img_decoded.set_shape([None,None,3]) img_decoded = tf.image.resize_images(img_decoded, (28, 28), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) img_decoded = tf.image.per_image_standardization(img_decoded) img_decoded = tf.cast(img_decoded, dty=tf.float32) label = tf.one_hot(label, 1) return img_decoded, la…
downvote count: 0
tagged with: python
answer count: 1
tagged with: conv-neural-network

http://stackoverflow.com/comment/86871827
score: 0
comment on: http://stackoverflow.com/q/49927690
type: Comment
has text: The `if "jrn." and "username" in line.lower()` doesn't do what (I think) you think it does. The first bit (`if "jrn."`) is always `True`.
type: QuestionComment

http://stackoverflow.com/a/49930003
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49929833
type: Answer
has comment: http://stackoverflow.com/comment/86956542
accepted answer of: http://stackoverflow.com/q/49929833
upvote count: 3
score: 3
downvote count: 0
has body: You could use Ajax or Websockets to display your result. However it also works the "normal" way you have implemented it. You should declare your button as a submit button to trigger the POST event. This will route you to the items() endpoint. Refresh To make sure each item will get shown only once you need to remove it from your list. @app.route("/items", methods=['GET', 'POST']) def items(): item = random.choice(items_list) items_list.remove(item) But then you should also think about what to do if no item is left anymore.

http://stackoverflow.com/comment/86988490
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49985942
has text: I would like to have the list of all possible combinations.

http://stackoverflow.com/comment/87058626
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50020640
has text: Possible duplicate of [Python Pandas Error tokenizing data](https://stackoverflow.com/questions/18039057/python-pandas-error-tokenizing-data) - please see if any of the answers there can help you out. You can easily find similar post by pasting **pandas.errors.ParserError: Error tokenizing data** into the search on SO.

http://stackoverflow.com/comment/86880147
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49932124
score: 0
has text: @chepner Still asking about the 99% :) `double` has been the standard for implementing floating-point numbers for a long time.

http://stackoverflow.com/comment/87079960
has text: Hi William, that was the point of the example. The 0 dimensional array was generate by `genfromtxt`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50031814
type: AnswerComment

http://stackoverflow.com/comment/86867330
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49925263
has text: @galaxyan my XML appeared in the previous question https://stackoverflow.com/questions/49792703/conditional-xml-parsing-in-python

http://stackoverflow.com/q/50045251
has comment: http://stackoverflow.com/comment/87137245
has comment: http://stackoverflow.com/comment/87107505
has comment: http://stackoverflow.com/comment/87110809
answer count: 0
has comment: http://stackoverflow.com/comment/87107774
type: UnansweredQuestion
has body: I would like to use datetime library to get current date -7 days. I started with the following incorrect code from google.appengine.ext import ndb from datetime import datetime, timedelta class ActivityCount(ndb.Model): last_login_date = ndb.DateTimeProperty(default=datetime.now()+timedelta(days=-7)) I know that because datetime.now() is being called when your module is initialised and that value is being used for the default. Hence I am not getting current date and solution for the same is created = models.DateTimeField(auto_now_add=True) However, I am not able to add +timedelta(days=-7) for the same. Can you please suggest how can do this ? Thanks in advance.
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87111000
has comment: http://stackoverflow.com/comment/87107568
favorite count: 0
has comment: http://stackoverflow.com/comment/87115064
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87134217
has title: datetime.now() is not setting current date
tagged with: python-datetime
tagged with: python

http://stackoverflow.com/comment/101400425
type: QuestionComment
has text: Google led me to this question when I also faced this error when trying to map(). The problem was I had square brackets around my dictionary: `pd.DataFrame({'x': [2, 3]})['x'].map([{2:'c', 3:'d'}])` (correct would be `pd.DataFrame({'x': [2, 3]})['x'].map({2:'c', 3:'d'})`)
score: 0
comment on: http://stackoverflow.com/q/49998740
type: Comment

http://stackoverflow.com/q/49976047
tagged with: xml-parsing
downvote count: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49982478
accepted answer: http://stackoverflow.com/a/49982478
type: AnsweredQuestion
score: 1
upvote count: 1
has title: add contents inside root tag of xml file
has comment: http://stackoverflow.com/comment/86982477
has body: I have one existing xml file and want to add some contents to it. Existing xml file: &lt;edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0"&gt; &lt;edmx:Reference Uri="/redfish/v1/Schemas/Resource_v1.xml"&gt; &lt;edmx:Include Namespace="Resource"/&gt; &lt;edmx:Include Namespace="Resource.v1_0_0"/&gt; &lt;edmx:Include Namespace="Resource.v1_0_2"/&gt; &lt;edmx:Include Namespace="Resource.v1_4_0"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:DataServices&gt; &lt;Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Service"&gt; &lt;EntityContainer Name="Service" Extends="ServiceRoot.v1_0_0.ServiceContainer"/&gt; &lt;/Schema&gt; &lt;/edmx:DataServices&gt; &lt;/edmx:Edmx&gt; Now I want to add the following contents without modifying contents of existing file My question is how to add contents of xml to existing file without modifying the contents of existing xml file inside this tag : &lt;edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0"&gt; I tried with this piece of code: new="""&lt;edmx:Reference Uri="/redfish/v1/Schemas/Chassis_v1.xml"&gt; &lt;edmx:Include Namespace="Chassis"/&gt; &lt;edmx:Include Namespace="Chassis.v1_0_0"/&gt; &lt;edmx:Include Namespace="Chassis.v1_0_1"/&gt; &lt;/edmx:Reference&gt;""" tree = ET.parse('metadata.xml') root = tree.getroot() ET.register_namespace('edmx','http://docs.oasis-open.org/odata/ns/edmx') ET.register_namespace('','http://docs.oasis-open.org/odata/ns/edm') root.text = new print ET.tostring(root,method="html") But output is: &lt;edmx:Edmx xmlns="http://docs.oasis-open.org/odata/ns/edm" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0"&gt;&amp;lt;edmx:Reference Uri="/redfish/v1/Schemas/Chassis_v1.xml"&amp;gt; &amp;lt;edmx:Include Namespace="Chassis"/&amp;gt; &amp;lt;edmx:Include Namespace="Chassis.v1_0_0"/&amp;gt; &amp;lt;edmx:Include Namespace="Chassis.v1_0_1"/&amp;gt; &amp;lt;/edmx:Reference&amp;gt;&lt;edmx:Reference Uri="/redfish/v1/Schemas/Resource_v1…
favorite count: 0
type: Question

http://stackoverflow.com/q/49939859
tagged with: stream
answer count: 1
has answer: http://stackoverflow.com/a/49940785
has title: Flask video stream using OpenCV images
has comment: http://stackoverflow.com/comment/86897240
has comment: http://stackoverflow.com/comment/86896016
has comment: http://stackoverflow.com/comment/86895783
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86896840
has body: I am trying to use Flask to show a stream of OpenCV images. I am using ROS and the Zed stereo camera. The issue is that the flask server only shows a broken image icon. I am guessing that the issue is in the gen() method because the cv2.imwrite('t.jpg', img) method is the wrong way to go. I have very little experience with OpenCV. The image data that the Flask server receives is an InputArray. I need a way of converting this and showing the image in the Flask server. I am using Python 2.7 and rospy (ROS). Any advice? UPDATE: The code for the ROS node accessing ZED cam: #!/usr/bin/env python # ROS imports import rospy from sensor_msgs.msg import Image # Utils import numpy as np import cv2 from cv_bridge import CvBridge, CvBridgeError import stream def callback(data): """ param data: data from zed/rgb/image_rect_color topic """ # convert from ROS sensor_msgs/Image to cv2 bridge = CvBridge() try: cv_img = bridge.imgmsg_to_cv2(data, desired_encoding='passthrough') stream.img = cv_img except CvBridgeError as e: print(e) # show image stream # cv2.imshow('zed', cv_img) # cv2.waitKey(3) def zed_sub(): # initialize ROS node 'zed_sub' rospy.init_node('zed_sub') # subscribe to the ROS topic 'zed/rgb/image_rect_color' rospy.Subscriber('zed/rgb/image_rect_color', Image, callback) # keep python from exiting until this node is stopped try: rospy.spin() except KeyboardInterrupt: cv2.destroyAllWindows() if __name__ == '__main__': zed_sub() The code for the Flask server: #!/usr/bin/env python from flask import Flask, render_template, Response import cv2 app = Flask(__name__) HOST = '192.168.1.3' # on-board computer's IP address PORT = 8080 img = None @app.route('/') def index(): return render_template('index.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') def gen(): """Video streaming generator function.""" global img while True: try: cv2.imwrite('t.jpg', img) yield(b'--frame\r\n' b'Content-Type: image/jp…
tagged with: ros
score: 10
accepted answer: http://stackoverflow.com/a/49940785
tagged with: python
tagged with: flask
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86896663
has comment: http://stackoverflow.com/comment/86896649
has comment: http://stackoverflow.com/comment/86896038
downvote count: 0
upvote count: 10

http://stackoverflow.com/comment/86983928
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49977615
has text: I edited the question as i have the some_func.py module and some_func method same. When i try to patch i'm doing @mock.patch('pkg.common.some_func.db_mysql'). But this is resulting in AttributeError: 'module' object has no attribute 'some_func'. I even have the __init__.py listed in the common directory.
type: Comment

http://stackoverflow.com/comment/87056288
comment on: http://stackoverflow.com/q/50019830
score: 0
type: Comment
type: QuestionComment
has text: Even if i do that, am unable to read last column

http://stackoverflow.com/comment/86931777
has text: Keys and tokens are tied to a particular account.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49957677
score: 1

http://stackoverflow.com/comment/86857174
score: 2
type: Comment
comment on: http://stackoverflow.com/a/49919339
type: AnswerComment
has text: I really like this answer ! To reduce its readibility tho i'll use : `[(r1['id'], r2['id']) for (_, r1), (_, r2) in itertools.combinations(df.iterrows(), 2) if (r1['rate'] == r2['rate'] or r1['name'] == r2['name'])]` in `add_edges_from`

http://stackoverflow.com/a/50027365
has comment: http://stackoverflow.com/comment/87073097
type: Answer
answers question: http://stackoverflow.com/q/49951795
has body: Initial assumption: I won't access data from a personal link for security reasons. It would be better if you could create a reproducible code snippet based solely on secure/persistent artifacts. However, I can confirm your problem happens when your code is ran against keras.datasets.mnist, with a small change: each sample is associated with a label 0: odd or 1: even. Short answer: you messed up the initialization. Change tf.random_uniform to tf.random_normal and set biases to a deterministic 0. Actual answer: ideally, you want the model to start predicting randomly, close to the 0.5. This will prevent the saturation of the sigmoid's output and result in large gradients in early stages of training. The sigmoid's eq. is s(y) = 1/(1 + e**-y), and s(y) = 0.5 &lt;=&gt; y = 0. Therefore, the layer's output y = w * x + b must be 0. If you used StandardScaler, then your input data follows a Gaussian distribution, mean = 0.5, std = 1.0. Your parameters must sustain this distribution! However, you've initialized your biases with tf.random_uniform, which uniformly draws values from the [0, 1) interval. By starting your biases at 0, y will be close to 0: y = w * x + b = sum(.1 * -1, .9 * -.9, ..., .1 * 1, .9 * .9) + 0 = 0 So your biases should be: biases = { 'b1': tf.Variable(tf.zeros([n_hidden_1])), 'b2': tf.Variable(tf.zeros([n_hidden_2])), 'output': tf.Variable(tf.zeros([n_output])) } This is sufficient to output numbers smaller than 0.5: [1. 0.4492423 0.4492423 ... 0.4492423 0.4492423 1. ] predictions mean: 0.7023628 confusion matrix: [[4370 1727] [1932 3971]] accuracy: 0.6950833333333334 Further corrections: Your neuralNetwork function does not take a biases parameter. It instead uses the one defined in the other scope, which seems like a mistake. You should not fit the scaler to the test data, because you will lose the statistics from train and because it violates the principle that that chunk of data is purely observational. Do this: scaler = StandardScaler() x_train = s…
has comment: http://stackoverflow.com/comment/87072010
has comment: http://stackoverflow.com/comment/87073334
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/86941991
type: AnswerComment
comment on: http://stackoverflow.com/a/49962862
has text: I have changed my Views.py and html as below, rest all codes are same def displayAlarmCount(request): sum_count = overallAccountDetail.objects.filter(marketName='MOAI',accountName='Idea').aggregate(Sum('Alarm_Count')) totalAlarmCount = sum_count['Alarm_Count__Sum'] #'WHERE marketName = %s and accountName = %s', account_filter) ctx = { 'totalAlarmCount': totalAlarmCount } return render_to_response('overallaccountdetail_filter.html', ctx, context_instance=RequestContext(request)) HTML {% block content %} {{ totalAlarmCount }} {% endblock %}
type: Comment
score: 0

http://stackoverflow.com/comment/86908951
type: QuestionComment
comment on: http://stackoverflow.com/q/49942360
has text: `wx.EXPAND | wx.ALL, 9)` should probably be `wx.EXPAND)` because the `wx.ALL, 9` part inserts a padding of 9 in ALL directions.
score: 1
type: Comment

python-sockets
tags question: http://stackoverflow.com/q/49956156
type: Tag
tag name: python-sockets

http://stackoverflow.com/comment/86919294
has text: Funny, I actually had that open, and yup that's where the data's coming from. Thank you for trying
type: Comment
comment on: http://stackoverflow.com/q/49951018
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86871517
has text: A little more work, but it might be worth reading each set of N lines into a simple class, check the members of each class instance to find the strings you are looking for, and then print all members of the instances that match.
type: Comment
comment on: http://stackoverflow.com/q/49927690
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86885322
comment on: http://stackoverflow.com/q/49932344
has text: add sample images. Typically you can try things like trained classifier detection, template matching an various other things, it really depends on your kind of data.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87161346
comment on: http://stackoverflow.com/a/50063211
type: Comment
has text: Yes, I appreciate that (CBC from ECB), although you could have done the same with pycryptodome's AES class in ECB mode. Again, the code looks great, I was just curious to know why you chose this method.
type: AnswerComment
score: 0

character-encoding
tags question: http://stackoverflow.com/q/49984954
tag name: character-encoding
tags question: http://stackoverflow.com/q/49983346
tags question: http://stackoverflow.com/q/49991870
type: Tag
tags question: http://stackoverflow.com/q/50032126

http://stackoverflow.com/comment/86939748
has text: Then it's just train with examples. Maybe that two branch idea you used could be good if the layers were multiplied? Like one layer with few parameters for the amplitude, another with many for the sinusoid? (That's specultation now)
comment on: http://stackoverflow.com/a/49959422
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49996676
has answer: http://stackoverflow.com/a/49996860
tagged with: python
has comment: http://stackoverflow.com/comment/87014525
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/87009982
tagged with: pandas
has title: Convert a string column to number in a dataframe
has answer: http://stackoverflow.com/a/49996815
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/49996815
has comment: http://stackoverflow.com/comment/87009867
has answer: http://stackoverflow.com/a/49996819
has body: I'm trying to convert a column in my DataFrame to numbers. The input is email domains extracted from email addresses. Sample: &gt;&gt;&gt; data['emailDomain'] 0 [gmail] 1 [gmail] 2 [gmail] 3 [aol] 4 [yahoo] 5 [yahoo] I want to create a new column where if the domain is gmail or aol, the column entry would be a 1 and 0 otherwise. I created a method which goes like this: def convertToNumber(row): try: if row['emailDomain'] == '[gmail]': return 1 elif row['emailDomain'] == '[aol]': return 1 elif row['emailDomain'] == '[outlook]': return 1 elif row['emailDomain'] == '[hotmail]': return 1 elif row['emailDomain'] == '[yahoo]': return 1 else: return 0 except TypeError: print("TypeError") and used it like: data['validEmailDomain'] = data.apply(convertToNumber, axis=1) However, my output column is 0 even when I know there are gmail and aol emails present in the input column. Any idea what could be going wrong? Also, I think this usage of conditional statements might not be the most efficient way to tackle this problem. Is there any other approach to getting this done?
accepted answer: http://stackoverflow.com/a/49996819
type: Question
tagged with: encoding

http://stackoverflow.com/comment/87024711
type: QuestionComment
comment on: http://stackoverflow.com/q/50004087
has text: The proper Unicode representation of "č" is most certainly *not* `\u00c4\u008d`. How did you get to that?
score: 1
type: Comment

http://stackoverflow.com/a/50068275
upvote count: 2
answers question: http://stackoverflow.com/q/50068183
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87153151
has body: You can use string.split(',') and you will get ['9 - Saturday', '19 May 2012']
has comment: http://stackoverflow.com/comment/87152976
type: Answer

http://stackoverflow.com/q/50070775
linked to: http://stackoverflow.com/q/31081563
tagged with: pyspark
has body: Just wondering what exactly does this do? I understand keyBy, but I struggle to under what exacltly is that combineByKey. I have read through pages (link) and still don't understand. df.rdd.keyBy( lambda row: row['id'] ).combineByKey( lambda row: [row], lambda rows, row: rows + [row], lambda rows1, rows2: rows1 + rows2, ) )
accepted answer: http://stackoverflow.com/a/50070967
answer count: 1
has title: `combineByKey`, pyspark
duplicate of: http://stackoverflow.com/q/31081563
linked to: http://stackoverflow.com/q/33937625
type: Question
tagged with: apache-spark
tagged with: python
duplicate of: http://stackoverflow.com/q/33937625
has answer: http://stackoverflow.com/a/50070967
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/98874573
has text: While this may answer the question, you should [edit] your answer to include some explanation of how this answers the question, to provide context for future users. A code dump by itself is not immediately useful to those who might come across the same issue later on.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/56120877
type: AnswerComment

http://stackoverflow.com/a/49948110
answers question: http://stackoverflow.com/q/49937982
has body: If you can't be sure about text content, you should enclose it in a CDATA section. Unfortunately, the plain \v is not accepted even inside a CDATA so you have two options Remove it or replace it with space Encoding as &amp;#xB;seems to work at list for a libxml2 utility (see example at bottom of answer). For python, lxml is based on libxml2 too. echo -e "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;root&gt;&lt;a&gt;&lt;\041[CDATA[asdf\ndf \v nbbv]]&gt;&lt;/a&gt;&lt;/root&gt;" | xmllint --format - Result with error: -:2: parser error : CData section not finished asdf d df nbbv]]&gt;&lt;/a&gt;&lt;/root&gt; ^ -:2: parser error : PCDATA invalid Char value 11 df nbbv]]&gt;&lt;/a&gt;&lt;/root&gt; ^ -:2: parser error : Sequence ']]&gt;' not allowed in content df nbbv]]&gt;&lt;/a&gt;&lt;/root&gt; ^ -:2: parser error : Sequence ']]&gt;' not allowed in content df nbbv]]&gt;&lt;/a&gt;&lt;/root&gt; ^ -:2: parser error : internal error: detected an error in element content df nbbv]]&gt;&lt;/a&gt;&lt;/root&gt; ^ Replacing with its HTML entity echo -e "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;root&gt;&lt;a&gt;&lt;\041[CDATA[asdf\ndf &amp;#xB; nbbv]]&gt;&lt;/a&gt;&lt;/root&gt;" | xmllint --format - &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;root&gt; &lt;a&gt;&lt;![CDATA[asdf df &amp;#xB; nbbv]]&gt;&lt;/a&gt; &lt;/root&gt;
score: 0
type: Answer

http://stackoverflow.com/q/50013767
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87122476
score: 2
tagged with: python-asyncio
has body: I've a trouble understand the reason for the below code, hope someone can shed some lights on this. I'm new in async programming. This is from websockets documentation #!/usr/bin/env python import asyncio import websockets async def echo(websocket, path): async for message in websocket: await websocket.send(message) asyncio.get_event_loop().run_until_complete( websockets.serve(echo, 'localhost', 8765)) asyncio.get_event_loop().run_forever() I have some questions about asyncio design and how I can take advantage of this. First of all, looking at the last two lines. If I understand correctly, shouldn't run_until_complete shutdown after finished its work? How can the second loop kept it alive with no jobs submitted into the loop? Secondly, I was trying to build a back_end that can process some data from the front_end using websockets and return the calculation in realtime. There will be two kinds of tasks, one is bit longer that need computation power a bit but will happen one time for a session, and bunch of streaming data processing that need to be send back immediately (90 frames per seconds). For the bigger tasks, should I just fire up another websocket server that process the longer work, and use the main websocket to consume on it? Or use another process to do the work in a chained async function? And for the smaller tasks, what would go wrong if I do the same as above? TLDR: Async programming is hammering my brain. Maintain a nonblocking session Which process hard work and light work simultaneously The light work should have zero latency The hard work should be as fast as possible but not effecting the light work. Thanks!!
downvote count: 0
tagged with: websocket
has comment: http://stackoverflow.com/comment/87044373
tagged with: concurrency
has comment: http://stackoverflow.com/comment/87044985
has title: Multiple event loop on websockets asyncio server example
has comment: http://stackoverflow.com/comment/87045055
favorite count: 0
type: Question
answer count: 0

http://stackoverflow.com/comment/87140595
comment on: http://stackoverflow.com/q/50062020
has text: This is format of proxies `http://login:password@0.0.0.0:976`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/77831889
type: Answer
has body: you can also use repository contents API to push to github. original answer coming from similar thread.
score: 0
answers question: http://stackoverflow.com/q/50071841

http://stackoverflow.com/comment/86880803
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49932505
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
type: Comment

http://stackoverflow.com/comment/87022378
score: 0
comment on: http://stackoverflow.com/q/50003007
has text: Possible duplicate of [Convert csv to Newick tree](https://stackoverflow.com/questions/26146623/convert-csv-to-newick-tree)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86947873
type: AnswerComment
comment on: http://stackoverflow.com/a/49964970
type: Comment
has text: This works fine for small Arrays. However for Arrays of size ~100k or bigger I get the following error message: "..\Anaconda3\lib\site-packages\ipykernel_launcher.py:12: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future. if sys.path[0] == '': ... AttributeError: 'bool' object has no attribute 'all' " (in the np.where call)
score: 0

http://stackoverflow.com/q/49984571
has comment: http://stackoverflow.com/comment/86985589
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86985585
has answer: http://stackoverflow.com/a/49994600
has comment: http://stackoverflow.com/comment/86987139
has comment: http://stackoverflow.com/comment/86987236
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86985831
answer count: 1
type: Question
has body: General python question- I have built a script using numpy and pandas libraries. I have now been told that I cannot use any libraries- only base python to code. This is because apparently open source libraries are not approved. Does this restriction make sense? Isn't base python as open source as pandas/numpy libraries are? Is it possible to convert pandas/numpy code to base python? Does this sound like a simple exercise or does it require learning a lot of new functions? Majority of the code is reading tables and then using if/then type statements and looking up values from other tables to generate and populate new tables.
tagged with: numpy
has title: Feasibility of converting all python pandas/numpy code to base python

websocket
tags question: http://stackoverflow.com/q/50059102
tags question: http://stackoverflow.com/q/50066428
tag name: websocket
tags question: http://stackoverflow.com/q/49979183
tags question: http://stackoverflow.com/q/50013767
type: Tag
tags question: http://stackoverflow.com/q/49933316

http://stackoverflow.com/q/49988488
tagged with: python
has answer: http://stackoverflow.com/a/49989436
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49988580
has title: Django: ManyToMany association name not defined
downvote count: 0
has body: this is my models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from userprofiles.models import UserProfile # Create your models here. import os class Category (models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Image(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) in_gallery = models.ManyToManyField(Gallery) title = models.CharField(max_length=100) def __str__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=100) have_images = models.ManyToManyField(Image) def __str__(self): return self.name class ImageInGallery (models.Model): image = models.ForeignKey(Image) gallery = models.ForeignKey(Gallery) line 22, in Image in_gallery = models.ManyToManyField(Gallery) NameError: name 'Gallery' is not defined I want to have manytomany relation for Image and Gallery and class ImageInGallery to store the Image~Gallery relation sets. also, I want images belonging to a certain gallery accessible from a gallery and vice versa, so I put both models.ManyToManyField(Gallery) and models.ManyToManyField(Image) in both classes whats the reason of the error: line 22, in Image in_gallery = models.ManyToManyField(Gallery) NameError: name 'Gallery' is not defined
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/49989658
favorite count: 0
answer count: 3
score: 1

http://stackoverflow.com/q/49949814
has answer: http://stackoverflow.com/a/49949931
has answer: http://stackoverflow.com/a/49957807
has answer: http://stackoverflow.com/a/49949858
has body: Given a list of data, I'm trying to create a new list in which the value at position i is the length of the longest run starting from position i in the original list. For instance, given x_list = [1, 1, 2, 3, 3, 3] Should return: run_list = [2, 1, 1, 3, 2, 1] My solution: freq_list = [] current = x_list[0] count = 0 for num in x_list: if num == current: count += 1 else: freq_list.append((current,count)) current = num count = 1 freq_list.append((current,count)) run_list = [] for i in freq_list: z = i[1] while z &gt; 0: run_list.append(z) z -= 1 Firstly I create a list freq_list of tuples, where every tuple's first element is the element from x_list, and where the second element is the number of the total run. In this case: freq_list = [(1, 2), (2, 1), (3, 3)] Having this, I create a new list and append appropriate values. However, I was wondering if there is a shorter way/another way to do this?
upvote count: 19
tagged with: list
accepted answer: http://stackoverflow.com/a/49949931
has title: Finding longest run in a list
score: 18
answer count: 6
has answer: http://stackoverflow.com/a/49958600
downvote count: 1
has comment: http://stackoverflow.com/comment/86916286
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49951456
has answer: http://stackoverflow.com/a/49955110
possible better answer: http://stackoverflow.com/a/49949858
tagged with: python

http://stackoverflow.com/comment/86863573
type: QuestionComment
comment on: http://stackoverflow.com/q/49923857
score: 0
has text: Can you share the terminal output of "python --version" ?
type: Comment

http://stackoverflow.com/comment/87009994
comment on: http://stackoverflow.com/a/49996765
type: Comment
score: 0
type: AnswerComment
has text: Nice! I tried it without regex but couldn't figure it out. Went with your solution because I believe in the fact that if it can be done without regex, do it! In my opinion, not using regex is more readable and maintainable so by default more pythonic

http://stackoverflow.com/comment/86933611
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49933642
has text: Mac Numbers is kinda like Excel, just a spreadsheet. I will try reading it through pandas. Thank you
type: AnswerComment

http://stackoverflow.com/q/50028664
has comment: http://stackoverflow.com/comment/87073482
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50028883
has comment: http://stackoverflow.com/comment/87073460
has comment: http://stackoverflow.com/comment/87073654
has title: How do I set up Python3 as the default Python version on Mac OS X?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87074659
type: UnansweredQuestion
has body: I have both Python 2.7 and Python 3.6 installed, and I can access either by typing "python" or "python3". However, when I try to install the latest version of Django with pip install Django==2.0.4, Python 2.7 is detected and the highest version that can be installed is version 1.11, since Django 2.0.4 requires Python3. In summary I need the default version of Python on my machine to be Python3, and I'm not sure how to accomplish this. Using an alias won't work, since I'm trying to make it so that other apps detect the correct version. My which python result should be Python3. Assumed Answer I would imagine that I need to edit my Path in a way that prefers Python3 over Python 2, but I'm unsure of how to do so. When I type echo $PATH I get /anaconda2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin. I'm not sure if that helps or not. Any ideas on what to do? Also, I'd prefer for Python3 to be the default, so I'd rather not use a virtualenv. edit: Just kidding, not solved. So pip3 installs Django2. But when I run Django2, I see that it's still relying on Python2.7. Here's the error: File "/anaconda2/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) from django.conf.urls import url, include, path ImportError: cannot import name path
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50028787

http://stackoverflow.com/comment/87098367
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50038678
has text: `xtick.color` sets the color for both, [tickmarkers](https://github.com/matplotlib/matplotlib/blob/b01bdf44c420115c923e266fbcbd97aab14960a5/lib/matplotlib/axis.py#L134) and [ticklabels](https://github.com/matplotlib/matplotlib/blob/b01bdf44c420115c923e266fbcbd97aab14960a5/lib/matplotlib/axis.py#L145).
type: Comment

http://stackoverflow.com/comment/87319654
comment on: http://stackoverflow.com/q/49995704
type: Comment
type: QuestionComment
has text: The issue is not in implementation. As I told, it is working fine on Firefox and for one of the domain on Chrome. The issue is while handling multiple domains on Chrome.
score: 0

http://stackoverflow.com/q/50056903
has answer: http://stackoverflow.com/a/50057039
upvote count: 2
tagged with: indexing
type: AnsweredQuestion
score: 2
tagged with: pandas
answer count: 1
downvote count: 0
has title: Exception when using set_index in Pandas
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50057039
has body: I am trying out the set_index() method in Pandas but I get an exception I can not explain: df movieId title genres 1 2 Jumanji (1995) Adventure|Children|Fantasy 5 6 Heat (1995) Action|Crime|Thriller 10 11 American President, The (1995) Comedy|Drama|Romance df.set_index(['a' , 'b' , 'c'], inplace = True) df KeyError: 'a'

http://stackoverflow.com/comment/87429355
has text: I cannot upgrade. That is part of the problem, I have tried many commands but I am still on 9.0.1. I actually deleted pip in attempts to re-download it but now I cannot even download it due to the same error.
comment on: http://stackoverflow.com/q/49988928
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50064916
accepted answer: http://stackoverflow.com/a/50065481
has answer: http://stackoverflow.com/a/50065481
has body: I'm trying to enable the downloading of previously uploaded files in Django, here's the code I'm using so far: def downloadview(request): path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' ) response = HttpResponse() response['Content-Type']='' response['Content-Disposition'] = "attachment; filename='Testname'" response['X-Sendfile']=smart_str(os.path.join(path)) return response The inspiration for this trial comes from this thread but I don't get it working. An empty txt file is downloaded instead of the image that is stored on the server. In this trial code the exact filename and extension is hard coded in the path variable.
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Downloading a file using Django
answer count: 1
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/32704177
favorite count: 0
type: Question
tagged with: download

http://stackoverflow.com/a/50022675
accepted answer of: http://stackoverflow.com/q/50022220
has comment: http://stackoverflow.com/comment/87061544
has comment: http://stackoverflow.com/comment/87061736
score: 2
has comment: http://stackoverflow.com/comment/87061413
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87061379
has comment: http://stackoverflow.com/comment/87061661
has body: I hope I understood you correctly. initial_value = 1 answer_list = [] answer_list.append(initial_value) for i in range(1, 3): answer_list.append((1+1/i)*answer_list[i-1]) print(answer_list) This should work for you, basically what you want to do is insert the answer into a list in a consecutive manner and multiple in the (index-1).
type: Answer
answers question: http://stackoverflow.com/q/50022220

http://stackoverflow.com/a/59471890
answers question: http://stackoverflow.com/q/50043573
score: 0
type: Answer
has body: If video is not getting saved, possibly the reason may be its capture size which is hardcoded as (640,480). You can try the below code: cap = cv2.VideoCapture(0) fourcc_codec = cv2.VideoWriter_fourcc(*'XVID') fps = 20.0 capture_size = (int(cap.get(3)), int(cap.get(4))) out = cv2.VideoWriter("output.avi", fourcc_codec, fps, capture_size)

http://stackoverflow.com/a/49955820
type: Answer
score: 0
has body: You are managing your own roles. Almost certainly, you did not give Zappa permission to do something it needs to do. Apparently, one thing it doesn't have permission to do is create the log group it wants to, which follows a naming convention based (IIRC) on the directory name and the Zappa profile name (production). If you remove manage_roles and role_name, you'll get a user that has all the permissions that Zappa needs and then some. You can then start removing them until you have a minimal set of requirements. After some trial and error, I found that the following was the good minimum set for a basic application. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:CreateExportTask", "logs:PutDestination", "logs:PutLogEvents" ], "Resource": [ "arn:aws:logs:us-east-1:xxxxxxxxxxxxxxxxxxxx:log-group:/aws/lambda/projectname-profilename:*" ] }, { "Effect": "Allow", "Action": [ "ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "lambda:InvokeFunction" ], "Resource": [ "arn:aws:lambda:us-east-1:xxxxxxxxxxxxxxx:function:projectname-profilename" ] }, { "Effect": "Allow", "Action": [ "xray:PutTraceSegments", "xray:PutTelemetryRecords" ], "Resource": [ "*" ] } ] } Lambda also needs to be able to assume this profile in order to run. So you must also edit your trust relationships: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "s3.amazonaws.com", "events.amazonaws.com", "apigateway.amazonaws.com", "lambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } If you have to talk to a database server, be sure to assign a VPC and security group as well.
answers question: http://stackoverflow.com/q/49941407

http://stackoverflow.com/comment/87141196
type: Comment
has text: Thanks for the help.
type: AnswerComment
comment on: http://stackoverflow.com/a/50058037
score: 0

http://stackoverflow.com/comment/86855623
type: AnswerComment
has text: recursion seems to do the trick just fine! Thanks for your input
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49919991

http://stackoverflow.com/a/49993795
has comment: http://stackoverflow.com/comment/105324403
type: Answer
score: 0
has body: Process to CPU/CPU core allocation is handled by the Operating System.
answers question: http://stackoverflow.com/q/49993687

http://stackoverflow.com/q/49986396
has comment: http://stackoverflow.com/comment/86990466
score: 2
has body: I have a script that converts and combines excel spreadsheets. I have around 50 worksheets which all have the same format. The only problem I run in is when I append the dataframes together. 0s and 1s are converted to False and True when they should not. I have looked at documentation but I cant find anything to help me. I believe the problem is when I use pd.ExcelFile(workbook). Here is my code xlsx_files = glob.glob("*.xlsx") combined_df = pd.DataFrame() for workbook in xlsx_files: excel_file = pd.ExcelFile(workbook) worksheets = excel_file.sheet_names for worksheet in worksheets: worksheet_df = excel_file.parse(worksheet) combined_df = combined_df.append(worksheet_df, ignore_index=True) # worksheet_df = pd.read_excel(excel_file, worksheet=worksheet) Here is the original worksheet information Observed Value Values Count **0 52708** 0.00825 4 0.0055 4 0.04 12 0.0075 2 0.00549 3 0.01 74 0.0036 2 0.03 21 0.0095 4 0.00634 3 0.00375 2 0.02 7 0.009 8 0.0085 2 0.007 2 0.008 6 0.00675 2 0.00577 3 0.00583 3 0.0065 8 0.0025 3 0.05 5 0.00625 4 0.005 2 0.0015 2 Here is output my code prints out Observed Value Values Count **FALSE 52708** 0.00825 4 0.0055 4 0.04 12 0.0075 2 0.00549 3 0.01 74 0.0036 2 0.03 21 0.0095 4 0.00634 3 0.00375 2 0.02 7 0.009 8 0.0085 2 0.007 2 0.008 6 0.00675 2 0.00577 3 0.00583 3 0.0065 8 0.0025 3 0.05 5 0.00625 4 0.005 2 0.0015 2 I am trying to get rid of the False value, any help is greatly appreciated
has comment: http://stackoverflow.com/comment/86996009
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87028764
linked to: http://stackoverflow.com/q/56614576
has comment: http://stackoverflow.com/comment/133176015
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/86990988
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86989524
tagged with: python
has comment: http://stackoverflow.com/comment/86990471
has title: Pandas read_excel converting 0 and 1 to True and False
tagged with: excel

http://stackoverflow.com/comment/86910851
comment on: http://stackoverflow.com/q/49946683
score: 0
type: Comment
type: QuestionComment
has text: @ekhumoro what do you mean. How?

http://stackoverflow.com/a/50052134
upvote count: 2
type: Answer
score: 2
has body: You can install to python 3 using pip3 install django python3 -m pip install django As abarnert says in the comments, you shouldn't remove the Python 2.7 installation or try to set Python 3 to be the default. It's good practice to use a virtual environment. Since you're using Python 3 you could use pipenv. Once the Python 3 virtual environment is activated, python will use the python 3 from the virtual environment.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50052050
accepted answer of: http://stackoverflow.com/q/50052050

http://stackoverflow.com/comment/87154525
comment on: http://stackoverflow.com/q/50068881
has text: As an explanation of *why* it is only one parameter, `one()` returns a single tuple - `return` really only returns one object, although of course that can be a tuple of other objects.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87065514
has text: Thank you very much! And if I want the keys to be integer numbers? Like this {'1': {'2': 2, '3': 5, '4': 1} and not this {'1': {'2': '2', '3': '5', '4': '1'}
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50023534

http://stackoverflow.com/comment/87245891
has text: Details about environment: SWIG Version 3.0.8, Ubuntu 16.04.3 LTS, g++ 5.4.0; Python 2.7.12 Above I simplified a little as my application is a bit more complex. The pair <int, string> actually contains the status of some operation and the string is a json with some data extracted from a database. In my case whenver the string (json) is bigger than 2GB the json load ( result = json.loads(result_db.second) ) fails with an exception that it can't load from a <Swig Object of type 'char *' at 0x7fd4205a6090>
comment on: http://stackoverflow.com/q/50056859
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86978261
score: 0
has text: Give us at least a screenshot of the content 'tags'
comment on: http://stackoverflow.com/q/49978532
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86926221
comment on: http://stackoverflow.com/q/49954083
score: 0
type: Comment
type: QuestionComment
has text: @MadProgrammer I tried it is not working.

http://stackoverflow.com/q/49948563
score: 1
has body: Im making a script that creates a database in AWS Athena and then creates tables for that database, today the DB creation was taking ages, so the tables being created referred to a db that doesn't exists, is there a way to check if a DB is already created in Athena using boto3? This is the part that created the db: client = boto3.client('athena') client.start_query_execution( QueryString='create database {}'.format('db_name'), ResultConfiguration=config )
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/56103279
has answer: http://stackoverflow.com/a/79296462
has title: boto3 check if Athena database exists
type: Question
upvote count: 2
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
possible better answer: http://stackoverflow.com/a/49950620
tagged with: amazon-athena
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49950620
answer count: 3
accepted answer: http://stackoverflow.com/a/56103279

http://stackoverflow.com/comment/86984534
type: QuestionComment
has text: Please fix your indentation, too.
score: 0
comment on: http://stackoverflow.com/q/49983951
type: Comment

http://stackoverflow.com/comment/86908775
comment on: http://stackoverflow.com/a/49945524
score: 0
type: Comment
type: AnswerComment
has text: @RockyLi - There are lots of worthwhile videos at [pyvideo.org](pyvideo.org)

http://stackoverflow.com/a/50045332
upvote count: 2
score: 2
has body: Desired capabilities and chrome options are two different configurations. The keyword "Open Browser" doesn't support chrome options, so the only way to add options to chrome is by keywords "Create WebDriver"
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49985035
type: Answer
accepted answer of: http://stackoverflow.com/q/49985035

http://stackoverflow.com/q/50067744
has body: I have code like this ` celldata="" count=0 for tableData in y: count = count+1 strcount=str(count) celldata += strcount + ")" + tableData .text + "\n" return celldata ` I am returning the value to be used in flask, the issue is I want each for loop row in a new line but after trying \n, and in the flask web app I am getting celldata in one single line with one space each between each output line of the for loop. Here is my current output for celldata in flask web 1)xxxx 2)yyyy I want the flask web url to return 1)xxxx 2)yyyy
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87151992
accepted answer: http://stackoverflow.com/a/50067885
has answer: http://stackoverflow.com/a/50067885
type: Question
possible better answer: http://stackoverflow.com/a/50067803
answer count: 2
has title: Python, return new line in function return
has answer: http://stackoverflow.com/a/50067803
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/86936253
type: Comment
type: AnswerComment
has text: Ok..here's another try: (results[0])[[1]].sum().compute() ----TypeError: url type not understood: <StringIO.StringIO instance at 0x37c9cb0>
score: 0
comment on: http://stackoverflow.com/a/49955896

http://stackoverflow.com/q/49924326
has body: please help to tell the basic logic of &gt;&gt;&gt;False == False == True False and the difference with (from the result, obviously the diff does have) &gt;&gt;&gt;(False == False) == True True
linked to: http://stackoverflow.com/q/6074018
has title: Python: how come False == False == True returns False?
tagged with: python
duplicate of: http://stackoverflow.com/q/6074018
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/48315777
linked to: http://stackoverflow.com/q/28104393
upvote count: 1
has comment: http://stackoverflow.com/comment/86864562
downvote count: 1
has comment: http://stackoverflow.com/comment/86864868
favorite count: 0
type: Question
score: 0

http://stackoverflow.com/a/49944654
type: Answer
has comment: http://stackoverflow.com/comment/86905721
answers question: http://stackoverflow.com/q/49944618
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86905974
score: 3
has comment: http://stackoverflow.com/comment/86905881
has body: sum with [], then using set set(sum(my_series,[]))#set(my_series.sum()) Out[85]: {'a', 'b', 'c', 'd', 'e'} Or using reduce set(functools.reduce(lambda x, y: x+y, my_series.tolist())) Out[90]: {'a', 'b', 'c', 'd', 'e'} With pandas unique pd.DataFrame(my_series.tolist()).stack().unique() Out[93]: array(['a', 'b', 'c', 'd', 'e'], dtype=object) With numpy import numpy as np np.unique(np.concatenate(my_series)) Out[95]: array(['a', 'b', 'c', 'd', 'e'], dtype='&lt;U32') Or with loop set(x for y in my_series for x in y)

http://stackoverflow.com/a/50004357
type: Answer
has comment: http://stackoverflow.com/comment/123539594
has comment: http://stackoverflow.com/comment/123557813
answers question: http://stackoverflow.com/q/50004310
has comment: http://stackoverflow.com/comment/123537778
has body: In python 3 you cannot do that: for k,v in newDict.items(): newDict.update({k.upper(): v.upper()}) because it changes the dictionary while iterating over it and python doesn't allow that (It doesn't happen with python 2 because items() used to return a copy of the elements as a list). Besides, even if it worked, it would keep the old keys (also: it's very slow to create a dictionary at each iteration...) Instead, rebuild your dict in a dict comprehension: newDict = {k.upper():v.upper() for k,v in newDict.items()} Note that it's not equivalent to what could be done with python 3, since rebuilding the dictionary loses the original lowercase keys. To keep both, there are 2 options: either iterate on a copy of the items: for k,v in tuple(newDict.items()): newDict.update({k.upper(): v.upper()}) or create the new dictionary and update the original with it. newDict.update({k.upper():v.upper() for k,v in newDict.items()}) Since argument is evaluated before update is called, there's no risk of conflict.
has comment: http://stackoverflow.com/comment/125174569
downvote count: 0
score: 23
upvote count: 23

http://stackoverflow.com/a/49944541
downvote count: 0
has comment: http://stackoverflow.com/comment/93438771
has body: I have take inspiration from both excellent answers as well as this answer from jezral to my previous question to apply this to the whole DataFrame. I did this so that I could treat an entire DataFrame in one go and so that each column would ffill the missing values in their respective columns (with my extra constraint). Setup a DataFrame, df = pd.DataFrame( {'val1': [1, 1, np.nan, np.nan, 2, 3, np.nan, np.nan, np.nan, np.nan, 1, 1], 'val2': [1, 2, np.nan, np.nan, 2, 4, 4, np.nan, np.nan, np.nan, np.nan, 2]} ) print(df) val1 val2 0 1.0 1.0 1 1.0 2.0 2 NaN NaN 3 NaN NaN 4 2.0 2.0 5 3.0 4.0 6 NaN # 4.0 7 NaN # NaN # 8 NaN # NaN # 9 NaN # NaN # 10 1.0 NaN # 11 1.0 2.0 Now do mask and ffill, mask_df = ( df.isnull() .groupby([df.notnull().all(axis=1).cumsum()]) .rank(method='max') - 1 ).gt(2) df = df.ffill().mask(mask_df) print(df) val1 val2 0 1.0 1.0 1 1.0 2.0 2 1.0 2.0 3 1.0 2.0 4 2.0 2.0 5 3.0 4.0 6 NaN # 4.0 7 NaN # NaN # 8 NaN # NaN # 9 NaN # NaN # 10 1.0 NaN # 11 1.0 2.0 Explaination We groupby using a cumulative sum over the non-nan values. This means the nan values become grouped together. If we take the max rank of these we get the length of the nan sequence + 1. Now we just use the mask function as shown by cᴏʟᴅsᴘᴇᴇᴅ's answer.
has comment: http://stackoverflow.com/comment/93444698
has comment: http://stackoverflow.com/comment/93444858
has comment: http://stackoverflow.com/comment/93418134
type: Answer
accepted answer of: http://stackoverflow.com/q/49940652
score: 4
has comment: http://stackoverflow.com/comment/93439685
upvote count: 4
has comment: http://stackoverflow.com/comment/93438547
answers question: http://stackoverflow.com/q/49940652
type: AcceptedAnswer

unicode-string
tags question: http://stackoverflow.com/q/49938375
tag name: unicode-string
type: Tag

http://stackoverflow.com/a/49964540
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49964476
answers question: http://stackoverflow.com/q/49964476
type: Answer
has body: Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number. This is the fixed version of your code: import random guesses = 0 number = random.randint(1, 100) def higher(guesses): print("Lower") guesses = guesses + 1 def lower(guesses): print("Higher") guesses = guesses + 1 def correct(guesses): print("You got it correct!") print("It was {0}".format(number)) guesses = guesses + 1 print ("It took you {0} guesses".format(guesses)) def _main_(guesses): print("Welcome to guess the number") while True: guess = int(input("Guess a number: ")) if guess &gt; number: higher(guesses) elif guess &lt; number: lower(guesses) elif guess == number: correct(guesses) while True: answer = input("Would you like to play again? Y or N: ") if answer == "Y": break elif answer == "N": exit() else: exit() _main_(guesses) What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module. Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code: import random def main(): number = random.randint(1, 100) guesses = 0 while True: guessed_num = int(input('Guess the number: ')) guesses += 1 if guessed_num &gt; number: print('Guess lower!') elif guessed_num &lt; number: print('Guess higher!') else: print('Correct!') print('The number was {}'.format(number)) print('It took you {} guesses.'.format(guesses)) break main()
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50000018
has comment: http://stackoverflow.com/comment/87017805
favorite count: 0
has comment: http://stackoverflow.com/comment/87018140
type: Question
has comment: http://stackoverflow.com/comment/87018178
tagged with: spacy
upvote count: 2
has comment: http://stackoverflow.com/comment/87019717
answer count: 1
tagged with: python
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87022087
accepted answer: http://stackoverflow.com/a/50001828
tagged with: conda
has body: I am trying to install Spacy. I was trying to use Pip but I kept getting and error related to C++ build tools (which I downloaded). Now, I am trying to use Conda, running conda install -c conda-forge spacy but I get the error shown below. I am not really sure what I am doing wrong. Based on what I've read, this should work. thanks, Update I ran anaconda search -t conda spacy. This is my output:
has comment: http://stackoverflow.com/comment/87019123
has title: Conda install Spacy - Package missing in current channels
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50001828
tagged with: anaconda
has comment: http://stackoverflow.com/comment/87017736
has comment: http://stackoverflow.com/comment/87018707
has comment: http://stackoverflow.com/comment/87019155
has comment: http://stackoverflow.com/comment/87019532
has comment: http://stackoverflow.com/comment/87018757

http://stackoverflow.com/a/49940260
type: Answer
accepted answer of: http://stackoverflow.com/q/49936735
upvote count: 4
answers question: http://stackoverflow.com/q/49936735
downvote count: 0
type: AcceptedAnswer
score: 4
has body: What you are trying to achieve is particularly cumbersome in Windows. The core issue is that when you decorate a function, you shadow it. This happens to work just fine in UNIX due to the fact it uses the fork strategy to create a new process. In Windows though, the new process will be a blank one where a brand new Python interpreter is started and loads your module. When the module gets loaded, the decorator hides the real function making it hard to find for the pickle protocol. The only way to get it right is to rely on a trampoline function to be set during the decoration. You can take a look on how is done on pebble but, as long as you're not doing it for an exercise, I'd recommend to use pebble directly as it already offers what you are looking for. from pebble import concurrent @concurrent.process(timeout=60) def my_function(var, keyvar=0): return var + keyvar future = my_function(1, keyvar=2) future.result()

decode
tag name: decode
tags question: http://stackoverflow.com/q/50019680
tags question: http://stackoverflow.com/q/49979262
tags question: http://stackoverflow.com/q/49938517
tags question: http://stackoverflow.com/q/49968431
tags question: http://stackoverflow.com/q/50060231
type: Tag

http://stackoverflow.com/a/50036889
answers question: http://stackoverflow.com/q/50036470
type: Answer
has comment: http://stackoverflow.com/comment/87093091
has body: The lines for door and item have the room name on them. Use that to access the proper element of the dictionary. d={} def dictnPart(): with open("gameconfiguration.txt",'r') as input_data: for line in input_data: li=line.strip() if not li.startswith("#"): abc=line.strip().split() # print(abc[1]) if abc[0]=="room": d[abc[1]] = {"name":abc[1]} # print(d) if abc[0]=="door": roomname = abc[3] d[roomname].update({abc[1]:{"dir":abc[4],"status":abc[2]}}) if "directions" in d[roomname]: d[roomname]["directions"].append(abc[1]) else: d[roomname]["directions"] = [abc[1]] # print(d) if abc[0]=="item": roomname = abc[2] d[roomname].update({"item":abc[1]}) if "directions" in d[roomname]: d[roomname]["directions"].append(abc[2]) else: d[roomname]["directions"] = [abc[2]] print(d)
has comment: http://stackoverflow.com/comment/87090193
has comment: http://stackoverflow.com/comment/87089967
accepted answer of: http://stackoverflow.com/q/50036470
has comment: http://stackoverflow.com/comment/87090390
has comment: http://stackoverflow.com/comment/87090123
has comment: http://stackoverflow.com/comment/87090124
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87090048
has comment: http://stackoverflow.com/comment/87090037
has comment: http://stackoverflow.com/comment/87090521
has comment: http://stackoverflow.com/comment/87090400
has comment: http://stackoverflow.com/comment/87090370

http://stackoverflow.com/a/50006695
downvote count: 0
has body: č is not represented by u'\u00c4\u008d'. Those two hex values are the UTF-8-encoded values, so should be written in a byte string as '\xc4\x8d'. Example: &gt;&gt;&gt; s = '\xc4\x8d' &gt;&gt;&gt; s.decode('utf8') u'\u010d' &gt;&gt;&gt; print(s.decode('utf8')) č Caveat: Your terminal must be configured with an encoding that supports the character to print correctly, or you will see a UnicodeEncodeError. If for some reason you have a mis-decoded Unicode string, you can take advantage of the fact that the first 256 code points of Unicode correlate to the latin1 encoding and fix it: &gt;&gt;&gt; s = u'\u00c4\u008d' &gt;&gt;&gt; s.encode('latin1') '\xc4\x8d' &gt;&gt;&gt; s.encode('latin1').decode('utf8') u'\u010d' &gt;&gt;&gt; print(s.encode('latin1').decode('utf8')) č If you have a mis-decoded Unicode string, you should show the file you have or the code that read it and solve that problem.
answers question: http://stackoverflow.com/q/50004087
has comment: http://stackoverflow.com/comment/131897239
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/49917098
tagged with: python
type: UnansweredQuestion
tagged with: flask
answer count: 1
tagged with: bytesio
has comment: http://stackoverflow.com/comment/86849689
has comment: http://stackoverflow.com/comment/86850502
type: Question
score: 0
has answer: http://stackoverflow.com/a/49920038
tagged with: text-extraction
has title: TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found
has body: I am trying for a week how to give input files to Textract from flask POST option. @app.route('/input', methods=['POST']) def input(): request_file = request.files.get('file') r = textract.process(io.BytesIO(request_file.read())) return r The above code throws me error TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found And I tried a small test with send_file to check if it actually takes the input and to check if BytesIO works well in my case: @app.route('/input', methods=['POST']) def input(): request_file = request.files.get('file') return send_file(io.BytesIO(request_file.read()),attachment_filename= request_file.filename) the above code works fine for pdf files and send responses(to download pdf file). And when i tried .docx,.txt files it show some strange outputs on the screen : PK My questions, how do i send this io.bytes(request_file.read()) as a file to Textract now ? I tried to find answer everywhere but i couldn't. Am i supposed to decode or encode now?

http://stackoverflow.com/comment/87020401
has text: @MichaelButscher using the `os` module tells me that Python can't find the path at all. Though VSCode can...
type: QuestionComment
comment on: http://stackoverflow.com/q/50000399
score: 0
type: Comment

http://stackoverflow.com/a/49932521
has body: That looks like json with bizarre quote characters. It would be useful to look at the source of the data to see if valid json is intended and where those quotes are converted to extended unicode quotes. Perhaps someone is running these through a word processor. Or there is some windows code page to unicode translation issue. Anyway, you can fix the quotes and (at least for your small example) the parsing works fix_quote_transform = str.maketrans({q:'"' for q in '‘”’“'}) for line in sys.stdin: obj = json.loads(line.trans(fix_quote_transform))
score: 0
answers question: http://stackoverflow.com/q/49932242
type: Answer

module
tags question: http://stackoverflow.com/q/49934177
type: Tag
tags question: http://stackoverflow.com/q/50017227
tags question: http://stackoverflow.com/q/50012624
tags question: http://stackoverflow.com/q/50050796
tag name: module
tags question: http://stackoverflow.com/q/49981755
tags question: http://stackoverflow.com/q/50007372
tags question: http://stackoverflow.com/q/49926751

kivy
tags question: http://stackoverflow.com/q/49920953
tags question: http://stackoverflow.com/q/50059185
type: Tag
tags question: http://stackoverflow.com/q/50028608
tags question: http://stackoverflow.com/q/50021096
tags question: http://stackoverflow.com/q/50050951
tag name: kivy
tags question: http://stackoverflow.com/q/50017886
tags question: http://stackoverflow.com/q/50040244
tags question: http://stackoverflow.com/q/49936896
tags question: http://stackoverflow.com/q/49940550
tags question: http://stackoverflow.com/q/49931474
tags question: http://stackoverflow.com/q/50062497
tags question: http://stackoverflow.com/q/49960057
tags question: http://stackoverflow.com/q/49935190
tags question: http://stackoverflow.com/q/50006684
tags question: http://stackoverflow.com/q/50072678
tags question: http://stackoverflow.com/q/50003036
tags question: http://stackoverflow.com/q/50052530
tags question: http://stackoverflow.com/q/50006093
tags question: http://stackoverflow.com/q/50028886
tags question: http://stackoverflow.com/q/49971489
tags question: http://stackoverflow.com/q/50024389
tags question: http://stackoverflow.com/q/49950999
tags question: http://stackoverflow.com/q/49942713
tags question: http://stackoverflow.com/q/49980612
tags question: http://stackoverflow.com/q/49948638
tags question: http://stackoverflow.com/q/50003188
tags question: http://stackoverflow.com/q/49980777
tags question: http://stackoverflow.com/q/50012762
tags question: http://stackoverflow.com/q/49963968
tags question: http://stackoverflow.com/q/49986466
tags question: http://stackoverflow.com/q/49994975
tags question: http://stackoverflow.com/q/50050776

http://stackoverflow.com/q/50035326
has title: Extracting the tuples from a list of tuples of tuples wherein the tuple contains a string
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50035413
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50035413
tagged with: list
downvote count: 2
has body: I have got a List of tuples of tuples like below: X= [(("a","b","c"),10),(("c","d","e"),20),(("f","e","g"),25)] and I am trying to extract the tuples wherein "c" is present. So the output should be [((("a","b","c"),10),(("c","d","e"),20)] I am trying to execute it in python. I tried this [item for item in X if "c" in item] However, it's not working. Any help in this regard will be appreciated.
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: tuples

http://stackoverflow.com/q/50009030
tagged with: python
accepted answer: http://stackoverflow.com/a/53813574
tagged with: gensim
tagged with: nlp
has answer: http://stackoverflow.com/a/53813574
has title: Correct way of using Phrases and preprocess_string gensim
linked to: http://stackoverflow.com/q/35716121
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90958692
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: What is the correct way to use gensim's Phrases and preprocess_string together ?, i am doing this way but it a little contrived. from gensim.models.phrases import Phrases from gensim.parsing.preprocessing import preprocess_string from gensim.parsing.preprocessing import strip_tags from gensim.parsing.preprocessing import strip_short from gensim.parsing.preprocessing import strip_multiple_whitespaces from gensim.parsing.preprocessing import stem_text from gensim.parsing.preprocessing import remove_stopwords from gensim.parsing.preprocessing import strip_numeric import re from gensim import utils # removed "_" from regular expression punctuation = r"""!"#$%&amp;'()*+,-./:;&lt;=&gt;?@[\]^`{|}~""" RE_PUNCT = re.compile(r'([%s])+' % re.escape(punctuation), re.UNICODE) def strip_punctuation(s): """Replace punctuation characters with spaces in `s` using :const:`~gensim.parsing.preprocessing.RE_PUNCT`. Parameters ---------- s : str Returns ------- str Unicode string without punctuation characters. Examples -------- &gt;&gt;&gt; from gensim.parsing.preprocessing import strip_punctuation &gt;&gt;&gt; strip_punctuation("A semicolon is a stronger break than a comma, but not as much as a full stop!") u'A semicolon is a stronger break than a comma but not as much as a full stop ' """ s = utils.to_unicode(s) return RE_PUNCT.sub(" ", s) my_filter = [ lambda x: x.lower(), strip_tags, strip_punctuation, strip_multiple_whitespaces, strip_numeric, remove_stopwords, strip_short, stem_text ] documents = ["the mayor of new york was there", "machine learning can be useful sometimes","new york mayor was present"] sentence_stream = [doc.split(" ") for doc in documents] bigram = Phrases(sentence_stream, min_count=1, threshold=2) sent = [u'the', u'mayor', u'of', u'new', u'york', u'was', u'there'] test = " ".join(bigram[sent]) print(preprocess_string(test)) print(preprocess_string(test, filters=my_filter)) The result is: ['mayor', 'new', 'york'] ['mayor', 'new_york'] #correct part of the code w…
downvote count: 0

http://stackoverflow.com/comment/87126382
type: Comment
type: QuestionComment
score: 0
has text: Why are you opening the file in `a+` mode just to read from it? That'll mean you always read nothing. And you weren't doing it in your original code, before adding the loop.
comment on: http://stackoverflow.com/q/50054958

http://stackoverflow.com/q/50042617
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87101260
has comment: http://stackoverflow.com/comment/87101166
answer count: 1
accepted answer: http://stackoverflow.com/a/50042680
has body: I have a logic need to count the iteration counts = [] for .. in ..: count = 0 for .. in ..: if ..: count +=1 counts.append(count) How to change this logic into single line loop in python
tagged with: python
has answer: http://stackoverflow.com/a/50042680
has comment: http://stackoverflow.com/comment/87101211
has title: Nested for loop in Single Line
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87118026
upvote count: 3
downvote count: 3
linked to: http://stackoverflow.com/q/18072759

http://stackoverflow.com/a/49958223
type: AcceptedAnswer
downvote count: 0
score: 2
accepted answer of: http://stackoverflow.com/q/49958177
has body: Use in colour= input("What is your favourite colour? ") if colour in ("red", "Red"): print("Red is my favourite colour as well")
type: Answer
answers question: http://stackoverflow.com/q/49958177
upvote count: 2
has comment: http://stackoverflow.com/comment/86932754

http://stackoverflow.com/q/50021933
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87059734
tagged with: python
has body: I have multiple uwsgi.ini. /etc/uwsgi/vassals/a/uwsgi_a.ini /etc/uwsgi/vassals/b/hoge/uwsgi_b.ini In this case, how can I specify multiple directories with Emperor? [uwsgi] emperor = /etc/uwsgi/vassals(.*)
score: 0
answer count: 0
has title: How can I specify different level of multiple directories with uwsgi Emperor?
has comment: http://stackoverflow.com/comment/87061448
tagged with: uwsgi

http://stackoverflow.com/q/50063091
has body: I'm trying to add a header using the Flatten function in Apache beam. However, there doesn't appear to be a way to set the order according to the documentation: https://beam.apache.org/documentation/sdks/pydoc/2.4.0/apache_beam.transforms.core.html?highlight=flatten#apache_beam.transforms.core.Flatten. Sometimes the header is at the end of the data, and others at the top. Is there a way to set the order? Wondering if there's something I'm missing. with beam.Pipeline(options=options) as p: header = [ ('name', 'number'), ] phones_list = [ ('amy', '111-222-3333'), ('james', '222-333-4444'), ('amy', '333-444-5555'), ('carl', '444-555-6666'), ] header = p | 'Header' &gt;&gt; beam.Create(header) phones = p | 'CreatePhones' &gt;&gt; beam.Create(phones_list) merged = ((phones,header) | 'MergedPColl' &gt;&gt; beam.Flatten()) output = merged output | 'Write' &gt;&gt; beam.io.WriteToText('./_output') Output 1: ('amy', '111-222-3333') ('james', '222-333-4444') ('amy', '333-444-5555') ('carl', '444-555-6666') ('name', 'number') Output 2: ('name', 'number') ('amy', '111-222-3333') ('james', '222-333-4444') ('amy', '333-444-5555') ('carl', '444-555-6666')
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: apache-beam
tagged with: python
has title: Flattening a PCollection in Tuple Order
has answer: http://stackoverflow.com/a/50475463
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/87066401
comment on: http://stackoverflow.com/q/50022829
type: QuestionComment
type: Comment
has text: You can just `driver.page_source` to get the HTML of the website if you want to use selenium. As for the error, it works fine on my machine. I don't know why it occurs in your case, but maybe [this](https://stackoverflow.com/questions/10667960/python-requests-throwing-sslerror) thread will help you.
score: 0

http://stackoverflow.com/q/50065665
score: 0
has answer: http://stackoverflow.com/a/50065756
linked to: http://stackoverflow.com/q/41369408
has body: I am trying to add a python function to my code, but when I do so I get an UnboundLocalError: Traceback (most recent call last): File "/Users/name/Documents/project.py", line 44, in logic(coinType, 3.56, bagWeight, 356, 0.01) File "/Users/name/Documents/project.py", line 14, in logic valueAddedCoins += value UnboundLocalError: local variable 'valueAddedCoins' referenced before assignment def logic(coin_txt, w1, wBag, cWeight, vCoin): diff = abs(wBag - cWeight) if diff == 0: print("Bag ok") return coins = diff / w1 value = coins * vCoin if wBag &lt; cWeight: valueAddedCoins += value print(int(coins), coin_txt, " coins missing") print(diff, "grams too little") else: valueRemovedCoins += value print(int(coins), coin_txt, " coins too many") print(diff, " grams too many") valueAddedCoins = 0 valueRemovedCoins = 0 numBagsChecked = 0 continueChecking = True; while continueChecking: #asking information about the coins and deducing wether or not the weight is correct bagWeight = float(input("Weight of bag of coins (no unit): ")) coinType = input("Type of coins in bag: 1 pence or 2 pence?") numBagsChecked += 1 if coinType == "1 pence": logic(coinType, 3.56, bagWeight, 356, 0.01) elif type_of_coin == "2 pence": logic(coinType, 7.12, bagWeight, 712, 0.02) check = input("Another bag? (Y/N): ") if check == "N": continueChecking = False Why am I getting an UnboundLocalError?
has title: UnboundLocalError when assigning value to variable initialised outside function
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87148120
tagged with: python
has answer: http://stackoverflow.com/a/50065846

http://stackoverflow.com/comment/87090678
type: Comment
comment on: http://stackoverflow.com/q/50037109
has text: Actually i just want to handle this Scenario because it is possible one.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86863397
type: QuestionComment
comment on: http://stackoverflow.com/q/49923765
score: 0
type: Comment
has text: Use multi threading, there are many options to do that in python.

http://stackoverflow.com/comment/86932776
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49957157
type: QuestionComment
has text: @martineau if I show you my code in private would you be able to give me some pointers as to how I could change them into classes?

http://stackoverflow.com/q/49971085
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49973238
has body: So as you are about to see, I am just starting with Python/Scrapy/programming in general. I am trying to figure out how to do multiple form requests in the same spider. I am trying to scrape data from a clerk and recorder’s webpage, but for two (or more) different names. Here is what gets me the first pages of desired results (for the name “Cruz”): Import scrapy class LoginSpider(scrapy.Spider): name = "CRSpider5" login_url = 'http://recordingsearch.car.elpasoco.com/rsui/opr/search.aspx' start_urls = [login_url] def parse(self, response): validation = response.css('input[name="__EVENTVALIDATION"]::attr(value)').extract_first() state = response.css('input[name="__VIEWSTATE"]::attr(value)').extract_first() generator = response.css('input[name="__VIEWSTATEGENERATOR"]::attr(value)').extract_first() data = { '__EVENTVALIDATION' : validation, '__VIEWSTATE' : state, '__VIEWSTATEGENERATOR' : generator, '__LASTFOCUS' : '', '__EVENTTARGET' : '', '__EVENTARGUMENT' : '', 'ctl00$ContentPlaceHolder1$btnSubmit' : 'Submit+Search', 'ctl00$ContentPlaceHolder1$lbxDocumentTypes' : 'TRANS', 'ctl00$ContentPlaceHolder1$txtGrantorGranteeName' : 'cruz', } yield scrapy.FormRequest(url=self.login_url, formdata=data, callback=self.parse_quotes) def parse_quotes(self, response): for test in response.css('table#ctl00_ContentPlaceHolder1_gvSearchResults tr')[1:-2]: yield { 'Debtor': test.css("span::text").extract_first(), 'Creditor': test.css("span::text")[1].extract(), 'Date Recorded': test.css('font::text')[3].extract(), 'Instrument Number': test.css('font::text').extract_first(), 'County': 'El Paso' } I would like to do the same thing above but with multiple names (changing the 'ctl00$ContentPlaceHolder1$txtGrantorGranteeName' field to a different name like “smith” or “Jones”). How would I do this in the same spider? Thanks!
tagged with: python
tagged with: forms
has title: How do I make multiple form requests in the same Python spider with Scrapy
score: 0
has answer: http://stackoverflow.com/a/49973238
answer count: 1
tagged with: web-scraping
tagged with: scrapy
type: Question

http://stackoverflow.com/comment/86867252
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49925475
has text: Please never call your variables the names of standard objects, like `dict` or `list`. You will shadow them, and this may lead to mind-boggling bugs were obviously correct code does not work.

http://stackoverflow.com/a/50055924
accepted answer of: http://stackoverflow.com/q/50055739
type: Answer
answers question: http://stackoverflow.com/q/50055739
score: 1
has body: The error is quite self explanatory. You are performing - operator on string and int. In your code, age = Subscriber().inp-self.year after using user.setYear(int(record["Year_of_Birth"])) the 2nd operand is int but you forgot about first one, i.e. Subscriber().inp. A quick solution would be to do take input as inp = int(input("Please enter in the current year: ")) or use age = int(Subscriber().inp)-int(self.year) P.S. I tried age = int(Subscriber().inp)-int(self.year) approach with your code and it is working fine.
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49995318
upvote count: 3
answer count: 1
downvote count: 0
has title: Text Zooming Effect Trembling
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/50046156
tagged with: cairo
type: UnansweredQuestion
tagged with: animation
tagged with: python
tagged with: moviepy
tagged with: cffi
has body: I created a text zooming animation with MoviePy and Gizeh. However the results turned out different when the code is run on different OS. The following two gifs are generated by the same python code. The effect looks pretty good on MacOS, but poor on Linux. pretty good on MacOS effect trembling on Linux I'm sure that the libraries(MoviePy, Gizeh, Cairocffi, cffi, etc.) versions are the same on both systems. I also tried high fps or downsize the test but it didn't work. I don't know if this may be an issue or bad coding from my side. I tried to find out what caused this issue. I found the return values of the function ctx.text_extents(txt) in gizeh.py Line 489 ( same as cairo_text_extents, in cairocffi library, context.py, Line 2003) varies every frame on Linux. And on Mac the function always return the same values. However, even if I fixed the values, the effect remained the same. import sys import gizeh as gz from moviepy.editor import * def make_frame(t): surface = gz.Surface(360, 180, bg_color=(0, 0, 0)) text = gz.text('ENLARGE', fontsize=40, fontfamily='Arial Unicode', fill=(255,255,255), xy=(180, 90), fontweight='normal') text = text.scale(1+0.5*t, center=[180, 90]) text.draw(surface) return surface.get_npimage() child_clip = VideoClip(make_frame, duration=3) child_clip.write_gif('Result.gif',fps=24) I have locate this problem in Cairo library. I wrote a simple demo to create a sequence of images enlarging the text string. And I printed the return values of the function cairo_text_extents() which indicated the extents of the string. I run the same code on Linux and MacOS. The values stayed the same on MacOS. While on Linux, the values varied every frame. Tring to figure out why. #include "cairo.h" #include &lt;stdio.h&gt; int draw (const char* filename, float t) { cairo_surface_t *ImageSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,360,360); cairo_t *cr = cairo_create(ImageSurface); cairo_set_source_rgb (cr, 1., 1., 1.); cairo_paint (cr); cairo_matrix…

http://stackoverflow.com/q/50010327
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/87038941
favorite count: 0
type: Question
has title: Many to Many Nested Relationship as List in Django Rest Framework
tagged with: django
has body: I'm building an API using the Django Rest Framework and I have two models that share a many to many relationship. The models are Contacts and Tasks. A Task can be shared with several Contacts and a Contact can have many Tasks shared with it. I'm also using a manual join table, rather than Django's built-in many-to-many relationship. In the API, I'd like to have the method for retrieving Tasks include a list of Contacts with whom the Task has been shared. I have a way of accomplishing this currently, but it isn't great. The serialized Task has an attribute shared_with, which is a related field that goes through the SharedWithSerializer class (which is the version of the ContactTaskJoin serializer for this side of the relationship). So the output is quite clunky. The SharedWithSerializer has just one attribute—contact—which references the ContactSerializer class. An example Task returned by the API: { 'id': 100, 'shared_with': [ { 'contact': { 'id': 1, 'name': 'Alice' } }, { 'contact': { 'id': 2, 'name': 'Bob' } } ] } What I would like is to just have a plain list of the Contacts with whom the Task was shared. Something like: { 'id': 100, 'shared_with': [ { 'id': 1, 'name': 'Alice' }, { 'id': 2, 'name': 'Bob' }, ] } Any suggestions would be much appreciated.
tagged with: python
has answer: http://stackoverflow.com/a/50011126
accepted answer: http://stackoverflow.com/a/50011126

http://stackoverflow.com/q/50017785
score: 4
has comment: http://stackoverflow.com/comment/87074600
accepted answer: http://stackoverflow.com/a/50059123
has title: Artifactory: Local Pypi repos 'slow' after upgrade to new artifactory 5.10.3 with new Pypi support
upvote count: 4
has answer: http://stackoverflow.com/a/50059123
has comment: http://stackoverflow.com/comment/87061860
answer count: 2
downvote count: 0
tagged with: artifactory
tagged with: pip
tagged with: pypi
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50030878
has body: we updated our artifactoy to the newest version 5.10.3 to support the pypi update. after this update we experience some really slow pip install --upgrade times. pip install is running fine. I was able to pinpoint this slower runs to the local pypi repositiory on the artifactory. The official pypi and the cached remote pypi on the artifactory were fast. But the virtual pypi (remote und local pypi) and if i only add the local pypi via --extra-index-url were both slow Some versions, maybe we have some issues there: python 2.7 and 3.5 pip 9.0.1 and 10.01 artifactory 5.10.3 Run with official Pypi only: pip install -U -r requirements.txt 1.21s user 0.08s system 99% cpu 1.296 total Run with local pypi as extra-index-url: pip install -U -r requirements.txt 1.51s user 0.09s system 8% cpu 19.658 total And with the virtual pypi: pip install -U -r requirements.txt 1.57s user 0.10s system 4% cpu 38.573 total Unfortunately i don't have and time before the update. some ideas?
has answer: http://stackoverflow.com/a/50030878
tagged with: python

http://stackoverflow.com/comment/87043514
has text: This is absolutely correct and easy to understand, it is slower(~30 times slower for this specific case )than the accepted answer but not too slow for small problems like this one.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49948732

http://stackoverflow.com/q/50033183
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has body: I am trying to fit a Gaussian with on the following dataset (could not paste it all but hopefully that is enough rows) 2.738237424 0.1956847 2.742886384 0.1956847 2.747535344 0.1956847 2.752184304 0.1956847 2.756833264 0.1776788 2.761482224 0.1956847 2.766131184 0.1956847 2.770780144 0.1776788 2.775429104 0.1776788 2.780078064 0.1956847 2.784727024 0.1956847 2.789375984 0.1956847 2.794024944 0.1776788 2.798673904 0.1776788 2.803322862 0.1956847 Here is my code: x = data[590:880,0] y = data[590:880,1] error = np.repeat(0.001, (880 - 590)) # Model object def func(x, a, b, c, d): return a*np.exp(-(x-b)**2/c**2) + d quad_model = odr.Model(func) # Create a RealData object dataset = odr.RealData(x, y, sx=error) # Set up ODR with the model and data. odr = odr.ODR(dataset, quad_model, beta0=[-0.6, 3.7, -0.4, 0.2]) I get the message "func() missing 3 required positional arguments: 'b', 'c', and 'd'" Do you know what is going on? Thank you!
has title: "func() missing 3 required positional arguments: 'b', 'c', and 'd'"
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50033244
has comment: http://stackoverflow.com/comment/87082563
tagged with: curve-fitting
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/87082577
answer count: 1

http://stackoverflow.com/a/50013556
has body: I suppose that the problem is in an attempt to directly share a numpy matrix. I see these options. Make a separate matrix fragment per task, and then stitch them. Use explicit memory sharing, e.g. via multprocessing.Array, but with numpy it must use some additional tricks. If access patterns don't partition neatly, use an in-memory key-value database (redis, unqlite, maybe even sqlite) and store results as (coords tuple, value) from within the processes.
type: Answer
has comment: http://stackoverflow.com/comment/87060633
score: 0
has comment: http://stackoverflow.com/comment/87048247
answers question: http://stackoverflow.com/q/50012835

http://stackoverflow.com/q/50006229
answer count: 2
has answer: http://stackoverflow.com/a/50006374
has body: SOLVED Thanks to @James, This issue was completely solved! Solution Creating a specific function to create directories, shown below: # SETTINGS.PY pathNAME = '../Location' PathName2 = pathNAME + '/Location2' # Define Functions def make_dir(directoryName): if os.path.exists(directoryName): if os.path.isdir(directoryName): return False os.mkdir(directoryName) print(directoryName) return True And then In The Main Script import settings settings.make_dir(settings.pathNAME) settings.make_dir(settings.pathName2) That is how you do it! Thanks for everyone who tried to help! And Extra Thanks to @James!! Original Post VIDEO The Video Showing All My Code, and the problem Description Basically, I am attempting to create folders for my project if they do not exist, however, when I run the .py file that creates the folders, it only creates two of them, and then claims that all the files already exist. Even though in the file explorer they do not (They also do not exist in terminal when I do ls). I tried moving the variables into the same file, and, I tried getting rid of the if statements, I also tried doing the os.mkdir() &amp; setting the existOk to true. I never get any errors Console Outputs First Run (No Folders Exist) True # Main Directory: It thinks the base directory already exists False # Logs Directory: It knows that the other directories do not exist False # Users Directory: ^ False # Inventory Directory: ^^ False # Stats Directory: ^^^ ../FrozenDesert # It Created The Base Directory ../FrozenDesert/Users # It Created The Users Directory Second Run (Users &amp; Main Directory Exist) True # Main Directory: Knows it exists True # Logs Directory: Thinks it exists True # Users Directory: Knows it exists True # Inventory Directory: Thinks it exists True # Stats Directory: Thinks it exists # No Directories were created The Code Login Directory (Irrelevant) #Imports import time import os import settings # Request User Input print('Welcome To The Frozen Desert. Would You Like…
has title: Issues With Directory Creation
type: Question
possible better answer: http://stackoverflow.com/a/50006374
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50006514
has comment: http://stackoverflow.com/comment/87029069
tagged with: python
tagged with: python-3.x
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/50006514
score: 0

http://stackoverflow.com/q/50034761
has comment: http://stackoverflow.com/comment/87126467
has comment: http://stackoverflow.com/comment/87115908
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87143499
linked to: http://stackoverflow.com/q/16114100
has comment: http://stackoverflow.com/comment/87145693
has body: I'm writing a function that I'd like to translate to C as much as possible using Cython. To do this, I'll need to use linear algebra operations. Here is my function. EDIT: The lesson I've learned is to try to take care of linear algebra outside of loops, which I've largely been able to do. Otherwise, resort to wrapping LAPACK/BLAS or writing my own functions. import numpy as np from scipy.stats import multivariate_normal as mv import itertools def llf(data, rho, mu, sigma, A, V, n): '''evaluate likelihood by guass-hermite quadrature Parameters ---------- data : array N x J matrix, columns are measurements rho : array length L vector of weights for mixture of normals mu : array L x K vector of means of mixture of normals sigma : array K x L*K matrix of variance matrices for mixture of normals A : array J x (K + 1) matrix of loadings V : array J x J variance matrix of measurement errors n : int number of sample points for quadrature ''' N = data.shape[0] L, K = mu.shape # getting weights and sample points for approximating integral v, w = np.polynomial.hermite.hermgauss(n) totllf = 0 for i in range(N): M_i = data[i, :] totllf_i = 0 for l in range(L): rho_l = rho[l] sigma_l = sigma[:, K*l:K*(l+1)] mu_l = mu[l, :] chol_l = np.linalg.cholesky(sigma_l) for ix in itertools.product(*(list(range(n)) for k in range(K))): wt = np.prod(w[list(ix)]) pt = np.sqrt(2)*chol_l.dot(v[list(ix)]) + mu_l totllf_i += wt*rho_l*mv.pdf(M_i, A[:, 0] + A[:, 1:].dot(pt), V) totllf += np.log(totllf_i) return totllf In order to accomplish this I'd need to have functions for matrix multiplication, transpose, determinant, matrix inverse and cholesky decompostion. I've seen some posts on using BLAS functions, but its really unclear to me how to use these. EDIT 04/29/18 As suggested, I've taken a memory view approach and initialized everything prior to the loop. My new function is written as def llf_c(double[:, ::1] data, double[::1] rho, double[:, ::1] mu, double[:, ::1] sigma, double[:, ::1] A, dou…
accepted answer: http://stackoverflow.com/a/50077045
has answer: http://stackoverflow.com/a/50077045
answer count: 1
downvote count: 0
score: 6
tagged with: cython
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87126359
has comment: http://stackoverflow.com/comment/87128159
has comment: http://stackoverflow.com/comment/87113294
tagged with: python
has comment: http://stackoverflow.com/comment/87119670
upvote count: 6
has comment: http://stackoverflow.com/comment/87117147
has title: Efficient matrix operations in cython with no python objects

http://stackoverflow.com/q/50049290
has answer: http://stackoverflow.com/a/50049945
possible better answer: http://stackoverflow.com/a/50049945
has answer: http://stackoverflow.com/a/50050109
tagged with: python
has title: Python printing list of floats given the range
type: Question
score: 0
answer count: 2
has body: I'm trying to emulate a really simple version of the gamble game "Crash", where there's a number that increases every second and it's also the multiplier of your credits. So if you put in 50 credits and the multiplier goes to 3.30, you will get 50*3.30=165 credits. The number randomly crashes, and if you did not withdraw your money, you lose them. from random import randrange, randint crash_max_range = 50 crash_min_range = 0 multiplier_crash = list(range(crash_min_range, crash_max_range)) multiplier_crash = [float(i) for i in multiplier_crash] print(*multiplier_crash, sep="\n") The main thing that i'm struggling with is printing the float list which should look like 0 0.01 0.02 0.03 etc.. (every number on a new line) I don't also know how to increase the chance that it will crash like 70% of the time at a low range because obviously the player can't always win. Could you help me with that?
accepted answer: http://stackoverflow.com/a/50050109
tagged with: gambling
type: AnsweredQuestion

http://stackoverflow.com/comment/87178067
comment on: http://stackoverflow.com/a/50070032
has text: Hi again Paul, I think you are assuming too much without questioning @Mauricio Rivera. You could be right but your "answer" is not an answer it's a comment. If you want to present it as an answer then care to elaborate a real answer. That was just my intention. Good luck
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86993379
has text: @Jean-FrançoisFabre you are right thanks! my brain just stopped for a second!
comment on: http://stackoverflow.com/a/49988217
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49950188
type: Question
has answer: http://stackoverflow.com/a/49950400
has comment: http://stackoverflow.com/comment/86917156
has comment: http://stackoverflow.com/comment/86917154
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: Python - Pass index value dynamically
has body: I am reading a deeply nested dictionary called response and getting a formatted output response = {u'ResultSet': {u'Rows': [ {u'Data': [{u'VarCharValue': u'Table_name'}, {u'VarCharValue': u'Validation_Scenario'}, {u'VarCharValue': u'No_of_Records'}, {u'VarCharValue': u'Result'}]}, {u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'01_scenario2'}, {u'VarCharValue': u'100'}, {u'VarCharValue': u'FAIL'}]}, {u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'02_scenario1'}, {u'VarCharValue': u'200'}, {u'VarCharValue': u'FAIL'}]}, {u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'03_scenario3'}, {u'VarCharValue': u'300'}, {u'VarCharValue': u'PASS'}]}, {u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'04_scenario4'}, {u'VarCharValue': u'400'}, {u'VarCharValue': u'PASS'}]}]}} print (("{0[ResultSet][Rows][0][Data][0][VarCharValue]}".format(response)), ("{0[ResultSet][Rows][0][Data][1][VarCharValue]}".format(response)), ("{0[ResultSet][Rows][0][Data][2][VarCharValue]}".format(response)), ("{0[ResultSet][Rows][0][Data][3][VarCharValue]}".format(response))) Output: ('Table_name', 'Validation_Scenario', 'No_of_Records', 'Result') Now when i want to loop through the indexes [0][Data] from 0 to 4 i am getting Python - TypeError: list indices must be integers, not str for i in range(4): print (("{0[ResultSet][Rows][i][Data][0][VarCharValue]}".format(response)), ("{0[ResultSet][Rows][i][Data][1][VarCharValue]}".format(response)), ("{0[ResultSet][Rows][i][Data][2][VarCharValue]}".format(response)), ("{0[ResultSet][Rows][i][Data][3][VarCharValue]}".format(response))) Error :TypeError: list indices must be integers, not str I understand that since there is " " i is treated as a string but i wanted to know how can i pass the index values dynamically?
accepted answer: http://stackoverflow.com/a/49950400
favorite count: 0

http://stackoverflow.com/q/50026147
tagged with: geocoding
tagged with: lambda
score: 0
has body: I was trying to do the geo-coding to pull the postcodes. I have two different data sources applied to the geo-coding. a. First try with street address &amp; city &amp; country b. If nothing rerun then try with city &amp; country My program is like below, it works fine if I just do the first approach but if I want to combine both it is problematic: from geopy.geocoders import Nominatim geolocator = Nominatim() geolocator=Nominatim(timeout=1000) import io import sys # import urllib.request sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码 import pandas as pd df = pd.read_csv("Italy.csv", encoding="cp1252") #改变标准输乳的默认编码 # print(df) df["Conca_1"]=df["country2"]+" " " "+df["City"]+" " " "+df["Address Line 1"] df["Conca_2"]=df["country2"]+" " " "+df["City"] # print(df["Conca2"]) df["Coordinates_1"]=df["Conca_1"].apply(geolocator.geocode) df["Coordinates_2"]=df["Conca_2"].apply(geolocator.geocode) # df["zip"] = df['Coordinates_1'].apply(lambda x: x[0].split(',')[-2] if x != None else None) df["zip"] = df['Coordinates_1'].apply(lambda x: x[0].split(',')[-2] if x != None else df['Coordinates_2'].apply(x[0].split(',')[-2] if x != None else None )) print(df["zip"]) writer = pd.ExcelWriter('coordinates_result.xlsx', engine='xlsxwriter') # Convert the dataframe to an XlsxWriter Excel object. df.to_excel(writer, sheet_name='Sheet1') writer.save()
tagged with: pandas
answer count: 1
has title: Geo-coding with Pandas - apply different geo-coding to lambda x based on conditions
type: Question
tagged with: geopy
has answer: http://stackoverflow.com/a/50031917
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50044373
downvote count: 1
possible better answer: http://stackoverflow.com/a/50044428
duplicate of: http://stackoverflow.com/q/588004
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87105213
has comment: http://stackoverflow.com/comment/87105609
upvote count: 3
has comment: http://stackoverflow.com/comment/87105708
tagged with: python
has comment: http://stackoverflow.com/comment/87105695
favorite count: 0
tagged with: precision
type: Question
score: 2
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/87105126
has title: np.arange's weird behavior
accepted answer: http://stackoverflow.com/a/50044444
has answer: http://stackoverflow.com/a/50044428
has comment: http://stackoverflow.com/comment/87106417
has answer: http://stackoverflow.com/a/50044444
has body: I am trying to make an array of N+1 bins for a distribution of N discrete scores. I assumed numpy's arange could be used for that. However, the function gives me odd values, which have a significant effect on the resulting numpy histograms. Here's a minimal example: n = 10 a = np.arange(0, 1.01 + 1/n, 1/n) print(a) for i in a: print(i) [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. 1.1] 0.0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6000000000000001 0.7000000000000001 0.8 0.9 1.0 1.1 The fact that simply printing the array outputs seemingly normal values is extra misleading. This is a big issue if I want to use this array as a bins argument to numpy's histogram() function because my values are k/10 decimals. In particular, all data points with the value of 0.7 will be placed in the [0.6000000000000001, 0.7000000000000001] bin, whereas I'd expect them to be inside [0.7, 0.8], as per np.histogram() documentation. The question is whether this is a bug or a feature.
linked to: http://stackoverflow.com/q/588004

http://stackoverflow.com/a/49977378
has comment: http://stackoverflow.com/comment/86980995
has comment: http://stackoverflow.com/comment/86980884
type: Answer
has body: You should avoid iterating pandas dataframe rows where possible, as this is inefficient and less readable. You can implement your logic using pd.DataFrame.merge and pd.Series.between. I have changed the data in your example to make it more interesting. import pandas as pd df_json = pd.DataFrame({'chromosome': [7, 12, 17, 6, 9], 'ensembl_id': ['ENSG00000122543', 'ENSG00000111325', 'ENSG00000181396', 'ENSG00000119900', 'ENSG00000106809'], 'gene_end': [5886362, 122980043, 82418637, 71308950, 92404696], 'gene_start': [5879827, 122974580, 82389223, 71288803, 92383967]}) df = pd.DataFrame({'rs_id': ['rs13184706', 'rs58824264'], 'variant': ['5:43888254:C:T', '5:43888493:C:T'], 'gene_id': [5880000, 43888493], 'chromosome': [7, 9]}) res = df_json.merge(df, how='left', on='chromosome') res = res[res['gene_id'].between(res['gene_start'], res['gene_end'])] print(res) # chromosome ensembl_id gene_end gene_start gene_id rs_id \ # 0 7 ENSG00000122543 5886362 5879827 5880000.0 rs13184706 # variant # 0 5:43888254:C:T
score: 0
answers question: http://stackoverflow.com/q/49976134

http://stackoverflow.com/q/50027201
downvote count: 0
score: 1
upvote count: 1
has title: Installation of pyrebase returns an error
favorite count: 0
type: Question
has body: I am trying to install pyrebase on a virtual environment of pyhon 3.6, but I get a long list of errors: Collecting googleapis-common-protos (from gcloud==0.17.0-&gt;pyrebase) Using cached https://files.pythonhosted.org/packages/00/03/d25bed04ec8d930bcfa488ba81a2ecbf7eb36ae3ffd7e8f5be0d036a89c9/googleapis-common-protos-1.5.3.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/setuptools/__init__.py", line 10, in &lt;module&gt; from setuptools.extern.six.moves import filter, filterfalse, map File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/setuptools/extern/__init__.py", line 1, in &lt;module&gt; from pkg_resources.extern import VendorImporter File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3017, in &lt;module&gt; @_call_aside File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3003, in _call_aside f(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3045, in _initialize_master_working_set dist.activate(replace=False) File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2577, in activate declare_namespace(pkg) File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2151, in declare_namespace _handle_ns(packageName, path_item) File "/Users/hugovillalobos/Documents/Code/FirebaseProject/FirebaseVenv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2091, in _handle_ns _rebuild_mod_path(path, packageName, m…
tagged with: firebase
has answer: http://stackoverflow.com/a/64349569
tagged with: python
accepted answer: http://stackoverflow.com/a/50103097
possible better answer: http://stackoverflow.com/a/64349569
has answer: http://stackoverflow.com/a/50103097
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/50039857
score: 1
accepted answer of: http://stackoverflow.com/q/50039771
type: Answer
answers question: http://stackoverflow.com/q/50039771
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Use map: s = df.groupby('Type').size() DFGroup = df.groupby('Type')['Nr'].nunique().reset_index() DFGroup['new'] = DFGroup['Type'].map(s) print (DFGroup) Type Nr new 0 One 2 5 1 Two 2 4 Better is use agg by both functions: DFGroup = df.groupby('Type')['Nr'].agg([('Nr', 'nunique'),('Count','size')]).reset_index() print (DFGroup) Type Nr Count 0 One 2 5 1 Two 2 4

mechanicalsoup
tags question: http://stackoverflow.com/q/50031945
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/49929821
type: Tag

http://stackoverflow.com/comment/86950739
type: QuestionComment
comment on: http://stackoverflow.com/q/49967190
score: 0
type: Comment
has text: https://docs.python.org/3.6/library/csv.html then perhaps? Python has builtin csv parsing.

http://stackoverflow.com/q/49972507
type: Question
upvote count: 2
tagged with: google-api
downvote count: 0
tagged with: google-calendar-api
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/49974861
has answer: http://stackoverflow.com/a/49974861
type: AnsweredQuestion
score: 2
has body: I am using Python Google API V3 to manipulate the Google Calendar from the server side of my web application. I would like users to be able to see new calendars they created through their web browsers. The thing is that I cannot find the URL needed to pass to HTML iframe in order for it to show up on the site. No URL, nor part of it, like the ID in form xxxxxxxxxx@group.calendar.google.com. Calendar dicts returned by thecal.calendarList().list().execute() contain nothing useful in regard to this problem. Does anyone know how to achieve what I want? I cannot go adding each new calendar manually.
tagged with: google-api-python-client
favorite count: 0
has title: Automatically embeding Google Calendar

http://stackoverflow.com/q/50018191
downvote count: 0
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50018219
type: AnsweredQuestion
has body: I have data, with 2 indices (date and time) which I imported with pandas.read_csv() and it looks initially like this: Date Time Volume 2016-01-04 2018-04-25 09:01:29 53645 2018-04-25 10:01:29 123 2018-04-25 10:01:29 1345 .... 2016-01-05 2018-04-25 10:01:29 123 2018-04-25 12:01:29 213 2018-04-25 10:01:29 123 .... I want to group it for every day on groups of 20min bins. It should look like this. Date Time Volume 2016-01-04 2018-04-25 09:00:00 53645 2018-04-25 09:20:00 456453 2018-04-25 09:40:00 13153 .... 2018-04-25 17:00:00 13153 2016-01-05 2018-04-25 09:00:00 46465 2018-04-25 09:20:00 454688 2018-04-25 09:40:00 45645 .... 2018-04-25 17:00:00 45646 I've already achieved what I want, but I'm quite sure, that there is a more "pythonic" and less memory consuming way to achieve my goal. My code now looks like: frames = [] for date, sub_df in _file_data.groupby(level=0): gr = sub_df.groupby(pd.Grouper(level=1, freq="20min")).sum() frames.append(gr) _file_data = pd.concat(frames)
tagged with: pandas-groupby
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/50018219
has title: pandas apply groupby on a groupby object
answer count: 1

http://stackoverflow.com/q/50042951
has comment: http://stackoverflow.com/comment/87108670
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/11779143
has title: Import librairy like JSON or XML for python, with IronPython on C# App
tagged with: python
has comment: http://stackoverflow.com/comment/87102501
has body: I am trying to execute a Python Script on a C# Application. So I choose Iron Python, I have managed to execute basic code. But while using libraries like xml or json. I cannot import and use them. I've tried a lot,but nothing works out. The main thing which I tried was to copy the xml librairy in my C# project folder, and then import it using the following code: import clr clr.AddReferenceToFileAndPath("..\\ElementTree.py") import ElementTree as ET clr.AddReferenceToFileAndPath("..json\\__init__.py") import json But i get this error : System.BadImageFormatException: 'The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)' Can someone provide me a with a good solution? If you need more details, please comment the question. Thanks in advance
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87326124
score: 1
downvote count: 0
tagged with: ironpython
tagged with: wpf
favorite count: 0
type: Question
tagged with: c#

http://stackoverflow.com/comment/87044424
score: 0
has text: @shadow, no, it should be just fine.
comment on: http://stackoverflow.com/a/49997966
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87102262
type: QuestionComment
has text: OK, from my research it suggested that if I could return the variable from a function I could avoid globals? So is there not really a way to achieve what I want without using a global do you think?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50042645

http://stackoverflow.com/comment/87109105
comment on: http://stackoverflow.com/q/50046164
score: 1
type: Comment
has text: @tobias_k: given that `data` is the result of a `map(float, ...)` call, I don't think the additional `float()` conversion is necessary there. :-P
type: QuestionComment

http://stackoverflow.com/a/49926039
answers question: http://stackoverflow.com/q/49921878
accepted answer of: http://stackoverflow.com/q/49921878
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Looks like you want to have an extra size attribute on your DataType Enum (and maybe a __doc__ as well). You can roll your own (if using the stdlib or the enum34 backport, or take advantage of aenum's advanced features1. Rolling your own with enum34 (py2/3) or the stdlib enum (3.4+): from enum import IntEnum class DataTypes(IntEnum): def __new__(cls, value, size, doc): obj = int.__new__(cls) obj._value_ = value return obj def __init__(self, value, size, doc): # value already handled, ignore it self.size = size self.__doc__ = doc Bytei = 0, 8, 'RAM buffer variable (on-off input)' Byteo = 1, 8, 'RAM buffer variable (on-off output)' Bytem = 2, 8, 'RAM buffer variable (flag)' Wordi = 3, 16, 'RAM system variable (signed int)' Wordo = 4, 16, 'RAM system variable (signed int)' Wordm = 5, 16, 'RAM buffer variable (signed int)' Wordp = 6, 16, 'E2PROM variable (parameter) (signed int)' Dworm = 7, 32, 'RAM buffer variable (signed long int)' Dworp = 8, 32, 'E2PROM variable (parameter) (signed long int)' Taking advantage of aenum's features (py2/3): from aenum import IntEnum class DataTypes(IntEnum): _init_ = 'value size __doc__' Bytei = 0, 8, 'RAM buffer variable (on-off input)' Byteo = 1, 8, 'RAM buffer variable (on-off output)' Bytem = 2, 8, 'RAM buffer variable (flag)' Wordi = 3, 16, 'RAM system variable (signed int)' Wordo = 4, 16, 'RAM system variable (signed int)' Wordm = 5, 16, 'RAM buffer variable (signed int)' Wordp = 6, 16, 'E2PROM variable (parameter) (signed int)' Dworm = 7, 32, 'RAM buffer variable (signed long int)' Dworp = 8, 32, 'E2PROM variable (parameter) (signed long int)' And in use: --&gt; print repr(DataTypes.Bytei) &lt;DataTypes.Bytei: 0&gt; --&gt; print DataTypes.Bytei DataTypes.Bytei --&gt; print DataTypes.Bytei.size 8 --&gt; print DataTypes.Bytei.__doc__ RAM buffer variable (on-off input) 1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
type: Answer
has comment: http://stackoverflow.com/comment/86878463
has comment: http://stackoverflow.com/comment/86874041
score: 2

http://stackoverflow.com/q/49936798
tagged with: python-3.x
answer count: 0
has body: I am trying to run a python script with command line "date" why do I get a number when I introduce sys.argv[1] import sys xDate=sys.argv[1] print(xDate) 43263 sys.version Out[134]: '3.5.3 |Intel Corporation| (default, Apr 27 2017, 18:08:47) \n[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)]'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86890194
has title: Command line sys.argv [1]
has comment: http://stackoverflow.com/comment/86889674
has comment: http://stackoverflow.com/comment/86889113
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86889413
type: Question

http://stackoverflow.com/a/50048589
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87113764
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50048494
has body: If I understand correctly what you're trying to do, you want to allow dashes everywhere in the match but preserve them in the output. Let's do exactly that: import re test = 'abcd---efghi-j-k-l---mnopq-r--st-uvw-x-yz' def match_gaps(match_string, match_target): chars = [re.escape(c) for c in match_target] # allow special-chars regex = re.compile('-*'.join(chars)) # allow dashes between chars return regex.findall(match_string) print(match_gaps(test, 'klmno')) ['k-l---mno'] You may need to make some minor adjustments so the output is exactly how you want it but the idea is identical. The only somewhat tricky part is the re.escape (which might not even be necessary for you).
answers question: http://stackoverflow.com/q/50048494
type: Answer

http://stackoverflow.com/comment/87099442
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50037919
has text: I do not understand what exactly your question is. Usually you want the latent vectors to be unit Gaussian. So you would use [tf.distributions.Normal](https://www.tensorflow.org/api_docs/python/tf/distributions/Normal) to sample such vectors.

http://stackoverflow.com/a/49928835
score: 0
type: Answer
has body: There are several problems with your code: You open the file for appending, but you don't want to append, you want to insert. Of course that is possible, but then you need to know where to position the file pointer, read everything after that in a buffer, write your new stuff, then write the buffer. Knowing where to position your file pointer is going to be the difficult part. You do yaml.allow_duplicate_keys = True but that doesn't do anything in PyYAML. It is a ruamel.yaml feature, that allows you to read files with duplicate keys (disallowed by the YAML specification, but silently ignored by the non-conforming PyYAML library). You should not manipulate the YAML file directly, and always use load the data from YAML, update it and dump. That way your YAML will be conforming, even if, for instance, one of your inputs contains a single or double quote, or spaces (as you can see from 'Trial ', that needs quotes in YAML because of the space). You are only using mappings in your YAML file, but such lists of trials, lend themselves much better to sequences. Your keys have enumeration information, this is almost always a bad idea, because you cannot know up-front what the key looks like. So instead of a key Board 1 you should have a key Board with a value 1, or as value a mapping with numbers of the boards as key. That way it is easy to get the data for a particular board number (or update the trials if handled in the same way) To start you should make the status.yaml file look like: - Board: 1 Trial: 1 Reading1: 450 Status: Pass - Board: 2 Trial: 1 Reading1: 758 Status: Fail - Board: 3 Trial: 1 Reading1: 450 Status: Pass or use: Boards: - nr: 1 Trials: - nr: 1 Reading1: 450 Status: Pass - nr: 2 Trials: - nr: 1 Reading1: 758 Status: Fail - nr: 3 Trials: - nr: 1 Reading1: 450 Status: Pass or (my favourite): Boards: 1: Trials: 1: Reading: 450 Status: Pass 2: Trials: 1: Reading: 758 Status: Fail 3: Trials: 1: Reading: 450 Status: Pass In the first example you should walk ove…
answers question: http://stackoverflow.com/q/49925187

http://stackoverflow.com/a/50020630
accepted answer of: http://stackoverflow.com/q/50020436
downvote count: 0
answers question: http://stackoverflow.com/q/50020436
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87057008
has body: string = """"(CB)-year-(3F)-year- (56)-ADDR(01)-DATA(06)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new- (56)-ADDR(01)-DATA(03)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new- (05)-ADDR5-[address0]-(E0)-tWHR2-nintK- (56)-ADDR(01)-DATA(05)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new-""" Your string above ending with - and in python the complete string is considered as single string not different one hence all other hyphens are not considered as end of string in .endswith() strings are just separated by new line \n so you need to split first and join them as below: In [12]: print('\n'.join([i[:-1] if i[-1] == '-' else i for i in string.split('\n')])) "(CB)-year-(3F)-year (56)-ADDR(01)-DATA(06)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new (56)-ADDR(01)-DATA(03)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new (05)-ADDR5-[address0]-(E0)-tWHR2-nintK (56)-ADDR(01)-DATA(05)-(00)-ADDR5-PBX-CHX-[address0]-(CA)-new Logic: '\n'.join(...) join all the string iterables with \n i[:-1] gives string without last character i[-1] == '-' checks if last character of string ending with hyphen - or not string.split('\n') splits your string with separator \n results in a list of string which is iterated in list comprehension Time comparison: In [18]: %timeit re.sub('-:?$', '', string, flags=re.MULTILINE) 2.74 µs ± 91.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [19]: %timeit '\n'.join([i[:-1] if i[-1] == '-' else i for i in string.split('\n')]) 1.56 µs ± 24.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
type: Answer
has comment: http://stackoverflow.com/comment/87057051

http://stackoverflow.com/comment/87168015
comment on: http://stackoverflow.com/a/50072702
score: 0
has text: @rouhollah ghasempour Thank you for references but I have enough knowledge about DR and PCA particularly and how it rise performance. But how "feature reduction (like PCA) approaches to tackle the overfitting problem" would work? I don't understand.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49966770
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86949478
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86951394
tagged with: python
tagged with: random-seed
score: 18
tagged with: numpy
upvote count: 19
has comment: http://stackoverflow.com/comment/86949174
has comment: http://stackoverflow.com/comment/86949351
answer count: 1
accepted answer: http://stackoverflow.com/a/49966799
has body: I would like to use np.random.seed() in the first part of my program and cancel it in the second part. Again, in the first part of my python file, I want the same random numbers to be generated at each execution in the second part , I want different random numbers to be generated at each execution
has title: How to cancel the effect of numpy seed()?
downvote count: 1
linked to: http://stackoverflow.com/q/49555991
has answer: http://stackoverflow.com/a/49966799
has comment: http://stackoverflow.com/comment/86949189

http://stackoverflow.com/comment/115975177
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50005190
type: AnswerComment
has text: @jstol, I like your solution, it's just missing a closing parenthesis: `df[g.ngroup().isin(choice(g.ngroups, 2, replace=False))]` and for those (like me that didn't spot it initially) that `import numpy as np`, the line should read `df[g.ngroup().isin(np.random.choice(g.ngroups, 2, replace=False))]`

http://stackoverflow.com/comment/86935069
type: Comment
comment on: http://stackoverflow.com/a/49957949
score: 0
has text: `Each entry in labels must be an index in [0, num_classes). Other values will raise an exception when this op is run on CPU, and return NaN for corresponding loss and gradient rows on GPU.`
type: AnswerComment

http://stackoverflow.com/a/49969646
has body: You have to setup the environment to where you have python installed or setup a virtual environment. Mine happens to be located in ~/anaconda3/bin/python on my linux and ~/local_interp/bin/python on my mac. If you use the command line you can search for the path where you installed python. If you downloaded using pip install or conda install it should lead you where you need to be. You can go to "Preferences" --> "Project Interpreter". Choose the tool button at the right top corner. Then choose "More..." --> "Show path for the selected interpreter" --> "Add". Then you can add a path. Check out this page. It doesn't have the exact answer you are looking for but it contains all of the information that you would need to figure it out for your particular case. How do I import modules in pycharm?
type: Answer
accepted answer of: http://stackoverflow.com/q/49969416
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49969416

http://stackoverflow.com/q/49971952
type: Question
has title: python MySQL connector and parameterized query
has comment: http://stackoverflow.com/comment/87350480
has body: Python 3.6 / MySQL 5.6 I am still pretty new to python though I've used MySQL in other coding languages for sometime. In a dev environment I want to drop all tables in a particular database. I could drop the database but the hosting provider locks down some MySQL controls so dropping "databases" is possible from the command line or code but creating them is only allowed through their management web panel. That is a time consuming pain. I can drop/create the tables from command line or code much easier. I wrote a python script that I can call from a Makefile when i want to clean/restart the project. import os import mysql.connector.django DBI = mysql.connector.connect( option_files=os.path.join(os.path.expanduser("~"), ".my.cnf"), option_groups="membersdev" ) cursorFind = DBI.cursor(buffered=True) cursorDrop = DBI.cursor(buffered=True) query = """ select TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA = %s """ cursorFind.execute(query, ('dev_site_org',)) query2 = "DROP TABLE IF EXISTS %s" for tableName in cursorFind.fetchall(): cursorDrop.execute(query2, tableName) cursorDrop.close() cursorFind.close() DBI.close() I am pretty sure that "query2" is syntactically correct with a parameter. I think that cursorDrop.execute(query2, tableName) is correct since tableName is a tuple; but, I keep getting the exception and stack trace: Traceback (most recent call last): File "/home/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 377, in cmd_query raw_as_string=raw_as_string) _mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''My_First_Table'' at line 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "misc_scripts/db_delete.py", line 35, in &lt;module&gt; cursorDrop.execute(query2) File "/home/me/.pyenv/versions/3.6.3/lib/python3.6/site-pack…
has answer: http://stackoverflow.com/a/50168068
tagged with: python
has answer: http://stackoverflow.com/a/50167289
type: AnsweredQuestion
score: 2
answer count: 2
linked to: http://stackoverflow.com/q/9394291
has comment: http://stackoverflow.com/comment/87352296
upvote count: 2
accepted answer: http://stackoverflow.com/a/50168068
possible better answer: http://stackoverflow.com/a/50167289
downvote count: 0
tagged with: mysql
favorite count: 0

http://stackoverflow.com/q/50063999
accepted answer: http://stackoverflow.com/a/50064076
has answer: http://stackoverflow.com/a/50064076
has title: how to add a value "1" for each values in a file, using python or bash
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/35789020
has comment: http://stackoverflow.com/comment/87144670
score: -3
has comment: http://stackoverflow.com/comment/87144666
tagged with: python
type: AnsweredQuestion
tagged with: bash
has comment: http://stackoverflow.com/comment/87144702
has body: how to add a value "1" for each number in a file, using python I have a file that looks like this; C1-S0 C2-S0 C3-C1 C1-S0-C2 S0-C1-H7 S0-C1-C3 C2-C4-C3 C2-C5-H10 O6-C5-H10 C2-C5-O6 C3-C1-S0-C2 H7-C1-S0-C2 C4-C2-S0-C1 C5-C2-S0-C1 using python or bash, how to add a value of 1 for each number that exists in this file. for atentre the following results: C2-S1 C3-S1 C4-C2 C2-S1-C3 S1-C2-H8 S1-C2-C4 C3-C5-C4 C3-C6-H11 O7-C6-H11 C3-C6-O7 C4-C2-S1-C3 H8-C2-S1-C3 C5-C3-S1-C2 C6-C3-S1-C2
upvote count: 0
answer count: 1
downvote count: 3

http://stackoverflow.com/comment/86927328
type: Comment
comment on: http://stackoverflow.com/q/49955429
type: QuestionComment
score: 0
has text: Are you planning on making multiple separate instances of `BlackShades`? Is there a difference in behaviour between `BlackShades` and `GreenShades` or is it just simple attributes like worth and colour?

http://stackoverflow.com/comment/86928964
score: 0
type: QuestionComment
has text: Excel won't expect the square brackets. Just write a normal CSV file. Use Python's [`csv.writer`](https://docs.python.org/3/library/csv.html#csv.writer)
type: Comment
comment on: http://stackoverflow.com/q/49955909

http://stackoverflow.com/comment/87111310
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50035108
type: Comment
has text: I've tried 2nd option, but that does not work. It assigns some huge weights to important values, but even though other values are close to 0 there a lot of them and they accumulate to some important amount. As I said, I've tried to zero them out every some operations, but the model still assigns some weights to them.

http://stackoverflow.com/q/50072289
tagged with: pycharm
answer count: 0
type: UnansweredQuestion
type: Question
has title: PyCharm import tensorflow has error but python console works
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87170468
has comment: http://stackoverflow.com/comment/87170469
has body: I'm using PyCharm 5.0.5 and Python3.6 installed by Anaconda. the Project Interpreter in Pycharm has been correct set to python3.6 Run "import tensoflow" in python console is ok. but when I try to import in PyCharm, it throws error: Traceback (most recent call last): File "E:/myself/test/test.py", line 14, in &lt;module&gt; import tensorflow as tf File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\__init__.py", line 52, in &lt;module&gt; from tensorflow.core.framework.graph_pb2 import * File "D:\ProgramData\Anaconda3\lib\site-packages\tensorflow\core\framework\graph_pb2.py", line 6, in &lt;module&gt; from google.protobuf import descriptor as _descriptor File "D:\ProgramData\Anaconda3\lib\site-packages\google\protobuf\__init__.py", line 37, in &lt;module&gt; __import__('pkg_resources').declare_namespace(__name__) File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 3088, in &lt;module&gt; @_call_aside File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 3072, in _call_aside f(*args, **kwargs) File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 3101, in _initialize_master_working_set working_set = WorkingSet._build_master() File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 565, in _build_master ws = cls() File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 558, in __init__ self.add_entry(entry) File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 614, in add_entry for dist in find_distributions(entry, True): File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 1964, in find_on_path for dist in factory(fullpath): File "D:\ProgramData\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 2034, in distributions_fro…
tagged with: python
has comment: http://stackoverflow.com/comment/87170470
score: 0

http://stackoverflow.com/q/50055065
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50055334
has comment: http://stackoverflow.com/comment/87126625
tagged with: pandas
has answer: http://stackoverflow.com/a/50055334
score: 1
has answer: http://stackoverflow.com/a/50055215
tagged with: dataframe
tagged with: python
tagged with: loops
has comment: http://stackoverflow.com/comment/87126774
has title: Subtracting values from a row based off other columns
has comment: http://stackoverflow.com/comment/87126703
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50055215
downvote count: 0
upvote count: 1
has body: Sorry about the vague title it's hard to explain. It's easier to display. I'm trying subtract values in the same row but based off strings in other columns. Here is an input df: import pandas as pd import numpy as np k = 5 N = 8 d = ({'Time' : np.random.randint(k, k + 100 , size=N), 'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'], 'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'], 'Number2' : ['xx',1,'xx',1,'xx',2,'xx',2]}) df = pd.DataFrame(data=d) Output: Events Number1 Number2 Time 0 ABC xx xx 14 1 DEF xx 1 34 2 GHI 1 xx 78 3 JKL xx 1 49 4 ABC xx xx 49 5 DEF xx 2 24 6 GHI 2 xx 19 7 JKL xx 2 67 I want to export values based on the difference in Time. The first time difference column will be ABC - DEF and the second column will be GHI - JKL. I need to repeat this process a number of times. The example above displays a loop of 2 times. I can use the integers for columns Number1 and Number2 but they aren't in order. I tried to combine and ffill these columns to display an order. And then use this column as a reference. for col in ['Number2']: df[col] = df[col].ffill() But this creates 5 identical integers when I need 4. I then manually subtracted the appropriate values via row slicing but it becomes very inefficient when I have to do this numerous times. Is it possible to create a loop subtracting the intended rows? For the above example the output would be: Diff_1 Diff_2 0 -20 29 1 25 -48
favorite count: 0

http://stackoverflow.com/comment/87126934
type: Comment
has text: Their is any underscore at the end thou.
comment on: http://stackoverflow.com/a/50054221
type: AnswerComment
score: 0

http://stackoverflow.com/a/58184191
type: Answer
upvote count: 2
has body: In recent TensorFlow 2.0 we could specify the required amount of memory explicitly. import tensorflow as tf assert tf.version.VERSION.startswith('2.') gpus = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_virtual_device_configuration(gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)]) (Source: https://github.com/tensorflow/tensorflow/issues/25138#issuecomment-533936197)
score: 2
answers question: http://stackoverflow.com/q/50001265
has comment: http://stackoverflow.com/comment/117206074
downvote count: 0

http://stackoverflow.com/q/50023552
downvote count: 0
tagged with: pip
favorite count: 0
has title: Where should I put project resources when doing pip install?
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50023656
type: Question
linked to: http://stackoverflow.com/q/11848030
upvote count: 1
has body: I have a PyQt project where I create a GUI displaying some jpegs. For comfortability when developing, the code would assume it is being run from the main project folder, so the jpegs path was relative to the main folder. Something like: # Do something with "images/new.jpeg" Now I would like to pip install the package and have an independant runnable. I have no idea where is the correct place to put the jpegs, and how I should access them in the code. I'm currently developing for Linux only (Ubuntu 16.04). Any idea how I can get started? Thanks.
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87025535
has text: In general, it is important to keep in mind that you get exponentially more representational capacity through depth compared to width, so enhancing your networks with narrow, deep, task-specific layers is usually helpful.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49953833
type: Comment

http://stackoverflow.com/a/50024641
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87066903
score: 2
has comment: http://stackoverflow.com/comment/87065303
has comment: http://stackoverflow.com/comment/87066182
answers question: http://stackoverflow.com/q/50024378
has comment: http://stackoverflow.com/comment/87066013
type: Answer
has comment: http://stackoverflow.com/comment/87066738
has body: I can certainly answer point 1): import pdb, s import subprocess import re import time from subprocess import Popen, PIPE, DEVNULL lower=1 upper=25 MAC_address_list1 = ["58:e2:zz:xx:28:d7"] MAC_address_list2 = ["08:05:xx:zz:75:c5"] MAC_address_list3 = ["##:##:##:##:##:##"] MAC_address_list4 = ["##:##:##:##:##:##"] MAC_addresses = ([MAC_address_list1],[MAC_address_list2]) [...] def detect_mac(input_address_list): # Assign list of devices on the network to "output" output = subprocess.check_output("arp -a", shell=True) str_output = output.decode("utf-8") for address_list in input_address_list: if any(address[0] in str_output for address in address_list): print(getdatetime() + str(address_list)) #sleep 10 minutes time.sleep(600) return True
accepted answer of: http://stackoverflow.com/q/50024378
upvote count: 2

http://stackoverflow.com/q/50050795
tagged with: python
has comment: http://stackoverflow.com/comment/87117980
has comment: http://stackoverflow.com/comment/87118401
has body: Problem: Write a program that will loop through a list and sum all values greater than the last value in the list. If there are no values greater than the list or if the list is empty, return -1. My Code: def go(list1): total = 0 count = 0 for i in range(0,len(list1)-1): if list1[i] &lt; list1[i+1]: total+=list1[i+1] count += 1 else: total += 0 if count is 0: total = -1 if len(list1) == 1: total = -1 return total print(go( [-99,1,2,3,4,5,6,7,8,9,10,5] )) print(go( [10,9,8,7,6,5,4,3,2,1,-99] )) print(go( [10,20,30,40,50,-11818,40,30,20,10] )) print(go( [32767] )) print(go( [255,255] )) print(go( [9,10,-88,100,-555,2] )) print(go( [10,10,10,11,456] )) print(go( [-111,1,2,3,9,11,20,1] )) print(go( [9,8,7,6,5,4,3,2,0,-2,6] )) print(go( [12,15,18,21,23,1000] )) print(go( [250,19,17,15,13,11,10,9,6,3,2,1,0] )) print(go( [9,10,-8,10000,-5000,-3000] )) My Output: 55 -1 180 0 -1 112 466 46 5 1077 -1 7010 Desired Output: 55 -1 180 -1 -1 112 466 46 5 1077 -1 7010 What am I doing wrong? Why is that output 0 instead of -1?
has comment: http://stackoverflow.com/comment/87118330
type: AnsweredQuestion
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/87118322
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/50051123
has comment: http://stackoverflow.com/comment/87118253
has title: Python: sum of values greater than last value
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50051007
has comment: http://stackoverflow.com/comment/87117995
possible better answer: http://stackoverflow.com/a/50051123
has comment: http://stackoverflow.com/comment/87117892
has answer: http://stackoverflow.com/a/50051007
has comment: http://stackoverflow.com/comment/87118762
has comment: http://stackoverflow.com/comment/87118338

http://stackoverflow.com/a/50058037
has body: In the class GUIDieSet(), remove the line self.grid() in __init()__ and it seems to work.
has comment: http://stackoverflow.com/comment/87141196
accepted answer of: http://stackoverflow.com/q/50054420
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87159038
type: Answer
answers question: http://stackoverflow.com/q/50054420

http://stackoverflow.com/a/54856228
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50030086
answers question: http://stackoverflow.com/q/50030086
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Try using: client.loop_start() instead of client.loop_forever() client.loop_forever() sometimes block the execution of program.

http://stackoverflow.com/comment/87117327
comment on: http://stackoverflow.com/q/50050543
score: 0
type: Comment
type: QuestionComment
has text: This might help you : https://stackoverflow.com/questions/9202224/getting-command-line-password-input-in-python

http://stackoverflow.com/comment/87151043
score: 0
has text: Are you using Command Prompt? Seems to be a Command Prompt thing. Works fine in Idle.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50067238

http://stackoverflow.com/a/50003990
has body: This is occurred because you have two packages: A and B. Package B can't get access to content of package A via relative import because it cant move outside top-level package. In you case both packages are top-level. You need reorganize you project, for example like that . ├── TL │ ├── A │ │ ├── __init__.py │ │ └── base.py │ ├── B │ │ ├── __init__.py │ │ └── base.py │ └── __init__.py └── app.py and change content pf you app.py to use package TL: from TL.A import ClassA from TL.B import ClassB if __name__ == "__main__":
accepted answer of: http://stackoverflow.com/q/49981741
type: Answer
score: 10
answers question: http://stackoverflow.com/q/49981741
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87048238
upvote count: 10

http://stackoverflow.com/a/49976610
accepted answer of: http://stackoverflow.com/q/49964957
type: Answer
answers question: http://stackoverflow.com/q/49964957
has comment: http://stackoverflow.com/comment/86990414
score: 0
has comment: http://stackoverflow.com/comment/86987097
has body: In your code you only provide io.popen a path to a Python script. function on_msg_receive (msg) if (msg.text=="Alarmon") then send_msg (msg.from.print_name, 'Sensor ON!', ok_cb, false) io.popen('/home/pi/led.py') end Your computer doesn't know what to do with it. From the Lua 5.3 Reference Manual: io.popen (prog [, mode]) This function is system dependent and is not available on all platforms. Starts program prog in a separated process and returns a file handle that you can use to read data from this program (if mode is "r", the default) or to write data to this program (if mode is "w"). So in order to make it work you have to actually start a program, which in your case is the Python interpreter. Given that you have the Python interpreter's location in your PATH system variable this should work: io.popen('Python') And as you want the interpeter to run a script you also provide the script's path as argument. io.popen('Python /home/pi/led.py') The same you would enter into the command line interface... If you're not planning to use any in or output to or from the program you can simply use: os.execute('Python /home/pi/led.py') instead
type: AcceptedAnswer

http://stackoverflow.com/comment/87157906
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50070546
score: 0
has text: There's a bug in your code: you redeclare `for person in direct_reports` but that shadows the `person` it was called with. Best to call it `subordinate` or `dr` or `p2` or whatever

http://stackoverflow.com/q/49963153
has answer: http://stackoverflow.com/a/50003347
has comment: http://stackoverflow.com/comment/86944505
favorite count: 0
has title: Word linker is linking words with rule different to what is specified
type: Question
tagged with: recursion
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86944720
has body: I am trying to make a program that recursively links words from a list so that the 3rd last and 2nd last letter is the same as the 2nd and 3rd letter of the next word. Although my program does this for the first two words correctly, from then on it only connects words that have the same 2nd and 3rd letters only. 'used' is a list that contains the indices of used words so they are not repeated. The function takes in a starting index and works from there. def linker(b): for i in range(len(words)): if b != i and i not in used: if words[b][-3] == words[i][1] and words[b][-2] == words[i][2]: #Compares 3rd last and 2nd last letters to 2nd and 3rd letters. if b not in used: linkedwords.append(words[b]) used.append(b) #Keeps track of used value's indicies linkedwords.append(words[i]) used.append(i) #Keeps track of used value's indicies linker(i) #Recursively checks matches for the next word Example output for 8 letter words: ['absences', 'aceldama', 'acentric', 'acequias', 'acerated', 'acerbate', 'acerbest', 'acerbity', 'acerolas', 'acervate', 'acervuli', 'acescent', 'acetamid', 'acetated', 'acetates'] As you can see the first two terms are correct, but it then proceeds to only link words where 'ce' are the 2nd and 3rd letters. I have no idea why it is doing this as my if statement only allows words that meet the proper requirement to be appended. Any ideas?
has comment: http://stackoverflow.com/comment/86944070
has comment: http://stackoverflow.com/comment/86963018
tagged with: python
has comment: http://stackoverflow.com/comment/86945734
has comment: http://stackoverflow.com/comment/86942762
has comment: http://stackoverflow.com/comment/86942303
tagged with: list
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/50073846
linked to: http://stackoverflow.com/q/49785120
has body: I am struggling with mocking attributes in my Python tests. The function I am trying to test keeps failing because the mock probably returns the right value but is the wrong type (Should be string and it is a MagicMock instead. I have found this answer and I understand I need to use a PropertyMock. But I can't get it to work neither with the context manager or using the @patch decorator. Mock attributes in Python mock? Here is my test: @patch('keys.views.requests.post') @patch('keys.views.requests.Response.text', new_callable=PropertyMock) def test_shows_message_when_receives_error(self, mock_response_text ,mock_post): expected_error = escape(MESSAGE) data_to_be_received = json.dumps({ "message":"Bad Request", "errors":[{ "resource":"Application", "field":"client_id", "code":"invalid" }] }) mock_response_text.return_value = data_to_be_received response = self.client.get('/users/tokenexchange?state=&code=abc123') self.assertContains(response, expected_error) And the code I am testing: def token_exchange(request): parameters = {'client_id': '##', 'client_secret': '##', 'code': code} response = requests.post('https://www.strava.com/oauth/token', parameters) data_received = json.loads(response.text) if 'errors' not in data_received: return HttpResponse(response.text) else: return render(request, 'home.html', {'error': STRAVA_AUTH_ERROR}) The error I keep getting is: File "##", line 66, in token_exchange data_received = json.loads(response.text) TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock'
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/16867509
upvote count: 4
has title: Mocking attributes using @patch decorator
tagged with: mocking
has answer: http://stackoverflow.com/a/50087632
answer count: 1
downvote count: 0
favorite count: 0
tagged with: unit-testing
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50087632

http://stackoverflow.com/comment/86930851
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49957157
type: Comment
has text: @Jean-FrançoisFabre the lists are the position, speed, energies of an rocket orbital motion

http://stackoverflow.com/comment/86925117
score: 0
type: QuestionComment
has text: Why don't you try to _Automate_ just the _Manual Steps_ instead of directly invoking a pre-compiled `url`?
comment on: http://stackoverflow.com/q/49953047
type: Comment

http://stackoverflow.com/a/50021134
has comment: http://stackoverflow.com/comment/87058415
has comment: http://stackoverflow.com/comment/87058091
has comment: http://stackoverflow.com/comment/87059665
answers question: http://stackoverflow.com/q/50020111
has comment: http://stackoverflow.com/comment/87061897
score: 0
type: Answer
has body: Your testApp inherits from tk.Tk, so it becomes the root. And it gets passed as the controller arg, so your frames can use that name to access it. Here's a quick demo derived from your code. import tkinter as tk class testApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) self.frames = {} for F in (StartPage,): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) confirmFrame = tk.Frame(self) confirmFrame.pack() self.buttonNo = tk.Button(confirmFrame, text="No, quit the program", command=controller.quit) self.buttonNo.pack() app = testApp() app.mainloop() BTW, it makes it a lot easier for us to help you if you post a MCVE. Otherwise we need to spend time figuring out what we need to add &amp; remove from your code before we can even run it.
has comment: http://stackoverflow.com/comment/87059281
has comment: http://stackoverflow.com/comment/87059957

http://stackoverflow.com/comment/86960945
comment on: http://stackoverflow.com/q/49972088
score: 0
type: QuestionComment
has text: not at the bottom of the pasted code
type: Comment

http://stackoverflow.com/q/50015737
tagged with: segmentation-fault
favorite count: 0
type: Question
has body: I'm using python 3.5.2 (64 bit) within a operating system Linux Mint 18 with a kernel release 4.4.0-109-generic. A long time ago I installed PyQt4 through sudo apt-get install python3-pyqt4 and everything worked perfectly, untill I recently installed through pip PyQt5. Since then, I'm able to import PyQt4 and import PyQt4.pyqtconfig but not the modules like import PyQt4.QtCore, import PyQt4.QtGui or import PyQt4.Qt for which exits python with 'Segmentation Fault'. I've also realized that the command (within python enviroment) help('modules') gives same output after some seconds. I've tried to remove PyQt5 with pip and reinstall PyQt4 from terminal (version 4.11.4+dfsg-1build4), but nothing seems to change. I also can see the directory from the PyQt4 from /usr/lib/python3/dist-packages/PyQt4 I've also tried to create a python virtual environment with virtualenv env --python=python3.5 inside a folder and copy the whole directory from PyQt4 to the dist-packages of the environment and also install sip within it. Using sip 4.19.8 version from pip. Another thing I've tried is to use gdb python3 to run a python program that only contains the code: #!/usr/bin/python3 import PyQt4.QtCore What it returns is this: $ gdb -q python3 Reading symbols from python3...Reading symbols from /usr/lib/debug/.build-id/59/a8ef36ca241df24686952480966d7bc0d7c6ea.debug...done. done. (gdb) run FaultPy35.py Starting program: /usr/bin/python3 FaultPy35.py [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Program received signal SIGSEGV, Segmentation fault. PyType_IsSubtype () at ../Objects/typeobject.c:1343 1343 ../Objects/typeobject.c: No such file or directory. (gdb) c Continuing. Program terminated with signal SIGSEGV, Segmentation fault. The program no longer exists. (gdb) I'm really new to gdb but apparently the problem goes beyond python packages... Note: I've checked via dpkg-query -L python3-pyqt4 what the package pyt…
tagged with: python
has title: importing PyQt4 modules gives Segmentation Fault after PyQt5 install
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: pyqt4
downvote count: 0

http://stackoverflow.com/comment/87137266
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/34735659/django-python-manage-py-runserver-gives-segmentation-fault-error?noredirect=1&lq=1 this might help
comment on: http://stackoverflow.com/q/50050739
score: 0

http://stackoverflow.com/comment/87035667
type: AnswerComment
has text: Oh, thank you. This sounds like the potential solution. I will look into how to do this. My first pass keeps generating werkzeug errors, but I'll look around on this front.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49951612

http://stackoverflow.com/q/50050181
duplicate of: http://stackoverflow.com/q/17411940
type: UnansweredQuestion
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/42056713
tagged with: python
linked to: http://stackoverflow.com/q/17411940
score: 2
answer count: 0
duplicate of: http://stackoverflow.com/q/23094774
upvote count: 2
has body: I am reading Machine Learning in action Chapter Two, I don't know how to label the dots which are separated into three group. The data has four columns and two columns in the first three are being used as x and y, the last column is the label (1 , 2 and 3). Dataset is in the same numpy array and is plot with different color and size with .scatter(X, Y, 15 * the value of label, 15 * the value of label) Here is the code for plotting without legend. fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(datingDataMat[:, 0], datingDataMat[:, 1], 15 * np.array(datingLabels), 15 * np.array(datingLabels)) fig.suptitle('Figure 2 Using X = Colume 0 and Y = Colume 1') plt.xlabel('Frequent Flyier Miles Earned Per Year') plt.ylabel('Percentage of Time Spent Playing Video Games') plt.show()
downvote count: 0
duplicate of: http://stackoverflow.com/q/28171131
has comment: http://stackoverflow.com/comment/87117450
favorite count: 0
type: Question
has title: How to put Lenged in matplotlib, data in the same numpy array

http://stackoverflow.com/comment/87139350
has text: You are not adding any `MyCustomWidget` to your main window.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50061518

http://stackoverflow.com/comment/87092742
score: 0
type: Comment
has text: Sorry, I need to use regex because it is an assignment.
comment on: http://stackoverflow.com/a/50037774
type: AnswerComment

http://stackoverflow.com/comment/86982817
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49983134
has text: One use case is if you want a `dict` key, since you can't use a list.
score: 0

http://stackoverflow.com/q/50012544
tagged with: python
favorite count: 0
has body: I have XML which contains unusual (but escaped) characters: &lt;key code="51" output="&amp;#x0008;"/&gt; &lt;!-- backspace --&gt; &lt;key code="53" output="&amp;#x001B;"/&gt; &lt;!-- escape --&gt; How can I parse this so that the values of the output attributes are the literal strings "&amp;#x0008;" and "&amp;#x001B;" (and not the actual backspace/escape control characters)? Python parsers like lxml.etree.fromstring seem to always decode these—which is fine for common characters like "&amp;#x0097;" -&gt; "a". Using etree.XMLParser with resolve_entities=False preserves things like &amp;amp;, but not &amp;#x...;, which I require. I intend to parse a file containing lines like that shown above, manipulate the tree with python, and finally save it to another file which looks like the first. Thank you!
tagged with: lxml
has title: Python: Parse XML treating (hexadecimal) escapes as literal strings
type: Question
tagged with: xml-parsing
answer count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87042316

http://stackoverflow.com/comment/86944979
score: 0
type: Comment
type: QuestionComment
has text: Please copy-paste errors directly into your question (using [code formatting](https://meta.stackexchange.com/a/22189/353194)), don't include screenshots of them.
comment on: http://stackoverflow.com/q/49964199

http://stackoverflow.com/q/49951166
type: AnsweredQuestion
score: 0
has body: I try to use Ni-Daq to generate pulse. the example provided by the nidaqmx is like as follows: import nidaqmx from nidaqmx.types import CtrTime with nidaqmx.Task() as task: task.co_channels.add_co_pulse_chan_time("Dev1/ctr0") sample = CtrTime(high_time=0.001, low_time=0.002) print('1 Channel 1 Sample Write: ') print(task.write(sample)) But after I run this script, it generate some errors as shown below: raise DaqError(error_buffer.value.decode("utf-8"), error_code) DaqError: The task is not buffered or has no channels. If the task is not buffered, use the scalar version of this function. If the task has no channels, add one to the task. Task Name: _unnamedTask&lt;0> Status Code: -201395 what cause the problem? how to fix that? Thank you very much!
tagged with: nidaqmx
accepted answer: http://stackoverflow.com/a/49986491
type: Question
has comment: http://stackoverflow.com/comment/86988171
answer count: 1
has comment: http://stackoverflow.com/comment/86987449
tagged with: python
has answer: http://stackoverflow.com/a/49986491
has title: nidaqmx co_channels can't write sample

rx-py
tag name: rx-py
type: Tag
tags question: http://stackoverflow.com/q/49972187

http://stackoverflow.com/comment/87340988
type: QuestionComment
has text: Yeah, that's what I wound up doing. I'm thinking about submitting a bug report.
type: Comment
comment on: http://stackoverflow.com/q/49999944
score: 0

http://stackoverflow.com/comment/86915720
score: 0
type: Comment
has text: No, I was more thinking about memory usage and speed in terms of, with this solution we have three objects: the string, the 1's/0's array, and the sparse matrix. I'm trying to have only the first and third object. Are you saying that just by splitting the string, we have already creating that middle object, so why not just make it a list of 1's and 0's? Bear in mind, the issue is that I'm doing this on a few hundred million of these rows and the strings are ~1k long. That's why I don't want 3 copies of the whole thing.
type: AnswerComment
comment on: http://stackoverflow.com/a/49948878

http://stackoverflow.com/q/50008022
answer count: 1
has body: My python code takes a screenshot of by desktop and looks for a red rectangle on a black background, when I use the cv2.findcountours it doesn't return an exact sized rectangle, it seems to be distorted. I would like to obtain the exact area of the shape. Also, the image on my screenshot has no pixelation and borders are sharp. Thanks for your help! frame_TS_new_raw = np.array(sct.grab(monitor_TS_new)) frame_TS_new = cv2.cvtColor(frame_TS_new_raw, cv2.COLOR_RGBA2RGB) green_mask_TS_new = cv2.inRange(frame_TS_new,green_lower_range, green_upper_range) # find contours for New TS cnts_green_new = cv2.findContours(green_mask_TS_new.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts_green_new = cnts_green_new[0] if imutils.is_cv2() else cnts_green_new[1] if len(cnts_green_new) &gt; 0: for c in cnts_green_new: # if the contour is not sufficiently large, ignore it if cv2.contourArea(c) &gt; 100: area = cv2.contourArea(c) screenshot of the masked and unmasked The image on the left is raw screenshot and the image on the right is the masked.
has answer: http://stackoverflow.com/a/50009438
has comment: http://stackoverflow.com/comment/87034073
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87032828
tagged with: opencv
score: 0
has title: Python 3 OpenCV Color Object Detect with defined edges

http://stackoverflow.com/comment/87051006
score: 0
has text: @user9686018 The index of `labels`...... So `0`, `1`, `2`, ... etc. for each one in turn. see my edit
comment on: http://stackoverflow.com/a/50017055
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87128100
comment on: http://stackoverflow.com/a/50055639
score: 0
has text: Perfect solution, Cumsum function is great .. thanks buddy!
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50001807
has title: How to display two images on top of another with matplotlib?
score: 8
has body: I have a heatmap with some values in it (model_prediction_i). Because I want to later rotate this heatmap before plotting it, I have to save it with plt.imsave. My goal is then, to display reference.jpg as a background of the plot, plot X_test_i over it, and then position the heatmap also on that plot, such that I can see the background, the plotted line and the heatmap, which hs smaller dimensions than the background picture -> it will only occlude a part of the background picture. As reference.jpg: Is this possible? import numpy as np from PIL import Image import matplotlib.pyplot as plt model_prediction_i = np.zeros((200,200)) model_prediction_i[160][160] = 1 model_prediction_i[160][161] = 1 model_prediction_i[160][162] = 1 model_prediction_i[160][163] = 1 model_prediction_i[160][164] = 1 model_prediction_i[160][165] = 1 model_prediction_i[160][166] = 1 model_prediction_i[160][167] = 1 model_prediction_i[160][168] = 1 model_prediction_i[160][169] = 1 model_prediction_i[160][170] = 1 model_prediction_i[160][171] = 1 plt.imsave('outfile.jpg', model_prediction_i, cmap='hot') rotated_img = Image.open('outfile.jpg') background = Image.open('reference.jpg') X_test_i = np.zeros((5, 2)) X_test_i[0] = [10 ,10] X_test_i[1] = [60 ,60] X_test_i[2] = [90 ,90] X_test_i[3] = [140 ,140] X_test_i[4] = [250 ,230] fig, ax = plt.subplots(figsize=(10, 10)) ax.plot(X_test_i[:, 0], X_test_i[:, 1], marker='o', markersize=7, color="red", label='Current position', antialiased=True) ax.imshow(rotated_img, cmap='hot', extent=[X_test_i[:, 0][-1]-10, X_test_i[:, 0][-1]+10, X_test_i[:, 1][-1]-10, X_test_i[:, 1][-1]+10]) ax.imshow(background) plt.show()
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87019757
has comment: http://stackoverflow.com/comment/87021718
has comment: http://stackoverflow.com/comment/87019935
upvote count: 8
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87019856
has comment: http://stackoverflow.com/comment/87020204
tagged with: data-visualization
tagged with: matplotlib
has answer: http://stackoverflow.com/a/58892885
linked to: http://stackoverflow.com/q/42481203
tagged with: python

http://stackoverflow.com/q/50005856
upvote count: 4
has title: Python: Generating multiple combinations of strings with spaces
has body: I have an array of n words as strings such as: input: ["just", "a", "test"] What I need to do is create all possible combinations of these words separated by spaces as well as in combination with the original strings. For example, the above should create: output: [["just", "a", "test"], ["just a", "test"], ["just a test"], ["just", "a test"]] I've been using itertools but can't get it to do what I need. What I have at the moment: iterable = ['just', 'a', 'test'] for n in chain.from_iterable(combinations(iterable, n) for n in range(len(iterable)+1)): print(n) The following almost works as required: iterable = ['just', 'a', 'test'] L = [''.join(reversed(x)).rstrip() for x in product(*[(c, c+' ') for c in reversed(iterable)])] print(L) Thank you. EDIT: To clarify how this should work for an array of length 4: input: ['an', 'even', 'bigger', 'test']` output: ['an', 'even', 'bigger', 'test'] ['an even', 'bigger', 'test'] ['an even bigger', 'test'] ['an even bigger test'] ['an', 'even bigger', 'test'] ['an even', 'bigger test'] ['an', 'even bigger test'] ['an', 'even', 'bigger test']
type: Question
linked to: http://stackoverflow.com/q/23596702
answer count: 2
has comment: http://stackoverflow.com/comment/87028678
tagged with: python
type: UnansweredQuestion
tagged with: combinations
score: 4
has answer: http://stackoverflow.com/a/50006010
tagged with: whitespace
downvote count: 0
tagged with: permutation
tagged with: string
has answer: http://stackoverflow.com/a/50006429
favorite count: 0

http://stackoverflow.com/comment/86906244
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49944571
has text: @Aran-Fey Can you submit your answer?

http://stackoverflow.com/q/50054160
downvote count: 1
favorite count: 0
type: Question
has title: PandasError: DataFrame constructor not properly called
has body: I am trying to convert some values to a dataframe. I have used the following code to achieve this: import pandas as pd import numpy as np k = 5 N = 8 d = ({'Time' : np.random.randint(k, k + 100 , size=N), 'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'], 'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'], 'Number2' : [1,1,'xx',1,'xx',2,'xx',2]}), df = pd.DataFrame(data=d) However, this produces an error code PandasError: DataFrame constructor not properly called!. I have tried to alter the code to df = pd.DataFrame(eval(d)) but get the same error? Any suggestions?
tagged with: python
upvote count: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50054206
has answer: http://stackoverflow.com/a/50054182
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50054206
accepted answer: http://stackoverflow.com/a/50054182
score: 1

http://stackoverflow.com/q/49956178
score: 2
has answer: http://stackoverflow.com/a/49970065
answer count: 2
has title: Generating possible sentences from a scrambled list of n-grams (python)
downvote count: 0
tagged with: nlp
favorite count: 0
type: Question
has body: Sample input stream: [ ('t','h'), ('h','e'), ('e', ' '), (' ','f') , ('f','o'), ('o','x'), ('x',' '), (' ','a'), ('a','t'), ('t','e'), ('e', &lt;p&gt;) ] Suppose you have a sentence {ABCABA}, where each letter is either a character or word, depending on tokenization. Then your bag-of-bigrams is {(AB), (BC), (CA), (AB), (BA)}. From here, I need an algorithm to list all the possible permutations of sentences with the same length as the original sentence, given these bigrams. Here, {ABCABA} (the original sequence) and (ABABCA) are both valid, possible sentences, but {ACBABA} is not. This example is for bigrams, but I also need this to work for any $n$. Any ideas?
upvote count: 2
tagged with: algorithm
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/49956793

http://stackoverflow.com/q/49929615
tagged with: memoization
tagged with: lru
tagged with: python
type: UnansweredQuestion
has title: LRU cache with large-key. Referencing?
tagged with: caching
score: 0
linked to: http://stackoverflow.com/q/49883177
answer count: 1
has comment: http://stackoverflow.com/comment/86875211
tagged with: python-2.7
type: Question
has body: I'm having the following dilemma, implementing LRU algorithm. For every entry I have to store (key, value, timestamp) As you guessed the cache structure can be : cache[key] = [ value, tstamp ] so far so good. The problem is that LRU algorithm requires that when I have to purge element (because the cache is full), I have to do linear search on the time stamp to delete the least used item, which is slow. On the other hand I can't build reverse hash tstamp => key, because the key is 1KByte big and the additional memory usage will negate the use of the cache. Any ideas to preserve the speed but not increase the memory usage ? If I could have something as reference I could probably reference cache-key w/o allocating additional memory ! I can't use LRU lib, because the key is unhashable by default I have to transform it beforehand. I'm also using 2.7
has answer: http://stackoverflow.com/a/49929677

http://stackoverflow.com/comment/86863470
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49922958
has text: Welcome to [so]! It is a good idea to ask your question (How do I get X to do Y ...?) in the first paragraph, or the last. Folks will keep reading if they need more context.

http://stackoverflow.com/comment/87133979
comment on: http://stackoverflow.com/a/50057117
has text: My bad, it was a silly mistake, I wasn't taking request.POST to f. Thanks for the support @Anjaneyulu Batta
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86916442
comment on: http://stackoverflow.com/q/49949885
type: Comment
type: QuestionComment
has text: As you can see from the object `id`s, yes, python has created two objects.
score: 0

http://stackoverflow.com/comment/86992987
score: 1
has text: Any explanations would be nice, even if it is not preferred to provide code without attempt. Without explanations and only downvote would not help to learn. Anyways nice solution!
type: Comment
comment on: http://stackoverflow.com/a/49988217
type: AnswerComment

http://stackoverflow.com/comment/86994175
type: Comment
has text: The `self` argument explains why the interpreter tells you that the type of `tree` is `App`, because when you add `self` by hand it becomes the second argument, so it is linked to `tree`
type: AnswerComment
comment on: http://stackoverflow.com/a/49985479
score: 1

http://stackoverflow.com/a/50051128
has comment: http://stackoverflow.com/comment/87118722
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87119674
has body: You could do it like this: df[df.groupby('key1')['key2'].transform(pd.DataFrame.rank) == 2] OR df[df.groupby('key1')['key2'].apply(lambda x: x.rank() == 2)] Output: key1 key2 1 a 2 4 b 5
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87118680
score: 1
accepted answer of: http://stackoverflow.com/q/50050918
has comment: http://stackoverflow.com/comment/87118761
answers question: http://stackoverflow.com/q/50050918

http://stackoverflow.com/a/50028588
type: Answer
score: 0
has body: Rather than doing pass after receiving a no answer, you should exit() or quit().
answers question: http://stackoverflow.com/q/50026554

http://stackoverflow.com/comment/86886255
type: Comment
type: QuestionComment
has text: Padding the short arrays with `nan` may help. There are some 'no nan' functions.
score: 0
comment on: http://stackoverflow.com/q/49934710

http://stackoverflow.com/comment/86954779
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49964533
type: Comment
has text: I cannot mark both answers as good, this version was working too, although I like previous answer because I like the idea to avoid using bash command. Thanks anyway!!

http://stackoverflow.com/q/49970147
upvote count: 6
accepted answer: http://stackoverflow.com/a/49970496
tagged with: opencv
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44019023
has title: OpenCV Masking Image - error: (-215) (mtype == 0 || mtype == 1) && _mask.sameSize(*psrc1) in function cv::binary_op
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49970496
score: 5
has body: I am trying to subtract the background from an image using a mask and OpenCV's bitwise_and. However, I get the following error: error: C:\ci\opencv_1512684736357\work\modules\core\src\arithm.cpp:241: error: (-215) (mtype == 0 || mtype == 1) &amp;&amp; _mask.sameSize(*psrc1) in function cv::binary_op My code looks like this: mask = get_mask() #function that returns a mask (boolean) #conversion of the mask mask = mask.astype('int') mask[mask == 0] = 255 mask[mask == 1] = 0 fg_masked = cv2.bitwise_and(img, img, mask=mask) A question here on StackOverflow (OpenCV Python Error: error: (-215) (mtype == CV_8U || mtype == CV_8S) &amp;&amp; _mask.sameSize(*psrc1) in function cv::binary_op) that addresses the same error indicates an issue with a potential shape mismatch. However, checking both the shape of my mask and my image it appears to me that they match, yielding: mask.shape OUT: (100, 83) img.shape OUT: (100, 83, 3) I am using Python v3 and OpenCV v2
tagged with: python

http://stackoverflow.com/q/49924824
has comment: http://stackoverflow.com/comment/86886834
has body: I'm a novice in Python. I'm working on the Titanic task from kaggle.com. Could someone explain me the difference between doing LogisticRegression this way: from sklearn.linear_model import LogisticRegression X2=train'male' y2=train['Survived'] logmodel = LogisticRegression() logmodel.fit(X2,y2) print(logmodel.coef_,logmodel.intercept_) and this way : from patsy import dmatrices import statsmodels.api as sm y3, X3 = dmatrices( 'Survived ~ male', data=train, return_type='dataframe') mod = sm.Logit(y_train2, X3) res = mod.fit() print (res.summary()) I hope to get the identical intercept and coefficient. But I've got at first log.reggression the next: Coefficient=-2.36631709 Intercept=1.04454658 and for the second one: Coefficient=-2.4676 Intercept=1.1141 Why are the coefficients and intercepts are different? Thanks in advance!
has comment: http://stackoverflow.com/comment/87435498
has comment: http://stackoverflow.com/comment/86865612
answer count: 0
score: 0
tagged with: scikit-learn
tagged with: kaggle
has comment: http://stackoverflow.com/comment/87006866
tagged with: logistic-regression
type: Question
tagged with: statsmodels
type: UnansweredQuestion
tagged with: python
has title: What is the difference between Statsmodels and LogisticRegression in Python?

http://stackoverflow.com/q/50041263
has comment: http://stackoverflow.com/comment/87098848
has comment: http://stackoverflow.com/comment/87099529
has comment: http://stackoverflow.com/comment/87098822
has body: class Render(QtWebKit.QWebPage): def __init__(self, urls,app, cb): QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) self.urls = urls self.cb = cb self.app=app self.crawl() self.app.exec_() print(1) def crawl(self): if self.urls: url = self.urls.pop(0) print ('Downloading', url) self.mainFrame().load(QUrl(url)) else: self.app.quit() print(2) def _loadFinished(self, result): frame = self.mainFrame() url = str(frame.url().toString()) html = frame.toHtml() self.cb(url, html) self.crawl() class King(Resource): global app app = QtGui.QApplication.instance() if app is None: app = QtGui.QApplication(sys.argv) Why it crashes after running for the second time?
type: Question
linked to: http://stackoverflow.com/q/21274865
tagged with: python-3.x
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/21274865
has comment: http://stackoverflow.com/comment/87098388
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/87099671
tagged with: python
has title: pyqt4 crashing after running the script
has comment: http://stackoverflow.com/comment/87099652
score: 0
answer count: 0

http://stackoverflow.com/comment/123416646
type: AnswerComment
has text: Spyder is an IDE (interactive development environment), xEMSF is a python package, so are 2 different things!
score: 2
comment on: http://stackoverflow.com/a/49999186
type: Comment

http://stackoverflow.com/comment/86859086
score: 0
comment on: http://stackoverflow.com/q/49920532
type: QuestionComment
has text: Thanks, now it's clear. You want to draw the red square on top of all the widgets. Then the answer by @BenjaminT is correct
type: Comment

http://stackoverflow.com/comment/86923184
comment on: http://stackoverflow.com/q/49953345
has text: def setOrtho(w, h): glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, w, h, 0, -200, 200) glMatrixMode(GL_MODELVIEW) , this is setOrtho(w, h): function
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49961854
type: AnsweredQuestion
has title: How to parse from a string the numbers and punctuation in Python
has answer: http://stackoverflow.com/a/49961859
upvote count: 0
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/37580151
has comment: http://stackoverflow.com/comment/86940078
favorite count: 0
linked to: http://stackoverflow.com/q/6633523
type: Question
has body: I want to turn a string like "$1,234.56" into 1234.56 so I can add it to a database, my current solution is using re.sub("[^0-9]", "", str1 this however strips the punctuation too, is there a way to keep it? I'm using python 3.6.5
has comment: http://stackoverflow.com/comment/86940076
accepted answer: http://stackoverflow.com/a/49961859
has comment: http://stackoverflow.com/comment/86939936
duplicate of: http://stackoverflow.com/q/6633523
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/86939960

http://stackoverflow.com/q/49968414
has comment: http://stackoverflow.com/comment/86952640
downvote count: 2
has comment: http://stackoverflow.com/comment/86960954
linked to: http://stackoverflow.com/q/388490
has answer: http://stackoverflow.com/a/49969426
tagged with: python
has body: I am currently working on exercises from a book called "Learn Python The Hard Way". On this particular exercise, it requires to set my computer to work with utf-8 files, but I am not able to configure this. I have tried reading different blogs and answers in here but can't find out how to do this. The image below shows (left)how it should look and (right)what I am getting on the right Thank you for the help!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86960942
upvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/40098771
tagged with: utf-8
has comment: http://stackoverflow.com/comment/86953724
score: 1
tagged with: windows-10
favorite count: 0
has comment: http://stackoverflow.com/comment/110687808
type: Question
has title: How do I set my windows 10 laptop to work with utf-8 unicode?
accepted answer: http://stackoverflow.com/a/49969426

http://stackoverflow.com/comment/87099831
type: AnswerComment
comment on: http://stackoverflow.com/a/50041643
has text: this is a numerical integration, I assume? Is there a way to get the symbolic result as well?
type: Comment
score: 0

http://stackoverflow.com/q/50010545
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/50010648
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50010648
type: Question
has title: Flask form data passed to database and redirect to homepage
has body: OK, so i've been trying to get a form to pass data through to a text file in Flask but every time I do, I get one of these error messages: "Method Not Allowed. The method is not allowed for the requested URL." or Not Found. The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. What I'd like to happen is when the user hits submit, be redirected to the homepage with a "Hi username" message. I've tried putting in the form action "/, index, index.html, {{ url_for('index') }}" (this last one just as a long shot but was running out of ideas!) My Flask code is as follows: @app.route('/signUp', methods = ['GET', 'POST']) def signUp(): if request.method == "POST": with open("data/users.txt", "a") as f: f.write(request.form["user"]) else: return render_template("signUp.html") My form code is as follows: Username Thanks for any input!
upvote count: 0
tagged with: python
score: -1
tagged with: flask

http://stackoverflow.com/comment/86989564
type: QuestionComment
comment on: http://stackoverflow.com/q/49986417
type: Comment
has text: Possible duplicate of [How to use threading in Python?](https://stackoverflow.com/questions/2846653/how-to-use-threading-in-python)
score: 0

http
tags question: http://stackoverflow.com/q/50023267
tags question: http://stackoverflow.com/q/49985282
tags question: http://stackoverflow.com/q/50045709
type: Tag
tags question: http://stackoverflow.com/q/49991581
tags question: http://stackoverflow.com/q/49940970
tag name: http

http://stackoverflow.com/a/49948954
score: 0
has body: On Mac OS X, the --windowed option has the opposite functionality that you desire: -w, --windowed, --noconsole Windows and Mac OS X: do not provide a console window for standard i/o. On Mac OS X this also triggers building an OS X .app bundle. This option is ignored in *NIX systems. See the description of the options here. Could you try removing this option and running pyinstaller again?
answers question: http://stackoverflow.com/q/49948484
type: Answer

http://stackoverflow.com/a/49939723
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49939624
score: 4
has body: In the LogEvent class you have def __int__ instead of def __init__.
answers question: http://stackoverflow.com/q/49939624
type: Answer
has comment: http://stackoverflow.com/comment/86895168
upvote count: 4
has comment: http://stackoverflow.com/comment/86895131
downvote count: 0

http://stackoverflow.com/a/76464205
downvote count: 1
score: 1
type: Answer
upvote count: 2
has body: For single reusable options, i just store the decorator returned by click.option in a variable. For multiple common options, i like to use a simple composition as a helper.. import functools compose = lambda *funcs: functools.reduce(lambda f, g: lambda x: f(g(x)), funcs) # reusable single option or argument spam = click.option("--spam") # reusable group foo_bar_baz = compose( click.option("--foo", is_flag=True), click.option("--bar", is_flag=True), click.option("--baz", is_flag=True), ) @click.command() @foo_bar_baz @spam def command1(foo, bar, baz, spam): pass @click.command() @foo_bar_baz @spam @click.option('--unique-flag', is_flag=True) def command2(foo, bar, baz, spam, unique_flag): pass
answers question: http://stackoverflow.com/q/50061342

http://stackoverflow.com/q/50064243
answer count: 0
type: UnansweredQuestion
score: 0
type: Question
has body: I'm working in Python. In a Monte Carlo scheme, I want to repeatedly convolve an image (of let's say 500x500 pixels) with a varying kernel, of between 50x50 and 200x200 pixels. I'm using convolve_fft from astropy.convolution to compute the convolution. Right now, the whole scheme is prohibitively slow. Odds are the answer to this question is simply 'no, there is not', but is there something I can do to speed things along?
has comment: http://stackoverflow.com/comment/87145406
tagged with: convolution
has comment: http://stackoverflow.com/comment/87151307
tagged with: python
tagged with: kernel
has title: Repeatedly convolving two large arrays [python]
has comment: http://stackoverflow.com/comment/87145263

http://stackoverflow.com/comment/87075717
type: Comment
type: QuestionComment
score: 0
has text: @internet_user you're right, see comment above :)
comment on: http://stackoverflow.com/q/50029044

http://stackoverflow.com/q/50006738
has answer: http://stackoverflow.com/a/65045420
tagged with: discord
favorite count: 0
has answer: http://stackoverflow.com/a/64926329
has comment: http://stackoverflow.com/comment/87032977
type: Question
has comment: http://stackoverflow.com/comment/87031160
has comment: http://stackoverflow.com/comment/87033107
downvote count: 0
has comment: http://stackoverflow.com/comment/87032952
type: UnansweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/87033018
has body: As you can see, the category says "No category". How can I change the category for a command? My code: @bot.command(pass_context=True) async def ping(ctx): """Pong""" await bot.say(":ping_pong: Pong!") print ("user has pinged")
has title: Categories on help command for Discord bot
answer count: 3
has answer: http://stackoverflow.com/a/50008416
upvote count: 6
tagged with: python

http://stackoverflow.com/q/50047495
has title: mongo db date saved as string, convert to ISO Date using RoboMongo or Python's PyMongo
type: Question
tagged with: mongodb
tagged with: python
accepted answer: http://stackoverflow.com/a/50048874
has answer: http://stackoverflow.com/a/50048874
has body: First of all, I am not a mongo db expert, so I might have some newbie mistakes. I have a mongodb database that was created with pymongo a while ago, from parsing a json. A sample piece of code is this: data = {parsed_json['location']['city']: 'local_time': parsed_json['current_observation']['local_time_rfc822'], 'full_name': parsed_json['current_observation'] ['observation_location']['full'], 'latitude': float(parsed_json['current_observation'] ['observation_location'] ['latitude']), 'longitude': float(parsed_json['current_observation'] ['observation_location'] ['longitude']), 'elevation_ft': float(parsed_json['current_observation'] ['observation_location'] ['elevation'].split(' ')[0]) }} collection = db[state_to_insert] collection.insert_one(data) print 'Inserted data successfully' The output in the db looks like the one below, however, one of the fields "local_time" is saved in the wrong format (string instead of date). { "_id" : ObjectId("5adb54ff59aea50aec2856bf"), "Ithaca" : { "weather" : "Clear", "full_name" : "Ithaca, New York", "windchill_f" : 47.0, "solarradiation" : 786, "heat_index" : "NA", "latitude" : 44.7, "wind_mph" : 0.0, "dewpoint" : 23, "precip_today_in" : 0.0, "temp_f" : 47.0, "elevation_ft" : 174.0, "pressure_trend" : "0", "visibility_mi" : 10.0, "wind_string" : "Calm", "pressure_in" : 30.34, "wind_dir" : "NNW", "wind_degrees" : 336.0, "relative_humidity_perc" : 0.38, "uv" : 3.7, "longitude" : -73.47, "local_time" : "Sat, 21 Apr 2018 11:13:03 -0400", "wind_gust_mph" : 0.0, "feels_like" : 47 } } My db is running on a local machine, in a db that has one collection called "NY": To fix the data type, so I can query the database properly by date, in robomongo, I run the following code: db.NY.find().forEach(function(element){ element.local_time = new Date(element.local_time); db.NY.save(element); }) Which produces the following output: { "_id" : ObjectId("5adb54ff59aea50aec2856bf"), "Ithaca" : { "weather" : "Clear", "full_name" : "Ithaca, New York", "w…
type: AnsweredQuestion
score: 0
tagged with: robo3t
answer count: 1
tagged with: pymongo

http://stackoverflow.com/q/49989889
score: 0
has answer: http://stackoverflow.com/a/49990044
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: dimensionality-reduction
type: Question
has body: I am looking to reduce the dimensionality of a set (~500) of N dimensional vectors to 2D vectors, so that for any two vectors: numpy.dot(vOriginal1, vOriginal2)==numpy.dot(vNew1, vNew2) where vNew1, vNew2 are the dimensionally reduced vOriginal1, vOriginal2 vectors. EDIT: I am not looking for an error of 0, just a low error. All the vectors are of fixed size M, and they are to be converted to size 2.
has comment: http://stackoverflow.com/comment/86996761
has comment: http://stackoverflow.com/comment/86997141
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86997062
has title: Reduce ND Vectors to 2D While Preserving Dot Product
tagged with: python

http://stackoverflow.com/comment/86902477
comment on: http://stackoverflow.com/q/49942914
score: 0
has text: Django 1.11.12 python 2.7.6
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49931414
has answer: http://stackoverflow.com/a/49932052
tagged with: sklearn-pandas
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has body: I am a beginner at python, so bear with me! My dataset is from excel and I was curious how to find and add a frequency column for my ID. I first performed the groupby function for ID and date by doing: dfcount = dfxyz.groupby(["ID", "Date"]) and then found the mean by doing: dfcount1 = dfcount.mean() The output i got was: What I am trying to do is get the frequency number beside it like this: I did not know how to copy python code, so I uploaded pictures! Sorry! Any help is appreciated for what code I can use to count the frequency for each ID AFTER I find the mean of the groupby columns. Thank you in advance!
tagged with: python
has comment: http://stackoverflow.com/comment/86879594
score: 0
tagged with: pandas-groupby
tagged with: pandas
has title: How to find and add frequency column for ID?
has answer: http://stackoverflow.com/a/49932043
has comment: http://stackoverflow.com/comment/86879219

http://stackoverflow.com/a/49948801
type: Answer
has body: after trying to print out the json_dict, we could locate the problem. {'office': {'medical': [{'room-number': 100, 'use': 'reception', 'sq-ft': 50, 'price': 75}, {'room-number': 101, 'use': 'waiting', 'sq-ft': 250, 'price': 75}, {'room-number': 102, 'use': 'examination', 'sq-ft': 125, 'price': 150}, {'room-number': 103, 'use': 'examination', 'sq-ft': 125, 'price': 150}, {'room-number': 104, 'use': 'office', 'sq-ft': 150, 'price': 100}]}, 'parking': {'location': 'premium', 'style': 'covered', 'price': 750}} The correct way of doing this would be: json_dict["office"]["medical"][0]["price"] hope it helps!
answers question: http://stackoverflow.com/q/49948661
score: 0

http://stackoverflow.com/comment/86871080
score: 0
type: AnswerComment
has text: My money is on `object` :) strip the comma and change to `int`.
comment on: http://stackoverflow.com/a/49927479
type: Comment

amazon-s3
tags question: http://stackoverflow.com/q/49940084
tags question: http://stackoverflow.com/q/50073489
tags question: http://stackoverflow.com/q/50039546
tags question: http://stackoverflow.com/q/49931446
tags question: http://stackoverflow.com/q/49989510
tags question: http://stackoverflow.com/q/49955487
tag name: amazon-s3
tags question: http://stackoverflow.com/q/50029087
tags question: http://stackoverflow.com/q/49983031
type: Tag
tags question: http://stackoverflow.com/q/49992886
tags question: http://stackoverflow.com/q/50072547
tags question: http://stackoverflow.com/q/49985718
tags question: http://stackoverflow.com/q/50004263
tags question: http://stackoverflow.com/q/50043330
tags question: http://stackoverflow.com/q/50009698
tags question: http://stackoverflow.com/q/50063668

http://stackoverflow.com/comment/86865064
score: 1
comment on: http://stackoverflow.com/q/49918479
type: Comment
type: QuestionComment
has text: Oh, I assumed you were running on MacOS or Linux because you linked to the pytorch website. Unfortunately, Windows isn't supported yet. I'm sorry that I didn't recognized that before. So, it looks like your error is not uncommon. https://discuss.pytorch.org/t/solved-windows-anaconda-pytorch/11080. They are using the same command as you did but without cuda80. But I don't now if it will make a difference. Maybe you can try using pytorch without gpu first. Look here for more info https://github.com/pytorch/pytorch/issues/494#issuecomment-351548433

http://stackoverflow.com/comment/86873376
score: 0
type: AnswerComment
has text: @Ken: I suggest you try the code line by line -- you will easily see what each statement does. If you don't understand something, follow [Python's tutorial](https://docs.python.org/3/tutorial/).
comment on: http://stackoverflow.com/a/49928442
type: Comment

http://stackoverflow.com/comment/87072989
comment on: http://stackoverflow.com/a/50025167
type: AnswerComment
has text: @pstatix can't say I'm massively surprised... There's going to be overhead involved when you're bringing a DataFrame into the picture vs a list of dicts...
score: 0
type: Comment

http://stackoverflow.com/a/50031805
has comment: http://stackoverflow.com/comment/87081196
answers question: http://stackoverflow.com/q/50031731
has comment: http://stackoverflow.com/comment/96026569
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Python provides a function atleast_1d so to solve the problem from numpy import array, concatenate, atleast_1d array1 = array([1.0, 2.0]) array2 = array(3.0) concatenate([atleast_1d(a) for a in [array1, array2]]) and in my original problem concatenate([atleast_1d(a) for a in mixed_list]) would solve the concatenation issue.
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50031731

http://stackoverflow.com/q/50038747
has comment: http://stackoverflow.com/comment/87133269
has body: I have this problem for physics class, I'm stuck on the last point. Generate a signal of 2s length with sampling frequency 500 Hz that contains (i) a white background noise as produced by a resistance of 1MW at 300K and a bandwidth of 10 kHz, (ii) a sine wave signal at frequency 80 Hz with amplitude 12 mV, (iii) a sine wave signal at frequency 170 Hz with amplitude 6 mV. - Calculate the power-spectrum from the signal in units of V2/Hz. Test if the area of the power spectrum is equal to the rms value of the signal. import numpy as np import matplotlib.pyplot as plt import random #Generate a signal of 2s length with sampling frequency 500 Hz that contains #sampling frequency 500 Hz Fs=500 #the number of points taken #Generate a signal of 2s length time=2 t=np.linspace(0,time,Fs*time) # (i) a white background noise as produced by a resistance of 1MW at 300K and a badwidth of 10kz Kb=1.3806504e-23 #Boltzman's constant T=300 #temperature kelving R=1000 #Ohms resistance DF=10000 #bandwith HZ N=np.power((4*Kb*DF*R*T),0.5) #Noise in VOLTS #Noise in uV from V N=N print ('Noise in uV: ' + str(N)) #the noise should move from twice its height, to -2 times its height... 2000 point up 2000 down, normalized with e-3 Noise=N*1e-3*np.asarray(random.sample(range(-2000,2000),len(t))) #array of random noise, size Fs makes noise from 0.8 to -0.8 uV #(ii) a sine wave signal at frequency 80 Hz with amplitude 12 mV #frequency 80 Hz f1 = 80 #sine wave signal at frequency 80 Hz #amplitude 12 mV a1=12e-6 #amplitude 12 microV # a sine wave signal x1 = a1*np.sin(2*np.pi*t*f1) #sin wave from time formula (the t gives it the array shape) #♦(iii)a sine wave signal at frequency 170 Hz with amplitude 6 mV #frequency 170 Hz f2=170 #a sine wave signal at frequency 170 Hz #with amplitude 6 mV a2=6e-6 # with amplitude 6 mV IVE PUT IT IN VOLTS NOT uV #a sine wave signal x2=a2*np.sin(2*np.pi*t*f2) #sin wave from time formula #- Calculate the power-spectrum from the signal in units of V2/Hz and dB. #total …
type: Question
tagged with: fft
has comment: http://stackoverflow.com/comment/87134911
type: UnansweredQuestion
tagged with: physics
has comment: http://stackoverflow.com/comment/87132526
tagged with: python
tagged with: frequency-analysis
has comment: http://stackoverflow.com/comment/87132796
has title: how to calculate area under power spectrum to test if it is equal to rms value (FFT, python, signal processing)
has comment: http://stackoverflow.com/comment/87190487
score: 0
has comment: http://stackoverflow.com/comment/87100460
answer count: 0

http://stackoverflow.com/q/49951143
type: Question
tagged with: remote-server
has title: Python Jupyter notebook: run via shell script (Ubuntu 16.04.4) (i.e. with nbconvert)
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
upvote count: 2
score: 2
has body: I am using a remote server and would like to run a few jupyter notebooks in the background such that when log out the job still runs and also making use of the 36 cpu cores I am paying for. So far I have the building blocks but would need help to synthesize them: nohup: usually when I run a python notebook in "background" I use nohup jupyter notebook. After that I just execute every single cell in the notebook, close it and close my terminal nbconvert: jupyter nbconvert --to python &lt;YourNotebook&gt;.ipynb would allow to run a jupyter notebook from the command line. shell script: via the WRDS "batch job" function I know that, i.e. I can run a script as follows: #!/bin/bash #$ -cwd #$ -m abe #$ -M myemail@myunisversity.ch echo "Starting Job at date" sas myscript.sas echo "Ending Job at date" And for instance, WRDS allows to run 5 batch jobs per user. Let's say I have: Notebook_1.ipynb Notebook_2.ipynb Notebook_3.ipynb How could I combine the three "building blocks" above to make my Notebook_1, Notebook_2 and Notebook_3 running as python scripts in the background as separate jobs (each making use a cpu core)? Can you show me an example script (especially when I use a virtualenv)?
tagged with: batch-processing
answer count: 0
downvote count: 0
tagged with: shell
favorite count: 0

http://stackoverflow.com/comment/86900333
comment on: http://stackoverflow.com/a/49940082
score: 0
type: AnswerComment
has text: It's not working well. It's filtering out many objects. :( I have other filters too applied on `problems`, not sure if that's the reason.
type: Comment

http://stackoverflow.com/comment/86921355
score: 0
has text: Have edited my question. Sorry for the previous question. @Wen
comment on: http://stackoverflow.com/q/49952307
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49985574
tagged with: counter
has comment: http://stackoverflow.com/comment/86989118
tagged with: python
tagged with: dictionary
score: -1
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/86987690
has answer: http://stackoverflow.com/a/49985725
has title: create nested dictionary or collection counter with pandas and python
downvote count: 2
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49985781
type: Question
possible better answer: http://stackoverflow.com/a/49985725
has answer: http://stackoverflow.com/a/49985781
has answer: http://stackoverflow.com/a/49985740
has body: I would like to create a nested dictionary or Collection in python by grouping seriesA = ["groupA", "groupA", "groupB", "groupB", "groupC"] seriesB = ["item1", "item1," "item3", "item1", "item2"] Desired output: { 'groupA': {'item1': 2}, 'groupB': {'item3': 1}, {'item1':1}, 'groupC': {'item2': 1}} In Python, is there an easier way or would I iterate through the listed tuples, and add a collection counter? nested_dict["groupA"]["item1"] ...should return 2 occurrences.
has comment: http://stackoverflow.com/comment/86987660

http://stackoverflow.com/q/50003534
answer count: 2
score: -2
has title: TypeError: __init__() takes exactly 1 argument (5 given)
has answer: http://stackoverflow.com/a/50003712
accepted answer: http://stackoverflow.com/a/50003712
tagged with: python
has answer: http://stackoverflow.com/a/64658765
has body: I'm practicing with flask case from https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm. I tried to run the codes and check on http://localshot:5000. They were working fine at the first 3 steps. When I tried to fill the contents on http://localhost:5000/new and click the "submit" button on last step, the error occurred. I'm using python2.7 with PyCharm in Mac. Thx. The codes are below: app.py # -*- coding: utf-8 -*- from flask import Flask, render_template, request, flash, redirect, url_for from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3' app.config['SECRET_KEY'] = "random string" db = SQLAlchemy(app) class students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr, pin): self.name = name self.city = city self.addr = addr self.pin = pin #db.create_all() # filter to the retrieved record set by using the filter attribute. # For instance, in order to retrieve records with city = ’Hyderabad’ # in students table # Students.query.filter_by(city = 'Hyderabad').all() @app.route('/') def show_all(): return render_template('show_all.html', students = students.query.all()) @app.route('/new', methods = ['GET', 'POST']) def new(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Please enter all the fields', 'error') else: student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) db.session.add(student) db.session.commit() flash('Record was successfully added') return redirect(url_for('show_all')) return render_template('new.html') if __name__ == '__main__': db.create_all() app.run(debug = True) new.html Students - Flask SQLAlchemy example {%- for category, message in get_flashed_messages(wi…
possible better answer: http://stackoverflow.com/a/64658765
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87023401
upvote count: 1
has comment: http://stackoverflow.com/comment/87040138
downvote count: 3
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87043300

http://stackoverflow.com/comment/86907837
comment on: http://stackoverflow.com/a/49944668
type: Comment
has text: Please add some explanation.
score: 0
type: AnswerComment

discord
tags question: http://stackoverflow.com/q/49968002
tag name: discord
type: Tag
tags question: http://stackoverflow.com/q/50072365
tags question: http://stackoverflow.com/q/50006738
tags question: http://stackoverflow.com/q/50055068
tags question: http://stackoverflow.com/q/50011917
tags question: http://stackoverflow.com/q/50002974
tags question: http://stackoverflow.com/q/49961993
tags question: http://stackoverflow.com/q/50050194

http://stackoverflow.com/q/50016584
type: Question
has body: Is this possible on python ? def NearSourceFactor(seismic_source_distance,seismic_source_select): Na = 0 if (seismic_source_distance &lt;= 2) and (seismic_source_select == "A"): Na == 1.5 elif (seismic_source_distance &lt;= 5) and (seismic_source_select == "A"): return Na == 1.2 elif (seismic_source_distance &gt; 10) and (seismic_source_select == "A"): return Na == 1.0 elif (seismic_source_distance &lt;= 2) and (seismic_source_select == "B"): return Na == 1.3 elif (seismic_source_distance &lt;= 5) and (seismic_source_select == "B"): return Na == 1.0 elif (seismic_source_distance &gt; 10) and (seismic_source_select == "B"): return Na == 1.0 elif (seismic_source_distance &lt;= 2) and (seismic_source_select == "C"): return Na == 1.0 elif (seismic_source_distance &lt;= 5) and (seismic_source_select == "C"): return Na == 1.0 elif (seismic_source_distance &gt; 10) and (seismic_bldg_geometry == "C"): return Na == 1.0 Na = NearSourceFactor(seismic_source_distance,seismic_source_select) seismic_source is 10 and seismic_source_select = B but unfortunately the answer is = "None" I'm expecting the answer is 1.0
tagged with: if-statement
has comment: http://stackoverflow.com/comment/87049547
has comment: http://stackoverflow.com/comment/87049766
has comment: http://stackoverflow.com/comment/87049361
tagged with: python
has comment: http://stackoverflow.com/comment/87049788
has comment: http://stackoverflow.com/comment/87049727
score: -3
has comment: http://stackoverflow.com/comment/87049812
has comment: http://stackoverflow.com/comment/87049778
accepted answer: http://stackoverflow.com/a/50016910
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87049759
downvote count: 3
has answer: http://stackoverflow.com/a/50016910
has title: Python multiple if else function and return
has comment: http://stackoverflow.com/comment/87049449
has comment: http://stackoverflow.com/comment/87049789
has comment: http://stackoverflow.com/comment/87049682
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/87053931
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50018857
score: 0
has text: yes but why it acts like that I have a range of j 4 so that shouldnt have happened ?

http://stackoverflow.com/a/49959894
score: 0
type: Answer
has body: Why I have to answer your question continuously? :)) You are misunderstood. just turn the sign of your code. while True: num+=1 Omn[i]=Omo[i-1]+0.01*np.random.normal() L=2*Omn[i] # Arbitrary equation just for test if L&gt;R: Omo[i]=Omn[i] else: Omo[i]=Omo[i-1] if (0&lt;Omo[i]&lt;0.29) or num&gt;100: break print(Omo[i],L)
answers question: http://stackoverflow.com/q/49946683

http://stackoverflow.com/comment/87065380
score: 0
comment on: http://stackoverflow.com/q/50024404
has text: Yes I did, I didn't find the solution. I know how to insert values to all columns, but I do not know how to insert to only one (specific) column
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49936978
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86890041
has body: Use xml module. and use enumerate. Ex import xml.etree.ElementTree as ET tree = ET.fromstring(s) for i, content in enumerate(tree.findall(".//test")): if i % 2 != 0: for val in content.findall("criteria/value"): print(val.text) Output: 0.655425 0.766545 0.943154
answers question: http://stackoverflow.com/q/49936895
has comment: http://stackoverflow.com/comment/86889682
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49936895

http://stackoverflow.com/comment/87015155
comment on: http://stackoverflow.com/q/49998613
type: QuestionComment
type: Comment
score: 0
has text: @Rakesh check my edit post

http://stackoverflow.com/q/50011264
tagged with: python
has answer: http://stackoverflow.com/a/50011323
has body: I'm trying to create a really basic software where the user can: 1) press a button to import a .csv file, and the program will read the file and print it 2) press another button to sort the data a specific way 3) Press a third and final button to export that data as a new .csv file Basically, I need help on steps 1 and 3, I have no clue how to do it. MY CODE: from tkinter import * import tkinter import tkinter.messagebox top = Toplevel() def UploadAction(): #Allows user to import a .csv of their choice into the program #Python should read the file into the system and display the contents def SortingCSV(): #Allows user to switch the contents of the file to the desired settings def Export(): #Exports the manipulated data into a new .csv file and downloads it B=Button(top, text ="Upload", command = UploadAction).grid(row=2,column=1) B=Button(top, text ="Convert File", command = SortingCSV).grid(row=6, column=1) B=Button(top, text ="Download File", command = Export).grid(row=7,column=1) top.mainloop()
has comment: http://stackoverflow.com/comment/87039086
downvote count: 3
has title: I need help programming functions for my buttons (importing, exporting)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87120056
tagged with: tkinter
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87039584
answer count: 1
score: -3

http://stackoverflow.com/a/50073556
answers question: http://stackoverflow.com/q/50073489
upvote count: 18
has comment: http://stackoverflow.com/comment/111518567
downvote count: 0
type: Answer
score: 18
has body: The keyname in S3 contains also the directory path, there are no real directories in buckets. Do it like this: s3 = session.resource("s3") obj = s3.Object("mybucket", "media/private/test.txt") obj.delete()
accepted answer of: http://stackoverflow.com/q/50073489
has comment: http://stackoverflow.com/comment/87168994
has comment: http://stackoverflow.com/comment/93455476
type: AcceptedAnswer

http://stackoverflow.com/comment/86903400
type: Comment
comment on: http://stackoverflow.com/q/49942622
type: QuestionComment
has text: Also you said on Windows, AWS Lambda is not Windows, it's serverless
score: 0

http://stackoverflow.com/a/50021790
type: Answer
score: 0
has body: You can use a generator for this: def yielder(x, value='Python'): match = False for word in x.split(): if match == True: yield word match = False if word == value: match = True res = list(yielder(str1)) ['is', 'has', 'interpreters', 'code', 'Software'] The benefit of this method is that it is lazy after splitting. For long strings, you can extract results as you iterate. To learn more, look up the following: Generators: how does yield statement work Split strings: how does str.split work
answers question: http://stackoverflow.com/q/50021676

http://stackoverflow.com/comment/87063312
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/50023533
has text: Please provide a [minimal, runnable example](https://stackoverflow.com/help/mcve) instead of these separate code snippets.

http://stackoverflow.com/comment/86914806
type: QuestionComment
has text: An updated duplicate: [NameError: name 'reduce' is not defined in Python](https://stackoverflow.com/questions/8689184/nameerror-name-reduce-is-not-defined-in-python)
comment on: http://stackoverflow.com/q/49948987
score: 0
type: Comment

http://stackoverflow.com/q/50057723
answer count: 1
upvote count: 1
has body: Right now I have an unstacked dataframe that came from something like: Total_People Age_Period Total_income Sge_group History 2015-01 1 12 2015-01 98730.77 2015-02 1 24 2015-02 41476.93 2 33 2015-02 84435.25 2015-03 1 101 2015-03 40630.45 2 99 2015-03 28969.07 3 22 2015-03 83927.98 and when I unstack it as by SGE = SGE['Total_income'].unstack(0) it produces this table, which was expected: sge_group 2015-01 2015-02 2013-03 History ------------------------------------------ 1 98730.77 41476.93 40630.45 2 nan 84435.25 28969.07 3 nan nan 32678.95 But I want to know if it is possible for me to add a column or two at the bottom where I can count the total number of people in each sge_group date or the total income of one, looking something like this like: sge_group 2015-01 2015-02 2013-03 History ------------------------------------------ 1 98730.77 41476.93 40630.45 2 nan 84435.25 28969.07 3 nan nan 32678.95 Total_People 12 57 222 Total_Income x x x
accepted answer: http://stackoverflow.com/a/50057908
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50057908
score: 0
tagged with: pandas
tagged with: python
has title: add new column to a reshaped dataframe

http://stackoverflow.com/comment/87151850
comment on: http://stackoverflow.com/a/50067344
has text: I've seen your update just after my first answer. It works with cmd but not with powershell. I update my anwser.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86997636
type: Comment
score: 0
has text: `ax = df.plot(x='Date', y = 'Market Cap', kind = 'line')` then `df2.plot(x='Date', y = 'Market Cap', kind = 'line', ax=ax)`
type: QuestionComment
comment on: http://stackoverflow.com/q/49990269

http://stackoverflow.com/comment/87039530
comment on: http://stackoverflow.com/q/50010964
score: 0
type: Comment
type: QuestionComment
has text: why? we're all adults here. (and the answers listed are way too convoluted). Perhaps what you're really looking for is `self.__dict = defaultdict(list)`? Then you would always do `self.__dict['...'].append(...)` and never `self.__dict['...'] = ...`

http://stackoverflow.com/comment/87966307
score: 0
has text: Thanks @FrankMerrow it worked with this workaround for a while but now I face a similar error -- ImportError: libblas.so.3gf: cannot open shared object file: No such file or directory. I did create a symbolic link: sudo ln -s /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 /usr/lib/x86_64-linux-gnu/blas/libblas.so.3gf I updated the ~/.bashrc with export LD_LIBRARY_PATH=:/usr/local/nest-python/lib:/usr/lib/x86_64-linux-gnu/atlas:/usr/local/lib:/usr/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu/lapack:/lib/x86_64-linux-gnu/blas But the issue persists. Any pointers? Plz let me know.
comment on: http://stackoverflow.com/q/50031831
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86963369
has text: your dict is not valid one , because key `a` cannot be duplicated in dict
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/49973682

http://stackoverflow.com/q/50060231
has comment: http://stackoverflow.com/comment/87140637
tagged with: python
has body: so I am trying to use something called DeepMoji to grade a csv full of tweets. The tweets must be encoded in Unicode. I have been able to make it work with a small dataset, but with the one that i have of over 200,000 points, i am receiving this error: UnicodeDecodeError: 'utf8' codec can't decode byte 0xe2 in position 254: unexpected end of data. The code and solution I have tried are the following, but gives the same error, does anyone have any ideas? TEST_SENTENCES = [] with open('Cleaned_Data3.csv', 'rU') as csvfile: reader = csv.DictReader(csvfile) for row in reader: TEST_SENTENCES.append(row["Tweet"]) try: [x.encode('utf-8') for x in TEST_SENTENCES] except: for rows in TEST_SENTENCES: #attempt to fix the problem str=unicode(str, errors='replace') Here is the full error code. Traceback (most recent call last): File "C:\Users\pjame\Desktop\DeepMoji-master\examples\score_texts_emojis.py", line 24, in &lt;module&gt; for row in reader: File "C:\Python27\lib\site-packages\unicodecsv\py2.py", line 217, in next row = csv.DictReader.next(self) File "C:\Python27\lib\csv.py", line 108, in next row = self.reader.next() File "C:\Python27\lib\site-packages\unicodecsv\py2.py", line 128, in next for value in row] UnicodeDecodeError: 'utf8' codec can't decode byte 0xe2 in position 254: unexpected end of data
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87140985
tagged with: decode
tagged with: list
has comment: http://stackoverflow.com/comment/87165084
has comment: http://stackoverflow.com/comment/87141038
has title: UnicodeDecodeError when reading from CSV/List: Unexpected End of Data
score: 0
has comment: http://stackoverflow.com/comment/87166696
tagged with: unicode
has comment: http://stackoverflow.com/comment/87166818
has comment: http://stackoverflow.com/comment/87141420
type: Question
tagged with: http://stackoverflow.com/tag/csv
answer count: 0

http://stackoverflow.com/a/49926924
score: 32
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86888867
answers question: http://stackoverflow.com/q/49926843
has comment: http://stackoverflow.com/comment/86918782
accepted answer of: http://stackoverflow.com/q/49926843
has body: Remember that Python int values are of arbitrary size. How does that work? Well, in CPython,1 an int is represented by a PyLong_Object, which has an array of 4-byte chunks2, each holding 30 bits3 worth of the number. 0 takes no chunks at all. 1 - (1&lt;&lt;30)-1 takes 1 chunk. 1&lt;&lt;30 - (1&lt;&lt;60)-1 takes 2 chunks. And so on. This is slightly oversimplified; for full details, see longintrepr.h in the source. In Python 2, there are two separate types, called int and long. An int is represented by a C 32-bit signed integer4 embedded directly in the header, instead of an array of chunks. A long is like a Python 3 int. If you do the same test with 0L, 1L, etc., to explicitly ask for long values, you will get the same results as in Python 3. But without the L suffix, any literal that fits in 32 bits gives you an int, and only literals that are too big give you longs.5 (This means that (1&lt;&lt;31)-1 is an int, but 1&lt;&lt;31 is a 2-chunk long.) 1. In a different implementation, this might not be true. IIRC, Jython does roughly the same thing as CPython, but IronPython uses a C# "bignum" implementation. 2. Why 30 bits instead of 32? Mainly because the implementation of pow and ** can be simpler and faster if it can assume that the number of bits in two "digits" is divisible by 10. 3. It uses the C "struct hack". Technically, a Py_LongObject is 28 bytes, but nobody ever allocates a Py_LongObject; they malloc 24, 28, 32, 36, etc. bytes then cast to Py_LongObject *. 4. In fact, a Python int is a C long, just to make things confusing. So the C API is full of things like PyInt_FromLong where the long means "32-bit int" and PyLong_FromSize_t where the long means "bignum". 5. Early versions of Python 2.x didn't integrate int and long as nicely, but hopefully nobody has to worry about those anymore.
type: Answer
upvote count: 32

http://stackoverflow.com/comment/86930749
type: AnswerComment
has text: @jsbueno sill one thing missing here how to make this attribute readonly. i don't think there is a way for this without overriding the `__setattr__`
comment on: http://stackoverflow.com/a/49948873
score: 1
type: Comment

http://stackoverflow.com/q/50028834
has comment: http://stackoverflow.com/comment/87073785
favorite count: 0
tagged with: oracle-database
score: 1
has title: How to update data in database using python 3.6 with GUI user inputs....?
tagged with: python
tagged with: python-3.6
type: Question
has body: This is my code but I'm getting an error which says that args are not defined. I want to know how to access data from database and also from user in GUI. def f6(): upst.deiconify() root.withdraw() import cx_Oracle con=None cursor=None try: con=cx_Oracle.connect("system/abc123") cursor=con.cursor() sql="update student set name='%s' where rno='%d'" args(name,rno) cursor.execute(sql % args) con.commit() msg=str(cursor.rowcount)+"row updated" messagebox.showinfo("Record updated",msg) except cx_Oracle.DatabaseError as e: if con is not None: con.rollback() messagebox.showerror("Failure",e) finally: cursor.close() if con is not None: con.close() btnUpdate=Button(root,text="Update",width=10,command=f6)
answer count: 0
has comment: http://stackoverflow.com/comment/87094697
type: UnansweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50050810
has body: I have a pandas Series with two columns, Index (of timestamps) and floats which I try to plot using Matplotlib as follows s2.plot() which gives me the following plot now I want to format the x-axis to just show the timestamp in '%Y-%m-%d' format so I try fig, ax = plt.subplots() xdfmt = dates.DateFormatter('%Y-%m-%d') ax.xaxis.set_major_formatter(xdfmt) ax.xaxis_date() s2.plot() which fails as follows dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC) ValueError: ordinal must be >= 1 How should I format the x-axis to display legible x-axis labels?
tagged with: axis-labels
has comment: http://stackoverflow.com/comment/87118068
has comment: http://stackoverflow.com/comment/87117949
type: Question
has comment: http://stackoverflow.com/comment/87118547
linked to: http://stackoverflow.com/q/44213781
tagged with: format
has comment: http://stackoverflow.com/comment/87117946
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87118438
has comment: http://stackoverflow.com/comment/87118147
tagged with: matplotlib
tagged with: timestamp
tagged with: python
duplicate of: http://stackoverflow.com/q/44213781
has comment: http://stackoverflow.com/comment/87118008
score: 0
answer count: 0
has title: How to format x axis in matplotlib when plotting pandas series with timestamp as index?

http://stackoverflow.com/comment/86893777
has text: @Parag S. Chandakkar thank you!
score: 0
comment on: http://stackoverflow.com/q/49937159
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87136107
type: QuestionComment
has text: Is there maybe a more simple way to deploy?
comment on: http://stackoverflow.com/q/49967860
score: 0
type: Comment

http://stackoverflow.com/comment/87068957
type: AnswerComment
has text: A simple more readable version yes, his answer wasn't listed here as I was typing it out.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50026300

http://stackoverflow.com/a/49938598
type: Answer
accepted answer of: http://stackoverflow.com/q/49937854
has body: You should use DateTimeField with validation instead of writing separate model as below: def validate_date(value): if not value.weekday() not in [0, 1, 2]: raise ValidationError("Day should be a Monday, Tuesday or Wednesday") # similarly implement validation for time if value.hour not in [6, 7, 8, 9] or value.minute != 0: raise ValidationError("Invalid Time") class TimeDay(models.Model): ... time = models.DateTimeField(validators=[validate_date]) ...
score: 0
answers question: http://stackoverflow.com/q/49937854
type: AcceptedAnswer

http://stackoverflow.com/q/50017584
tagged with: django-views
score: 1
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: python
tagged with: django-forms
accepted answer: http://stackoverflow.com/a/50017640
type: Question
has answer: http://stackoverflow.com/a/50017640
has body: I am creating a web application using the Django web framework. As part of the application, I wanted to give users the ability to update their profile as they choose. When a user tries to update their profile however, the information remains the same even after the user has submitted new information. I've checked my database and the values are not being updated in there either. It is possible however, to change a Users information on the admin page. Below is how I have tried to implement the functionality. Model class UserProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveIntegerField(blank=True, null=True) email = models.EmailField(max_length=254, null=True, blank=True, unique=True) height = models.PositiveIntegerField(blank=True, null=True) weight = models.PositiveIntegerField(blank=True, null=True) Form class UpdateProfile(forms.ModelForm): class Meta: model = UserProfileModel fields = ('email', 'age', 'height', 'weight') Views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): form.save() # return HttpResponseRedirect(reverse('account:profile')) return render(request, 'account/profile.html') else: form = UpdateProfile() if request.user.is_authenticated(): form = UpdateProfile(instance=request.user) args['form'] = form return render(request, 'account/edit_profile.html', args) Url app_name = 'account' urlpatterns = [ url(r'^profile/$', views.profile, name='profile'), url(r'^profile/edit/$', views.update_profile, name='edit_profile'), url(r'^home/$', views.home, name='home'), ] HTML {% block body %} {% csrf_token %} {{ form.as_p }} Submit {% endblock %}
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
has title: Edit UserProfile using Django Forms
type: AnsweredQuestion

http://stackoverflow.com/comment/86890236
type: Comment
comment on: http://stackoverflow.com/q/49937031
score: 2
has text: It seems to me that the cause of this behavior is that only the first print is executed in the main thread, and the others in the other threads.
type: QuestionComment

http://stackoverflow.com/q/49955037
type: Question
has body: I am trying to send image to python code from Xamarin forms (cross platform), I'm using flask-restful (python API) to build web server and call it from the Xamarin app , so first I converted image to base 64: Image2.Source = ImageSource.FromStream(() =&gt; file.GetStream()); var stream = file.GetStream(); var bytes = new byte[stream.Length]; await stream.ReadAsync(bytes, 0, (int)stream.Length); base64 = System.Convert.ToBase64String(bytes); and the post code in xamarin: var imageContent = new MultipartFormDataContent { { new StringContent(base64), "ImageData" } }; var httpClient = new HttpClient(); var imageResponse = await httpClient.PostAsync("http://localhost:52524/", imageContent); // var resultImageContent = imageResponse.Content.ReadAsStringAsync().Result; if (resultImageContent != null) { //some code here } now how I can receive the image from the python code.
answer count: 0
has comment: http://stackoverflow.com/comment/86927124
type: UnansweredQuestion
tagged with: xamarin
has comment: http://stackoverflow.com/comment/86928483
tagged with: c#
score: 0
has title: send and receive image using flask-restful (python API) and C# client
tagged with: cross-platform
tagged with: python
tagged with: flask-restful

http://stackoverflow.com/q/49922535
score: 0
answer count: 1
has body: I am a new beginner in programming. I have multiple events(more than 1000 Number of events) inside the single text file(data.txt). For example BoardID: 31 Channel: 1 Event Number: 3123 Pattern: 0x0000 2627.000000 2627.000000 2626.009033 2629.000000 . . .(up to 1024 data) BoardID: 31 Channel: 1 Event Number: 3124 Pattern: 0x0000 2627.000000 2627.000000 2628.949707 2626.099365 . . ....(up to 1024 data) . ..1000 number of events How can I plot all the data one by one by using a loop over the multiple events. I am trying the following python code but it does not work: with open("data.txt") as f: for i in range(1000): #I have 1000 number of events all_lines = f.readlines() def plot_event(start = 4, all_lines= 'all_lines'): lines = all_lines[start : 1029 - 4 + start] return (plot_event(4*i, all_lines)) x = np.array(range(1,1025)) #for all the events x has same range y2 = float(lines.split()[0]) y2_=list(y2) y22 = [((j / 4096)-0.5) for j in y2_] fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel('Time (ns)') ax.set_ylabel('counts') ax.plot(x,y22, 'k-', color= 'b', label='data') fig=plt.gcf() plt.show() plt.draw() Can somebody explain how I can have each event be plotted one by one using a loop?
type: Question
has title: How to use loop over multiple events in a single text file?
has answer: http://stackoverflow.com/a/49923172
tagged with: python
accepted answer: http://stackoverflow.com/a/49923172
tagged with: plot
type: AnsweredQuestion

http://stackoverflow.com/comment/86908952
has text: Although this does work perfectly in my example, for some reason it does not work with my data. I think it might be related with the fact that I constructed a dictionary using the class `Vividict` given by AaronHall in [this answer](https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionariesl)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49930611
type: Comment

http://stackoverflow.com/comment/87448671
has text: @Azxdreuwa See my answer for an implementation that should work
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50004081
score: 0

http://stackoverflow.com/comment/87095107
comment on: http://stackoverflow.com/a/50016182
score: 0
type: Comment
type: AnswerComment
has text: My fault, I forgot that the skimage region labelling and the scipy region labelling worked a bit different. I've edited the code now.

http://stackoverflow.com/q/49925598
answer count: 2
tagged with: categorical-data
possible better answer: http://stackoverflow.com/a/49925724
tagged with: pandas
has answer: http://stackoverflow.com/a/49925724
downvote count: 0
has title: Pandas Dataframe remap categorical column with two values to binary
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49925676
linked to: http://stackoverflow.com/q/31888871
linked to: http://stackoverflow.com/q/24870306
has answer: http://stackoverflow.com/a/49925676
tagged with: dataframe
tagged with: python
has body: I have a dataframe coming in and would like to check for strings of 'Male' or 'Female', and if the dataframe contained them it would be replaced with '1' or '0'. At the moment I'm using the code below thanks to @Anand S Kumar's answer. if dataframe['gender']: dataframe['gender'].replace([0,1],['Female','Male'],inplace=True) if dataframe['sex']: dataframe['sex'].replace([0,1],['Female','Male'],inplace=True) However, I'd like to also cover any other variations like 'male', 'M', and 'm' or 'female', 'F', 'f', and would rather avoid using two more if statements for each variation. I've tried using a larger list such as... dataframe['gender'].replace([0,1,0,1,0,1,0,1],['Female','Male','male','female','M','F','m','f'],inplace=True) A dictionary... dataframe['gender'].replace({0:'Female',1:'Male', 0:'female',1:'male',0:'F',1:'M',0:'f',1:'m'},inplace=True) But have gotten the 'The truth value of a Series is ambiguous.' ValueError for both. Does anyone know a better way, or what I'm doing wrong with my current attempts? Thanks in advance! Edit: My ValueError was because of my if statement being vague. I changed it to if 'gender' in dataframe.columns: to fix it. Found the fix here.
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/50011824
answers question: http://stackoverflow.com/q/49998528
type: Answer
has body: How about this modification? From : q="123456789 in parents" To : q="'123456789' in parents" Note : I confirmed that in my environment, an error occurs for the former, and no errors occur for the latter. Reference : Search for Files If this was not what you want, I'm sorry.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49998528

flask
tags question: http://stackoverflow.com/q/50020938
tags question: http://stackoverflow.com/q/49993026
tags question: http://stackoverflow.com/q/49957822
tags question: http://stackoverflow.com/q/50021538
tags question: http://stackoverflow.com/q/49965097
tags question: http://stackoverflow.com/q/50018387
tags question: http://stackoverflow.com/q/50072357
tags question: http://stackoverflow.com/q/50013264
tags question: http://stackoverflow.com/q/49940265
tags question: http://stackoverflow.com/q/49957034
tags question: http://stackoverflow.com/q/50018194
tags question: http://stackoverflow.com/q/49974199
tags question: http://stackoverflow.com/q/49970388
tags question: http://stackoverflow.com/q/49960341
tags question: http://stackoverflow.com/q/49927893
tags question: http://stackoverflow.com/q/50016967
tags question: http://stackoverflow.com/q/49957262
tags question: http://stackoverflow.com/q/50065047
tags question: http://stackoverflow.com/q/49949162
tags question: http://stackoverflow.com/q/49928825
tags question: http://stackoverflow.com/q/49943515
tags question: http://stackoverflow.com/q/50067744
tags question: http://stackoverflow.com/q/49970249
tags question: http://stackoverflow.com/q/50012780
tags question: http://stackoverflow.com/q/50001356
tags question: http://stackoverflow.com/q/49956176
tags question: http://stackoverflow.com/q/49937810
tags question: http://stackoverflow.com/q/49941302
tags question: http://stackoverflow.com/q/50071198
tags question: http://stackoverflow.com/q/49985282
tags question: http://stackoverflow.com/q/49921053
tags question: http://stackoverflow.com/q/49969856
tags question: http://stackoverflow.com/q/50053312
tags question: http://stackoverflow.com/q/50010318
tags question: http://stackoverflow.com/q/50002386
tags question: http://stackoverflow.com/q/49941515
tags question: http://stackoverflow.com/q/50071153
tags question: http://stackoverflow.com/q/49954262
tags question: http://stackoverflow.com/q/50048718
tags question: http://stackoverflow.com/q/50062769
tags question: http://stackoverflow.com/q/49959491
tags question: http://stackoverflow.com/q/49991581
tags question: http://stackoverflow.com/q/50030447
tags question: http://stackoverflow.com/q/49950617
tags question: http://stackoverflow.com/q/49948198
tags question: http://stackoverflow.com/q/50042492
tags question: http://stackoverflow.com/q/49954268
tags question: http://stackoverflow.com/q/50013136
tags question: http://stackoverflow.com/q/50011349
tags question: http://stackoverflow.com/q/50045041
tags question: http://stackoverflow.com/q/49939859
tags question: http://stackoverflow.com/q/49963872
tags question: http://stackoverflow.com/q/49987780
tags question: http://stackoverflow.com/q/50058144
tags question: http://stackoverflow.com/q/49921400
tags question: http://stackoverflow.com/q/50010545
tags question: http://stackoverflow.com/q/49926261
tags question: http://stackoverflow.com/q/49955054
tags question: http://stackoverflow.com/q/50043215
tags question: http://stackoverflow.com/q/50037096
tags question: http://stackoverflow.com/q/50068856
tags question: http://stackoverflow.com/q/50028447
tags question: http://stackoverflow.com/q/49946180
tags question: http://stackoverflow.com/q/50061088
tags question: http://stackoverflow.com/q/49964340
tags question: http://stackoverflow.com/q/50034981
tags question: http://stackoverflow.com/q/49964093
tags question: http://stackoverflow.com/q/50059102
tags question: http://stackoverflow.com/q/49965552
tags question: http://stackoverflow.com/q/49944181
tags question: http://stackoverflow.com/q/50073349
tags question: http://stackoverflow.com/q/49962413
tags question: http://stackoverflow.com/q/49993719
tags question: http://stackoverflow.com/q/50001950
tags question: http://stackoverflow.com/q/49967995
tags question: http://stackoverflow.com/q/49982298
tags question: http://stackoverflow.com/q/50057243
tags question: http://stackoverflow.com/q/50051425
tags question: http://stackoverflow.com/q/50070979
tags question: http://stackoverflow.com/q/49924356

http://stackoverflow.com/q/49981224
linked to: http://stackoverflow.com/q/18692364
tagged with: tastypie
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50040119
has title: Extending tastypie API with related objects
has answer: http://stackoverflow.com/a/50040119
tagged with: python
has body: I'm new to Django, Tastypie and asking questions here. I've got a Django application with an API using Tastypie. If I make a GET request to /api/v1/ou/33/, my API returns the object with the id==33, which is ok. { "child_ou_uri": "/api/v1/ou/33/child_ou/", "displayname": "Mother", "id": 33, "inherit": true, "name": "Mother", "resource_uri": "/api/v1/ou/33/" } The thing is, I'm trying to extend the API so that it returns related objects via the child_ou_uri URI from the above object. The children are the same type of objects as their parents. The model has an attribute parent_id pointing to the pk of its parent. My OuResource looks like this: class OuResource(ModelResource): class Meta: queryset = OU.objects.all() resource_name = 'ou' list_allowed_methods = ['get'] detail_allowed_methods = ['get'] filtering = { 'name': ['icontains'], } authentication = SessionAuthentication() authorization = OperatorLocationAuthorization() def get_child_ou(self, request, **kwargs): self.method_check(request, ['get', ]) ous = OuResource().get_list(request, parent_id=kwargs['pk']) return ous def prepend_urls(self): return [ url(r'^(?P&lt;resource_name&gt;%s)/(?P&lt;pk&gt;\w[\w/-]*)/child_ou%s$' % (self._meta.resource_name, '/'), self.wrap_view('get_child_ou'), name='api_get_child_ou') ] def dehydrate(self, bundle): kwargs = dict(api_name='v1', resource_name=self._meta.resource_name, pk=bundle.data['id']) bundle.data['child_ou_uri'] = reverse('api_get_child_ou', kwargs=kwargs) return bundle When I navigate to /api/v1/ou/33/child_ou/ I'd like to get the list of child objects which have their attribute parent_id set to 33, but instead I get ALL of my objects without any filtering at all, equivalent to me navigating to /api/v1/ou/. { "meta": { "limit": 20, "next": "/api/v1/ou/?offset=20&amp;limit=20&amp;format=json", "offset": 0, "previous": null, "total_count": 29 }, "objects": [ { "child_ou_uri": "/api/v1/ou/33/child_ou/", "displayname": "Mother", "id": 33, "inherit": true, "name": "Moth…

http://stackoverflow.com/q/49940522
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I'm creating a pretty large pivot table, but in the Python IDE or notebook I can see only partial results. I would like to have all the results in a better format, such as an excel sheet. but if a try to export results to excel I can only see the D computed field, not the data from A and C variable. do you have an idea on better managing large pivot table in pandas? import numpy as np import pandas as pd N = 100 df = pd.DataFrame({ 'A': pd.date_range(start='2016-01-01',periods=N,freq='D'), 'x': np.linspace(0,stop=N-1,num=N), 'y': np.random.rand(N), 'C': np.random.choice(['Low','Medium','High'],N).tolist(), 'D': np.random.normal(100, 10, size=(N)).tolist() }) my_table=pd.pivot_table(df,index=["A","C"],values=["D"], aggfunc='sum',margins=True) writer = pd.ExcelWriter('C:/pandas_positioning.xlsx', engine='xlsxwriter') my_table.to_excel(writer, sheet_name='my_data', startrow=7, startcol=4, header=False, index=False) writer.save()
has comment: http://stackoverflow.com/comment/86898063
type: UnansweredQuestion
has title: handle large pivot tables in Pandas
tagged with: pivot-table
has answer: http://stackoverflow.com/a/49941211
tagged with: python
tagged with: excel

http://stackoverflow.com/q/49965331
downvote count: 0
tagged with: machine-learning
tagged with: keras
has title: Bottle Neck is giving me wrong shape
favorite count: 0
has body: I am trying to implement my VGG16 model , here is my code: model_vgg = applications.VGG16(include_top=False, weights='imagenet') train_generator_bottleneck = datagen.flow_from_directory( train_data_dir, target_size=(64,64), batch_size=batch_size, class_mode=None, shuffle=False) Found 9741 images belonging to 15 classes. Now i am extracting my feature and saving them bottleneck_features_train = model_vgg.predict_generator(train_generator_bottleneck, 19) np.save(open(bottleneck_features_train.npy', 'wb'), bottleneck_features_train) Now loading my data train_data = np.load(open('bottleneck_features_train.npy', 'rb')) train_labels = train_generator_bottleneck.classes train_labels = to_categorical(train_labels, num_classes=15) Here i am getting the wrong shape of labels and data print train_data.shape print train_labels.shape Output: (9728L, 2L, 2L, 512L) (9741L, 15L) Why i am getting the wrong shape output please help ?
upvote count: 3
score: 3
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49965731
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/50033290
has comment: http://stackoverflow.com/comment/87083592
answers question: http://stackoverflow.com/q/50033186
type: Answer
has body: You are close. list.sort does an in-place sort and returns None. "pythonic" API's that modify an object generally don't return that object. Most programs wouldn't use that object so it would just be a pointless increment and decrement of the reference count. Use sorted instead return sorted(odd_arr).extend(even_arr) You can also ditch that filter and lambda stuff with generators def sort_array(source_array): arr = sorted(x for x in source_array if not x % 2).extend( x for x in source_array if x % 2) return arr
score: 0
has comment: http://stackoverflow.com/comment/87083248

http://stackoverflow.com/q/50032481
has answer: http://stackoverflow.com/a/58816011
upvote count: 8
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87081631
has comment: http://stackoverflow.com/comment/87081195
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67167364
has answer: http://stackoverflow.com/a/50032581
tagged with: python
answer count: 4
score: 8
has answer: http://stackoverflow.com/a/65756997
tagged with: linked-list
has body: I want to write a function called print_iterator_explicit() which prints all of the items in a linked list by making use of the Iterator. However, you are not permitted to use the standard "for ... in" loop syntax - instead you must create the Iterator object explicitly, and print each item by calling the next() method Use the iter() and next() methods in your function definition - and remember to handle the StopIteration exception! Below is what I've tried, but the print_iterator_explicit seems to have some problem which I can only print the first element but not the whole list. class LinkedListIterator: def __init__(self, head): self.current = head def __next__(self): if self.current == None: raise StopIteration else: item = self.current.get_data() self.current = self.current.get_next() return item class LinkedList: def __init__(self): self.head = None def __iter__(self): return LinkedListIterator(self.head) def add(self, item): new_node = Node(item) new_node.set_next(self.head) self.head = new_node def print_iterator_explicit(items): it = items.__iter__() print(it.__next__())
downvote count: 0
has title: linked list iterator python
has comment: http://stackoverflow.com/comment/87081188

http://stackoverflow.com/comment/86928807
score: 0
type: AnswerComment
has text: @sciroccorics the example is a simplified version of the dictionaries I'll be dealing with. Most will have varying levels of nesting going from 1-5...
type: Comment
comment on: http://stackoverflow.com/a/49955586

http://stackoverflow.com/a/50066263
downvote count: 1
has comment: http://stackoverflow.com/comment/87346436
has body: You could try the following: import csv def save_output(mydict, output_file_name): keys = [list(mydict.keys())] values = [mydict[key] for key in mydict.keys()] final = keys + values with open(output_file_name, 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=' ') writer.writerows(final) mydict = {'k1':[1,2,3], 'k2':[4,5,6], 'k3':[6,7,8]} save_output(mydict, "output_file_name.csv") The output when you open the csv file is this: k1 k2 k3 1 2 3 4 5 6 6 7 8
type: Answer
answers question: http://stackoverflow.com/q/50065474
score: 0
upvote count: 1

http://stackoverflow.com/comment/87149904
score: 0
has text: the django's cache offers nice solutions to your problem
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50066638

http://stackoverflow.com/comment/87019520
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50001328
has text: in python 3.4 with `re` package I don't have fuzziness, that"s why
score: 0

http://stackoverflow.com/a/50004613
has comment: http://stackoverflow.com/comment/126415245
type: Answer
has body: You can set the cursor position on various events, such as when the line-edit widget loses focus: class CustomLineEdit(QLineEdit): def __init__(self, txt, parent=None): super(CustomLineEdit, self).__init__(txt, parent) self.setCursorPosition(0) def focusOutEvent(self, e): self.setCursorPosition(0) and possibly other events, such as when the selection changes, if you want.
has comment: http://stackoverflow.com/comment/87033254
accepted answer of: http://stackoverflow.com/q/50004337
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50004337
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87026321

http://stackoverflow.com/comment/87113990
comment on: http://stackoverflow.com/a/50048915
type: AnswerComment
has text: Very complete and interesting. Thank you!
score: 1
type: Comment

http://stackoverflow.com/q/49952610
answer count: 2
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/49952687
downvote count: 0
tagged with: pyqt5
possible better answer: http://stackoverflow.com/a/55948250
has body: I am trying to make it such that when I click a QPushButton a line is drawn. However the code I have right now makes the line at the beginning when the code is initiated and not after. The QPushButton doesn't seem to do any drawing. I also don't quite understand why when drawing you need an 'event' argument in the function. import sys from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QMainWindow, QGridLayout,QPushButton, QApplication, QWidget from PyQt5.QtCore import QSize, QCoreApplication, Qt from PyQt5.QtGui import QPainter, QPen class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(300, 300)) pybutton = QPushButton('button', self) pybutton.clicked.connect(self.paintEvent) pybutton.resize(100,100) pybutton.move(100, 100) def paintEvent(self,event): print('click') painter = QPainter(self) pen = QPen(Qt.red, 3) painter.setPen(pen) painter.drawLine(0,0,100,100) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit( app.exec_() )
favorite count: 0
type: Question
tagged with: python
tagged with: line
tagged with: qpushbutton
tagged with: paintevent
has answer: http://stackoverflow.com/a/55948250
type: AnsweredQuestion
has title: PyQt5: Draw a line by clicking QPushButton
accepted answer: http://stackoverflow.com/a/49952687

http://stackoverflow.com/q/49965938
tagged with: python
has body: i use python and pyqt4 for web view. here my simple code : import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * import os app = QApplication(sys.argv) web_view= QWebView() google='https://www.google.com' web_view.load(QUrl(google)) web_view.show() sys.exit(app.exec_()) i want to create a new button where that button any time to execute i want to take current url text link and store it in some variable. how to do that ?how to take current url from web view ?
has title: How to get the current url of QwebView?
favorite count: 0
type: Question
upvote count: 2
tagged with: pyqt
type: UnansweredQuestion
answer count: 1
tagged with: pyqt4
downvote count: 0
tagged with: qwebview
has answer: http://stackoverflow.com/a/49966015
score: 2
tagged with: python-2.7

http://stackoverflow.com/comment/87021011
comment on: http://stackoverflow.com/a/49999229
type: Comment
has text: Yes, the output should be as above, but where i must write flags=re.IGNORECASE?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87178708
comment on: http://stackoverflow.com/q/50050194
has text: @LegacyKS the problem is that you use both the `commands` way, and `on_message` way of creating commands. To fix this, you can either replace your `on_message` commands with `commands` commands, or add `await bot.process_commands(message)` after your command `if` statement in `on_message`(PS sorry for answering in a comment, I am unable to put it in an actual answer because your question was marked as off-topic)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87180995
type: QuestionComment
comment on: http://stackoverflow.com/q/50020504
score: 0
has text: Thanks, I checked it. Unfortunately the space is entered by users' mistake and should be removed
type: Comment

http://stackoverflow.com/a/50053180
upvote count: 1
has comment: http://stackoverflow.com/comment/87123046
answers question: http://stackoverflow.com/q/50052820
has comment: http://stackoverflow.com/comment/87122819
type: Answer
has body: You need to make a few changes to your code: (1) Replace new_text with text so that text's value gets updated in each iteration. (2) Break out of the while loop once the user has reached the max number of tries. (3) There's no point in asking the user to input text when the count has reached the max, so instead of getting raw_input, just print "Thanks for playing!". Here's the updated code that works: count = 0 print "Hello. I have a name inside my head. Please guess what name it is." text = raw_input ("What is your answer? ") while (text != "Name" and count &lt; 10): count = count + 1 attempt = 10 - count if count &gt;= 10: print "That is the maximum amount of attempts allowed. Sorry!" print "Thanks for playing!" if count &lt; 10: print "Sorry, that is not the answer. You have", attempt, "more attempts." text = raw_input ("What is your next guess? ") if (text == "Name"): print "Amazing. You got it correct!"
score: 1
has comment: http://stackoverflow.com/comment/87122851
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50052820

http://stackoverflow.com/q/50050053
has comment: http://stackoverflow.com/comment/87122562
type: UnansweredQuestion
has title: How can I escape from python environment hell?
tagged with: python
score: 0
tagged with: environment-variables
has answer: http://stackoverflow.com/a/50050349
tagged with: ubuntu-16.04
answer count: 1
has body: I don't know how I've gotten here but I have many competing installations of python on my Ubuntu 16.04 path. Some I use, some I don't. I'm at the point now where I want to clean up things to save headache when troubleshooting issues but I don't know any strategies or tools of tackling this. What is the best way I can find out which environments are being used and not used? How can I determine which python directories are being pointed to and which ones are abandoned? Whats a quick way I can get a list of non-standard packages installed to each environment?
has comment: http://stackoverflow.com/comment/87116464
type: Question

http://stackoverflow.com/comment/87029865
score: 0
type: QuestionComment
has text: @user1443098 - Not a BSOD, but an APPCRASH in python.exe. (At least that's what happens for me.)
type: Comment
comment on: http://stackoverflow.com/q/50002917

http://stackoverflow.com/comment/87041567
comment on: http://stackoverflow.com/a/50012210
has text: This is not properly indented
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/86914627
type: Comment
comment on: http://stackoverflow.com/q/49949011
has text: `df.loc[df.col2=='','col1'].unique()`
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86970519
type: QuestionComment
comment on: http://stackoverflow.com/q/49976591
score: 1
has text: Your simplified example is not consistent with you constraints: how could you remove 10 in O(1) from `d[a]`
type: Comment

http://stackoverflow.com/q/49996293
favorite count: 0
type: Question
has body: I want to assign every href I find with beautifulsoup to variable. For example link1, link2, link3 .... my function look like this now def board_list(): html = driver.page_source soup=BeautifulSoup(html, "html.parser") for link in soup.findAll('a', {'class': 'board-tile'}): href = driver.current_url+link.get('href') title = link.string print(title) print(href)
type: UnansweredQuestion
has title: assigning variable to href from beautifull soap
downvote count: 0
has comment: http://stackoverflow.com/comment/87008983
upvote count: 1
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87008979

http://stackoverflow.com/comment/86906444
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49945055
has text: @cᴏʟᴅsᴘᴇᴇᴅ I would say using pandas is more safety : -)
type: Comment

http://stackoverflow.com/comment/87399842
score: 0
has text: Why you don't read the error log. It says clearly: AttributeError: 'TextureRegion' object has no attribute 'bilt' Repleace the word bilt with blit.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49964199

http://stackoverflow.com/q/49986522
has body: I want to read the data stored in a TFRecord file that I've used as a train record in TF Object Detection API. However, I get an InvalidArgumentError: Input to reshape is a tensor with 91090 values, but the requested shape has 921600. I don't understand what the root of the error is, even though the discrepancy seems to be a factor of 10. Question: How can I read the file without this error? I can't rule out that the error is from creating the record, or if the error is in how I read it. Therefore, I've included my code for both. I'm able to run object_detection/train.py with the data, AND generate a frozen graph from the trained model. From this answer (and its mentioned GitHub issue), I figured out that I had to convert my PNG images into JPG, hence the as_jpg-part (see my code below). I used the code from this answer as a starting point to read the file. I use Tensorflow 1.7.0, Python 3.5 There is only one class: "Human". The record has 1000 images; each image can have a single bounding box, or multiple. (One for each human in the respective image.) How I read the TFRecord: As mentioned above: I used the code from this answer as a starting point to read the file: train_record = 'train.record' def read_and_decode(filename_queue): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ 'image/height': tf.FixedLenFeature([], tf.int64), 'image/width': tf.FixedLenFeature([], tf.int64), 'image/source_id': tf.FixedLenFeature([], tf.string), 'image/encoded': tf.FixedLenFeature([], tf.string), 'image/format': tf.FixedLenFeature([], tf.string), 'image/object/bbox/xmin': tf.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature(tf.float32), 'image/object/class/text': tf.VarLenFeature(tf.string), 'imag…
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/49989803
has title: Read data from TFRecord file used in Object Detection API
tagged with: tensorflow
score: 8
type: Question
linked to: http://stackoverflow.com/q/37151895
tagged with: object-detection-api
linked to: http://stackoverflow.com/q/46217630
type: UnansweredQuestion
tagged with: tfrecord
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/q/50070362
has comment: http://stackoverflow.com/comment/87157416
accepted answer: http://stackoverflow.com/a/50070863
type: Question
has answer: http://stackoverflow.com/a/50082059
answer count: 2
has comment: http://stackoverflow.com/comment/87158965
has answer: http://stackoverflow.com/a/50070863
has comment: http://stackoverflow.com/comment/87173078
has body: I have encounter this issue in multiple situations. One use case here is, say I have a directory structure that can include unknown layers of sub-directories, and I want to get the total count of files under rootdir. What's the best way to iterate over this tree dynamically? This is an example of the folder structure: rootdir -&gt; subdir1 -&gt;file1 -&gt; subsubdir1 -&gt; file1 -&gt; file2 -&gt; subsubdir2 -&gt; file1 -&gt; subsubdir3 -&gt; file1 -&gt; subsubsubdir -&gt; file1 -&gt; subdir2 -&gt; subsubdirA -&gt; file1 -&gt; file2 -&gt; subsubdirB -&gt; file1 -&gt; file2 I'm getting the folder structure from an API call, not the file-system directly. Here is part of the api response. Suppose this is what I get from calling the rootdir, then I want to save the sub-folder id [1,2], then go into each sub-folder and iterate the same process of finding if sub-folder exist while keeping count of the files. The response includes a total_count, which is the number of items (one sub-folder will be count as 1). So I need to keep track of the sub-folder id, and initiate a new api call for each sub-folder, to get the number of files in each sub-folder (and potentially subsubfolder), while keeping track of the total number of files. (Hope I explained this clearly. Feel free to comment if anything is unclear.) { "item_collection":{"total_count":3, "entries":[ {"type":"folder","id":"1","sequence_id":"0","etag":"0"}, {"type":"folder","id":"2","sequence_id":"0","etag":"0"}, {"type":"file","id":"3","file_version"{"type":"file_version","id":"303835527128"},"sequence_id":"0","etag":"0",} ], ]} } This is what I have so far, but I'm not sure how to keep track of each sub-folder and iterate over them dynamically. Any help is appreciated! def total_file_count(client, folder_id): total_file_count = 0 subfolder_ids = [] folder = client.get_folder(folder_id=folder_id) item_count = folder['item_collection']['total_count'] subfolder = True if item_count &gt; 0: while subfolder: for i in folder…
has comment: http://stackoverflow.com/comment/87157514
has comment: http://stackoverflow.com/comment/87157349
tagged with: iteration
has title: how to iterate over sub directories dynamically
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87157311
tagged with: python
possible better answer: http://stackoverflow.com/a/50082059

pycharm
tags question: http://stackoverflow.com/q/50072289
tags question: http://stackoverflow.com/q/49930102
tags question: http://stackoverflow.com/q/49971489
tags question: http://stackoverflow.com/q/50060194
tag name: pycharm
tags question: http://stackoverflow.com/q/50052728
type: Tag
tags question: http://stackoverflow.com/q/50006229
tags question: http://stackoverflow.com/q/50022613
tags question: http://stackoverflow.com/q/49963666
tags question: http://stackoverflow.com/q/49983219
tags question: http://stackoverflow.com/q/49919115
tags question: http://stackoverflow.com/q/50018054
tags question: http://stackoverflow.com/q/49996592
tags question: http://stackoverflow.com/q/49958375
tags question: http://stackoverflow.com/q/49959335
tags question: http://stackoverflow.com/q/50018700
tags question: http://stackoverflow.com/q/50044230
tags question: http://stackoverflow.com/q/50022252
tags question: http://stackoverflow.com/q/50042704
tags question: http://stackoverflow.com/q/49949833

http://stackoverflow.com/comment/87009446
type: AnswerComment
has text: I added speed test for all the solutions. You can check it out in the question now! Thank you
comment on: http://stackoverflow.com/a/49979393
type: Comment
score: 0

http://stackoverflow.com/q/49971584
has body: I created a PyQt5 GUI using QtDesigner and converted it to Python. I was planning to update and display the value from the sensor reading from the Raspberry Pi. Since the GUI is in a loop, there is no way I can update data from outside that loop. Currently I used the code below where I use the QTimer widget that executes the function every given interval. Is this solution appropriate or not? What other methods are available to accomplish this task? from PyQt5 import QtCore, QtGui, QtWidgets from uimainwindow import Ui_MainWindow class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): numTest=0; def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setupUi(self) QtCore.QTimer.singleShot(1000, self.getSensorValue) def getSensorValue(self): print(self.numTest) self.numTest=self.numTest+1 QtCore.QTimer.singleShot(1000, self.getSensorValue) if __name__=="__main__": import sys app = QtWidgets.QApplication(sys.argv) w=MainWindow() w.show() sys.exit(app.exec_())
tagged with: qt
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: qt-designer
has comment: http://stackoverflow.com/comment/86991354
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49995024
accepted answer: http://stackoverflow.com/a/49995024
tagged with: pyqt5
duplicate of: http://stackoverflow.com/q/32362340
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86967864
linked to: http://stackoverflow.com/q/32362340
tagged with: python
has title: Updating PyQt5 GUI with Live Data

http://stackoverflow.com/comment/86987577
type: Comment
has text: neo4j library seems like a better option but there is no way to keep track of the progress in community version
type: QuestionComment
comment on: http://stackoverflow.com/q/49973713
score: 0

http://stackoverflow.com/comment/87128947
has text: Assuming your `compute` method works properly (no errors) when you install/upgrade your module, then it will apply to all records, old and new. If for some reason you install/upgrade your module and it fails before completion, then it will have the field stored in the database, but without values. In that case, the easiest way to recompute is to (carefully) drop that column (`ALTER TABLE res_partner DROP COLUMN is_customer_string`) and then re-upgrade your module.
comment on: http://stackoverflow.com/a/50056077
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87114713
type: Comment
has text: Ah, good point. I have modified my answer. Thanks for the catch.
type: AnswerComment
comment on: http://stackoverflow.com/a/50049044
score: 0

http://stackoverflow.com/comment/94474902
type: QuestionComment
has text: Possible duplicate of [pip: Reinstall a package even if it exists](https://stackoverflow.com/questions/53065940/pip-reinstall-a-package-even-if-it-exists)
score: 0
comment on: http://stackoverflow.com/q/49932926
type: Comment

http://stackoverflow.com/comment/86988437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49948580
score: 0
has text: @hisi thank you for the suggestion, but it did not work - still puts it in a separate directory.

http://stackoverflow.com/q/49968591
downvote count: 0
tagged with: mxnet
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50051962
has body: I am trying to use the graph structure of MXNet to speed up some calculations, and I am currently trying to mimic behavior that I have already implemented in PyTorch. However, I am confused on how to properly do this, be it with gluon.Trainer or some other method. To explain with an example, what I have working in PyTorch is the following (slightly modified to try to give the simplest example), and I want to translate this to MXNet. import torch.optim def unconstrained_fit(objective, data, pdf, init_pars, tolerance): init_pars.requires_grad = True optimizer = torch.optim.Adam([init_pars]) max_delta = None n_epochs = 10000 for _ in range(n_epochs): loss = objective(init_pars, data, pdf) optimizer.zero_grad() loss.backward() init_old = init_pars.data.clone() optimizer.step() max_delta = (init_pars.data - init_old).abs().max() if max_delta &lt; tolerance: break return init_pars As The Straight Dope points out in the PyTorch to MXNet cheatsheet, in MXNet one would usually be able to use a Trainer where one would use an optimizer in PyTorch. However, I don't understand how to properly initialize the Trainer in my case, as where one would usually do something along the lines of trainer = gluon.Trainer(net.collect_params(), 'adam') I assume that I will need to collect the parameters myself as I don't have a neural network that I want to use, but rather objective that I want to minimize. I am confused on how to do this properly, as the below is obviously not correct. import mxnet as mx from mxnet import gluon, autograd def unconstrained_fit(self, objective, data, pdf, init_pars, tolerance): ctx = mx.cpu() # How to properly do this chunck? init_pars = mx.gluon.Parameter('init_pars', shape=init_pars.shape, init=init_pars.asnumpy().all) init_pars.initialize(ctx=ctx) optimizer = mx.optimizer.Adam() trainer = gluon.Trainer([init_pars], optimizer) ### max_delta = None n_epochs = 10000 for _ in range(n_epochs): with autograd.record(): loss = objective(init_pars, data, pdf) loss.ba…
type: UnansweredQuestion
has title: Possible to Use MXNet gluon.Trainer without a Neural Network?
upvote count: 1
tagged with: python
score: 1
answer count: 1

http://stackoverflow.com/comment/87071815
type: QuestionComment
comment on: http://stackoverflow.com/q/50027429
score: 0
type: Comment
has text: @DavidZemens, sure, but I actually *need* the quote, unfortunately.

http://stackoverflow.com/comment/87063317
score: 0
has text: i want to go through a table or values and minus the difference between them to find out if there are any forms that have a larger number than 2 students than another form. But the user inputs the number of forms they want so the number of rows in the table is not fixed hence the reason why i am using a loop
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50022851

http://stackoverflow.com/a/50035543
has body: You can use pandas. import pandas as pd product = {'barcode': [123, 456], 'Name': ['Milk', 'Bread'], 'Price': ['2', '3.5'], 'weight': ['2', '0.6']} df = pd.DataFrame(product) for _, row in df.iterrows(): print(row['barcode'], row['Name'], row['Price']) 123 Milk 2 456 Bread 3.5 Edit: Using pure Python: product = {'barcode': [123, 456], 'Name': ['Milk', 'Bread'], 'Price': ['2', '3.5'], 'weight': ['2', '0.6']} for tup in zip(*list(product.values())[:-1]): print(*tup) 123 Milk 2 456 Bread 3.5
accepted answer of: http://stackoverflow.com/q/50035356
has comment: http://stackoverflow.com/comment/87087599
has comment: http://stackoverflow.com/comment/87089727
type: Answer
has comment: http://stackoverflow.com/comment/87089004
score: 0
answers question: http://stackoverflow.com/q/50035356
has comment: http://stackoverflow.com/comment/87088709
has comment: http://stackoverflow.com/comment/87088895
type: AcceptedAnswer

http://stackoverflow.com/a/50070463
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50070398
has body: It looks like you have an error in your import statement. Try from tensorflow.contrib.learn import DNNClassifier

http://stackoverflow.com/a/50380350
downvote count: 0
score: 6
has body: Your error seems to be coming from an invalid JSON format. I've found that online JSON lints are a quick and easy way to figure out what's going on with a JSON file: https://jsonlint.com/
answers question: http://stackoverflow.com/q/49993514
upvote count: 6
type: Answer

http://stackoverflow.com/q/49925471
tagged with: beautifulsoup
has body: I am required to change the xkcd project in the AtBS book to download the comics from a different website. Here is my script. #! python3 # getwebcomic.py - Downloads every single smbc comic. import requests, os, bs4 os.chdir('C:\\Users\\Bob\\Desktop\\') url = 'https://smbc-comics.com' # starting url os.makedirs('smbc', exist_ok=True) # store comics in ./smbc noAbuse=0 for noAbuse in range(0, 5): #while not url.endswith('#'): # Download the page. print('Downloading page %s...' % url) res = requests.get(url) res.raise_for_status() soup = bs4.BeautifulSoup(res.text, "html.parser") # Find the URL of the comic image. comicElem = soup.select('#cc-comicbody') print('I am finding it') print(comicElem) if comicElem == []: print('Could not find comic image.') else: print(comicElem[0].get('src')) print('I dont know why the .get is returning NONE!') print('It is there???') print('...and now it crashes') comicUrl = 'https//smbc-comics.com' + comicElem[0].get('src') print(comicUrl) # Download the image. print('Downloading image %s...' % (comicUrl)) res = requests.get(comicUrl) res.raise_for_status() # Save the image to ./smbc imageFile = open(os.path.join('smbc', os.path.basename(comicUrl)), 'wb') for chunk in res.iter_content(100000): imageFile.write(chunk) imageFile.close() # Get the Prev button's url. prevLink = soup.select('a[rel="prev"]')[0] url = 'http://smbc-comic.com' + prevLink.get('href') print('Done.') OutPut Downloading page https://smbc-comics.com... I am finding it [&lt;div id="cc-comicbody"&gt;&lt;img border="0" id="cc-comic" src="/comics/1524150658-20170419 (1).png" title="You can also just use an infinite quantity of compasses as on-off switches."/&gt;&lt;br/&gt;&lt;/div&gt;] None I dont know why the .get is returning NONE! It is there??? ...and now it crashes Traceback (most recent call last): File "C:\Users\Bob\PythonScripts\getwebcomic.py", line 31, in &lt;module> comicUrl = 'https//smbc-comics.com' + comicElem[0].get('src') TypeError: must be str, not NoneTyp…
type: UnansweredQuestion
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49925632
has comment: http://stackoverflow.com/comment/86867278
has title: My script is not retrieving an item for a list. I would appreciate it, if someone could help me understand why?
answer count: 1
has comment: http://stackoverflow.com/comment/86867718
type: Question

http://stackoverflow.com/q/49958375
tagged with: python
has comment: http://stackoverflow.com/comment/86971941
has body: In previous version 17 of pycharm everything was working fine with refactoring. I had upgraded to new version 18.1 and it appears they had disabled refactoring function. I had tried to see if enabled in settings to no avail.
has title: in pycharm 18.1 community refactoring is disabled. anybody knows if this is a bug or intentional
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87041470
answer count: 0
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/87031218
type: QuestionComment
comment on: http://stackoverflow.com/q/50007372
has text: "import pizza into make_pizza" makes no sense. `make_pizza` is a function defined *by* the module `pizza`. If `from pizza import make_pizza` fails, then you haven't configured your IDE properly to find the file `pizza.py`.
score: 1
type: Comment

http://stackoverflow.com/q/49988057
has title: python: couple of values to be called reciprocally?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86993522
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/1456373
has comment: http://stackoverflow.com/comment/86992461
linked to: http://stackoverflow.com/q/3318625
tagged with: python
has comment: http://stackoverflow.com/comment/86992651
tagged with: performance
has body: I have a set (potentially a very large number) of values generated at random, which I need to have quick access to and so from both sides. meaning: take a tuple: (133: 42) one way: getIDfromValue(42) &gt;&gt;&gt;133 the other: getValuefromID(133) &gt;&gt;&gt;42 the way i have been doing this so far is by making two dictionnaries and accessing one or the other depending the need. like: values = {42:133, ...} ids = {133:42, ...} values[42] &gt;&gt;&gt;133 ids[133] &gt;&gt;&gt;42 but that doesn't feel quite nor right nor efficient. how would one do this? (subsidiary question: is a argument of dictionary accessed directly in memory, or is the dictionary iterated?) thanks a lot
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/86992473
upvote count: 1
linked to: http://stackoverflow.com/q/1456373
downvote count: 1
has comment: http://stackoverflow.com/comment/86994268
favorite count: 0
type: Question

http://stackoverflow.com/q/49949078
has comment: http://stackoverflow.com/comment/86914713
tagged with: python
score: 0
has body: I have defined a list in R in following way: list(type_ = "angles", units = "radians", template = "none", modulo = "asis", zero = 0, rotation = "counter") I tried using the list() function of Python but it does not allow me to assign values to objects in the list. I also tried defining a dictionary but I can't define it the following way: {type_ = 'angles', units = 'radians', template = 'none', modulo = 'asis', zero = 0, rotation = 'counter'} Since it gives me syntax error and if I change the "=" sign as ':', it gives me an error saying "type_" variable not defined. How do I define such a list in Python?
has title: Python equivalent of list() function in R
has comment: http://stackoverflow.com/comment/86914758
type: Question
has comment: http://stackoverflow.com/comment/86914804
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/87236385
type: QuestionComment
comment on: http://stackoverflow.com/q/50054412
has text: @JCN if my solution helps, you could accept it as an answer or if you have further questions, just ask.
score: 0
type: Comment

http://stackoverflow.com/a/50066592
type: Answer
accepted answer of: http://stackoverflow.com/q/50066468
has body: The best way would be to just make the calls constant def sub_function_1( x, y, z): return x + y + z def sub_function_2( x, y, z ): return x + y def master_function( x, y, z, F ): return x * y + F(x,y,z) But you can have it be more dynamic if you like: def sub_function_1( x, y, z, **kwargs): return x + y + z def sub_function_2( x, y, **kwargs ): return x + y def master_function( x, y, z, F ): return x * y + F(**locals()) This works better in Python 3 potential as: def sub_function_1(*args): return args[0] + args[1] + args[2] def sub_function_2(*args): return args[0] + args[1] def master_function(*args, F): return args[0] * args[1] + F(*args) . . . &gt;&gt;&gt; master_function(1,2,3,F=sub_function_1) 8 &gt;&gt;&gt; master_function(1,2,3,F=sub_function_2) 5 &gt;&gt;&gt; master_function(1,2,F=sub_function_2) 5 &gt;&gt;&gt; master_function(1,2,F=sub_function_1) IndexError: tuple index out of range
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50066468
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87149934
has comment: http://stackoverflow.com/comment/87150142
score: 1

http://stackoverflow.com/comment/86986169
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49984765
type: QuestionComment
has text: @Jean-FrançoisFabre yes. It is corrected. Thanks

http://stackoverflow.com/comment/87008218
type: QuestionComment
has text: @AniketBote, Python Version - 3.5.2
score: 0
comment on: http://stackoverflow.com/q/49995624
type: Comment

http://stackoverflow.com/a/49974925
has body: LLVM built with Clang will produce libclang for you which, luckily, happens to have great Python bindings right out of the box. Get the latest LLVM and Clang from the releases page, the current stable one being LLVM 6.0.0. Make sure you have the appropriate Python development dependencies and build all of it. Then you can use Clang's Tooling to do all sorts of things to transform or modify your source code, here's a good page to get you started. I would suggest using Tooling instead of a hand rolled or generated parser especially for C++ due to its complexity. The library however handles it for you and allows you to transform or introspect the produced AST, letting you build on top of that. No one will generally provide a fully working solution to a complex problem like you've presented, you will have to do the bulk of the work yourself, but those resources are great if you want to get started.
answers question: http://stackoverflow.com/q/49974799
has comment: http://stackoverflow.com/comment/87018575
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86966056
score: 3
upvote count: 3

http://stackoverflow.com/comment/87090632
type: Comment
type: QuestionComment
has text: You need to convert the string (variable with brackets) into an int. 2 options: `int()` or `eval()`
score: 0
comment on: http://stackoverflow.com/q/50037192

http://stackoverflow.com/a/50045466
has body: Using zip Ex: import pandas as pd Sr1 = pd.Series([1,2,3,4], index = [0, 1, 2, 3]) Sr2 = pd.Series([3,4,-3,6], index = [1, 2, 3, 4]) sr3 = [sum(i) for i in zip(Sr1, Sr2)] print(sr3) Output: [4, 6, 0, 10]
upvote count: 1
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/87109315
type: Answer
answers question: http://stackoverflow.com/q/50045388
has comment: http://stackoverflow.com/comment/87108178

http://stackoverflow.com/a/50073915
answers question: http://stackoverflow.com/q/50073511
has body: errors= is from a python 3 open statement, you are clearly trying to run python 3 code on python 2. We can't say how you got the wrong version of scapy because you don't show how you installed it. Your options are to either install the python 2 version of scapy (probably the easiest) or to upgrade to python 3.
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50073511
downvote count: 0
type: Answer

http://stackoverflow.com/a/49934198
has body: You can also do regex match in pandas replace method py passing, regex=True df.replace("^\w.*$", "-999999", regex=True) From pandas replace function documentation: to_replace : str, regex, list, dict, Series, numeric, or None str or regex: str: string exactly matching to_replace will be replaced with value regex: regexs matching to_replace will be replaced with value list of str, regex, or numeric: First, if to_replace and value are both lists, they must be the same length. Second, if regex=True then all of the strings in both lists will be interpreted as regexs otherwise they will match directly. This doesn’t matter much for value since there are only a few possible substitution regexes you can use. str and regex rules apply as above.
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86883989
answers question: http://stackoverflow.com/q/49933425
downvote count: 1
has comment: http://stackoverflow.com/comment/86884688
upvote count: 0

http://stackoverflow.com/comment/87123224
comment on: http://stackoverflow.com/q/50053275
type: QuestionComment
has text: @LucaAmerio In SO nobody tries to insult you, asking you to show what you have tried does not imply that. Here we work with what they propose, it is better that you learn from your mistakes, that enriches the question and improves the answers. You can have n-years with a language but it does not imply that you are good with another. So we recommend that you show your intent when necessary, and read the links that we have shown you so you can better understand how SO works. It is easier for you to adapt to the community, for the community to adapt to you. :D
score: 1
type: Comment

http://stackoverflow.com/comment/87017076
has text: Thanks again! Yeah, that's exactly what I wanted!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49999493

http://stackoverflow.com/comment/87141800
has text: i not type as an answer and not read this article! And you try bad!
comment on: http://stackoverflow.com/q/50062414
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87149276
comment on: http://stackoverflow.com/q/50066335
type: Comment
type: QuestionComment
has text: Count and size also differ in that count ignores NaN values, where as size gets he size of the data including NaN.
score: 2

http://stackoverflow.com/comment/87273160
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50054412
score: 0
has text: @JL: Thank you for helping. How do I accept? Issue solved now! I am not sure about the root cause. I simply resumed where I left when I experienced the fatal error.

http://stackoverflow.com/comment/87086988
type: Comment
type: QuestionComment
has text: IMO, it should be: BAACAADAA, KACAADAA, KAUADAA, BAAUADAA. Hence 4 should be the output.
score: 0
comment on: http://stackoverflow.com/q/50034347

http://stackoverflow.com/a/49954675
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86950063
has comment: http://stackoverflow.com/comment/86949660
type: Answer
has comment: http://stackoverflow.com/comment/87337953
has comment: http://stackoverflow.com/comment/86925846
has comment: http://stackoverflow.com/comment/86957541
has comment: http://stackoverflow.com/comment/86949637
has comment: http://stackoverflow.com/comment/86943388
has comment: http://stackoverflow.com/comment/86943512
has comment: http://stackoverflow.com/comment/86950057
has comment: http://stackoverflow.com/comment/86943432
has body: Here is a sample script for what you want to do : what is did is added each candidate element to dictionary with key as candidate name+ a string all seeds . When looping through seeds i just append this key's value with +=1 import codecs import itertools import threading import csv candidates = [] seeds = [] tweets = [] global lock with codecs.open("d:\\untitled\\candidates.csv", encoding='utf8') as candFile: readCSV = csv.reader(candFile, delimiter=',') for lines in candFile: if lines.rstrip() != "" : candidates.append(lines.rstrip()) with codecs.open("d:\\untitled\\seeds.csv",encoding='utf8') as candFile: readCSV = csv.reader(candFile, delimiter=',') for lines in candFile: if lines.rstrip() != "" : seeds.append(lines.rstrip()) with codecs.open("d:\\untitled\\tweets.csv", encoding='utf8') as candFile: readCSV = csv.reader(candFile, delimiter=',') for lines in candFile: if lines.rstrip() != "" : tweets.append(lines.rstrip()) counts = {} def findMatch(listToWorkWith,tweet): for CS in listToWorkWith: if (CS[0] in tweet) and (CS[1] in tweet): try: counts[CS[0] + "+ All Seeds"] += 1 except: counts[CS[0] + "+ All Seeds"] = 1 listOFAugrs = list(itertools.product(candidates, seeds)) lock = threading.Lock() threads = [threading.Thread(target=findMatch, args=(listOFAugrs,x)) for x in tweets[0:10]] for t in threads: t.start() for t in threads: t.join() print(counts) This is the best we can do Here, Still the number are huge for each tweet we have an exponential amount of combinations to loop . So It is going to take some time. Output for 10 Tweets and all the combinations i.e tweets[0:10] {'jypetwic+ All Seeds': 2, 'twiceth+ All Seeds': 2, '5th+ All Seeds': 2, 'mini+ All Seeds': 2, 'albumltwhat+ All Seeds': 2, 'lovegtreleas+ All Seeds': 2, 'onlinemelon+ All Seeds': 2, 'twice+ All Seeds': 2, '트와이스+ All Seeds': 2, 'whatislov+ All Seeds': 2, 'u+ All Seeds': 16, 'voidtopaz+ All Seeds': 4, 'fandom+ All Seeds': 4, 'lolchoni+ All Seeds': 4, 'm+ All Seeds': 26, 'sinhuigang+ All Seeds…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87008893
has comment: http://stackoverflow.com/comment/86966437
accepted answer of: http://stackoverflow.com/q/49954452
has comment: http://stackoverflow.com/comment/86964901
has comment: http://stackoverflow.com/comment/86963556
answers question: http://stackoverflow.com/q/49954452
downvote count: 0

http://stackoverflow.com/q/49984503
score: 0
answer count: 0
has title: Exporting response.txt to csv file
has comment: http://stackoverflow.com/comment/86985465
type: UnansweredQuestion
has body: I'm trying to parse data that I receive from a curl request through python. The data is in the following format: {'meta': {'from': '1520812800', 'granularity': 'daily', 'to': '1523232000', 'total': 6380}, 'data': [{'count': 660, 'date': '2018-03-12'}, {'count': 894, 'date': '2018-03-13'}]} Originally, the data was returned as a string probably because I used response.text to retrieve the data. I converted the string into a dictionary using ast.literal_eval(response.text). I managed to parse the "data" key and ignore "meta". So currently, data = [{"date":"2018-03-12","count":660},{"date":"2018-03-13","count":894}]}`. I am trying to export the values for "date" and "count" to a csv file. In my code I have this: keys = data[0].keys() print("----------KEYS:---------") print keys #['date','count'] print("------------------------") with open('mycsv.csv','wb') as output_file: thewriter = csv.DictWriter(output_file, fieldnames = ['date','count']) thewriter.writeheader() thewriter.writerow(data) However, python does not like this and gives me an error: Traceback (most recent call last): File "curlparser.py", line 45, in &lt;module&gt; thewriter.writerow(data) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 152, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 148, in _dict_to_list + ", ".join([repr(x) for x in wrong_fields])) ValueError: dict contains fields not in fieldnames: {"date":"2018-03-12","count":660},{"date":"2018-03-13","count":894}
has comment: http://stackoverflow.com/comment/86987046
linked to: http://stackoverflow.com/q/26944274
type: Question
has comment: http://stackoverflow.com/comment/86986055
tagged with: python

http://stackoverflow.com/a/50475345
has body: "Suggestions" is irrelevant. What's happening is that it's trying to access a website to pull data from a file and that website is failing a certificate validation process on your machine. A lot of suggestions hint at updating your certificates, but so far, none of that seems to help me. From https://github.com/ros/rosdistro/issues/9721: "I got the same error and fixed it by updating and upgrading the system" Also: "To solve the error I installed 'ca-certificates' package sudo apt-get install ca-certificates Then it worked for me"
has comment: http://stackoverflow.com/comment/88018029
upvote count: 0
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50060718
answers question: http://stackoverflow.com/q/50060718
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/88059230

http://stackoverflow.com/a/49949931
accepted answer of: http://stackoverflow.com/q/49949814
has body: Here's a simple solution that iterates over the list backwards and increments a counter each time a number is repeated: last_num = None result = [] for num in reversed(x_list): if num != last_num: # if the number changed, reset the counter to 1 counter = 1 last_num = num else: # if the number is the same, increment the counter counter += 1 result.append(counter) # reverse the result result = list(reversed(result)) Result: [2, 1, 1, 3, 2, 1]
answers question: http://stackoverflow.com/q/49949814
has comment: http://stackoverflow.com/comment/86926079
type: Answer
score: 27
upvote count: 27
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49952854
has title: FlaskAdmin : triggering a function when clicking SAVE button
type: UnansweredQuestion
tagged with: flask-admin
tagged with: python
score: 0
has body: I'd like to add a bunch of program anytime the user is adding data to the model, after clicking the save button (or delete / edit). In my program, one column is filled by raw SQL queries. So before inserting the record in the model, I'd like to program to test the query to make sure the SQL language has been correctly imputed. here is the model: from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from flask_admin import Admin from flask_admin.contrib.sqla import ModelView db = SQLAlchemy(app) admin = Admin(app, template_mode='bootstrap3') class rGraphs(db.Model): __tablename__ = 'rGraphs' graph_id = db.Column(db.Integer, primary_key=True) Description = db.Column(db.Text, nullable=True) TABLE_SRC = db.Column(db.String(50), nullable=True) G_QUERY = db.Column(db.Text, nullable=True) colfilters = db.relationship('tblParamColFilter', backref='rGraphs', lazy='dynamic') coltransfos = db.relationship('tblParamColformat', backref='rGraphs', lazy='dynamic') graphlayouts = db.relationship('tblParamGraphLayout', backref='rGraphs', lazy='dynamic') def __repr__(self): return self.Description class rGraphsView(ModelView): form_columns = ['graph_id', 'Description', 'TABLE_SRC','G_QUERY'] admin.add_view(rGraphsView(rGraphs, db.session, name='Graphics list')) if __name__ == '__main__': #si modele doit etre mis a jour #manager.run() app.run(debug=True)
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49955506

http://stackoverflow.com/q/49944893
tagged with: python
score: 2
upvote count: 3
has body: I have 2 dataframes, one is sampled monthly, the other is sampled yearly. I want to multiply the values from a column in the monthly dataframe by the value from a column in the yearly dataframe if it is the same year. How can I do that? df1 = pd.DataFrame({'column1' : [1, 1, 1, 2, 2]}, index=['2018 - 01', '2018 - 02', '2018 - 03', '2019 - 01', '2019 - 02']) df1 column1 2018 - 01 1 2018 - 02 1 2018 - 03 1 2019 - 01 2 2019 - 02 2 df2 = pd.DataFrame({'columnX' : [2, 3]}, index=['2018', '2019']) df2 columnX 2018 2 2019 3 Expected result: column1 2018 - 01 2 2018 - 02 2 2018 - 03 2 2019 - 01 6 2019 - 02 6
has answer: http://stackoverflow.com/a/49945044
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49945689
has answer: http://stackoverflow.com/a/49945129
downvote count: 1
favorite count: 0
type: Question
has title: Pandas: multiplying a column by another if it is the same year
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86907005

http://stackoverflow.com/comment/86974544
has text: @Costantin The 0 doesn't denote the first element of the campaigns array; it's the first element of ad_accounts.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49969164

http://stackoverflow.com/a/49968649
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86960691
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49968484
answers question: http://stackoverflow.com/q/49968484
type: Answer
has body: The first part of your code is full of repetitions. Terrible to the eye! Please note that the first 102 lines of your program can be shortened a lot, by using a for loop and a list: print("\nPlease enter the 6 numbers you expected..") print("--------------------------------------------------------") numbers = [] for num in ('1st', '2nd', '3rd', '4th', '5th', '6th'): while True: n = int(input('{} expected number: '.format(num))) if n not in range(1,46): print('Please enter a number from 1 to 45.') elif n in numbers: print('Duplicate numbers. Please re-enter.') else: numbers.append(n) break For the next part, first I suggest you to separate the 6 winners from the additional number, in this way: import random *winners, additional_winner = random.sample(range(1,46), 7) print("Lotto number for this week : {}, {}, {}, {}, {}, {}, and {}".format(*winners, additional_winner)) print("Your numbers are {}, {}, {}, {}, {}, {}".format(*numbers)) The next part, in your code had a problem because with if 'a, b, c, d, e, f' in winners you would check if the string 'a, b, c, d, e, f' is contained in winners which is a list of integers, so that is always false. Instead, using sets to check for intersection of played numbers with winning numbers, leads to a simpler code: intersection = set(numbers) & set(winners) if len(intersection) == 6: print("\nCongratulations! You are the 1st!") elif len(intersection) == 5 and additional_winner in numbers: print("\nCongratulations! You are 2nd!") elif len(intersection) == 5: print("\nCongratulations! You are 3rd!") elif len(intersection) == 4: print("\nCongratulations! You are 4th!") elif len(intersection) == 3: print("\nCongratulations! You are 5th!") else: print("\nNext time...!") Program output: Please enter the 6 numbers you expected.. 1st expected number: 1 2nd expected number: 2 3rd expected number: 3 4th expected number: 4 5th expected number: 5 6th expected number: 6 Lotto number for this week : 1, 4, 2, 9, 10, 3, and 6 Your numbers are 1…

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/49975264
tags question: http://stackoverflow.com/q/50052421
tags question: http://stackoverflow.com/q/50017528
tags question: http://stackoverflow.com/q/49949146
tags question: http://stackoverflow.com/q/49957263
tags question: http://stackoverflow.com/q/50046643
type: Tag
tags question: http://stackoverflow.com/q/50011028
tags question: http://stackoverflow.com/q/49959545
tags question: http://stackoverflow.com/q/49922118
tags question: http://stackoverflow.com/q/50032941
tags question: http://stackoverflow.com/q/49962170
tag name: r
tags question: http://stackoverflow.com/q/49927107
tags question: http://stackoverflow.com/q/49953620

http://stackoverflow.com/comment/86969184
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49976576
has text: And why would you want to rewrite perfectly good code into a one-liner that's more difficult to read?
type: Comment

http://stackoverflow.com/q/50037319
type: AnsweredQuestion
has title: pandas read_table with regex delimiter, since negative numbers don't have intervening whitespace
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50037426
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50037426
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87091830
upvote count: 2
has comment: http://stackoverflow.com/comment/87093983
tagged with: python
has body: I am trying to read a space separated table (sample below) into a pandas dataframe using the read_table function. 1 0.00000E+00-7.52896E-04 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 1.00247E-01 0.00000E+00 9 2.57945E+00-9.98377E-04 0.00000E+00 1.80923E+02 0.00000E+00 0.00000E+00 1.08995E+03 0.00000E+00 0.00000E+00 1.00795E+01 1.00002E-01 0.00000E+00 18 2.37285E+00-2.20000E-01 0.00000E+00 1.81079E+02-5.53001E+00 0.00000E+00 1.30827E+03 2.01207E+03 0.00000E+00 9.87285E+00 8.64615E-01 0.00000E+00 The problem, however is that the negative values appear without a delimeter e.g. 1.81079E+02-5.53001E+00 The following two options do not generate the desired output: t=pds.read_table(filepath, sep='\s+|\d\-\d', engine='python') t=pds.read_table(filepath, sep='(\s+|\d\-\d)', engine='python') Any help is greatly appreciated!
tagged with: regex
tagged with: number-formatting
has comment: http://stackoverflow.com/comment/87090921
score: 2

http://stackoverflow.com/q/50043330
has title: Compare json in s3 bucket to same json loaded to table in dynamodb with python
tagged with: amazon-dynamodb
has comment: http://stackoverflow.com/comment/87109143
has comment: http://stackoverflow.com/comment/87108552
linked to: http://stackoverflow.com/q/12186993
score: 0
has comment: http://stackoverflow.com/comment/87108481
has body: When I am comparing 2 json files in different buckets I used etag in order to compare. I loaded the json file into table in dynamodb and now I want to compare that the data is same. Do I have the option to do it? This is what I did for comparing the 2 files between different buckets. conn = client('s3') # again assumes boto.cfg setup, assume AWS S3 for key2 in conn.list_objects(Bucket='freedom-meital')['Contents']: for key in conn.list_objects(Bucket='freedom-meital3')['Contents']: if key['Key'] == key2['Key']: if key['ETag'] != key2['ETag']: print(key['Key']+" is not equal between the 2 buckets") else: print(key['Key']+" is equal between the 2 buckets")
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/87111381
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/87107607
has comment: http://stackoverflow.com/comment/87104778
has comment: http://stackoverflow.com/comment/87103799
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50033408
answers question: http://stackoverflow.com/q/50033119
has body: based on Ajax1234 answer, but more readable: import itertools from collections import ChainMap sum_of_qty = [ list(b) for _, b in itertools.groupby(d, key=lambda x: [x[k] for k in x if k != 'qty']) ] for i, item in enumerate(sum_of_qty): sum_of_qty[i] = dict(ChainMap(*item)) sum_of_qty[i]['qty'] = sum(map(lambda x: x['qty'], item))
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49945427
type: Question
possible better answer: http://stackoverflow.com/a/49945623
tagged with: python
has answer: http://stackoverflow.com/a/49945623
has title: python, selenium - python dont execute the else - statement
tagged with: selenium-webdriver
has body: I need the the search Result from any search term from Google. I wrote an if-statement where it looks first if the searchResult is true, then print it. Otherwise print 0. I know it says that it can't find the element, but i want to say to my script if he cant find the element, type 0. So as the else statement. Code: elif inputOfUser == '': if chrome.find_element_by_xpath('//*[@id="resultStats"]') == True: table.update_cell(row, 5, chrome.find_element_by_xpath('//*[@id="resultStats"]').text[:-27]) else: table.update_cell(row, 5, str(0)) Error: Traceback (most recent call last): File "c:/Users/TechDynasty/Desktop/Programmieren/Allintitle/Test.py", line 39, in &lt;module&gt; print(chrome.find_element_by_xpath('//*[@id="resultStats"]')) File "C:\Users\TechDynasty\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 385, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Users\TechDynasty\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element 'value': value})['value'] File "C:\Users\TechDynasty\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\Users\TechDynasty\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="resultStats"]"} (Session info: chrome=65.0.3325.181) (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64)
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: selenium
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/49945876
has answer: http://stackoverflow.com/a/49945876

http://stackoverflow.com/q/50006447
has title: PuLP programming output
has body: I am working with a collaborator on a certain optimization project involving linear programming. We both use Coin-OR branch-and-cut solver to solve the problem. I construct the .LP file using Python-based PuLP package. I am not entirely sure how the collaborator creates their .LP file (definitely not using Python), but essentially, we have two different systems generating .LP files for the exact same problem - i.e. the objective function, variables, constraints are exactly the same. I typically solve my problem within Python (myProblm.solve()), but I have also been generating a .LP file and calling a CBC solver from the command line to solve this file (problem). Next, I compare the output I get from my system (either Python or command-line), to that my collaborator obtains. [Please note that the output of the problem on my side is exactly the same whether solved in PuLP or on command-line.] The values of the objective function match well between us, but the other details do not exactly match. For example, if we were to solve this Whiskas blending problem, the total cost of ingredients would be exactly same, but the ratios of ingredients differ. Any idea why that would be? I manually compared our .LP files and noticed a few differences. For starters, the sequence of constraints and variables is different. In other words, if there are 5 constraints, my file lists them as C1,C2,C5,C4,C3, whereas the same constraints will be listed as C1,C2,C3,C4,C5. Also, my Python code rounds all numbers to 10's place, while his system rounds them to 1's place. Hence, the coefficients of some of the variables have slightly different values. Do these differences play a role in the exact output of the solver? Also, the next question by extension is: What should we do to get the exact same output when solving a linear programming optimization problem? Which factors influence the solution of LP problems? Do factors like the structure of an .LP file play a role? Will I get the exact same o…
has answer: http://stackoverflow.com/a/50032547
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/136503906
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/136503583
tagged with: pulp
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/136503771
score: 1
answer count: 1
tagged with: coin-or-cbc

http://stackoverflow.com/a/49997827
answers question: http://stackoverflow.com/q/49997558
type: AcceptedAnswer
downvote count: 0
has body: Instead of d['id','year'], use the tuple (d['id'], d['year']) as your key.
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49997558
score: 5

http://stackoverflow.com/comment/86901593
comment on: http://stackoverflow.com/a/49938308
score: 0
type: Comment
type: AnswerComment
has text: `a` should be a Variable.. because will be updated by backword

http://stackoverflow.com/comment/129313368
score: 0
has text: I have a similar case and for me this doesn't work as `both_id` is not a field within the `Task` model (if I understood the question correctly). The provided solution returns `'Meta.fields' must not contain non-model field names: both_id`
comment on: http://stackoverflow.com/a/49973625
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50043318
has body: it should've been screen_height with an underscore. your code has screen.height instead
score: 4
downvote count: 0
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50043285

http://stackoverflow.com/q/49997258
score: 0
tagged with: abstract-class
tagged with: metaclass
type: Question
has body: I am trying to implement abstract classes using python's abc module as below import abc class AbstractBaseClass(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def first_method(self): pass class LearnAbstractBaseClass(object): __metaclass__ = AbstractBaseClass def first_method(self): print "Hello" obj = LearnAbstractBaseClass() What's wrong with the above code and why am I getting the below error &gt;&gt;&gt; python AbstractBaseClasses.py C:\Python27\lib\abc.pyc Traceback (most recent call last): File "AbstractBaseClasses.py", line 41, in &lt;module&gt; class LearnAbstractBaseClass(object): TypeError: Error when calling the metaclass bases object() takes no parameters Note: In the above code, I am using __metaclass__ attribute for LearnAbstractBaseClass for using the parent class AbstractBaseClass as metaclass, but when I inherit the child class LearnAbstractBaseClass from parent class AbstractBaseClass, it works fine Works fine class LearnAbstractBaseClass(AbstractBaseClass): def first_method(self): passs Not working class LearnAbstractBaseClass(object): __metaclass__ = AbstractBaseClass def first_method(self): passs So what does the error mean exactly?
has comment: http://stackoverflow.com/comment/87010855
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87011060
has title: TypeError: Error when calling the metaclass bases object() takes no parameters
tagged with: python
has comment: http://stackoverflow.com/comment/87011136

http://stackoverflow.com/q/50013378
answer count: 2
has body: With the following code, from bokeh.plotting import figure, show, output_file from bokeh.sampledata.iris import flowers colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) output_file("iris.html", title="iris.py example") show(p) I can make a circle plot where I color the species: But what I want to do is to color all the point based on range of value in petal_length. I tried this code but fail: from bokeh.models import LinearColorMapper exp_cmap = LinearColorMapper(palette='Viridis256', low = min(flowers["petal_length"]), high = max(flowers["petal_length"])) p.circle(flowers["petal_length"], flowers["petal_width"], fill_color = {'field' : flowers["petal_lengh"], 'transform' : exp_cmap}) output_file("iris.html", title="iris.py example") show(p) And also in the final desired plot, how can I put the color bar that show the range of values and the assigned value. Something like this: I'm using Python 2.7.13.
has title: How to draw a circle plot the LinearColorMapper using python Bokeh
upvote count: 3
has answer: http://stackoverflow.com/a/50048081
downvote count: 0
possible better answer: http://stackoverflow.com/a/50050784
tagged with: bokeh
has answer: http://stackoverflow.com/a/50050784
tagged with: plot
favorite count: 0
type: Question
score: 3
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50048081

http://stackoverflow.com/q/50012126
downvote count: 0
tagged with: .net
has comment: http://stackoverflow.com/comment/87605172
has answer: http://stackoverflow.com/a/50331108
tagged with: image-processing
upvote count: 7
possible better answer: http://stackoverflow.com/a/50265949
score: 7
has answer: http://stackoverflow.com/a/50348500
favorite count: 0
tagged with: c#
has comment: http://stackoverflow.com/comment/87605246
type: Question
accepted answer: http://stackoverflow.com/a/50348500
tagged with: python
has title: OpenCV MatchTemplate in C# is too slow compared to Python
has body: I've programmed a solution in Python which worked great, but required several libraries to install and a lot of burocratic setup to work. I've decided to build it with a GUI in C# on Visual Studio Community 2017 but in the first successful function the result was way slower than in Python. Which IMO it should actually be faster. The code essentially is just doing a needle in a haystack image search, by getting all images from a folder and testing each needle (total 60 images) in a haystack, in python I return the string, but in C# I'm only printing. My code in Python is the following: def getImages(tela): retorno = [] folder = 'Images' img_rgb = cv2.imread(tela) for filename in os.listdir(folder): template = cv2.imread(os.path.join(folder,filename)) w, h = template.shape[:-1] res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED) threshold = .96 loc = np.where(res &gt;= threshold) if loc[0]&gt;0: retorno.append(filename[0]+filename[1].lower()) if len(retorno)&gt; 1: return retorno and in C#: Debug.WriteLine(ofd.FileName); Image&lt;Bgr, byte&gt; source = new Image&lt;Bgr, byte&gt;(ofd.FileName); string filepath = Directory.GetCurrentDirectory().ToString()+"\\Images"; DirectoryInfo d = new DirectoryInfo(filepath); var files = d.GetFiles(); foreach (var fname in files){ Image&lt;Bgr, byte&gt; template = new Image&lt;Bgr, byte&gt;(fname.FullName); Image&lt;Gray, float&gt; result = source.MatchTemplate(template, Emgu.CV.CvEnum.TemplateMatchingType.CcoeffNormed); double[] minValues, maxValues; Point[] minLocations, maxLocations; result.MinMax(out minValues, out maxValues, out minLocations, out maxLocations); if (maxValues[0] &gt; 0.96) { Debug.WriteLine(fname); } } I didn't measure the time elapsed between each one, but I can say the result in C# takes about 3 seconds and in Python about 100ms. There is room for optimization, if anyone would like to suggest any improvements, they are welcome.
has answer: http://stackoverflow.com/a/50265949
type: AnsweredQuestion
tagged with: image-recognition
answer count: 3

http://stackoverflow.com/comment/87093496
comment on: http://stackoverflow.com/q/50029546
type: Comment
has text: Did you try the code without the two lines setting height and width `ret = cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 45)` ?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/126470112
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59764707
has text: On bare ubuntu xerox has a dependency on xclip, pyperclip seems to run standalone.

http://stackoverflow.com/a/49994501
score: 3
has comment: http://stackoverflow.com/comment/93037421
has comment: http://stackoverflow.com/comment/95320945
has comment: http://stackoverflow.com/comment/98444669
downvote count: 1
answers question: http://stackoverflow.com/q/49918479
has comment: http://stackoverflow.com/comment/87008634
type: Answer
has body: Can you please try with below steps conda create -n pytorch_env python=3.5 source activate pytorch_env conda install -c soumith pytorch python &gt; import torch You can even find pytorch after you execute command conda list.
upvote count: 4

http://stackoverflow.com/q/49981093
answer count: 1
tagged with: javascript
tagged with: python
has body: In Odoo (v. 10) pivot report values false appear as "Undefined" while values true appear as "true". I found in odoo source the line if (value === false) return _t("Undefined"); What might be the logic behind that (to make "false" look "Undefined") while leaving "true" as "true"?
score: 0
tagged with: odoo
has answer: http://stackoverflow.com/a/49982999
has title: Odoo pivot report false values are translated to "Undefined"
type: Question
tagged with: report
tagged with: pivot
type: UnansweredQuestion

http://stackoverflow.com/q/50064719
score: 1
has answer: http://stackoverflow.com/a/50064934
downvote count: 0
has comment: http://stackoverflow.com/comment/87146231
has body: I have a pandas series, for example: x = pandas.Series([-1,20,"test"]). Now I would like to test if -1 is contained in x without looping over the whole series. I could transform the whole series to string and then test if "-1" in x but sometimes I have -1.0 and sometime -1 and so on, so this is not a good choice. Is there another possibility to approach this?
upvote count: 1
has title: Testing if value is contained in Pandas Series with mixed types
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50064934
has answer: http://stackoverflow.com/a/50064848
tagged with: python
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50064816
possible better answer: http://stackoverflow.com/a/50064816

http://stackoverflow.com/comment/86924411
score: 0
type: QuestionComment
has text: Martin's right but if that was the problem your script should have imported only the last row of the file, isn't it ?
type: Comment
comment on: http://stackoverflow.com/q/49937810

http://stackoverflow.com/comment/87010354
score: 0
comment on: http://stackoverflow.com/q/49996216
type: Comment
type: QuestionComment
has text: @abarnert Thank you for commenting in so much detail - it is very helpful! I am starting from a clean slate so it's excellent to understand what options are available. I now have a list of possible solutions which I can look into further and understand. Thank you! P.s. If you post the comments as an answer I will accept it.

http://stackoverflow.com/q/49952712
type: Question
has comment: http://stackoverflow.com/comment/86922046
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
tagged with: large-data
tagged with: keras
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86922019
upvote count: 1
answer count: 1
has body: I am using keras for my image classification , here is my code: train_generator = datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode="categorical") validation_generator = datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode="categorical") Found 70000 images belonging to 15 classes. Found 6000 images belonging to 15 classes. Then i am using this data to fit into my model here is my code: model.fit_generator( train_generator, steps_per_epoch=train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=validation_samples// batch_size,) I have used various batch size, but result are insufficient , my model is too slow to train it takes hours to train and also it crashes sometime , can someone please help to train model when we have large data set , how to do that efficiently ? Model Code: # a simple stack of 3 convolution layers with a ReLU activation and followed by max-pooling layers. model = Sequential() model.add(Convolution2D(32, (3, 3), input_shape=(img_width, img_height,3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(15)) model.add(Activation('sigmoid'))
has title: Deal with large data set for image classification
has answer: http://stackoverflow.com/a/49952780
favorite count: 0

http://stackoverflow.com/q/50005459
type: Question
has comment: http://stackoverflow.com/comment/87027434
accepted answer: http://stackoverflow.com/a/50005609
tagged with: python
has body: everyone, I have a question about python dict, currently, I want to store some value with 2 layers (parent), something like below this is the original David= {'Date of birth': '12111922','Age': 7, 'Height ': '1.7m'} but I want to add one more layer(parent on top) : Character = {David {'Date of birth': '12111922','Age': 7, 'Height ': '1.7m'}}
has comment: http://stackoverflow.com/comment/87028301
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50005609
has comment: http://stackoverflow.com/comment/87027444
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Python: two layer of Dictionary
favorite count: 0

http://stackoverflow.com/a/72440355
has body: You can use minmax_scale to normalize a column from sklearn.preprocessing import minmax_scale df['size'] = minmax_scale(df['total'])
answers question: http://stackoverflow.com/q/50027959
type: Answer
score: 0

http://stackoverflow.com/comment/87224700
type: QuestionComment
comment on: http://stackoverflow.com/q/50056859
has text: Are you sure that something is indeed wrong and it's not a matter of efficiency? Cause printing *2G* on screen is anything but smart, (and would probably take forever.)
score: 0
type: Comment

http://stackoverflow.com/comment/87139203
has text: Assuming that zipfile gets into current directory as mentioned by `wget` command, just specify `glove.6B.zip` as path -- I think it should work
type: Comment
comment on: http://stackoverflow.com/a/50060301
score: 0
type: AnswerComment

http://stackoverflow.com/q/49929581
tagged with: python
type: Question
tagged with: video
score: 0
has title: Write video with opencv with fourcc H264: Cannot load libcuda.so.1
answer count: 0
type: UnansweredQuestion
has body: I'm trying to create a video using opencv-python. I have to use H.264 codec for my video so I have the following lines: import cv2 width = ... height = ... name = ... fourcc = cv2.VideoWriter_fourcc(*'H264') self.video = cv2.VideoWriter(name, fourcc, 30, (width, height)) When I run the code I get the following error: [h264_nvenc @ 0x562490d62d80] Cannot load libcuda.so.1 Could not open codec 'h264_nvenc': Unspecified error As I see in the error, I need libcuda.so.1 library which comes with nvidia driver afaik, but my laptop has no dedicated graphic card. Is it possible to write a video using H.264 using my laptop? If yes, please advice how. Thank you!
tagged with: h.264
has comment: http://stackoverflow.com/comment/86877596
tagged with: opencv
has comment: http://stackoverflow.com/comment/86877632
has comment: http://stackoverflow.com/comment/86886661

http://stackoverflow.com/comment/86947817
has text: @soon I just did (by simply copying `class partial` into my code) and it's ever worse than "roughly equivalent to" one: `17.7 ms ± 595 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)`
type: Comment
comment on: http://stackoverflow.com/q/49965774
score: 0
type: QuestionComment

http://stackoverflow.com/a/49971468
type: Answer
answers question: http://stackoverflow.com/q/49971417
has body: Your "wanted" output is 3d not 2d - this is how to get a 2d output: Create file: data = """7ee0c0d15fe800000f80202278e0c0f1 00007ee0c0d15fc000000f802022c0f1""" fn = "someFile.txt" with open(fn,"w") as f: f.write(data) Read file: fn = "someFile.txt" k = [] with open(fn,"r") as f: for line in f: k.append(list(line.rstrip("\n"))) # convert each line into list, strip \n print(k) # these are all strings # convert to int d = [ [int('0x'+i,16) for i in x] for x in k] print(d) # 2d list Output: [['7', 'e', 'e', '0', 'c', '0', 'd', '1', '5', 'f', 'e', '8', '0', '0', '0', '0', '0', 'f', '8', '0', '2', '0', '2', '2', '7', '8', 'e', '0', 'c', '0', 'f', '1'], ['0', '0', '0', '0', '7', 'e', 'e', '0', 'c', '0', 'd', '1', '5', 'f', 'c', '0', '0', '0', '0', '0', '0', 'f', '8', '0', '2', '0', '2', '2', 'c', '0', 'f', '1']] [[7, 14, 14, 0, 12, 0, 13, 1, 5, 15, 14, 8, 0, 0, 0, 0, 0, 15, 8, 0, 2, 0, 2, 2, 7, 8, 14, 0, 12, 0, 15, 1], [0, 0, 0, 0, 7, 14, 14, 0, 12, 0, 13, 1, 5, 15, 12, 0, 0, 0, 0, 0, 0, 15, 8, 0, 2, 0, 2, 2, 12, 0, 15, 1]] To get to your output, simply wrap the integer conversion into a 1 - elem list: # convert to 3d int d3 = [ [ [int('0x'+i,16)] for i in x] for x in k] print(d3) # converted to int Output: [[[7], [14], [14], [0], [12], [0], [13], [1], [5], [15], [14], [8], [0], [0], [0], [0], [0], [15], [8], [0], [2], [0], [2], [2], [7], [8], [14], [0], [12], [0], [15], [1]], [[0], [0], [0], [0], [7], [14], [14], [0], [12], [0], [13], [1], [5], [15], [12], [0], [0], [0], [0], [0], [0], [15], [8], [0], [2], [0], [2], [2], [12], [0], [15], [1]]] To get be left with "hex-strings" in your output, don't do integer conversion: # convert to 3d int d3h = [ [ [i] for i in x] for x in k] print(d3h) # converted to int Output: [[['7'], ['e'], ['e'], ['0'], ['c'], ['0'], ['d'], ['1'], ['5'], ['f'], ['e'], ['8'], ['0'], ['0'], ['0'], ['0'], ['0'], ['f'], ['8'], ['0'], ['2'], ['0'], ['2'], ['2'], ['7'], ['8'], ['e'], ['0'], ['c'], ['0'], ['f'], ['1']], [['0'], ['0'], ['0'], ['0'], ['7']…
score: 2
downvote count: 1
upvote count: 3

http://stackoverflow.com/comment/87062090
comment on: http://stackoverflow.com/q/50022814
type: Comment
type: QuestionComment
score: 0
has text: Have you checked https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable?

http://stackoverflow.com/comment/87079521
score: 0
type: Comment
has text: Yep, this is what I wanted, no looping, would you be kind enough to explain ** syntax is for.
type: AnswerComment
comment on: http://stackoverflow.com/a/50031666

http://stackoverflow.com/a/50064515
has comment: http://stackoverflow.com/comment/87146192
upvote count: 0
downvote count: 1
score: -1
accepted answer of: http://stackoverflow.com/q/50064456
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50064456
has body: Like you mentioned you will get malformed string error (ValueError) if you get input like ast.literal_eval('c1'). You will also get SyntaxError if you do something like ast.literal_eval('1c'). You will want get the input data and then pass it to literal_eval. You can then catch both of these exceptions, and then return your 'Not Possible'. from ast import literal_eval def distance_from_zero(x): try: return abs(literal_eval(x)) except (SyntaxError, ValueError): return 'Not possible' x = raw_input("Please try to enter a number ") print distance_from_zero(x)

http://stackoverflow.com/comment/87155358
type: QuestionComment
has text: Filter it in what sense? You question is unclear.
comment on: http://stackoverflow.com/q/50069430
score: 0
type: Comment

http://stackoverflow.com/a/50000627
has comment: http://stackoverflow.com/comment/87038150
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49999875
has body: in your views add this vote_from_user_ids = Vote.objects.values('from_user__id') now exclude vote objects from User by using users = User.objects.exclude(id__in = vote_from_user_ids) now the fromusers of vote model are excluded from User model

http://stackoverflow.com/comment/86961823
has text: What happens if you run `python -m pip --version`?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49972908

http://stackoverflow.com/q/49944027
has body: In Python, I have a list of tuples, that is: list_tup = [('123', 'A'), ('123', 'B')] If I want to find out if there is, for example, the tuple ('123', 'A'), I just write: ('123', 'A') in list_tup =&gt; True But what if I'd like to know if there's anything different from ('123', 'B') in that list of tuples, where the only different element is the second one ('B')? Is it possible? For example, I want to know if in list_tup there is something different from ('123', 'B').
has title: Difference between tuples in list of tuples
tagged with: python
has comment: http://stackoverflow.com/comment/86904446
has answer: http://stackoverflow.com/a/49944183
score: 2
upvote count: 2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49944183
favorite count: 0
type: Question
tagged with: tuples
has comment: http://stackoverflow.com/comment/86904335
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86904324

http://stackoverflow.com/comment/87002514
comment on: http://stackoverflow.com/q/49993066
type: Comment
type: QuestionComment
has text: Save that result to a dictionary, let's say `dct`, then use `dct['temp']`
score: 0

http://stackoverflow.com/a/50016305
upvote count: 1
answers question: http://stackoverflow.com/q/50011155
score: 1
has comment: http://stackoverflow.com/comment/87057420
has comment: http://stackoverflow.com/comment/87057984
type: Answer
has comment: http://stackoverflow.com/comment/87057016
has body: Alternatively to Desperado's answer you can use css selectors which are much simpler but more than enough for your use case: $ scrapy shell "https://shop.app4health.it/" In [1]: response.css('.level0 .level-top::attr(href)').extract() Out[1]: ['https://shop.app4health.it/sonno', 'https://shop.app4health.it/monitoraggio-e-diagnostica', 'https://shop.app4health.it/terapia', 'https://shop.app4health.it/integratori-alimentari', 'https://shop.app4health.it/fitness', 'https://shop.app4health.it/benessere', 'https://shop.app4health.it/ausili', 'https://shop.app4health.it/prodotti-in-offerta', 'https://shop.app4health.it/kit-regalo'] scrapy shell command is perfect for debugging issues like this.
accepted answer of: http://stackoverflow.com/q/50011155
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87054404
score: 0
comment on: http://stackoverflow.com/a/50018810
has text: I am doing this for OpenCV
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87158936
type: Comment
comment on: http://stackoverflow.com/a/50063211
has text: Awesome code, but wouldn't it be much simpler/better to use [pycryptodome](https://pycryptodome.readthedocs.io/en/latest/) or [cryptography](https://cryptography.io/en/latest/)? Or is the OP not permitted to use third party libs?
type: AnswerComment
score: 1

http://stackoverflow.com/a/50066291
has body: Something like this? for i in set_dict: x = set(diff_list).intersection(set_dict[i]) if x: diff = x
downvote count: 0
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50066245
answers question: http://stackoverflow.com/q/50066245
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49938766
has title: Filling in login forms in Instagram using selenium and webdriver (chrome) python OSX
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/86893248
has body: I want to log in to instagram using selenium, but I can't seem to enter values into the fields. Here's my script: #go to this address browser.get('https://www.instagram.com') #sleep for 1 seconds sleep(1) #find the 'login' button on homepage login_elem = browser.find_element_by_xpath( '//*[@id="react-root"]/section/main/article/div[2]/div[2]/p/a') #navigate to login page login_elem.click() Having trouble from here onwards: #locate the username field within the form unform = browser.find_element_by_xpath( '//*[@id="f3b8e6724a27994"]') #clear the field textunform.clear() #enter 'test' into field unform.send_keys('test')
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51371916
tagged with: selenium
has answer: http://stackoverflow.com/a/55302160
has answer: http://stackoverflow.com/a/68771543
has answer: http://stackoverflow.com/a/57513626
has answer: http://stackoverflow.com/a/49940401
score: 4
downvote count: 1
has answer: http://stackoverflow.com/a/65166565
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/57329972
answer count: 9
tagged with: instagram
upvote count: 5
has answer: http://stackoverflow.com/a/49938830
has answer: http://stackoverflow.com/a/49939562
tagged with: python

http://stackoverflow.com/comment/87150151
type: QuestionComment
has text: Don't expect any speed up when using an array and `vectorize`. If anything it might be slower than applying the same `regex` test to elements of a list.
type: Comment
comment on: http://stackoverflow.com/q/50064422
score: 0

http://stackoverflow.com/q/50011890
tagged with: numpy
score: 0
answer count: 0
has title: If I have a function of two variables, how do I efficiently create a two dimensional array out of the functional values in python?
type: UnansweredQuestion
tagged with: arrays
type: Question
linked to: http://stackoverflow.com/q/45496096
has body: Suppose I have a function: def func(x, y): return x*y and I am given a list of x and y x = numpy.array([0, 1, 2]) y = numpy.array([1, 2]) I want two dimensional array of element wise product of x and y size size(x) by size(y), in this case 3 by 2, such that the output be: [[0, 0], [1, 2], [2, 4]] An easy way is to do the for loop output = [] for i in range(len(x)): output.append(func(x[i], y)) But this process is not very efficient for large array size. Is there any clever way to achieve the same using numpy array functions? I am looking for a method that works not just on this particular function, but on arbitrary function of two variables.
tagged with: python
has comment: http://stackoverflow.com/comment/87040448
duplicate of: http://stackoverflow.com/q/45496096
has comment: http://stackoverflow.com/comment/87040309
has comment: http://stackoverflow.com/comment/87040280

http://stackoverflow.com/comment/86907466
type: Comment
has text: The use of the `label` argument can be used to create legends, but is also used to pass the label of each node to the `onpick` function, which is a bit cleaner than accessing `pos` from within the function itself. I'm not sure why `label=[*pos]` produces a syntax error for you. You could also try `label=list(pos.keys())` instead. I didn't notice the second part of your question. I will edit my answer shortly to address this.
type: AnswerComment
comment on: http://stackoverflow.com/a/49926398
score: 0

http://stackoverflow.com/comment/87139900
score: 0
comment on: http://stackoverflow.com/q/50061088
type: QuestionComment
has text: Thanks! I tried doing that but the `feedback.txt` in the `writer` dir doesn't get modified :(
type: Comment

http://stackoverflow.com/comment/87136596
type: QuestionComment
has text: A csv file is a text files containing data as comma separated value. It is not a spreadsheet and has no notion of queries
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50060079

http://stackoverflow.com/a/50039984
has body: I've created a little generator which should do what you need. I've opted for the generator instead of iterating over the features directly, because it's more convenient if you'd like to inspect the arrays. If you want, you can still iterate over the generator. import gdal import ogr, osr # converts coordinates to index def bbox2ix(bbox,gt): xo = int(round((bbox[0] - gt[0])/gt[1])) yo = int(round((gt[3] - bbox[3])/gt[1])) xd = int(round((bbox[1] - bbox[0])/gt[1])) yd = int(round((bbox[3] - bbox[2])/gt[1])) return(xo,yo,xd,yd) def rasclip(ras,shp): ds = gdal.Open(ras) gt = ds.GetGeoTransform() driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(shp, 0) layer = dataSource.GetLayer() for feature in layer: xo,yo,xd,yd = bbox2ix(feature.GetGeometryRef().GetEnvelope(),gt) arr = ds.ReadAsArray(xo,yo,xd,yd) yield arr layer.ResetReading() ds = None dataSource = None Assuming your shapefile is called shapefile.shp and your raster big_raster.tif you can use it like so: gen = rasclip('big_raster.tif','shapefile.shp') # manually with next clip = next(gen) ## some processing or inspection here # clip with next feature clip = next(gen) # or with iteration for clip in gen: ## apply stuff to clip pass # remove
has comment: http://stackoverflow.com/comment/90132302
has comment: http://stackoverflow.com/comment/87117670
has comment: http://stackoverflow.com/comment/122514681
accepted answer of: http://stackoverflow.com/q/50035578
answers question: http://stackoverflow.com/q/50035578
has comment: http://stackoverflow.com/comment/87115945
type: AcceptedAnswer
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/87113849
upvote count: 5
type: Answer

http://stackoverflow.com/comment/86875927
type: AnswerComment
score: 0
type: Comment
has text: Investigate the answer of nosklo then :)
comment on: http://stackoverflow.com/a/49929875

http://stackoverflow.com/comment/86934545
comment on: http://stackoverflow.com/a/49959067
score: 0
type: Comment
has text: Throwing a weaponized one-liner like this at an OP who's struggling to concatenate strings should be banned by the Geneva Conventions. Any chance you can make that monstrosity readable?
type: AnswerComment

http://stackoverflow.com/q/49932140
has answer: http://stackoverflow.com/a/49948052
tagged with: callback
favorite count: 0
type: AnsweredQuestion
tagged with: ctypes
has title: ctypes with callback: access violation on exit
tagged with: dll
tagged with: python
has comment: http://stackoverflow.com/comment/86881264
accepted answer: http://stackoverflow.com/a/49932885
type: Question
has answer: http://stackoverflow.com/a/49932885
answer count: 2
has body: I've asked this question before with no replies. I'm asking it again, much more simplified this time. I have a dll called by Python ctypes, with a callback function. The callback works correctly all the way through (I can see it in operation if I step through the program in Visual Studio), but on exit Visual Studio throws an "access violation" exception. BUT if I remove the call to the callback from the dll, it exits normally without an access violation. Is there something else I must do to exit from a dll with a callback? I have researched this for hours and I haven't found anything online that solves this. Here's the ctypes code. I omitted the dll code to keep this short (it's written in NASM) but if it's needed I can post it, too. def SimpleTestFunction_asm(X): Input_Length_Array = [] Input_Length_Array.append(len(X)*8) CA_X = (ctypes.c_double * len(X))(*X) length_array_out = (ctypes.c_double * len(Input_Length_Array))(*Input_Length_Array) hDLL = ctypes.WinDLL("C:/Test_Projects/SimpleTestFunction/SimpleTestFunction.dll") CallName = hDLL.Main_Entry_fn CallName.argtypes = [ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_longlong)] CallName.restype = ctypes.POINTER(ctypes.c_int64) #__________ #The callback function LibraryCB = ctypes.WINFUNCTYPE(ctypes.c_double, ctypes.c_double) def LibraryCall(ax): bx = math.ceil(ax) return (bx) lib_call = LibraryCB(LibraryCall) lib_call = ctypes.cast(lib_call,ctypes.POINTER(ctypes.c_longlong)) #__________ ret_ptr = CallName(CA_X,length_array_out,lib_call) I would really REALLY appreciate any ideas on how to solve this. I hope this simplified post will help. Thanks very much.
possible better answer: http://stackoverflow.com/a/49948052
downvote count: 0
has comment: http://stackoverflow.com/comment/86880450
upvote count: 1
score: 1

http://stackoverflow.com/q/49936599
upvote count: 1
tagged with: web
favorite count: 0
type: Question
has body: I have backend of web app by django, include registrations/user profile, the ability to add photo(video) file and view them, and list of places with the ability to book them. Now I need to add the ability to work with a mobile application written in ReactJS. The problem is that before that I did not work with mobile applications and I do not know what strategy to choose, but the frontend developer did not work with the backend. Can I pass django variables directly to the ReactJS code? Do I need additional technologies or frameworks? I would be grateful if someone shared their experience and described how to do it (preferably the least simple way)
accepted answer: http://stackoverflow.com/a/49937116
tagged with: reactjs
has title: Using django web app backend with mobile app on ReactJS
tagged with: mobile
has answer: http://stackoverflow.com/a/49937116
tagged with: django
has comment: http://stackoverflow.com/comment/86889531
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/128170198
type: AnswerComment
comment on: http://stackoverflow.com/a/61079810
type: Comment
score: 0
has text: The greatest way!

http://stackoverflow.com/comment/86875635
score: 0
has text: In that case, all of the `.csv` would be removed, but I'm not totally convinced that is relevant to what the OP is asking here :)
type: Comment
comment on: http://stackoverflow.com/a/49929713
type: AnswerComment

http://stackoverflow.com/q/49964327
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49965395
has body: A B C D 0 2002-01-12 10:00:00 John 19 1 2002-01-12 11:00:00 Africa 15 2 2002-01-12 12:00:00 Mary 30 3 2002-01-13 09:00:00 Billy 5 4 2002-01-13 11:00:00 Mira 6 5 2002-01-13 12:00:00 Hillary 50 6 2002-01-13 12:00:00 Romina 50 7 2002-01-14 10:00:00 George 30 8 2002-01-14 11:00:00 Denzel 12 9 2002-01-14 11:00:00 Michael 12 10 2002-01-14 12:00:00 Bisc 25 11 2002-01-16 10:00:00 Virgin 16 12 2002-01-16 11:00:00 Antonio 10 13 2002-01-16 12:00:00 Sito 5 I want to create two new columns df['E'] and df['F'], knowing that the same A and B values, always correspond to the same D value: df['E']: percent of variance of D value respect previous D value. df['F']: percent of variance between D and previous D value at 12:00:00. Output should be: A B C D E F 0 2002-01-12 10:00:00 John 19 0 0 1 2002-01-12 11:00:00 Africa 15 -21.05 0 2 2002-01-12 12:00:00 Mary 30 100.00 0 3 2002-01-13 09:00:00 Billy 5 -83.33 -83.33 4 2002-01-13 11:00:00 Mira 6 20.00 -80.00 5 2002-01-13 12:00:00 Hillary 50 733.33 66.66 6 2002-01-13 12:00:00 Romina 50 733.33 66.66 7 2002-01-14 10:00:00 George 30 -40.00 -40.00 8 2002-01-14 11:00:00 Denzel 12 -60.00 -76.00 9 2002-01-14 11:00:00 Michael 12 -60.00 -76.00 10 2002-01-14 12:00:00 Bisc 25 108.33 -50.00 11 2002-01-16 10:00:00 Virgin 16 -36.00 -36.00 12 2002-01-16 11:00:00 Antonio 10 -37.50 -60.00 13 2002-01-16 12:00:00 Sito 5 -50.00 -80.00 Would it be possible to use map to get it? I´ve tried: x = df[df['B'].eq(time(12))].drop_duplicates(subset=['A']).set_index('A')['D'](100 * (df.D - df.D.shift(1)) / df.D.shift(1)).fillna(0) df['F'] = df['A'].map(x)
accepted answer: http://stackoverflow.com/a/49965395
has title: Percent of difference between consecutive and fixed values
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/45437284

http://stackoverflow.com/q/50069108
tagged with: dictionary
has title: printing from nested dictionaries in classes
accepted answer: http://stackoverflow.com/a/50070190
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50070190
favorite count: 0
has comment: http://stackoverflow.com/comment/87156891
type: Question
has body: Having isues figuring out why this particular setup isnt working. class market(object): def __init__(self, market, coin): self.coin = coin self.market = market req = requests.get(f"http://bittrex.com/api/v1.1/public/getticker?market={market}-{coin}") sum = requests.get(f"https://bittrex.com/api/v1.1/public/getmarketsummary?market={market}-{coin}") self.address = req.json() self.marketsum = sum.json() def ticker(self): while True: print(self.address["result"]) time.sleep(5) def marketsummary(self): print(f"Market Summary for {coin}") print('_' * 20) print("Market Name: ", self.marketsum['result']['MarketName']) print("High: ", self.marketsum['result']['High'])) print("Low: ", self.marketsum['result']['Low']) print("Volume: ", self.marketsum['result']['Volume']) print("Last: ", self.marketsum['result']['Last']) print("BaseVolume: ", self.marketsum['result']['BaseVolume']) print("TimeStamp: ", self.marketsum['result']['TimeStamp']) print("Bid: ", self.marketsum['result']['Bid']) print("Ask: ", self.marketsum['result']['Ask']) print("OpenBuyOrders: ", self.marketsum['result']['OpenBuyOrders']) print("OpenSellOrders: ", self.marketsum['result']['OpenSellOrders']) print("Previous Day: ", self.marketsum['result']['PrevDay']) print("Created: ", self.marketsum['result']['Created']) print("DisplayMarketName: ", self.marketsum['result']['DisplayMarketName'])` Ive previously used this method with static(?jaron?) variables in if statements, such as usdt_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=USDT-ADA") btc_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=BTC-ADA") eth_ticker = requests.get("https://bittrex.com/api/v1.1/public/getticker?market=ETH-ADA") print("Which trade pairing would you like for this coin?") tradepair = input("&gt; ") if str.lower(tradepair) == "usdt" or "tether": actual_ticker = usdt_ticker.json() elif str.lower(tradepair) == "btc" or "bitcoin": actual_ticker = btc_ticker.json() elif str.lower(tr…
tagged with: python

http://stackoverflow.com/comment/86930773
has text: I recommend either clarifying this question with what you want to accomplish or ask another question.
type: Comment
comment on: http://stackoverflow.com/a/49956952
type: AnswerComment
score: 0

http://stackoverflow.com/a/49949675
accepted answer of: http://stackoverflow.com/q/49944199
has comment: http://stackoverflow.com/comment/86983741
has comment: http://stackoverflow.com/comment/86993502
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87267977
has comment: http://stackoverflow.com/comment/87839275
has body: Visio cannot do that. You cannot "convert all pages into a single HTML file". You'll have a "root" file and a folder of "supporting" files. VisSaveAsWeb is pretty well documented, no need to guess: https://msdn.microsoft.com/en-us/vba/visio-vba/articles/vissaveasweb-object-visio-save-as-web -- update With python, it turned out to be not that trivial to deal with SaveAsWeb. It seems to default to a custom interface (non-dispatch). I don't think it's possible deal with this using win32com library, but with comtypes seems to work (comtypes library is building the client based on the type library, i.e. it also supports "custom" interfaces): import sys import comtypes from comtypes import client from os.path import abspath f = abspath(sys.argv[1]) visio = comtypes.client.CreateObject("Visio.InvisibleApp") doc = visio.Documents.Open(f) comtypes.client.GetModule("{}\\SAVASWEB.DLL".format(visio.Path)) saveAsWeb = visio.SaveAsWebObject.QueryInterface(comtypes.gen.VisSAW.IVisSaveAsWeb) webPageSettings = saveAsWeb.WebPageSettings.QueryInterface(comtypes.gen.VisSAW.IVisWebPageSettings) webPageSettings.TargetPath = "{}.html".format(f) webPageSettings.QuietMode = True saveAsWeb.AttachToVisioDoc(doc) saveAsWeb.CreatePages() visio.Quit() exit(0) Other than that, you can try "command line" interface: http://visualsignals.typepad.co.uk/vislog/2010/03/automating-visios-save-as-web-output.html import sys import win32com.client from os.path import abspath f = abspath(sys.argv[1]) visio = win32com.client.Dispatch("Visio.InvisibleApp") doc = visio.Documents.Open(f) visio.Addons("SaveAsWeb").Run("/quiet=True /target={}.htm".format(f)) visio.Quit() exit(0) Other than that you could give a try to my visio svg-export :)
score: 1
answers question: http://stackoverflow.com/q/49944199
type: Answer
has comment: http://stackoverflow.com/comment/87150131
has comment: http://stackoverflow.com/comment/87678129
has comment: http://stackoverflow.com/comment/87037206

http://stackoverflow.com/q/50007357
has comment: http://stackoverflow.com/comment/87031278
accepted answer: http://stackoverflow.com/a/50007853
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: filter
has title: How to create a new pandas column by scanning cross multiple columns using for-loops?
tagged with: pandas
tagged with: function
has body: I have 25 variables DXCODE1 to DXCODE25, which I want to scan across to see if any of these values for each row matches the icd_list. For example, in each row, I want to scan across from DXCODE1 to DXCODE25 and see if any of these contains any one of the following three values: 'F32', 'F33', 'F34', if it does, then I want to return 1. I tried the following: def scan_icd (row): icd_list = ['F32', 'F33', 'F34'] for i in range(1, 26): dx_code_loc = 'DXCODE' + str(i) for j in range(0, len(icd_list)): if icd_list[j] in row[dx_code_loc]: return 1 df['ICD_DX'] = df.apply(scan_icd, axis=1) But I got this error: TypeError: ("argument of type 'float' is not iterable", 'occurred at index 1') Also I would like to make it flexible so I can somehow specify the icd code as a list in the parameter. But I don't know how to apply syntax-wise: def scan_icd (row, icd_list): icd_list = icd_list for i in range(1, 26): dx_code_loc = 'DXCODE' + str(i) for j in range(0, len(icd_list)): if icd_list[j] in row[dx_code_loc]: return 1 df['ICD_DX'] = df.apply(scan_icd (['F32', 'F33', 'F34']), axis=1) TypeError: apply() got multiple values for argument 'axis' =================== Edit: The columns are labeled DXCODE1,DXCODE2, ... DXCODE25
answer count: 1
has answer: http://stackoverflow.com/a/50007853
has comment: http://stackoverflow.com/comment/87031330
type: Question
has comment: http://stackoverflow.com/comment/87031409
has comment: http://stackoverflow.com/comment/87031507

http://stackoverflow.com/a/49925999
has comment: http://stackoverflow.com/comment/86868294
has body: Already by looking at the produced C-code, you can already see that size is a property and not a simple C-member. Here is the original Cython-code for memory-views: @cname('__pyx_memoryview') cdef class memoryview(object): ... cdef object _size ... @property def size(self): if self._size is None: result = 1 for length in self.view.shape[:self.view.ndim]: result *= length self._size = result return self._size It is easy to see, that the product is calculated only once and then cached. Clearly it doesn't play a big role for 3 dimensional arrays, but for a higher number of dimensions caching could become pretty important (as we will see, there are at most 8 dimensions, so it is not that clearly cut, whether this caching is really worth it). One can understand the decision to lazily calculate the size - after all, size is not always needed/used and one doesn't want to pay for it. Clearly, there is a price to pay for this laziness if you use the size a lot - that is the trade off cython makes. I would not dwell too long on the overhead of calling a.size - it is nothing compared to the overhead of calling a cython-function from python. For example, the measurements of @danny measure only this python-call overhead and not the actual performance of the different approaches. To show this, I throw a third function into the mix: %%cython ... def both(): a.size+a.shape[0]*a.shape[1]*a.shape[2] which does double amount of the work, but &gt;&gt;&gt; %timeit mv_size 22.5 ns ± 0.0864 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) &gt;&gt;&gt; %timeit mv_product 20.7 ns ± 0.087 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) &gt;&gt;&gt;%timeit both 21 ns ± 0.39 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) is just as fast. On the other hand: %%cython ... def nothing(): pass isn't faster: %timeit nothing 24.3 ns ± 0.854 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In a nutshell: I would use a.size because of the readabili…
score: 8
accepted answer of: http://stackoverflow.com/q/49919768
upvote count: 8
answers question: http://stackoverflow.com/q/49919768
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50050040
has answer: http://stackoverflow.com/a/50051535
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
tagged with: exponential
possible better answer: http://stackoverflow.com/a/50051900
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/87116749
score: 4
upvote count: 4
type: AnsweredQuestion
has title: Curve fit exponential growth function in Python
answer count: 3
has body: I have the following data points that I would like to curve fit: import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit t = np.array([15474.6, 15475.6, 15476.6, 15477.6, 15478.6, 15479.6, 15480.6, 15481.6, 15482.6, 15483.6, 15484.6, 15485.6, 15486.6, 15487.6, 15488.6, 15489.6, 15490.6, 15491.6, 15492.6, 15493.6, 15494.6, 15495.6, 15496.6, 15497.6, 15498.6, 15499.6, 15500.6, 15501.6, 15502.6, 15503.6, 15504.6, 15505.6, 15506.6, 15507.6, 15508.6, 15509.6, 15510.6, 15511.6, 15512.6, 15513.6]) v = np.array([4.082, 4.133, 4.136, 4.138, 4.139, 4.14, 4.141, 4.142, 4.143, 4.144, 4.144, 4.145, 4.145, 4.147, 4.146, 4.147, 4.148, 4.148, 4.149, 4.149, 4.149, 4.15, 4.15, 4.15, 4.151, 4.151, 4.152, 4.152, 4.152, 4.153, 4.153, 4.153, 4.153, 4.154, 4.154, 4.154, 4.154, 4.154, 4.155, 4.155]) The exponential function that I want to fit to the data is: The Python function representing the above formula and the associated curve fit with the data is detailed below: def func(t, a, b, alpha): return a - b * np.exp(-alpha * t) # scale vector to start at zero otherwise exponent is too large t_scale = t - t[0] # initial guess for curve fit coefficients a0 = v[-1] b0 = v[0] alpha0 = 1/t_scale[-1] # coefficients and curve fit for curve popt4, pcov4 = curve_fit(func, t_scale, v, p0=(a0, b0, alpha0)) a, b, alpha = popt4 v_fit = func(t_scale, a, b, alpha) ss_res = np.sum((v - v_fit) ** 2) # residual sum of squares ss_tot = np.sum((v - np.mean(v)) ** 2) # total sum of squares r2 = 1 - (ss_res / ss_tot) # R squared fit, R^2 The data compared to the curve fit is plotted below. The parameters and R squared value are also provided. a0 = 4.1550 b0 = 4.0820 alpha0 = 0.0256 a = 4.1490 b = 0.0645 alpha = 0.9246 R² = 0.8473 Is it possible to get a better fit with the data using the approach outlined above or do I need to use a different form of the exponential equation? I'm also not sure what to use for the initial values (a0, b0, alpha0). In the example, I chose points fro…
has comment: http://stackoverflow.com/comment/87118907
accepted answer: http://stackoverflow.com/a/50051130
has comment: http://stackoverflow.com/comment/87117000
downvote count: 0
has answer: http://stackoverflow.com/a/50051900
has answer: http://stackoverflow.com/a/50051130

http://stackoverflow.com/q/49982153
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/86989144
has comment: http://stackoverflow.com/comment/86980452
score: 0
answer count: 0
has body: The following code snippet has a runtime of around 1 min in jupyter notebook and below 1 second in the ipython shell: test_list = [] max_len = 1000 for i in range(max_len): test_list.append(np.random.randn(784)) Can somebody reproduce this issue or is it specific to my environment? I'm not sure what could cause the issue and would be glad if someone could help. edit1: Figured that this problem is specific to my environment. installed packages
type: Question
has comment: http://stackoverflow.com/comment/86982463
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87020488
tagged with: python
has title: Jupyter notebook large lists

http://stackoverflow.com/q/50061509
type: Question
has comment: http://stackoverflow.com/comment/87139348
has comment: http://stackoverflow.com/comment/87139339
has comment: http://stackoverflow.com/comment/87143637
has title: TypeError: object of type 'Text' has no len()
has comment: http://stackoverflow.com/comment/87140399
accepted answer: http://stackoverflow.com/a/50063794
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
linked to: http://stackoverflow.com/q/14824163
has body: what is this error and how can i fix it? def check_number(): if (len(txtNum1)!=11): error_number = "the number that you entered is wrong" msg = tk.Message(frame, text = error_number , fg="red") msg.pack() title = Label(frame, text="enter your number", fg="gray") title.pack() txtNum1 = Text (frame, height=1, width=30) txtNum1.pack(side=tk.TOP) button = tk.Button(frame, text="chek", fg="green", command=check_number) button.pack(side=tk.BOTTOM) root.mainloop() i just test __len__method but its not working well.
upvote count: 0
answer count: 1
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/87139334
has answer: http://stackoverflow.com/a/50063794
favorite count: 0

http://stackoverflow.com/comment/87112082
has text: @ChaitanyaKirty yes you can do that. I edited the answer to show an example.
comment on: http://stackoverflow.com/a/50047877
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50051746
has body: Based upon https://docs.djangoproject.com/en/dev/ref/urls/#django.urls.path, you need to use re_path() instead of path(), as it is interpreting ^$ literally, per zvadym's prior comment. This is new in Django 2.0, so it depends on your version.
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50051627
upvote count: 1
answers question: http://stackoverflow.com/q/50051627
type: Answer

http://stackoverflow.com/comment/86867641
type: QuestionComment
comment on: http://stackoverflow.com/q/49922991
type: Comment
score: 0
has text: You should also provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), to make sure we will solve your problem, and not something else.

http://stackoverflow.com/a/49961970
has body: Here is another way you can structure your logic. This method also deals with string to integer conversion. def splitter(item): split = item.split(',') return (split[0], int(split[1]), int(split[2])) d = {} with open('portfolio1.txt', 'r') as f: for line in f: k, vals = line.rstrip().split(':') v = [splitter(x) for x in vals.split(';')] d[k] = v Result: {'Alan': [('Intel', 20, 10), ('Dell', 10, 50), ('Apple', 80, 80), ('Dell', -10, 55)], 'Barb': [('Intel', 20, 40), ('Intel', -10, 45), ('IBM', 40, 30), ('Intel', -10, 35)], ...
answers question: http://stackoverflow.com/q/49961872
score: 0
type: Answer

http://stackoverflow.com/q/49962659
has title: Python 3.6 utf-8 UnicodeEncodeError
has comment: http://stackoverflow.com/comment/86941863
answer count: 2
score: 0
downvote count: 2
tagged with: utf-8
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/49962683
type: Question
linked to: http://stackoverflow.com/q/3828723
linked to: http://stackoverflow.com/q/2276200
has body: #!/usr/bin/env python3 import glob import xml.etree.ElementTree as ET filenames = glob.glob("C:\\Users\\####\\Desktop\\BNC2\\[A00-ZZZ]*.xml") out_lines = [] for filename in filenames: with open(filename, 'r', encoding="utf-8") as content: tree = ET.parse(content) root = tree.getroot() for w in root.iter('w'): lemma = w.get('hw') pos = w.get('pos') tag = w.get('c5') out_lines.append(w.text + "," + lemma + "," + pos + "," + tag) with open("C:\\Users\\####\\Desktop\\bnc.txt", "w") as out_file: for line in out_lines: line = bytes(line, 'utf-8').decode('utf-8', 'ignore') out_file.write("{}\n".format(line)) Gives the error: UnicodeEncodeError: 'charmap' codec can't encode character '\u2192' in position 0: character maps to undefined I thought this line would have solved that: line = bytes(line, 'utf-8').decode('utf-8', 'ignore')
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86941390
tagged with: python
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/86941693
has answer: http://stackoverflow.com/a/49962760

http://stackoverflow.com/comment/86910408
comment on: http://stackoverflow.com/q/49946851
type: QuestionComment
score: 0
type: Comment
has text: @Patrick the screenshot attached is just to show you that there no output after running the code.

http://stackoverflow.com/a/49972272
has comment: http://stackoverflow.com/comment/86960622
has comment: http://stackoverflow.com/comment/86960677
has comment: http://stackoverflow.com/comment/86960540
score: 0
has comment: http://stackoverflow.com/comment/86960742
answers question: http://stackoverflow.com/q/49972252
has comment: http://stackoverflow.com/comment/86960662
upvote count: 1
has comment: http://stackoverflow.com/comment/86960643
downvote count: 1
has comment: http://stackoverflow.com/comment/86960713
has comment: http://stackoverflow.com/comment/86960521
has comment: http://stackoverflow.com/comment/86960661
type: Answer
has body: Store and update the index and only print it at the end: s = "hello" search = 'l' last_found = None for idx, letter in enumerate(s): if letter == search: last_found = idx print (last_found) or loop in reverse order: for idx in range(len(s)-1,-1,-1): if s[idx] == search: break print (idx)

http://stackoverflow.com/comment/87263236
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50050631
type: QuestionComment
has text: Sorry for the delay. I've added the rest of it.

http://stackoverflow.com/a/50031061
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/87095284
accepted answer of: http://stackoverflow.com/q/50027652
type: AcceptedAnswer
has body: You do the self.sess.run(tf.global_variables_initializer()) in the __init__ of your Model class, but only in the train() method do you set up the tf.train.AdamOptimizer(). The latter also creates some variables that need to be initialized. Move the self.sess.run(tf.global_variables_initializer()) line right after train = tf.train.AdamOptimizer(0.1).minimize(loss) and it will work. Full code (tested): import tensorflow as tf import numpy as np class Model: def __init__(self,input_neuron=2,hidden_neuron=10,output_neuron=2): self.input_neuron = input_neuron self.hidden_neuron = hidden_neuron self.output_neuron = output_neuron self.x = tf.placeholder(tf.float32,[None,self.input_neuron]) self.y = tf.placeholder(tf.float32,[None,self.output_neuron]) self.model = self.graph() self.sess = tf.InteractiveSession() @staticmethod def one_hot_encode(y): y_ = np.zeros((len(y),2)) for i in range(len(y)): y_[i,y[i][0]]=1 return y_ def graph(self): w1=tf.Variable(tf.random_normal([self.input_neuron,self.hidden_neuron])) l1=tf.nn.relu(tf.matmul(self.x,w1)) w2=tf.Variable(tf.random_normal([self.hidden_neuron,self.output_neuron])) l2=tf.matmul(l1,w2) return l2 def train(self,xTrain,yTrain): yTrain = self.one_hot_encode(yTrain) loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2( logits=self.model,labels=self.y)) train = tf.train.AdamOptimizer(0.1).minimize(loss) self.sess.run(tf.global_variables_initializer()) for epoch in range(100): self.sess.run(train,feed_dict={self.x:xTrain,self.y:yTrain}) print("Training done!") def predict(self,xTest): prediction = tf.argmax(self.model) return self.sess.run(prediction,feed_dict={x:xTest}) model = Model() xTrain = np.array([[0,0],[0,1],[1,0],[1,1]]) yTrain = np.array([[0],[1],[1],[0]]) model.train(xTrain,yTrain) Based on your comment, if you don't want to re-initialize the whole network at each call of the train() method, then you need to initialize the network at the __init__() method and use tf.report_uninitialized_variables() to ge…
answers question: http://stackoverflow.com/q/50027652
has comment: http://stackoverflow.com/comment/87097677
score: 2
downvote count: 0

setuptools
tags question: http://stackoverflow.com/q/50062168
tags question: http://stackoverflow.com/q/49918859
tag name: setuptools
tags question: http://stackoverflow.com/q/49949693
tags question: http://stackoverflow.com/q/49994133
type: Tag

http://stackoverflow.com/q/50071198
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87159589
answer count: 0
has comment: http://stackoverflow.com/comment/87159167
has title: Flask-SQlAlchemy Query not consistent between Production and Development config
downvote count: 0
upvote count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87159171
has body: So, I am running a Flask web app as the frontend to a small SQLite inventory database. I am using Flask-SQLAlchemy for all of the database interaction. I have a search feature built in, so that you could (for example) find all pieces of hardware assigned to Person X. Or, find all pieces of hardware from Project ABC that have the status Available. The search feature supports optional criteria. For security reasons, I can't post executable code here, but this is my search function: for system in db.session.query(System).filter(and_(System.assignee_id.like("%{}%".format(assignee_id)), System.serial.like("%{}%".format(serial)), System.user_id.like("%{}%".format(user_id)), System.project_id.like("%{}%".format(project_id)), System.status_id.like("%{}%".format(status_id)))): results.append(system) The weird thing is, this works perfectly when I run the app in the Development config. But, in my Production config, if I try to use the 'Assignee' or 'User' criteria (both of which are strings of an email address), I get bad results. It shows me a bunch of systems, some of which have the correct assignee, but most of which don't. The only differences between the Production and Development configs are the file path to the SQLite database and the authentication mechanism to sign into the application. Why would this return different results between the two? It works EXACTLY like it is supposed to in the Dev config. UPDATE After some additional debugging as suggested by the comments, it looks like the problem is in the actual data of the ProductionConfig. However, when I browse the .sqlite file in DB Browser, initially everything looks correct. Where is it getting these random assignees?
type: UnansweredQuestion

http://stackoverflow.com/comment/86922578
comment on: http://stackoverflow.com/q/49952933
type: Comment
type: QuestionComment
score: 0
has text: Python does neither pass by reference nor pass by value. It uses a ["call by sharing"](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) evaluation strategy, sometimes called "call by object". I suggest you read the following: https://nedbatchelder.com/text/names.html

http://stackoverflow.com/comment/87031160
type: QuestionComment
comment on: http://stackoverflow.com/q/50006738
type: Comment
score: 0
has text: I actually forgot how to do this (because I have a bad habit of caring more about functionality than organization), but if you visit the Discord API server, or Egg And Sebi's Bot Tutorial server, they can definitely help you out. It is also likely that the information you are looking for can be found in the discord.py API: http://discordpy.readthedocs.io/en/latest/api.html

http://stackoverflow.com/a/49971714
has comment: http://stackoverflow.com/comment/86962994
answers question: http://stackoverflow.com/q/49971695
has comment: http://stackoverflow.com/comment/86969877
has body: why not create a list and then append more lists to it like this: x = [] for in in range(1,4): x.append([i, i*2, i*3]) print(x) # [[1,2,3], # [2,4,6], # [3,6,9]]
type: Answer
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/50013794
type: AnsweredQuestion
tagged with: color-profile
has comment: http://stackoverflow.com/comment/87045502
has body: I have been having trouble trying to save a png image with sRGB and an alpha channel. I first crop an image and then save it like this: from PIL import Image import cv2 inputPath = 'picture.png' img = cv2.imread(inputPath) crop_img = img[bounds[3]:bounds[2], bounds[1]:bounds[0]] pth = name + ".png" crop_img.save(pth) This however creates a file like this: I want the file to be like this though: How can I get this result in python? P.S. The original image does have an alpha channel and sRGB colour profile. Any help is greatly appreciated!
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50014978
has answer: http://stackoverflow.com/a/50014978
type: Question
has title: Python: Apply sRGB colour profile and alpha channel to image
tagged with: alpha
has comment: http://stackoverflow.com/comment/87045478
downvote count: 0
answer count: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/png
favorite count: 0
tagged with: opencv

http://stackoverflow.com/comment/87010973
type: Comment
type: QuestionComment
has text: @JimK Thank you very much. I saw your post recently, and I used it as a help for my trouble, and it worked perfectly for converting the pdf to odg. (I checked your answer for that reason). However, I was looking for the conversion to .docx, that seems to be more difficult... In any case, my operating system is Windows 7.
comment on: http://stackoverflow.com/q/49965818
score: 0

http://stackoverflow.com/comment/86982327
comment on: http://stackoverflow.com/q/49982799
score: 1
type: Comment
has text: How do you start _rabbitmq_ _receiver_?
type: QuestionComment

http://stackoverflow.com/comment/87066649
type: AnswerComment
has text: Could you please explain why?
type: Comment
comment on: http://stackoverflow.com/a/50025216
score: 0

http://stackoverflow.com/a/50071087
has body: The python open() function returns a file object. This is not what you want to send to the API. Instead, you can use: with open(file_path, 'rb') as f: r = requests.post(myurl, headers=headers, data=f.read()) Syntax taken from here.
downvote count: 0
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87158891
answers question: http://stackoverflow.com/q/50071013

http://stackoverflow.com/a/49979393
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49976576
has body: Another possibility is to join all the word combinations, and then replace \s with | for re.sub: import re b = ['test Lorem ipsum dolor sit amet', 'consectetur adipiscing elit', 'test Nulla lectus ligula', 'imperdiet at porttitor quis', 'smth commodo eget tortor', 'Orci varius natoque penatibus et magnis dis parturient montes'] a = ['test', 'smth commodo'] replaced_strings = [re.sub(re.sub('\s', '|', ' '.join(a)), '', i) for i in b] Output: [' Lorem ipsum dolor sit amet', 'consectetur adipiscing elit', ' Nulla lectus ligula', 'imperdiet at porttitor quis', ' eget tortor', 'Orci varius natoque penatibus et magnis dis parturient montes'] To remove additional whitespace, apply an additional pass: new_data = [re.sub('^\s+', '', i) for i in replaced_strings] Output: ['Lorem ipsum dolor sit amet', 'consectetur adipiscing elit', 'Nulla lectus ligula', 'imperdiet at porttitor quis', 'eget tortor', 'Orci varius natoque penatibus et magnis dis parturient montes']
has comment: http://stackoverflow.com/comment/87009446

http://stackoverflow.com/q/49918271
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50239405
possible better answer: http://stackoverflow.com/a/50198137
has answer: http://stackoverflow.com/a/50239405
has answer: http://stackoverflow.com/a/50198137
tagged with: python
has body: I was able to train a model in TensorFlow with my own data. Input and Output of the model are images. I now tried to get the output of the predictions and save it to an png image file to see what's going on. Unfortunately I am getting an error when running the following function I created to test with predictions. My goal is to save the prediction that is also an image so I can open it with a normal image viewer. Some more to the code. In my main I am creating an estimator def predict_element(my_model, features): eval_input_fn = tf.estimator.inputs.numpy_input_fn( x=features, num_epochs=1, shuffle=False) eval_results = my_model.predict(input_fn=eval_input_fn) predictions = eval_results.next() #this returns a dict with my tensors prediction_tensor = predictions["y"] #get the tensor from the dict image_tensor = tf.reshape(prediction_tensor, [IMG_WIDTH, -1]) #reshape to a matrix due my returned tensor is a 1D flat one decoded_image = tf.image.encode_png(image_tensor) write_image = tf.write_file("output/my_output_image.png", decoded_image) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(write_image)) def get_input(): filename_dataset = tf.data.Dataset.list_files("features/*.png") label_dataset = tf.data.Dataset.list_files("labels/*.png") # Make a Dataset of image tensors by reading and decoding the files. image_dataset = filename_dataset.map(lambda x: tf.cast(tf.image.decode_png(tf.read_file(x), channels=1),tf.float32)) l_dataset = label_dataset.map(lambda x: tf.cast(tf.image.decode_png(tf.read_file(x),channels=1),tf.float32)) image_reshape = image_dataset.map(lambda x: tf.reshape(x, [IM_WIDTH * IM_HEIGHT])) label_reshape = l_dataset.map(lambda x: tf.reshape(x, [IM_WIDTH * IM_HEIGHT])) iterator = image_reshape.make_one_shot_iterator() iterator2 = label_reshape.make_one_shot_iterator() next_img = iterator.get_next() next_lbl = iterator2.get_next() features = [] labels = [] # read all 10 images and labels and put it in the array # so …
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87113033
has comment: http://stackoverflow.com/comment/87221342
downvote count: 0
has title: Saving predicted tensor to image in TensorFlow - Graph finalized
tagged with: tensorflow

http://stackoverflow.com/a/50028356
has comment: http://stackoverflow.com/comment/87073341
has comment: http://stackoverflow.com/comment/87094048
type: Answer
accepted answer of: http://stackoverflow.com/q/50028214
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Did you think about having another dictionary with idx -> plane? then in self.plane_dict[plane_uuid] you would just store idx instead of object. this will save memory and speed up your app, though you'd need to modify the lookup method.
answers question: http://stackoverflow.com/q/50028214

mixed-models
tag name: mixed-models
type: Tag
tags question: http://stackoverflow.com/q/50052421

http://stackoverflow.com/comment/86879657
comment on: http://stackoverflow.com/q/49931936
type: Comment
type: QuestionComment
score: 0
has text: @Barmar He does for the sake of skipping over them, like "Hi. I'm SpOnGeBoB."

http://stackoverflow.com/comment/86980429
type: Comment
score: 0
type: QuestionComment
has text: You should change `[2:3]` to [2, 3].
comment on: http://stackoverflow.com/q/49980814

http://stackoverflow.com/comment/87090572
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50036829
has text: Seems so, this is interesting. My guess would be that tensorflow need additional GPU memory for sharing the weights between GPUs. How much free gpu space do you have when training with a batch_size of 32 on a single GPU?

http://stackoverflow.com/comment/87139155
has text: Please provide a sample `csv` (two or 3 lines) and state exactly in which line the error occurs. Preferably post the stackdump.
comment on: http://stackoverflow.com/q/50060781
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/86904877
type: Comment
type: AnswerComment
has text: Really interesting that `pandas` has same functions like `SQL` . I am just glamorous about how complex is `pandas` and works perfecly with python for machine learning applications. +1
comment on: http://stackoverflow.com/a/49943939
score: 1

http://stackoverflow.com/comment/86941778
comment on: http://stackoverflow.com/q/49962533
type: QuestionComment
has text: Input is `json` ? Is possible use `json_normalize` ?
type: Comment
score: 0

http://stackoverflow.com/q/49949020
has comment: http://stackoverflow.com/comment/86917377
score: 0
tagged with: angular
has body: I am new to Angular and I need help in saving the value from a table through a POST service. Below is my code. saveCalendar(value: any) { console.log("Updated Value"+ value); // value from the table this.body = { "promotionname": this.promotionname, "period": this.period, "indicator": this.indicator, "value": this.value }; this.services.saveCalendar(this.body) .then( response =&gt; { if(response == "Success") { this.firstPage(this.clickedItem); } } ); } Service: saveCalendar(body: object): Promise&lt;any&gt; { return this.http.post(environment.serverUrl+'/api/update_promocal', body) .toPromise() .then( response =&gt; { if(response['_body'] == "Save Successful!") { return "Success"; } } ) .catch(error =&gt; console.log('Error while getting response: '+error)) } Below is the service from the backend: def update_promocal(request): id1 = request.GET.get('id') column = request.GET.get('column') data = request.GET.get('data') test = Promocal.objects.get(id = id1) if column == 'promotionname': test.promotion_name = data elif column == 'period': test.period = data elif column == 'indicator': test.indicator = data elif column == 'value': test.value = data elif column == 'marketdriver': test.market_driver = data else: test.save() test.save() I want to send this updated value back to the service via POST method so that it can be saved in the database.But I am missing out something. Please help here.
answer count: 1
has comment: http://stackoverflow.com/comment/86917936
type: Question
tagged with: rest
type: UnansweredQuestion
has title: Angular 4: Saving variable from the table element through POST service
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/86917828
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/49963442

http://stackoverflow.com/comment/86989307
type: Comment
has text: @Aran-Fey An OrderedDict would also be good
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49986397

http://stackoverflow.com/comment/87153640
comment on: http://stackoverflow.com/a/50051644
has text: I'm trying the second, but on python,org it said to write "-m pip install <package_name>
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86952640
type: Comment
type: QuestionComment
score: 0
has text: What does it mean to set your computer to work with utf-8 files?
comment on: http://stackoverflow.com/q/49968414

http://stackoverflow.com/q/49991947
tagged with: class
type: AnsweredQuestion
has body: So I got my code to work, but two lines are messing me up, and not quite sure what to put. Code(the two lines are marked): class Person(object): numPerson = 0 def __init__(self,firstName,lastName): self.firstName = firstName self.lastName = lastName def fullName(self): print self.firstName +' '+self.lastName class Employee(Person): numEmployee = 0 def __init__(self,firstName,lastName,pay,employID): Person.__init__(self, firstName, lastName) self.pay = pay self.employID = employID Employee.numEmployee += 1 class Programmer(Employee): def __init__(self,firstName,lastName,pay,employID,proLang): self.proLang = proLang Employee.__init__(self, firstName, lastName, pay, employID) class Manager(Employee): def __init__(self,firstName,lastName,pay,employID,progList): self.progList = progList Employee.__init__(self, firstName, lastName, pay, employID) def addProgrammer(self): self.progList.append(Programmer.fullName) &lt;------------------- This line def removeProgrammer(self): if len(self.progList) == 0: pass else: del self.progList[0] def printList(self): print self.progList a = Manager('Alfred','Jones',20.00,0001,[]) b = Programmer('James','Smith', 11.75, 0002, 'Java') a.addProgrammer() &lt;--------------------------------------------- And This line a.printList() I'm trying to add the programmer's name to the progList using the .addProgramer method. I keep trying different combos and this is the closest I got. Output: [&lt;unbound method Programmer.fullName&gt;] So, I'm not sure what needs to be in the addProgramer method in order to properly add the programmers name, or if I need an argument inside the a.addProgrammer at the very end.
tagged with: call
score: 1
has title: Creating a call function for multiple classes
answer count: 1
downvote count: 0
tagged with: multiple-inheritance
upvote count: 1
accepted answer: http://stackoverflow.com/a/49992009
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49992009
tagged with: python

http://stackoverflow.com/a/49937395
accepted answer of: http://stackoverflow.com/q/49937365
has body: In my opinion here is best/fast cast boolean mask to integers: se = (se &gt;= 3).astype(int) Or use numpy.where, but Series constructor is necessary, because returned numpy array: se = pd.Series(np.where(se &lt; 3, 0, 1), index=se.index) print (se) 0 0 1 0 2 1 3 1 4 1 5 1 dtype: int32
type: Answer
answers question: http://stackoverflow.com/q/49937365
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49951360
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86919768
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49951706
upvote count: 2
has answer: http://stackoverflow.com/a/49951706
has title: Tweepy writing to text file
linked to: http://stackoverflow.com/q/21553327
tagged with: python
linked to: http://stackoverflow.com/q/49961156
has body: I am learning the tweepy library to access the twitter api. I have a csv file with some preliminary data (such as tweet_id) and I pulled that into a dataframe. I need to use that data to pull more data using tweepy. I am trying to write that data to a text file and then create a new dataframe off of that. I have been trying different things the past couple evenings, and I don't understand why this isn't writing the data to the text file. I have all the necessary tokens stored in variables. auth = tweepy.OAuthHandler(Consumer_Key, Consumer_Secret) auth.set_access_token(Access_Token, Access_Secret) tweetapi = tweepy.API(auth, wait_on_rate_limit=True,wait_on_rate_limit_notify=True) #writing text file txtfile = open("jsontweet3.txt", "a") txtfile.write('tweet_id retweet_count favorite_count''\n') #pulling tweet info for tweet_id in fdf.tweet_id: try: twitinfo = tweetapi.get_status(str(tweet_id),tweet_mode='extended') retweets = twitinfo.retweet_count favorites = twitinfo.favorite_count txtfile.write(twitinfo+' '+str(retweets)+' '+str(favorites)+'\n') txtfile.close() I would be greatly appreciative of any help!
score: 2

http://stackoverflow.com/q/49944907
has comment: http://stackoverflow.com/comment/139987390
tagged with: python
has title: Selecting record from mySQL via cursors returns an None object
score: 2
answer count: 1
downvote count: 0
tagged with: mysql
has body: I am writing a script in python 3.x using mysqlconnector. What I am trying to achieve right now is to check if there is a record inside my db which may be a duplicate to the one I am analyzing right now. I came up with such code: def fill_data(self, db_name, data): cursor = self.cnx.cursor(buffered=True) isDuplicate = cursor.execute(("SELECT destination FROM {0} WHERE destination = '{1}';") .format(db_name, data['destination'])) print(cursor.statement) self.commit() print(isDuplicate is None) Though I still get isDuplicate as None object. I tried to check via cursor.statement what statement is being passed to my db: it turned out that while in script I get None obj while passed in db that query works fine. I also tried SELECT COUNT(1) FROM db_name which also gave me different results. I am out of ideas: maybe you guys can help me out? Update: The solution that works for me was: q = ("SELECT * FROM {0} WHERE destination = %s AND countryCode = %s AND prefix = %s") .format(db_name) cursor.execute(q, (data['destination'], data['country_code'], data['prefix'])) self.cnx.commit() isDoubled = cursor.fetchone() So at the end of the day it was all about fetching data from the cursor :)
tagged with: mysql-connector
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49945166
tagged with: database

http://stackoverflow.com/a/50055719
type: Answer
has comment: http://stackoverflow.com/comment/87128179
answers question: http://stackoverflow.com/q/50055675
has body: What you want is fnmatch module instead of glob: Example: import glob extList = ["*pdf","*.cod","*log*","*.log.*"] any(fnmatch.fnmatch(path, ext) for ext in extList) Test: &gt;&gt;&gt; any(fnmatch.fnmatch(u'test.pdf', ext) for ext in extList) True &gt;&gt;&gt; any(fnmatch.fnmatch(u'test.zip', ext) for ext in extList) False
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/50034149
answer count: 0
type: UnansweredQuestion
has title: C++ calls Python - error LNK2019
type: Question
has comment: http://stackoverflow.com/comment/87084523
tagged with: python
has comment: http://stackoverflow.com/comment/87084440
has comment: http://stackoverflow.com/comment/87429086
has body: I used c++ to call Python in my project and it always goes well on my Visual Studio. But my teacher got the follow errors when he opened my project on his Visual Studio: error LNK2019: unresolved external symbol _Py_Finalize referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyString_AsString referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyObject_CallObject referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyTuple_SetItem referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _Py_BuildValue referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyTuple_New referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyCallable_Check referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyDict_GetItemString referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyModule_GetDict referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyImport_Import referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyString_FromString referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : error LNK2019: unresolved external symbol _PyRun_SimpleStringFlags referenced in function "int __cdecl main_CcallPy(int)" (?main_CcallPy@@YAHH@Z) 1>demo.obj : err…
tagged with: visual-studio
tagged with: c++
score: 0

http://stackoverflow.com/q/49994379
type: Question
has body: My data was like this : {'yMax': u'156', 'xMax': u'4802', 'xMin': u'4770','yMin': u'141', 'id': '1', 'name': ''} {'yMax': u'157', 'xMax': u'4895', 'xMin': u'4810','yMin': u'141', 'id': '2', 'name': ''} in a .txt file, i had to change it per the requirement to a .csv file it now looks like this: image id name xMin xMax yMin yMax 1-0.png 1 4770 4802 141 156 1-0.png 2 4810 4895 141 157 i used to read my .txt file using : import ast file = open("1-0.txt", 'r') labels1 = [] for line in file.readlines(): dicObj = ast.literal_eval(line.strip('\n')) labels1.append(dicObj) basically as a list of dictionaries after transforming the string shaped {} in my txt file to dics. How can i now read the data from my new csv file that i described its shape above ?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/87004994
possible better answer: http://stackoverflow.com/a/49994415
accepted answer: http://stackoverflow.com/a/49994443
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49994415
has answer: http://stackoverflow.com/a/49994443
answer count: 2
score: 1
has title: How can i properly read my csv data?
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87097453
comment on: http://stackoverflow.com/q/50039222
score: 1
type: Comment
type: QuestionComment
has text: Thank you for the update. It's a convenience thing - if people can easily copy and paste your code they are more likely to write an answer. For me that is the most important reason :)

http://stackoverflow.com/a/49975017
answers question: http://stackoverflow.com/q/49974905
has body: Use map if all values of df2['C'] exist in df1['C'] and then multiple by mul and divide by div: mapping = df1.set_index('C')['D'] s = df2['H'].mul(100).div(df2['C'].map(mapping)) print (s) 0 69.510269 1 71.532385 2 2.582345 3 71.936759 dtype: float64 Another solution is use merge with inner join for new DataFrame: df = df1.merge(df2, on='C') s = df['H'].mul(100).div(df['D']) print (s) 0 69.510269 1 71.532385 2 2.582345 3 71.936759 dtype: float64
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/49974905
has comment: http://stackoverflow.com/comment/109356313
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/86913468
has text: actually i recently started with python so dont understand half of the things so can you please help me solve the error @Alexander
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49947856
score: 0

http://stackoverflow.com/comment/87124814
type: Comment
has text: That's actually what I had originally when I was working with python 2, but I got ImportError: No module named 'mysql' EDIT: posted before you added the mysqlclient part. Now it works. Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/50054075
score: 0

http://stackoverflow.com/comment/87065737
type: QuestionComment
has text: for this to be considered as CSV, there has to be a unique separator in all rows. in youy headers you have '+' as separator, whereas in other rows it is '|'. Neither pandas not CSV module, will be be able to read this as is
comment on: http://stackoverflow.com/q/50024699
score: 0
type: Comment

http://stackoverflow.com/a/50059334
has comment: http://stackoverflow.com/comment/87145423
type: AcceptedAnswer
downvote count: 0
has body: You're currently defining timer inside of the function. Thus it'll be forgotten and set back to 0 every time the function is called. The value of timer also seems to be independent of the actual time: it's randomly updated 0 to 4 times a loop, where a loop might take more than 1 millisecond in a busy period. A better implementation might be: class MarsRover(object): time_left_disabled = 0 def disable(self): self.time_left_disabled = 2000 def update_disabled(self, time_taken): # There are several ways to implement this, including if-statements self.time_left_disabled = max(self.time_left_disabled - time_taken, 0) def is_enabled(self): return (self.time_left_disabled &lt;= 0) # your other code here With a part of your main loop as follows: # Check if the rover should be disabled again if randint(0, 2500) &lt; 25: rover.disable() else: rover.update_disabled(dt) # Do some other stuff # Check the keyboard input if keys_pressed[pg.K_LEFT] and rover.is_enabled(): rover.move_left() if keys_pressed[pg.K_RIGHT] and rover.is_enabled(): rover.move_right() if keys_pressed[pg.K_SPACE] and rover.is_enabled(): rover.thrust() # some other stuff # Ensure the FPS is not going crazy dt = clock.tick(framerate)
accepted answer of: http://stackoverflow.com/q/50058459
has comment: http://stackoverflow.com/comment/87153474
score: 3
answers question: http://stackoverflow.com/q/50058459
type: Answer
upvote count: 3

http://stackoverflow.com/comment/86963690
comment on: http://stackoverflow.com/q/49940930
score: 0
has text: Then what else you used for hadoop? can give me any other suggestions instead of pickle
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49973765
type: Answer
has body: Try a list comprehension. X = [0,5,0,0,3,1,15,0,12] X = [i for i in X if i != 0]
downvote count: 0
upvote count: 49
answers question: http://stackoverflow.com/q/49973739
score: 49

http://stackoverflow.com/comment/87025047
has text: Sorry, I don't understand your response. Have you tried replacing the target host name with the IP address? Did the performance improve in that case?
comment on: http://stackoverflow.com/q/49992461
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87073760
score: 0
comment on: http://stackoverflow.com/q/50012174
type: QuestionComment
has text: @TheHeadRush Thanks for the help! I have done the changes not I get org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed; nested exception is javax.persistence.PersistenceException: Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Composite-id class must implement Serializable:
type: Comment

http://stackoverflow.com/comment/86989890
type: AnswerComment
has text: Nice. Similar to mine except you apply `OrderedDict` instead of `dict(enumerate(...))`. +1
comment on: http://stackoverflow.com/a/49986623
type: Comment
score: 0

http://stackoverflow.com/q/50010040
tagged with: keras
has answer: http://stackoverflow.com/a/50886956
has comment: http://stackoverflow.com/comment/87039434
has title: How can I increase the accuracy of my image classification model?
upvote count: 3
has comment: http://stackoverflow.com/comment/87038320
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87036959
has comment: http://stackoverflow.com/comment/87036930
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am trying to classify a group of bee images into two classes - bumble bee and honey bee with the resulting format being a CSV file like - id,bumble_bee,honey_bee 20000,0.75, 0.25. I have a running model, but the accuracy is very low and I've tried a bunch of different things such as adding a base_model like VGG16 or InceptionV3, adjusting the epochs, adjusting the optimizer type... and I just haven't noticed much difference. All of my changes still result in an accuracy of around 70-79%. How can I increase the accuracy of my model? Here is my code: from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K # dimensions of our images. img_width, img_height = 200, 200 train_data_dir = 'data/train/' validation_data_dir = 'data/validation/' nb_train_samples = 2978 nb_validation_samples = 991 epochs = 50 batch_size = 25 if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(2)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), metrics=['accuracy']) # this is the augmentation configuration we will use for training train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # this is the augmentation configuration we will use for testing: # onl…
downvote count: 2
type: UnansweredQuestion
tagged with: classification
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87038291
tagged with: python

http://stackoverflow.com/a/49991727
downvote count: 0
has comment: http://stackoverflow.com/comment/128805239
has comment: http://stackoverflow.com/comment/128786484
upvote count: 9
type: Answer
has body: Try using newTag.attrs['async'] = None: from urllib import request f = request.urlopen("http://www.example.com") s = f.read() f.close() from bs4 import BeautifulSoup soup = BeautifulSoup(s, "lxml") newTag = soup.find("meta", charset = "utf-8") tagCopy = newTag newTag.attrs['async'] = "" print(newTag) tagCopy.attrs['async'] = None print(tagCopy) This produces the following output: &lt;meta async="" charset="utf-8"/&gt; &lt;meta async charset="utf-8"/&gt;
has comment: http://stackoverflow.com/comment/128789541
score: 9
answers question: http://stackoverflow.com/q/49991604

http://stackoverflow.com/comment/86918403
type: AnswerComment
has text: Then go for it ;)
type: Comment
comment on: http://stackoverflow.com/a/49950686
score: 0

http://stackoverflow.com/q/49972908
has title: pip install 'what you want to install' isn't working
has answer: http://stackoverflow.com/a/49972980
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87000170
downvote count: 0
has comment: http://stackoverflow.com/comment/86961823
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86961832
score: 2
answer count: 1
favorite count: 0
type: Question
has body: When I try to do pip install py2exe it says 'pip' is not recognized as an internal or external command, operable program or batch file. I've tried to add C:\Python364\Scripts and C:\Python364\ to my path or environmental settings. I don't know what to do, I'm on Windows 8.1, Python 3.6.4, If anyone knows whats going wrong it would be appreciated. Thank You!

http://stackoverflow.com/a/50022136
score: 9
has body: You could use the function confusion_matrix from scikit learn. It seems to produce exactly what you're after. from sklearn.metrics import confusion_matrix y_true = [2, 0, 2, 2, 0, 1] y_pred = [0, 0, 2, 2, 0, 2] confusion_matrix(y_true, y_pred)
type: Answer
answers question: http://stackoverflow.com/q/50021928
upvote count: 10
downvote count: 1

http://stackoverflow.com/q/49940684
favorite count: 0
type: Question
tagged with: pipenv
has title: Pinning one package breaks the graph
type: UnansweredQuestion
has body: I am pinning django to a specific, older version: ... [packages] ... Django = "==1.10.8" I can not install: $ pipenv install Could not find a version that matches Django==1.10.8,&gt;=1.11,&gt;=1.6,&gt;=1.7,&gt;=1.8,&gt;=1.8.7 Well, of course, those constraints are mutually exclusive. So I force a install anyway, to take a look at the graph: $ pipenv install --skip-lock And now taking a look at the graph: django-allauth==0.35.0 - Django [required: &gt;=1.11, installed: 1.10.8] - python3-openid [required: &gt;=3.0.8, installed: 3.1.0] - defusedxml [required: Any, installed: 0.5.0] - requests [required: Any, installed: 2.18.4] - certifi [required: &gt;=2017.4.17, installed: 2018.4.16] - chardet [required: &gt;=3.0.2,&lt;3.1.0, installed: 3.0.4] - idna [required: &gt;=2.5,&lt;2.7, installed: 2.6] - urllib3 [required: &gt;=1.21.1,&lt;1.23, installed: 1.22] - requests-oauthlib [required: &gt;=0.3.0, installed: 0.8.0] - oauthlib [required: &gt;=0.6.2, installed: 2.0.7] - requests [required: &gt;=2.0.0, installed: 2.18.4] - certifi [required: &gt;=2017.4.17, installed: 2018.4.16] - chardet [required: &gt;=3.0.2,&lt;3.1.0, installed: 3.0.4] - idna [required: &gt;=2.5,&lt;2.7, installed: 2.6] - urllib3 [required: &gt;=1.21.1,&lt;1.23, installed: 1.22] (this happens with several packages) What should I do now? What I think will solve my issue is: search for all packages which are requiring a version higher than the one I want take a look at the homepages of those packages, and see if I can use an older version with lower requirements, matching my current max requirements for django This seems very cumbersome, and besides seems that is something that could be automatically solved by pipenv. Is there an easier solution than pinning several packages manually? Ideally I would like to pin only django, and let pipenv do the rest.
tagged with: pip
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49941921
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49964393
linked to: http://stackoverflow.com/q/739882
upvote count: 0
type: UnansweredQuestion
has body: I want to apply some statistics on a list of objects of a class. These objects have 6 values (open, high, low, close, volume and timestamp) each. Lets say i want to print a list with just the volume of each object. How can i do this?
downvote count: 2
answer count: 1
tagged with: python
has title: Printing a list of object values out of a list of objects in python
has comment: http://stackoverflow.com/comment/86944906
score: -2
has answer: http://stackoverflow.com/a/49964485
favorite count: 0
type: Question

http://stackoverflow.com/comment/87036374
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50009727
type: Comment
has text: The OP's code expects `chunk_size` to be an integer; as I read this, it would end up a string.

http://stackoverflow.com/q/49963684
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/49965085
has comment: http://stackoverflow.com/comment/86946157
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86943483
duplicate of: http://stackoverflow.com/q/24072790
favorite count: 0
type: Question
has title: Detect keyboard presses in Python 3 on Raspberry Pi
linked to: http://stackoverflow.com/q/24072790
score: 1
linked to: http://stackoverflow.com/q/16044229
downvote count: 1
tagged with: python
has body: I have tried all the ways I can find to detect keypresses in python on Raspberry Pi 3 but I can't get any to work. - I want it to be that when I press Up Arrow my Raspberry Pi robot will move forwards. Thanks Edit - I known this seems like a duplicate as others but others were for windows or Linux, which worked on those platforms because it tried but it didn't work on raspberry pi.
upvote count: 2

http://stackoverflow.com/comment/87111431
type: Comment
has text: I'm pretty sure that the pip is just placing it in a python3.4 folder. Official cx_Oracle documentation says it's compatable with 2.7: https://oracle.github.io/python-cx_Oracle/
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50045458

http://stackoverflow.com/q/50012525
has answer: http://stackoverflow.com/a/50012638
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50012638
has body: I have the following dataframe: import pandas as pd df = pd.DataFrame({'id': [2967, 5335, 13950, 6141, 6169], 'Player': ['Cedric Hunter', 'Maurice Baker', 'Ratko Varda', 'Ryan Bowen', 'Adrian Caldwell'], 'Year': [1991, 2004, 2001, 2009, 1997], 'Age': [27, 25, 22, 34, 31], 'Tm': ['CHH', 'VAN', 'TOT', 'OKC', 'DAL'], 'G': [6, 7, 60, 52, 81]}) df.set_index('Player', inplace=True) It shows: Out[128]: Age G Tm Year id Player Cedric Hunter 27 6 CHH 1991 2967 Maurice Baker 25 7 VAN 2004 5335 Ratko Varda 22 60 TOT 2001 13950 Ryan Bowen 34 52 OKC 2009 6141 Adrian Caldwell 31 81 DAL 1997 6169 How can I sort by the index ('Player') using some arbitrary order? For example, as in the following. reorderlist = ['Maurice Baker', 'Adrian Caldwell', 'Ratko Varda', 'Ryan Bowen', 'Cedric Hunter']
tagged with: categorical-data
tagged with: pandas
downvote count: 0
favorite count: 0
type: Question
score: 39
has answer: http://stackoverflow.com/a/63902171
possible better answer: http://stackoverflow.com/a/63902171
tagged with: indexing
has comment: http://stackoverflow.com/comment/87041660
upvote count: 39
has comment: http://stackoverflow.com/comment/87041435
has answer: http://stackoverflow.com/a/72402855
tagged with: python
answer count: 6
tagged with: sorting
has title: How to sort a pandas dataframe by a custom order on a string index
has answer: http://stackoverflow.com/a/77573957
has answer: http://stackoverflow.com/a/71724446
has answer: http://stackoverflow.com/a/50012559

http://stackoverflow.com/comment/87035015
score: 1
type: Comment
type: QuestionComment
has text: why not sort the list first if you're on a *nix machine? using `parallel` or `xargs` you can chomp through this pretty fast
comment on: http://stackoverflow.com/q/50009125

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/50028608

http://stackoverflow.com/a/49949956
type: Answer
answers question: http://stackoverflow.com/q/49948581
has body: I'm not sure but I don't think there is a tricky way to reverse this behavior because it is coded as so: fmt is processed and put in kw: def _plot_args(self, tup, kwargs): ret = [] if len(tup) &gt; 1 and isinstance(tup[-1], str): linestyle, marker, color = _process_plot_format(tup[-1]) tup = tup[:-1] elif len(tup) == 3: raise ValueError('third arg must be a format string') else: linestyle, marker, color = None, None, None ... kw = {} for k, v in zip(('linestyle', 'marker', 'color'), (linestyle, marker, color)): if v is not None: kw[k] = v Use kw and kwargs to call _makeline: if self.command == 'plot': func = self._makeline else: kw['closed'] = kwargs.get('closed', True) func = self._makefill ... for j in range(max(ncx, ncy)): seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs) ret.append(seg) return ret kwargs overwrite kw in _makeline: def _makeline(self, x, y, kw, kwargs): kw = {**kw, **kwargs} # Don't modify the original kw. default_dict = self._getdefaults(None, kw) self._setdefaults(default_dict, kw) seg = mlines.Line2D(x, y, **kw) return seg It seems that the best way is to "go through the annoying task of determining if the strings in the formats array contains a color" potentially the same way as matplotlib does.
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87144516
comment on: http://stackoverflow.com/a/50049277
score: 0
type: Comment
type: AnswerComment
has text: @Deadmon I've updated the answer with what I think you're going for, lmk if it works for you

http://stackoverflow.com/q/49967935
type: Question
has comment: http://stackoverflow.com/comment/86951630
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49968024
has answer: http://stackoverflow.com/a/49968024
tagged with: python
has body: I want to: Pass a function around, making it receive one argument at first, and then the other later. Here are the details: def SuLQ(g, S, d): sigma = 0 for i in S: sigma += g(d[i]) if sigma &lt;= len(S) and sigma &gt;= 0:#required for DP return sigma + np.random.normal(loc = 0.0,scale = R) else: return 0 def sa_dir(wj, di): if np.dot(wj, di) &lt;= 0: return 1 else: return 0 whole_set = [i for i in xrange(48843)]#[n] two_d_array, targ = predict_on_b() w0 = [ 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0] num_mis_vecs = SuLQ(sa_dir(wj = w0,), whole_set, two_d_array) In the line: num_mis_vecs = SuLQ(sa_dir(wj = w0,), whole_set, two_d_array) I passed the function sa_dir as an argument to SuLQ, while giving sa_dir one argument wj (the direction vector). the other argument for sa_dir is given in the function(where g is another name for sa_dir(wj,di) with argument wj already fixed) SuLQ(g, S, d) when executing sigma += g(d[i]) But it seems that python does not allow this. Here is the error i got. TypeError: sa_dir() takes exactly 2 arguments (1 given) I don't want to hard-code wj into sa_dir because I want to change wj later. Anyone has got suggestions? Thanks in advance. (Just in case you are interested, I am re-implementing a paper's framework using python.) (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.126.209&amp;rep=rep1&amp;type=pdf)
has comment: http://stackoverflow.com/comment/86951667
has title: Python Function fill in one argument at first, then the rest
has comment: http://stackoverflow.com/comment/86959913
upvote count: 2
answer count: 1
score: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87031418
comment on: http://stackoverflow.com/q/50006621
type: QuestionComment
score: 0
has text: As you might have noticed I highlighted the "specific". On SO you can ask questions for specific problems you have encountered while programming. Asking for a whole task to be done is too broad.
type: Comment

http://stackoverflow.com/comment/87033535
type: Comment
has text: @Lemayzeur Added full traceback
type: QuestionComment
comment on: http://stackoverflow.com/q/50007474
score: 0

http://stackoverflow.com/comment/87433464
comment on: http://stackoverflow.com/a/49993518
has text: Now i am getting error , when i execute " os.system("bitbake -g fss-image-full-l100")" . Because , directory is not going inside " poky/build". Please help me in solving this
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87123187
type: AnswerComment
type: Comment
has text: yes. compGuess//2 is the same thing as int(compGuess/2) but it is the more pythonic syntax.
comment on: http://stackoverflow.com/a/50053152
score: 0

http://stackoverflow.com/a/62761109
score: 0
has body: Here is an example for a Vivotek IP8136W IP Camera. It does not support streaming. This code continuously grabs still frames, at about 2fps. No observed CPU loading. import numpy as np import cv2 # for webcams, request stream only once. #cap = cv2.VideoCapture(0) while(True): # For single image IP cams, request frame every time. cap = cv2.VideoCapture("http://root:0002A78D65F2@192.168.1.38/cgi-bin/viewer/video.jpg") ret, frame = cap.read() # Display the resulting frame if ret: cv2.imshow('camera',frame) else: print("error getting frame.") if cv2.waitKey(1) & 0xFF == ord('q'): break # Done. release the capture cap.release() cv2.destroyAllWindows()
type: Answer
answers question: http://stackoverflow.com/q/50058811

http://stackoverflow.com/comment/86915981
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49949611
has text: Did you know that you can save multiple pickles to a single file? `with open(path, 'wb') as f: pickle.dump(obj1, f); pickle.dump(obj2, f); ...`
score: 1

http://stackoverflow.com/comment/93418134
type: AnswerComment
has text: If setting `df.iloc[9,1] = 23` this stops to work if you want to treat each column of the `df` separately. My current workaround is to define a mask function `def masker(df, limit): return (df.isna().groupby([df.notna().cumsum()]).rank(method='max') - 1).gt(limit)` and apply this function along the columns: `mask_df = df_ext.apply(masker, axis=0, args=(limit,))`. I guess this is quite slow for big dataframes. Is there any way I can do this directly without apply?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49944541

http://stackoverflow.com/comment/86957654
type: QuestionComment
has text: OK, a copy-n-paste does hit the limit.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49969861

http://stackoverflow.com/q/49991750
has comment: http://stackoverflow.com/comment/98837639
has comment: http://stackoverflow.com/comment/128486877
upvote count: 6
has comment: http://stackoverflow.com/comment/101462643
tagged with: python
has comment: http://stackoverflow.com/comment/89695016
has comment: http://stackoverflow.com/comment/87034688
tagged with: python-tesseract
has comment: http://stackoverflow.com/comment/89695083
has body: I am using Anaconda Navigator 1.7.0 on windows 10, I have created a virtual environment named "venv" and installed Python version 3.5.2 in that along with selenium, fuzzywuzzy and other modules. Everything works just fine except pytesseract. My python script: import pytesseract from PIL import Image im =Image.open("C:\\Users\\stan\\Desktop\\sample.jpg") text = pytesseract.image_to_string(im, lang ='eng') print(text) I get the below error: Traceback (most recent call last): File "C:\Users\stan\MyPythonScripts\tess11.py", line 1, in &lt;module&gt; import pytesseract ModuleNotFoundError: No module named 'pytesseract' I used pip install to install all modules. Steps taken by me to solve this till now: I installed pytesseract in the virtual env using pip install pytesseract from inside that virtual environment (venv), I looked into the "site-packages" folder (..\Local\Continuum\anaconda3\envs\venv\Lib\site-packages) and I do see that "pytesseract" folder does exist there along with "pytesseract-0.2.0.dist-info". Note that this is also the folder where I can see "selenium" and other modules which run perfectly fine. I installed Pillow just to make sure. I researched online for the same error and found solutions stating that I should pip install pytesseract and also check if pytesseract exists in my "site-packages" of the virtual env which I am trying to run in, both of which steps I have already taken. I have also installed tesseract-OCR version 3.05.01, which is, by default, located in "C:\Program Files (x86)" If I try to run pip install pytesseract again just below the "ModuleNotFoundError", I get the below message: Requirement already satisfied: pytesseract in c:\users\stan\appdata\local\continuum\anaconda3\envs\venv\lib\site-packages (0.2.0) Requirement already satisfied: Pillow in c:\users\stan\appdata\local\continuum\anaconda3\envs\venv\lib\site-packages (from pytesseract) (5.1.0) I have also tried uninstalling pytesseract and manually deleting any file name contain…
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 6
favorite count: 0
type: Question
has title: ModuleNotFoundError: No module named 'pytesseract'
tagged with: python-3.x
tagged with: anaconda

http://stackoverflow.com/q/50023299
has comment: http://stackoverflow.com/comment/87062700
type: UnansweredQuestion
downvote count: 0
has body: Afternoon, Very new to python, but I'm stuck with the following error when trying to use sqlalchemy create_engine and pandas to_sql with Teradata. Error message DatabaseError: (teradata.api.DatabaseError) (0, '[08001] [TPT][ODBC SQL Server Wire Protocol driver]Invalid Connection Data., [TPT][ODBC SQL Server Wire Protocol driver]Invalid attribute in connection string: DBCNAME.') Background I'm reading in some customer identifiers and connecting to a number of Teradata databases to extract some info and put it into pandas data frames, as per sample in section one of the code below. This approach is repeated a number of times and works fine. I now need to insert this data into another Teradata database. As such I would like to use sqlalchmey create_engine and pandas to_sql I have installed "sqlalchemy-teradata" as well The code throws the above error when the “df_name.to_sql… “ line is executed I have read the following, but can’t seem to find how to pass DBCNAME into the connection string, or what’s causing the error I am trying to construct an sqlalchemy engine using a dict which has variables parsed to it from tkinter https://github.com/Teradata/sqlalchemy-teradata/wiki/Examples http://docs.sqlalchemy.org/en/latest/core/engines.html I have Teradata SQL assistant installed which uses the following connection info, below, which I can login to with no problems [ODBC] DRIVER=Teradata UID= abcdef DBCNAME= aaaaa.bbb.ccccccc.co.uk I can also ping the DBCname from the command prompt , which works fine Environment 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] / windows 7 Teradata version 15.10.05.04 # section one import pandas as pd import pyodbc # define my sql string here xref_query = "SELECT A, B,C, "\ "FROM someting "\ "WHERE A= " +sql_param #connect to terdata ** this works fine** #Specify connection string conn = pyodbc.connect(r'DRIVER= {Teradata};DBCName=aaaaa.bbb.ccccccc.co.uk;DATABASE=somthing; Username=abcdef;password=ghijk') …
tagged with: python
has title: Invalid attribute in connection string: DBCNAME. when using create_engine & Pandas to_sql
favorite count: 0
score: 2
answer count: 0
linked to: http://stackoverflow.com/q/31852582
tagged with: pandas
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/87062788
upvote count: 2

http://stackoverflow.com/comment/86941407
type: AnswerComment
has text: @paddu Any specific reason here? You asked for something more "pythonic and performant" and this is both.
comment on: http://stackoverflow.com/a/49962692
type: Comment
score: 3

http://stackoverflow.com/comment/87061099
type: AnswerComment
has text: `C:\Users\asus>python -m tkinter C:\Python36\python.exe: No module named tkinter`
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50012000

http://stackoverflow.com/q/49940099
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86895770
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86895796
has comment: http://stackoverflow.com/comment/86896055
accepted answer: http://stackoverflow.com/a/49940373
type: AnsweredQuestion
downvote count: 2
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86895873
tagged with: opencv
has comment: http://stackoverflow.com/comment/86895951
has title: Python - UnboundLocalError: local variable "ID" referenced before assignment
has comment: http://stackoverflow.com/comment/86895780
type: Question
has body: Id, conf = recognizer.predict(gray[y:y+h,x:x+w] def hour(cn): for z in range(9,17): if now.hour == z: worksheet(cn, str(z)+":00") def identify(number): sht = gc.open("Test") wks3 = sht.worksheet("NAMES") b = wks3.acell('B'+str(number)).value a = wks3.acell('A'+str(number)).value if(Id == a and conf&lt;65): print(Id, conf) Id = str(b) Time = time.ctime() hour(number) elif(conf&gt;64): print(conf) Id = "Unknown" for m in range(2,100): identify(m) The above code is being used for facial recognition, I copied what I felt was necessary, it is not the entire code. I'm trying create a function which I want to call back in a for loop What am I doing wrong? I've been looking t this for 6 hours now, and anything I try doesn't seem to work. I get a message back saying "UnboundLocalError: local variable 'Id' referenced before assignment" It's impossible because I'm assigning with: a = wks3.acell('A'+str(number)).value So it grabs the ID number from the google spread sheet and checks if it is equaled to that, can someone tell me where I'm going wrong here?
has comment: http://stackoverflow.com/comment/86895808
has answer: http://stackoverflow.com/a/49940373

http://stackoverflow.com/q/49948868
score: 0
answer count: 1
tagged with: jupyter
tagged with: ipython
type: Question
tagged with: compiler-errors
tagged with: theano
has title: Theano error: no matching function for call to ‘batch_gemm<float>
type: UnansweredQuestion
tagged with: python
has body: I'm trying to launch some Python projects which I need for my bachelor thesis and they use theano. The problem is, that one of the cell compiles these functions and fails with following compiler error: https://pastebin.com/TunvSwWU That's the piece of code which causes that: params_to_optimize = [W_mean,U_mean,b_mean,softmax_W_mean,softmax_b_mean,h0_mean, var_log_sigma] train_fn = theano.function([X_tensor1, X_tensor2, Mask_matrix1, Mask_matrix2, Y_vector], cost, updates=lasagne_adagrad(cost, params_to_optimize, learning_rate=lr), on_unused_input='ignore' ) predict_fn = theano.function([X_tensor1, X_tensor2, Mask_matrix1, Mask_matrix2], output, on_unused_input='ignore') The strangest thing is that in other notebook I have this code and it compiles just fine: train_fn = theano.function([X_tensor1, X_tensor2, Mask_matrix1, Mask_matrix2, Y_vector], cost, updates=lasagne_adagrad(cost, [W,U,h0,b,softmax_W,softmax_b], learning_rate=lr), on_unused_input='ignore' ) predict_fn = theano.function([X_tensor1, X_tensor2, Mask_matrix1, Mask_matrix2], output, on_unused_input='ignore') I'm not really experienced theano user and right now just try to run this code before digging into it. What can be the problem? Update: It may have some problems with cost function which is this in compile-error case: softmax_cost = -T.sum(T.log(output)[T.arange(Y_vector.shape[0]), Y_vector])*X_train1.shape[0]/X_tensor1.shape[0] all_param_mean = [W_mean.flatten(),U_mean.flatten(), h0_mean.flatten(), b_mean.flatten(),softmax_W_mean.flatten(),softmax_b_mean.flatten()] all_param_tensor = T.concatenate(all_param_mean) first_part = T.exp(2*var_log_sigma)/T.exp(2*prior_log_sigma) second_part = T.dot(prior_mu- all_param_tensor,(prior_mu-all_param_tensor).T)/T.exp(2*prior_log_sigma) third_part = -np.sum([len(i.eval()) for i in all_param_mean]) fourth_part = 2*prior_log_sigma - 2*var_log_sigma KLD = 0.5* (first_part + second_part + third_part + fourth_part) cost = softmax_cost + KLD And this in compiling case…
has answer: http://stackoverflow.com/a/49967895

http://stackoverflow.com/a/69843136
type: Answer
answers question: http://stackoverflow.com/q/49945576
has body: This error can occur if you specify a custom MIGRATION_MODULES entry that points to a path that does not contain a __init__.py.
score: 0

http://stackoverflow.com/q/49966671
answer count: 1
favorite count: 0
type: Question
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has title: How to properly line-wrap a django statement to satisfy flake8?
downvote count: 0
tagged with: flake8
has answer: http://stackoverflow.com/a/49966774
has body: This code gets E501 line too long (85 &gt; 79 characters) from flake8: qobjs &amp;= Q( latest_visit__visitstatistics__worst_zscore__gte=worst_zscore_min_filter) This code gets E251 unexpected spaces around keyword / parameter equals: qobjs &amp;= Q( latest_visit__visitstatistics__worst_zscore__gte= worst_zscore_min_filter) What is the right thing to satisfy flake8? EDIT: I ended up telling flake8 to ignore with noqa. I thought it didn't work, but I just had to read the docs more carefully.
accepted answer: http://stackoverflow.com/a/49966774

http://stackoverflow.com/comment/87147210
type: Comment
has text: I think you better should have a list of dictionary with one dictionary for each product like this : product_list = [ {'Name': 'Milk, 2 Litres', 'Price': '2.0', 'weight': '2',}, {'Name': 'Bread', 'Price': '3.5', 'weight': '0.6'} ]
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50064510

http://stackoverflow.com/comment/87112543
comment on: http://stackoverflow.com/a/50044983
score: 0
type: AnswerComment
type: Comment
has text: Hi Haggi, no its not deleted yet, because its a button, and myDic will be on the memmory until the function was finished (when i clouse the program) so i could call it again and again... btw thanks Haggi

http://stackoverflow.com/q/50010434
downvote count: 0
favorite count: 0
type: Question
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50010925
has title: python pandas function return multiple values and put them into columns
tagged with: python
has body: i have two functions as below. The second one works but the first one doesn't work. Why? import pandas as pd df = pd.DataFrame(data = {'a': [1, 2, 3], 'b': [4, 5, 6]}) def add_subtract_list(a, b): return [1,2,3,4] add_subtract_list(5,8) df'c','d','x','y' = df.apply( lambda row: add_subtract_list(row['a'], row['b']), axis=1) below function works. It is from this page import pandas as pd df = pd.DataFrame(data = {'a': [1, 2, 3], 'b': [4, 5, 6]}) def add_subtract_list(a, b): return [a + b, a - b] df'sum', 'difference' = df.apply( lambda row: add_subtract_list(row['a'], row['b']), axis=1)
tagged with: return-value
tagged with: pandas
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/50011830
answer count: 1

http://stackoverflow.com/a/50027139
downvote count: 0
score: 1
upvote count: 1
has body: itertools.accumulate is the way to go, but if you're wondering how you could do it on your own, here's one way def apply_all (x, f = None, *fs): if f is None: return [] else: next = f (x) return [ next ] + apply_all(next, *fs) funcs = \ [ lambda x: x , lambda x: x+3 , lambda x: x+5 , lambda x: x+1 ] print(apply_all(8, *funcs)) # [ 8, 11, 16, 17 ] If you need the form in your original question def apply_all (fs, x): if not fs: return [] else: next = fs[0](x) return [ next ] + apply_all(fs[1:], next) funcs = \ [ lambda x: x , lambda x: x+3 , lambda x: x+5 , lambda x: x+1 ] print(apply_all(funcs, 8)) # [ 8, 11, 16, 17 ] The above form operates on fs[0] and fs[1:] which shows this can be expressed as a vanilla reduce from functools import reduce def apply_all (fs, x): def reducer (acc, f): (seq, x) = acc next = f (x) return (seq + [next], next) return reduce(reducer, fs, ([], x)) [0] funcs = \ [ lambda x: x , lambda x: x+3 , lambda x: x+5 , lambda x: x+1 ] print(apply_all(funcs, 8)) # [ 8, 11, 16, 17 ]
type: Answer
answers question: http://stackoverflow.com/q/50011450

http://stackoverflow.com/comment/87123890
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
comment on: http://stackoverflow.com/q/50053629
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/49985726
tagged with: selenium
tagged with: webdriver
has comment: http://stackoverflow.com/comment/86988430
type: Question
linked to: http://stackoverflow.com/q/9567069
type: UnansweredQuestion
has title: Selenium, Firefox, Error checking if an ID is on a page?
has comment: http://stackoverflow.com/comment/86988386
tagged with: python
has body: sorry if this is kind of vague I do not know how to explain it well but basically I am trying to run a function which checks if an ID is on a page and I do not know how to do it. Here is my code of what I've attempted so far. def checkoutpage(): driver1.find_element_by_id('test') try: if checkoutpage == True: print("Working") else: print("Not working") except: print("ERROR") It returns Not working not matter if the ID is on the page or not, help is appreciated.
linked to: http://stackoverflow.com/q/45695874
score: 0
answer count: 0
tagged with: firefox

http://stackoverflow.com/comment/87143587
comment on: http://stackoverflow.com/a/50050579
score: 0
type: AnswerComment
has text: In the for loop where you construct dict_2, overwrite the previous entry with newer one.
type: Comment

http://stackoverflow.com/a/49995099
has comment: http://stackoverflow.com/comment/87007174
has body: Give you a Django FileField way Implemention: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_&lt;id&gt;/&lt;filename&gt; suffix = filename[filename.rindex(".")+1:] return 'upfiles/{0}/{1}.{2}'.format(instance.user.username, get_randomfilename(),suffix) class Picture(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) file = models.ImageField(upload_to=user_directory_path) date_added = models.DateTimeField(auto_now_add=True) @parser_classes((MultiPartParser,)) @permission_classes((IsAuthenticated, )) def upload_picture(request): ''' :input :{"file":f} :return:{"id":pictureId} ''' if "file" in request.FILES: f = request.FILES["file"] picture = Picture() picture.user= request.user picture.file = f picture.save() return Response(data={"id":picture.id}) else: return Response({},status=status.HTTP_400_BAD_REQUEST)
has comment: http://stackoverflow.com/comment/87007073
type: Answer
has comment: http://stackoverflow.com/comment/87006568
has comment: http://stackoverflow.com/comment/87006897
answers question: http://stackoverflow.com/q/49995017
score: 0
has comment: http://stackoverflow.com/comment/87006486
has comment: http://stackoverflow.com/comment/87007901

http://stackoverflow.com/comment/86989019
has text: In case the problem with JSON libraries is that the JSON is embedded in a larger document like a webpage and you don't know how to parse only the JSON, check out https://github.com/alexmojaki/jsonfinder
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49985863

http://stackoverflow.com/comment/86949251
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49966217
has text: If I want to replace only one label in the nested array how to use it?
type: Comment

http://stackoverflow.com/comment/87042744
type: Comment
comment on: http://stackoverflow.com/q/50013117
type: QuestionComment
score: 0
has text: Yea since this is on their ftp server you should be able to list all the files in that directory. Then you could get the latest or get the one that starts with `StormEvents` or however you wanted to do it

http://stackoverflow.com/comment/87001348
has text: check your python version first!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49972980
type: Comment

http://stackoverflow.com/q/49952618
score: 0
has comment: http://stackoverflow.com/comment/86922206
has comment: http://stackoverflow.com/comment/86921888
tagged with: models
has body: I have run done these: delete all files under migrations (except init) 2. python manage.py makemigrations python manage.py migrate and even python manage.py migrate --run-syncdb delete db.sqlite3 Thankfully, it solved the problem. However, I had to do step 3 to solve this. How do you solve this problem without deleting the database since I can't afford to do such later on when I already have too much data? Or what causes this problem? Thanks EDIT: Error is OperationalError - no such table
tagged with: database
has comment: http://stackoverflow.com/comment/86922013
tagged with: sqlite
has comment: http://stackoverflow.com/comment/86921915
has title: How to solve OperationalError without deleting the db - django 2.0
type: Question
has comment: http://stackoverflow.com/comment/86921864
answer count: 0
has comment: http://stackoverflow.com/comment/86921804
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86921829
has comment: http://stackoverflow.com/comment/86921841
has comment: http://stackoverflow.com/comment/86921801

http://stackoverflow.com/q/49954037
possible better answer: http://stackoverflow.com/a/49954176
score: -2
linked to: http://stackoverflow.com/q/5278122
tagged with: python
has answer: http://stackoverflow.com/a/49954198
has comment: http://stackoverflow.com/comment/86924802
has comment: http://stackoverflow.com/comment/86924647
type: AnsweredQuestion
has title: Check all elements are different in the list in python
downvote count: 3
has comment: http://stackoverflow.com/comment/86924860
upvote count: 1
accepted answer: http://stackoverflow.com/a/49954198
has comment: http://stackoverflow.com/comment/86924950
has comment: http://stackoverflow.com/comment/86924662
duplicate of: http://stackoverflow.com/q/5278122
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86924680
has body: I have to find all list elements are equal. I have used below code: all(x == list[0] for x in list) Now I have to find all list values are different. Please help me how to achieve this. List = ['a', 'b', 'x', 'y'] Expected Output: True List = ['a', 'a', 'x', 'y'] Expected Output: False List = ['a', 'a', 'a', 'a'] Expected Output: False Tried below code: list = ["aa", "bb", "bb"] len(set(list)) != 1 output: will result True. I am expecting False, reason bb is same elements repeated
has comment: http://stackoverflow.com/comment/86924643
answer count: 2
has answer: http://stackoverflow.com/a/49954176

http://stackoverflow.com/q/50039500
has comment: http://stackoverflow.com/comment/87097637
favorite count: 0
type: Question
has body: Saving a Pandas dataframe to gzipped csv in memory works like this in Python 2.7 (Pandas 0.22.0): from io import BytesIO import gzip import pandas as pd df = pd.DataFrame.from_dict({'a': ['a', 'b', 'c']}) s = BytesIO() f = gzip.GzipFile(fileobj=s, mode='wb', filename='file.csv') df.to_csv(f) s.seek(0) content = s.getvalue() However, in Python 3.6 (Pandas 0.22.0), the same code throws error when calling to_csv: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "lib/python3.6/site-packages/pandas/core/frame.py", line 1524, in to_csv formatter.save() File "lib/python3.6/site-packages/pandas/io/formats/format.py", line 1652, in save self._save() File "lib/python3.6/site-packages/pandas/io/formats/format.py", line 1740, in _save self._save_header() File "lib/python3.6/site-packages/pandas/io/formats/format.py", line 1708, in _save_header writer.writerow(encoded_labels) File "miniconda3/lib/python3.6/gzip.py", line 260, in write data = memoryview(data) TypeError: memoryview: a bytes-like object is required, not 'str' How should I resolve this? Do I need to alter the GzipFile object somehow for to_csv to handle it properly? To clarify, I want to create the gzipped file in-memory (the content variable) so that I can save it to Amazon S3 using Boto 3 put_object later.
answer count: 2
type: UnansweredQuestion
downvote count: 0
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/68556677
upvote count: 6
has title: Pandas to_csv to GzipFile in Python 3 not working
has answer: http://stackoverflow.com/a/51522682
tagged with: pandas

http://stackoverflow.com/q/50052077
favorite count: 0
has comment: http://stackoverflow.com/comment/87120623
type: Question
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/50052224
possible better answer: http://stackoverflow.com/a/50052224
has title: What does .start() function do in Python?
downvote count: 7
has answer: http://stackoverflow.com/a/50052120
tagged with: python
has comment: http://stackoverflow.com/comment/87120677
answer count: 2
has comment: http://stackoverflow.com/comment/87120792
has body: What does .start() do in the following script? import re str2 = re.search("\((\w+)\)", str1) return str1[:str2.start()].strip()
score: -2
accepted answer: http://stackoverflow.com/a/50052120
has comment: http://stackoverflow.com/comment/87261842
has comment: http://stackoverflow.com/comment/129397118

http://stackoverflow.com/q/50030416
tagged with: python-3.x
answer count: 1
downvote count: 0
has body: I'm trying to send a python dictionary, using something like: import zmq context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:%s" % port socket.send_pyobj({'hello':'world'}) and receive it using: socket.connect ("tcp://localhost:%s" % port) topicfilter = "1" socket.setsockopt_string(zmq.SUBSCRIBE, topicfilter) while True: print(socket.recv_pyobj()) Questions: I can't seem to figure out how to set the topic for send_pyobj(). Needless to say, I don't receive anything on the other end. I managed to get it going with strings and send_string(), so it's definitely connecting. What am I doing wrong? Can I have many PUB servers broadcasting? Thereby creating a sort of many-to-many, where other apps can dip into the flow?
favorite count: 0
has answer: http://stackoverflow.com/a/50032682
accepted answer: http://stackoverflow.com/a/50032682
has title: How do I send a dict with the PUB/SUB pattern using pyzmq?
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: pyzmq
tagged with: zeromq
tagged with: python
type: Question

rss
type: Tag
tags question: http://stackoverflow.com/q/49971496
tag name: rss

http://stackoverflow.com/comment/87073738
type: Comment
comment on: http://stackoverflow.com/a/50028789
type: AnswerComment
has text: If you think your solution is unique enough or more *up-to-date*, you should add it to the duplicate linked to in the question.
score: 0

http://stackoverflow.com/comment/86920090
comment on: http://stackoverflow.com/q/49951828
type: QuestionComment
score: 1
has text: Is your expected output supposed to be a dictionary?
type: Comment

http://stackoverflow.com/comment/87048126
score: 0
has text: @HannahLee - What is expected output if `KS Equity` and `JP Equity` ? 3 columns?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50015713

http://stackoverflow.com/a/56852354
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49949775
has body: Go into the directory: ~/miniconda3/lib/python3.7/site-packages/pybinding/support In the file: collections.py change line 2: from matplotlib.collections import Collection, allow_rasterization to from matplotlib.collections import Collection from matplotlib.artist import allow_rasterization

http://stackoverflow.com/comment/86913210
type: AnswerComment
has text: You're welcome! My suggestion is to read a whole python book and then things will start to make sense :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49948010

http://stackoverflow.com/comment/87021911
type: Comment
has text: How to specify for Class-0 randomly or class-1 because sample method does not have that
type: QuestionComment
comment on: http://stackoverflow.com/q/50002579
score: 0

http://stackoverflow.com/comment/87092241
type: Comment
has text: @khelwood. Thanks. I did not think of that.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50038021

http://stackoverflow.com/q/49973586
answer count: 0
tagged with: machine-learning
type: UnansweredQuestion
tagged with: scikit-learn
type: Question
has comment: http://stackoverflow.com/comment/86965640
has comment: http://stackoverflow.com/comment/86965202
tagged with: python
has title: Why does MinMaxScaler fail with integers?
has comment: http://stackoverflow.com/comment/86963626
has body: This looks handy for pre-fixing data: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0,1)) scaler.fit_transform([[x] for x in [1,2,3]]) # gives [0, 0, 0] and it gives all zeros, no errors or warnings!? Changing to 1.0,2.0,3.0 makes it output the expected 0, .5, 1 scaled values.
has comment: http://stackoverflow.com/comment/86969670
has comment: http://stackoverflow.com/comment/86966131
score: 0

http://stackoverflow.com/comment/87016019
comment on: http://stackoverflow.com/q/49999623
score: 0
has text: Can you post how and what are you sending to the Pulsar server?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87081437
type: AnswerComment
comment on: http://stackoverflow.com/a/50030845
has text: In this case, you would keep track of the answers you get for each combination of input values -- that's called "memoizing". Then, if a branch of recursion gets you to a combination you've already computed, you find that in your memo table and return the stored value instead of repeating the computation.
score: 0
type: Comment

http://stackoverflow.com/q/50041315
tagged with: django
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50042903
upvote count: 1
score: 1
tagged with: python
has title: Django: TruncYear and annotate/aggregate?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50042903
has body: I'm having the following model: class Order(models.Model): placed_at = models.DateTimeField() amount = models.DecimalField() And I want to know the total of amount for each year. When running: Order.objects.annotate(year=TruncYear('placed_at')) .values('year') .annotate(total=Sum('amount')) Django returns a queryset with the year and total for every record in the database (so total == amount). When using aggregate: Order.objects.annotate(year=TruncYear('placed_at')) .values('year') .aggregate(total=Sum('amount')) Django returns the grand total ({'total': Decimal('72822.41')}). The result I'm looking for should be the total broken down per year. Like &lt;QuerySet [{'year': 2016, 'total': Decimal('20000.00')}, {'year': 2017, 'total': Decimal('30000.00')}] Any idea what I'm overlooking here?
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87034739
type: AnswerComment
has text: Thanks a lot! nextafter seems exactly what I was looking for. Out of curiosity, do you know why someone downvoted my question? I thought it was clear and pertinent...
comment on: http://stackoverflow.com/a/50005057
score: 0
type: Comment

http://stackoverflow.com/q/49955629
has answer: http://stackoverflow.com/a/49958397
tagged with: selenium
accepted answer: http://stackoverflow.com/a/49958576
downvote count: 1
linked to: http://stackoverflow.com/q/33225947
favorite count: 0
has answer: http://stackoverflow.com/a/49958576
type: Question
has comment: http://stackoverflow.com/comment/86929523
has comment: http://stackoverflow.com/comment/86927808
score: 1
tagged with: geckodriver
tagged with: python
has title: Website detects selenium webdriver
has body: I was creating an automation login to enter this site using selenium an everything was normal until yesterday(only appear a icon in the tab and a blank browser page)...i can load all other sites, but not this through selenium..using this: from selenium import webdriver url="https://www.eurobic.pt/" driver=webdriver.Firefox() driver.get(url) don't work. I have read this article and maybe this is the reason, they can detect the webdriver or simply put me on blacklist.How can i load the site again through selenium?
tagged with: webdriver
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49958397
upvote count: 2

http://stackoverflow.com/a/49917891
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49917743
has body: Is this what you aim for: a = '''38 186 298 345 0.93345 27 198 277 389 0.86006 33 127 293 354 0.89782''' b = [line.split() for line in a.split('\n')] b #[['38', '186', '298', '345', '0.93345'], # ['27', '198', '277', '389', '0.86006'], # ['33', '127', '293', '354', '0.89782']]
score: 0
has comment: http://stackoverflow.com/comment/86851580
type: Answer
accepted answer of: http://stackoverflow.com/q/49917743
has comment: http://stackoverflow.com/comment/86851422

http://stackoverflow.com/a/49950224
has comment: http://stackoverflow.com/comment/86958688
type: Answer
has body: You seem to have ruled it out, but I suspect https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor, or https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor would work, if you are able to move to Python 3, or add a dependency for Python 2. If the extra work from each file doesn't have to be triggered until that file is processed, you can have a single coordinating thread that triggers all the others, and so deadlock can be prevented, as in below example. from concurrent.futures import ThreadPoolExecutor import time pool = ThreadPoolExecutor(max_workers=3) def find_work_inputs(dummy_file): print("{}: Finding work...".format(dummy_file)) time.sleep(1) work = range(0, dummy_file) print("{}: Work is {}".format(dummy_file, work)) return work def do_work(dummy_file, work_input): print("{}: {}".format(dummy_file, work_input)) print("{}: Doing work {}...".format(dummy_file, work_input)) time.sleep(1) return work_input * work_input dummy_files = [1,2,3,4,5] futures = [] for dummy_file in dummy_files: work_inputs = pool.submit(find_work_inputs, dummy_file) for work_input in work_inputs.result(): result = work_input futures.append((dummy_file, result, pool.submit(do_work, dummy_file, result))) for dummy_file, work_input, future in futures: print("Result from file:{} input:{} is {}".format(dummy_file, work_input, future.result())) Alternatively, if each thread on the first level needs to trigger the work themselves, the extra work may need to be in another pool to prevent deadlock (depending on when result() is called on each future) as below. from concurrent.futures import ThreadPoolExecutor import time find_work_pool = ThreadPoolExecutor(max_workers=3) do_work_pool = ThreadPoolExecutor(max_workers=3) def find_work_inputs(dummy_file): print("{}: Finding work...".format(dummy_file)) time.sleep(1) work = range(0, dummy_file) print("{}: Work is {}".format(dummy_file, work)) futures = [] for work_input in work: futures.append((dummy_f…
answers question: http://stackoverflow.com/q/49947935
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49947935

http://stackoverflow.com/a/49988504
score: 1
upvote count: 1
has body: Your form is submitting directly to the view profile page. But that page is presumably not expecting to validate a form. You need to submit it back to the update_profile page, which you normally do by using an action of just "." in the form HTML element. &lt;form method="POST" action="."&gt; Once you've done that, you'll see some issues with your form save() method. That method does not do anything useful anyway; you should remove it and let the superclass one be called automatically.
answers question: http://stackoverflow.com/q/49988421
has comment: http://stackoverflow.com/comment/86994022
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86996107
type: AnswerComment
comment on: http://stackoverflow.com/a/49985059
has text: I had to add the following before I created the divisor - by default cums had index of 0. cums = cums.reset_index(drop=True)
type: Comment
score: 0

http://stackoverflow.com/q/50010858
has comment: http://stackoverflow.com/comment/87040508
has answer: http://stackoverflow.com/a/50011009
has answer: http://stackoverflow.com/a/50010935
type: Question
tagged with: python-3.x
has title: Search and replace previous line python
has answer: http://stackoverflow.com/a/50010978
upvote count: 0
has comment: http://stackoverflow.com/comment/87038332
downvote count: 1
possible better answer: http://stackoverflow.com/a/50010978
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
has body: In a file I have the following text: xxxxxx PCTFREE 10 INITRANS 8 MAXTRANS 255 STORAGE ( BUFFER_POOL DEFAULT ), ) I am trying to search for line that startswith(")") and remove the "," from the previous line.
answer count: 3
accepted answer: http://stackoverflow.com/a/50011009
tagged with: python
score: -1

http://stackoverflow.com/a/50054783
upvote count: 2
type: Answer
has body: Here's a simple example that explains the patterns you're seeing Suppose you have 4 people with 4 empty glasses of water in front of them. Think of get() as "Finish drinking the water in your glass, i'm going to wait until you do before moving on". Think of apply_async as being "I'm going to fill up your glass, start drinking but I'm moving on". So what happens: count == 1 We fill person A's glass and they're drinking slowly We wait for person B to finish their cup, it's already empty, we move on count == 2 We fill person B's glass and they're drinking slowly We wait for person C to finish their cup, it's already empty, we move on ... count == 4 We fill person D's glass and they're drinking slowly We wait for person A to finish their cup OK so suppose A takes 30 seconds to finish their water but only takes us 5 seconds to do the steps above. We're now going to be waiting 25 seconds for A to finish their drink before we move on. But with all that waiting time, person B, C and D also finished their drink, so once A is done, we zoom through the next 3 people, until we get back to A again.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50054527

http://stackoverflow.com/comment/86996543
has text: First, NaN is only for floats, not ints. But since all but the last row in your YAML have floats anyway, that seems like an even bigger problem. Second, you need to show us the code that reads this YAML and generates an array out of it before we can debug it for you.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49989805

http://stackoverflow.com/comment/86920442
type: QuestionComment
comment on: http://stackoverflow.com/q/49951994
has text: please provide a full, running example. It's hard to help if we cannot even run the code.
score: 2
type: Comment

http://stackoverflow.com/q/50016048
has comment: http://stackoverflow.com/comment/87104189
has title: Django channels 2 with selenium test failed
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45715996
has comment: http://stackoverflow.com/comment/87072199
tagged with: django-channels
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/50062173
has answer: http://stackoverflow.com/a/50062173
has comment: http://stackoverflow.com/comment/87067303
has comment: http://stackoverflow.com/comment/87086253
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
answer count: 1
tagged with: selenium
has body: I am trying to follow Django channels tutorial. I was able to implement chat functionality as discribed here. But unittests completly copy pasted from this page failed with following error AttributeError: Can't pickle local object 'DaphneProcess.__init__.&lt;locals&gt;.&lt;lambda&gt;'. Full traceback: Traceback (most recent call last): File "C:\Users\user\PycharmProjects\django_channels_test\venv35\lib\site-packages\django\test\testcases.py", line 202, in __call__ self._pre_setup() File "C:\Users\user\PycharmProjects\django_channels_test\venv35\lib\site-packages\channels\testing\live.py", line 42, in _pre_setup self._server_process.start() File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\context.py", line 212, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\context.py", line 313, in _Popen return Popen(process_obj) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__ reduction.dump(process_obj, to_child) File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\reduction.py", line 59, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'DaphneProcess.__init__.&lt;locals&gt;.&lt;lambda&gt;' My consumer class: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from W…
has comment: http://stackoverflow.com/comment/87066829
has comment: http://stackoverflow.com/comment/87128214

http://stackoverflow.com/comment/87050077
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50016231
has text: Same as Vasilis. Are you running this code in an unusual environment that does weird things with builtins, like pycharm's PyDev console?
type: QuestionComment

http://stackoverflow.com/q/49991670
tagged with: pandas
tagged with: date-range
favorite count: 0
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: time-series
has body: I want to turn data imported into python through a .csv file to time-series. GDP = pd.read_csv('GDP.csv') [87]: GDP Out[87]: GDP growth (%) 0 0.5 1 -5.2 2 -7.9 3 -9.1 4 -10.3 5 -8.8 6 -7.4 7 -10.1 8 -8.4 9 -8.7 10 -7.9 11 -4.1 Since data imported through a .csv file are into a DataFrame format, I first tried turning them into pd.Series: GDP2 = pd.Series(data = GDP, index = pd.date_range(start = '01-2010', end = '01-2018', freq = 'Q')) But what I got looked like this: GDP2 Out[90]: 2010-03-31 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2010-06-30 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2010-09-30 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2010-12-31 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2011-03-31 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2011-06-30 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2011-09-30 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2011-12-31 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2012-03-31 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2012-06-30 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2012-09-30 (G, D, P, , g, r, o, w, t, h, , (, %, )) 2012-12-31 (G, D, P, , g, r, o, w, t, h, , (, %, )) The same happened when I tried to do that through a pd.DataFrame: GDP2 = pd.DataFrame(data = GDP, index = pd.date_range(start = '01-2010', end = '01-2018', freq = 'Q')) GDP2 Out[92]: GDP growth (%) 2010-03-31 NaN 2010-06-30 NaN 2010-09-30 NaN 2010-12-31 NaN 2011-03-31 NaN 2011-06-30 NaN 2011-09-30 NaN 2011-12-31 NaN 2012-03-31 NaN 2012-06-30 NaN 2012-09-30 NaN Or when I tried this through the use of reindex(): dates = pd.date_range(start = '01-2010', end = '01-2018', freq = 'Q') dates Out[100]: DatetimeIndex(['2010-03-31', '2010-06-30', '2010-09-30', '2010-12-31', '2011-03-31', '2011-06-30', '2011-09-30', '2011-12-31', '2012-03-31', '2012-06-30', '2012-09-30', '2012-12-31', '2013-03-31', '2013-06-30', '2013-09-30', '2013-12-31', '2014-03-31', '2014-06-30', '2014-09-30', '2014-12-31', '2015-03-31', '2015-06-30', '2015-09-30', '2015-12-31', '2016-03-31', '2016-06-30', '2016-09-30…
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49991899
accepted answer: http://stackoverflow.com/a/49991899
tagged with: python
has answer: http://stackoverflow.com/a/49991867
possible better answer: http://stackoverflow.com/a/49991867
type: Question
answer count: 2
has title: How can I turn data imported into python from a csv file to time-series?
downvote count: 0

http://stackoverflow.com/comment/86908822
comment on: http://stackoverflow.com/q/49945938
has text: @jpp yes, sorry, I've included an example. The problem is generalizable though - how do you extract a defined list of rows defined by some logical criteria for each row in the data frame efficiently? I just don't know the best pattern.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50063010
has body: I want to read out the newest E-Mail in the inbox, select the attachment out of it and move the E-Mail to a folder. I already have a code to save the attachment: from exchangelib import Credentials, Account import os credentials = Credentials('test.name@mail.com', 'password') account = Account('test.name@mail.com', credentials=credentials, autodiscover=True) for item in account.inbox.all().order_by('-datetime_received')[:1]: for attachment in item.attachments: fpath = os.path.join("C:/destination/path", attachment.name) with open(fpath, 'wb') as f: f.write(attachment.content) But I have a problem to move the E-Mail to another folder than the inbox. So far I only found this option: item.move(to_folder) But I don`t know how I should write in the name of the folder. Could anyone give me an example for this? Thanks in advance.
type: UnansweredQuestion
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/75443107
answer count: 2
score: 5
downvote count: 0
tagged with: exchangelib
favorite count: 0
has title: Exchangelib: Moving Email from Inbox to Folder
type: Question
has answer: http://stackoverflow.com/a/50066408

http://stackoverflow.com/comment/87361944
type: Comment
type: AnswerComment
has text: @Axil I do believe that if you search the PayPal documentation carefully you will find a solution. In case you don't find what you are looking for, you can create a new question here on SO detailing your problem. I am suggesting this to you because asking multiple questions in a single post (or in the comments) is not a good SO practice.
score: 0
comment on: http://stackoverflow.com/a/50018563

http://stackoverflow.com/q/50004404
has comment: http://stackoverflow.com/comment/87025270
has answer: http://stackoverflow.com/a/50004502
tagged with: python
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: 0
answer count: 1
has title: exclude duplicate lines before downloading in the list(Python3)
has body: I have code that loads information into the list U_INSERT from web pages. The web page contains a table, data from the table I extract using pandas for example 3 url addresses that contain strings: url 1: [[55323600, '1234_MB] ,[55323601, '1582_MB]] url 2: [[55323602, '1245_MB] ,[55323603, '1579_MB]] url 3: [[55323602, '1245_MB] ,[55323603, '1579_MB]] I wrote this but this is not the best way to exclude duplicate lines: RESULTU = [] #contains a list of url-addresses U_INSERT = [] #data from web pages for ind,val in enumerate(RESULTU): df = pd.read_html(val,header=0)[0] df = df.as_matrix().tolist() for i in df: U_INSERT.append(i) print (list(set(U_INSERT))) I'm looking for a way to check if the line was previously loaded into the list U_INSERT, then do not download it and go to the next url address.

http://stackoverflow.com/a/50029720
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Let's try pulling this out of a loop and see what happens. Your lambda x: x(i) is calling each function with the argument i and map (roughly) turns this into a list. list(map(lambda x: x(0), funcs)) -&gt; [0,0] This is the same as saying: [multiply(0), add(0)]. If we try again with 1: list(map(lambda x: x(0), funcs)) -&gt; [1,2] This is the same as saying: [multiply(1), add(1)]. The function that you are applying, the first argument to map, is your lambda. That happens to be a higher order function that returns the result of it's input. A similar way to rewrite this program would be: def multiply_and_add(i): return [multiply(i), add(i)] result = map(multiply_and_add, range(5)) for value in result print(value)
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50029585
answers question: http://stackoverflow.com/q/50029585

http://stackoverflow.com/comment/86880915
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49932343
has text: But seriously, a loop implies at least the possibility of multiple iterations, while a `try` block defines exactly what you want: a sequence of instructions that might be interrupted as various points.

attributes
tags question: http://stackoverflow.com/q/49919768
tag name: attributes
tags question: http://stackoverflow.com/q/50024737
type: Tag
tags question: http://stackoverflow.com/q/49966492

http://stackoverflow.com/comment/86944171
has text: Ah i know why. I had a syntax issue Thank you.
comment on: http://stackoverflow.com/q/49963872
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87142653
has text: thank you, can you explain more about the virtual env?
comment on: http://stackoverflow.com/a/50018487
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87144005
has text: ok, say you had a normal code of line just like, how would you then split that??? just a single line of code Line 1: ['"Jane, I don\'t like cavillers or questioners', ' besides, there is something truly forbidding in a child taking up her elders in that manner.']
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50063194

http://stackoverflow.com/comment/86881263
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49924561
has text: Thanks a lot for @Divakar 's answer.
type: QuestionComment

http://stackoverflow.com/comment/86931273
has text: Any function that is bijective.
score: 0
comment on: http://stackoverflow.com/q/49957573
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50067315
has comment: http://stackoverflow.com/comment/87151193
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87151144
has comment: http://stackoverflow.com/comment/87151370
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/50067550
has answer: http://stackoverflow.com/a/50067550
tagged with: wget
downvote count: 0
linked to: http://stackoverflow.com/q/20227324
tagged with: python-requests
has comment: http://stackoverflow.com/comment/87151262
has title: difference between wget and requests.get with respect to file download
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50067476
has comment: http://stackoverflow.com/comment/87152158
has answer: http://stackoverflow.com/a/50067476
upvote count: 5
tagged with: python
has body: I have an weird error. There's a file on dropbox which i'm downloading with the following python code: import requests import shutil url = 'https://www.dropbox.com/s/fgyso9fq40qp1vl/testfiles.tar.gz?dl=0' r = requests.get(url, stream=True) path_to_save = "/tmp/data.dload-1" with open(path_to_save, 'wb') as f: shutil.copyfileobj(r.raw, f) this downloads to /tmp/data.dload-1. same file downloaded with wget wget https://www.dropbox.com/s/fgyso9fq40qp1vl/testfiles.tar.gz?dl=0 -O /tmp/data.dload-2 these two files have the same type: (dl)x:x$ file /tmp/data.dload-1 /tmp/data.dload-1: gzip compressed data, from Unix (dl)x:x$ file /tmp/data.dload-2 /tmp/data.dload-2: gzip compressed data, last modified: Thu Apr 26 23:05:15 2018, from Unix but un-taring them produces different results: (dl)x:x$ tar -zxvf /tmp/data.dload-1 tar: This does not look like a tar archive tar: Skipping to next header tar: Exiting with failure status due to previous errors (dl) x:x$ tar -zxvf /tmp/data.dload-2 testfiles/a testfiles/b (dl)x:x$ anybody has any idea why this might happen and more importantly how can i download that tar file with Python (preferably requests) This is the result from r.headers: (dl) x:x$ python dload-test.py {'Server': 'nginx', 'Date': 'Fri, 27 Apr 2018 17:27:06 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding', 'Cache-Control': 'no-cache', 'Content-Security-Policy': "script-src 'unsafe-eval' https://www.dropbox.com/static/compiled/js/ https://www.dropbox.com/static/javascript/ https://www.dropbox.com/static/api/ https://cfl.dropboxstatic.com/static/compiled/js/ https://www.dropboxstatic.com/static/compiled/js/ https://cfl.dropboxstatic.com/static/js/ https://www.dropboxstatic.com/static/js/ https://cfl.dropboxstatic.com/static/previews/ https://www.dropboxstatic.com/static/previews/ https://cfl.dropboxstatic.com/static/api/ https://www.dropboxstatic.com/static/api/ https://cfl.dropboxsta…

http://stackoverflow.com/a/49984497
type: Answer
accepted answer of: http://stackoverflow.com/q/49984257
has comment: http://stackoverflow.com/comment/86993312
has comment: http://stackoverflow.com/comment/86992674
answers question: http://stackoverflow.com/q/49984257
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86994681
score: 0
has comment: http://stackoverflow.com/comment/86986774
has body: This is working code (Updated): from selenium import webdriver from selenium.webdriver.support import ui from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get("https://www.binance.com/trade.html?symbol=TRIG_BTC") elements = ui.WebDriverWait(browser, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".depths"))) print(elements) Output: [&lt;selenium.webdriver.remote.webelement.WebElement (session="08e1be69e2b4b7eff2d76c4b8420a287", element="0.8669087765654466-1")&gt;, &lt;selenium.webdriver.remote.webelement.WebElement (session="08e1be69e2b4b7eff2d76c4b8420a287", element="0.8669087765654466-2")&gt;] You have 2 elements with such class (here is JavaScript code for checking): Then access separate element in the loop or by index in the list (elements). Hope it helps you!

http://stackoverflow.com/comment/87062979
type: Comment
type: AnswerComment
has text: Sorry about that. I wrote the wrong line on my previous comment. It should be `packs = ([10] * pack10) + ([25] * pack25) + ([50] * pack50) + ([100] * pack100)`.
score: 0
comment on: http://stackoverflow.com/a/49967780

http://stackoverflow.com/a/50030274
type: Answer
has comment: http://stackoverflow.com/comment/87076662
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50030199
score: 5
accepted answer of: http://stackoverflow.com/q/50030199
upvote count: 5
has body: PEP8 argues for gpio.Input(), etc. There's also the style of using a short unique prefix to group related names together. This is not used much in Python, ... In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name.

http://stackoverflow.com/comment/87156268
score: 0
comment on: http://stackoverflow.com/a/50069837
type: Comment
type: AnswerComment
has text: @What that doesn't resolve the issue: it'll return `[['pakistan' 'india'], ['china', 'pakistan']]` instead of `['pakistan', 'india', 'china']` and also excludes any potential non-matches.

http://stackoverflow.com/a/49950455
accepted answer of: http://stackoverflow.com/q/49949840
type: AcceptedAnswer
downvote count: 0
has body: You have heaps problems with your code JSON invalid, missing a closing } before the last ] Your b and y nodes do not have a name set Your structure is inconsistent: each item of your data is a node, each element in children is a node, but your data itself is not a node. Furthermore, your outermost data uses a { 'a': ..., 'b': ... } structure, but children use a [ { 'a': ... }, { 'b': ... } ] structure. dict-wrapping nodes make it hard to get the actual nodes out. Ie, if I give you { 'x': nodeX } where 'x' is an unknown value, it's difficult for your program to extract nodeX We start by fixing 1 and 2 data = \ { 'a': { 'children': [] , 'name': 'a' } , 'b': { 'children': [ { 'x': { 'children': [] , 'name': 'x' } } , { 'y': { 'children': [ { 'z': { 'children': [] , 'name': 'z' } } ] , 'name': 'y' # you missed this } } # you missed this ] , 'name': 'b' # you missed this } } Then we fix 3 by making a uniform structure with a root node root = \ { 'root': { 'children': [ {k:v} for (k,v) in data.items() ] , 'name': 'root' } } Then we fix 4 with an unwrap_node helper def unwrap_node (wrapped_node): node, *_ = wrapped_node.values() if 'children' in node and len (node['children']) &gt; 0: return { 'name': node['name'] , 'children': [ unwrap_node(n) for n in node['children'] ] } else: return node Now we get to the meat of your problem. We write a generic traverse function that simply yields an ancestor path (list) for each node in your tree def traverse (node, path = []): if 'children' in node and len (node['children']) &gt; 0: for n in node['children']: yield from traverse (n, path + [ node ]) else: yield path + [ node ] Using each ancestor path, we can easily join the node by name property and separate using "-&gt;" for path in traverse (unwrap_node (root)): print (" -&gt; ".join (node['name'] for node in path)) # root -&gt; a # root -&gt; b -&gt; x # root -&gt; b -&gt; y -&gt; z Lastly, achieve your desired output writing print_tree similar to our loop above. We can filter o…
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49949840
score: 2

http://stackoverflow.com/a/49973104
score: 3
accepted answer of: http://stackoverflow.com/q/49972792
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86962607
has body: Here is some indexing madness which I believe does what you are asking for: &gt;&gt;&gt; def magic(data): ... n, m = data.shape ... assert n==m ... rows = np.zeros((n, n-1, n, n), data.dtype) ... cols = np.zeros((n, n-1, n, n), data.dtype) ... idx = np.argsort(np.identity(n), kind='mergesort', axis=1) ... self = idx[:, -1] # should be just 0, 1, 2, 3, ... ... other = idx[:, :-1] ... rows[self, :, self, :] = data[:, None, :] - data[other[..., None], self] ... cols[self, ..., self] = data.T[:, None, :] - data.T[other[..., None], self] ... return rows.reshape(-1, n*n), cols.reshape(-1, n*n) ... &gt;&gt;&gt; magic(np.array([[.5,0], [.1,1.2]])) (array([[ 0.4, -1.2, 0. , 0. ], [ 0. , 0. , -0.4, 1.2]]), array([[ 0.5, 0. , -1.1, 0. ], [ 0. , -0.5, 0. , 1.1]])) &gt;&gt;&gt; magic(np.array([[.2,.9], [.6,.1]])) (array([[-0.4, 0.8, 0. , 0. ], [ 0. , 0. , 0.4, -0.8]]), array([[-0.7, 0. , 0.5, 0. ], [ 0. , 0.7, 0. , -0.5]]))
downvote count: 0
has comment: http://stackoverflow.com/comment/86962558
has comment: http://stackoverflow.com/comment/86962251
has comment: http://stackoverflow.com/comment/86962510
type: Answer
answers question: http://stackoverflow.com/q/49972792
has comment: http://stackoverflow.com/comment/86962332

http://stackoverflow.com/comment/86925402
type: AnswerComment
has text: @SharvariGc - thank you. So second mask is `b = df'D','E'.eq(df['D'], axis=0)` ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49952469

http://stackoverflow.com/a/49938729
has comment: http://stackoverflow.com/comment/122845539
answers question: http://stackoverflow.com/q/49921400
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/123552547
has body: Use the @action decorator. Simple example below, the text "Recalculate Charges" is what appears in the drop-down menu. class TransactionView(AdminView): from flask_admin.actions import action @action('recalculate', 'Recalculate Charges', 'Are you sure you want to recalculate selected transactions(s)?') def action_recalculate(self, ids): count = 0 for _id in ids: # Do some work with the id, e.g. call a service method transaction_service.recalculate_transaction(_id) count += 1 flash("{0} transaction (s) charges recalculated".format(count))
downvote count: 0
type: AcceptedAnswer
score: 13
has comment: http://stackoverflow.com/comment/86896226
accepted answer of: http://stackoverflow.com/q/49921400

http://stackoverflow.com/a/50021783
has body: The solution which I found thanks to Mike Driscoll and nekomatic: Create a new conda env with Python 2.7. Install https://anaconda.org/bjornfjohansson/wxpython . conda install python.app Use pythonw instead of python. The last two steps are probably specific to macOS.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50006314

http://stackoverflow.com/q/49998997
has comment: http://stackoverflow.com/comment/87038196
answer count: 1
type: Question
tagged with: django-wsgi
type: UnansweredQuestion
tagged with: wsgi
has answer: http://stackoverflow.com/a/49999585
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87014191
score: 0
has body: I'm trying to deploy my Django project in my server but I'm encountering some issues. My environment : Ubuntu 16.04 Server Django 2.0 Python 3.5 Apache2 2.4 WSGI Django configuration : My Django project is located to : /var/www/html/DatasystemsCORE I have wsgi.py file (/var/www/html/DatasystemsCORE/DatasystemsCORE) which looks like : import os, sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DatasystemsCORE.settings") application = get_wsgi_application() I have ALLOWED_HOST like this : ALLOWED_HOSTS = ['localhost', '172.30.10.86', '[::1]'] Apache2 configuration : In my apache2.conf file, I have : WSGIScriptAlias / /var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py WSGIPythonPath /var/www/html/DatasystemsCORE Alias /static/ /var/www/html/DatasystemsCORE/static/Theme/ Require all granted Require all granted And I have in sites-available/000-default.conf : ServerAdmin webmaster@localhost DocumentRoot /var/www/html/DatasystemsCORE ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined To my mind, all parameters seem to be right, but when I write : 172.30.10.86:80 in my browser, I get : 500 Internal Server Error Traceback This is the Traceback given by error.log in apache2 : [Tue Apr 24 12:07:32.526764 2018] [wsgi:error] [pid 2611:tid 139723751765760] [client 172.30.10.73:50128] mod_wsgi (pid=2611): Target WSGI script '/var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py' cannot be loaded as Python module. [Tue Apr 24 12:07:32.526839 2018] [wsgi:error] [pid 2611:tid 139723751765760] [client 172.30.10.73:50128] mod_wsgi (pid=2611): Exception occurred processing WSGI script '/var/www/html/DatasystemsCORE/DatasystemsCORE/wsgi.py'. [Tue Apr 24 12:07:32.526970 2018] [wsgi:error] [pid 2611:tid 139723751765760] [client 172.30.10.73:50128] Traceback (most recent call last): [Tue Apr 24 12:07:32.527038 2018] [wsgi:error] [pid 2611:tid 139723751765760] [client 172.30.10.73:50128] File "/var/ww…
has title: Issue between Django 2.0 / Apache2 and WSGI
tagged with: mod-wsgi

http://stackoverflow.com/comment/87018674
score: 1
has text: Here are a couple of posts to get you started: https://stackoverflow.com/q/13621651/1288 https://codereview.stackexchange.com/q/178603/2105 Also, neighbor checking is a big component of Conway's Game of Life. You might check different implementations of that to see how it's done.
type: QuestionComment
comment on: http://stackoverflow.com/q/50001201
type: Comment

http://stackoverflow.com/q/49936194
accepted answer: http://stackoverflow.com/a/49936351
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49936351
tagged with: django-rest-framework
type: Question
has title: Django serializer request JSON value
tagged with: python
tagged with: django-serializer
has body: used django 2.0.2 MAC OS 10.13 views.py from rest_framework import viewsets from .serializers import RegisterSerializer from rest_framework.response import Response import json class RegisterViewSet(viewsets.ModelViewSet): queryset = '' serializer_class = RegisterSerializer def create(self,request, *args, **kwargs): print(json.loads(request.body)) serializer_class = RegisterSerializer(json.loads(request.body)) return Response(serializer_class) serializers.py from rest_framework import serializers from .models import register import uuid class RegisterSerializer(serializers.Serializer): UserEmail = serializers.EmailField(allow_blank=True,default=uuid.uuid4()) UserPassword = serializers.CharField(allow_blank=True,default=uuid.uuid4()) UserSex = serializers.IntegerField(default=0) UserAge = serializers.IntegerField(default=0) DeviceId = serializers.CharField(allow_blank=True,default=uuid.uuid4()) PushKey = serializers.CharField(allow_blank=True,default=uuid.uuid4()) OS = serializers.IntegerField(default=0) OSVersion = serializers.CharField(allow_blank=True,default=0) def create(self,validated_date): return True api test.html enter image description here i input this value succese print(json.loads(request.body)) how to use this value at serializer after raise this exception You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation.
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86892673
comment on: http://stackoverflow.com/q/49938446
has text: Your `subtask` function and `subtask` loop variable are clashing
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/101946895
score: 0
has text: No, so I stopped using it:-)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50028953

http://stackoverflow.com/comment/86927842
has text: x.shape: (8782, 3). lda_transformed.shape: (8782, 1)
comment on: http://stackoverflow.com/q/49955592
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/87130740
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50056920
has text: I don't see any code on your link above. I tried it: https://repl.it/repls/NuttyJauntyLicense and it worked

http://stackoverflow.com/comment/87130579
type: QuestionComment
comment on: http://stackoverflow.com/q/50057047
type: Comment
score: 0
has text: `a, b = b, a+b` performs the assignments in parallel. Your version changes `a` then uses it to calculate `b`.

http://stackoverflow.com/comment/87024000
has text: File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 249, in broadcast_arrays shape = _broadcast_shape(*args) File "/Users/Andrew/PycharmProjects/HelloWorld/venv/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 184, in _broadcast_shape b = np.broadcast(*args[:32]) ValueError: shape mismatch: objects cannot be broadcast to a single shape
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50003741

http://stackoverflow.com/comment/87007432
type: Comment
type: QuestionComment
has text: Hmmm, unfortuantely I cannot simulate it, so no idea how solve it. Problem should be in data or in pandas/python.
score: 0
comment on: http://stackoverflow.com/q/49979122

http://stackoverflow.com/comment/87075394
comment on: http://stackoverflow.com/q/50029560
score: 0
has text: Although it _might_ be an interesting project to build a “sympy compiler” that takes your parse tree and builds a sympy expression that you can then do stuff with.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86852050
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49917161
has text: there is else condition after : print('{}: Ip is Already Tried: '.format(line)) and in your script you didn't include else after continue. Please check my above script and confirm if your script will work in this case as well
type: Comment

http://stackoverflow.com/q/50007924
type: Question
type: UnansweredQuestion
has title: how to have notebook output be in cell format consistently for easy excel pasting?
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/50008146
has body: How do I get the output of a jupyter notebook to be in cell format for easy copy into excel? Like instead of I had thought it was with the display module but looks like that's not the reason. Sorry for the large imagine, not sure why it's blown up like this.. Thanks!
tagged with: python
tagged with: jupyter-notebook

http://stackoverflow.com/a/49970847
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49970678
has comment: http://stackoverflow.com/comment/86959578
score: 1
has body: Instead of defaultdict you can use dict.setdefault: d = {} for k, v in new_dict.items(): for company, shares, price in v: if shares &gt; 0: d.setdefault(company, [0, 0])[0] += shares else: d.setdefault(company, [0, 0])[1] -= shares Result {'Apple': [180, 40], 'Dell': [30, 10], 'IBM': [40, 0], 'Intel': [70, 30]} Explanation Set default value for dictionary items to [0, 0]. Then we can iterate new_dict and increment shares at the appropriate index. For shares sold we must negate in order to extract a positive result. defaultdict solution from collections import defaultdict d = defaultdict(lambda: [0, 0]) for k, v in new_dict.items(): for company, shares, price in v: if shares &gt; 0: d[company][0] += shares else: d[company][1] -= shares
has comment: http://stackoverflow.com/comment/86959658
upvote count: 1
has comment: http://stackoverflow.com/comment/86959585
has comment: http://stackoverflow.com/comment/86959633

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/49953785
tag name: python-packaging

http://stackoverflow.com/q/50012089
tagged with: python
has comment: http://stackoverflow.com/comment/87040681
has body: For example, the digits of 123431 and 4577852 increase and then decrease. I wrote a code that breaks the numbers into a list and is able to tell if all of the digits increase or if all of the digits decrease, but I don't know how to check for digits increasing then decreasing. How do I extend this? x = int(input("Please enter a number: ")) y = [int(d) for d in str(x)] def isDecreasing(y): for i in range(len(y) - 1): if y[i] &lt; y[i + 1]: return False return True if isDecreasing(y) == True or sorted(y) == y: print("Yes")
has comment: http://stackoverflow.com/comment/87040964
favorite count: 0
has answer: http://stackoverflow.com/a/50012635
accepted answer: http://stackoverflow.com/a/50012635
has comment: http://stackoverflow.com/comment/87638082
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/50012133
possible better answer: http://stackoverflow.com/a/50012133
has answer: http://stackoverflow.com/a/50012283
score: 8
upvote count: 8
type: Question
downvote count: 0
has title: How can I determine if the numbers in a list initially increase (or stay the same) and then decrease (or stay the same) with Python?

http://stackoverflow.com/q/50024389
tagged with: python
type: UnansweredQuestion
tagged with: kivy
has comment: http://stackoverflow.com/comment/87067825
has body: I'm looking for installing Kivy in a virtual environment created in Anaconda for python 2.7 I have been through the following references: one two three perhaps, they didn't work for me. Here's the output I see, that confuses me: (py27anc) mister-t@BrightMachine:~/PycharmProjects/StockAnalysisGUI$ sudo apt-get install python-kivy Reading package lists... Done Building dependency tree Reading state information... Done python-kivy is already the newest version (1.9.0-3build1). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. (py27anc) mister-t@BrightMachine:~/PycharmProjects/StockAnalysisGUI$ which python /home/mister-t/anaconda3/envs/py27anc/bin/python (py27anc) mister-t@BrightMachine:~/PycharmProjects/StockAnalysisGUI$ python Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:09:15) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org &gt;&gt;&gt; import kivy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named kivy Besides this I tried doing it via IDE (PyCharm). Returns Error beyond my grasp. I installed necessary packages for same especially the Cython library, yet fails. Also, note I tried with Pip, Upgraded pip to latest version and retried. Created new Virtual ENV and tried all over again and yet fails.
has comment: http://stackoverflow.com/comment/87086809
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87256240
linked to: http://stackoverflow.com/q/19113270
type: Question
has title: python kivy installation in virtual environment returns already installed but doesn't import
answer count: 0

http://stackoverflow.com/comment/87096464
has text: @Alasdair ok,will take a look,thnks.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50040060

http://stackoverflow.com/comment/87071660
type: Comment
type: QuestionComment
has text: This is because your data is not numeric. [Edit](https://stackoverflow.com/posts/50027737/edit) your question and add the output of `print(Data.dtypes)`.
comment on: http://stackoverflow.com/q/50027737
score: 7

http://stackoverflow.com/comment/86876808
has text: I get the error 'list indices must be integers or slices, not str'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49929796
type: AnswerComment

http://stackoverflow.com/q/49978320
accepted answer: http://stackoverflow.com/a/49995596
has title: AsyncIO run in executor using ProcessPoolExecutor
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
tagged with: multiprocessing
has body: I tried to combine blocking tasks and non-blocking (I/O bound) tasks using ProcessPoolExecutor and found it's behavior pretty unexpected. class BlockingQueueListener(BaseBlockingListener): def run(self): # Continioulsy listening a queue blocking_listen() class NonBlockingListener(BaseNonBlocking): def non_blocking_listen(self): while True: await self.get_message() def run(blocking): blocking.run() if __name__ == "__main__": loop = asyncio.get_event_loop() executor = ProcessPoolExecutor() blocking = BlockingQueueListener() non_blocking = NonBlockingListener() future = loop.run_in_executor(executor, run(blocking)) loop.run_until_complete( asyncio.gather( non_blocking.main(), future ) ) I was expecting that both tasks will have control concurrently, but blocking task started in ProcessPoolExecutor blocks and never return control. How could it happen? What the proper way to combine normal coroutines and futures started in multiprocessing executor?
type: AnsweredQuestion
tagged with: python
tagged with: concurrency
has answer: http://stackoverflow.com/a/49995596

http://stackoverflow.com/q/49956945
answer count: 1
downvote count: 0
tagged with: neural-network
tagged with: keras
score: 4
has comment: http://stackoverflow.com/comment/86930107
accepted answer: http://stackoverflow.com/a/49959422
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49959422
type: AnsweredQuestion
tagged with: python
has title: Teach LSTMs concept of different frequencies
tagged with: lstm
upvote count: 4
has comment: http://stackoverflow.com/comment/86930152
has body: Training an LSTM on a sine wave is simple enough. The LSTM easily understands how to predict the wave hundreds of timesteps into the future. However, the LSTM becomes grossly incompetent once I try to have it predict a sine wave of a different frequency. Even if I try to train it on many waves of different frequencies, it forgets the first wave to learn the next one. An example of how my LSTM fails when I changed the frequency of the test data: How do I train my LSTM to recognize the concept of frequency and work on any sinusoid? Edit: The model that I am using: inputs = Input(shape=(self.timesteps, self.features)) bd_seq = Bidirectional(LSTM(128, return_sequences=True, kernel_regularizer='l2'), merge_mode='sum')(inputs) bd_sin = Bidirectional(LSTM(32, return_sequences=True, kernel_regularizer='l2'), merge_mode='sum')(bd_seq) bd_1 = Bidirectional(LSTM(self.features, activation='linear'), merge_mode='sum')(bd_seq) bd_2 = Bidirectional(LSTM(self.features, activation='tanh'), merge_mode='sum')(bd_sin) output = Add()([bd_1, bd_2]) self.model = Model(inputs=inputs, outputs=output)

http://stackoverflow.com/comment/86929983
type: QuestionComment
comment on: http://stackoverflow.com/q/49956924
has text: `dict(zip(keys, [list(z) for z in zip(*values)]))`
score: 0
type: Comment

http://stackoverflow.com/comment/86964403
has text: 1st and 2nd column makes my entry unique.eg. a-b ,d-e and a-c are the unique keys
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49973842
type: Comment

http://stackoverflow.com/q/50019210
has comment: http://stackoverflow.com/comment/87054502
has comment: http://stackoverflow.com/comment/87055544
accepted answer: http://stackoverflow.com/a/50019697
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/87054809
has answer: http://stackoverflow.com/a/50019697
has body: In my Django(2.0.1) project, I want to read spreadsheets(excel, csv, ods) and convert it into python dictionary for processing. I was looking into django-excel but it doesn't support Django 2. Hence, I am planning to use Pandas. I want to know what are the pros and cons(mainly complexity vs performance) in this scenario. Please suggest other solutions which can be used? Project detail: It is a SPA using DRF for backend. Users will upload excel file and I want to process this in Django view.
answer count: 2
has title: Using Pandas with Django to read and parse excel file
possible better answer: http://stackoverflow.com/a/50019824
downvote count: 0
tagged with: django
score: 4
favorite count: 0
tagged with: excel
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87055591
tagged with: python
has answer: http://stackoverflow.com/a/50019824

http://stackoverflow.com/comment/87088344
has text: Make use of `time.time()`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50035372

http://stackoverflow.com/q/49932226
answer count: 2
has title: Writing and Saving CSV File From Scraping Data
has answer: http://stackoverflow.com/a/49932304
type: Question
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/49932284
possible better answer: http://stackoverflow.com/a/49932304
accepted answer: http://stackoverflow.com/a/49932284
type: AnsweredQuestion
has body: In the code below, I have successfully scraped a list of every MLB team and their corresponding win probability for the day (April 18th). I would like to export this data to a CSV file, but when I write the code, only one team and win probability gets exported. Does anyone know why this happens? I'm thinking there needs to be another for loop written with the CSV writer but I am not exactly sure how to do that with two separate sources of scraped data (team name and win probability) Thanks in advance! import requests import csv from bs4 import BeautifulSoup page=requests.get('https://www.fangraphs.com/livescoreboard.aspx?date=2018- 04-18') soup=BeautifulSoup(page.text, 'html.parser') [link.decompose() for link in soup.find_all(class_='lineup')] f=csv.writer(open('Win_Probability.csv','w')) f.writerow(['Teams','Win_Prob']) team_name_list=soup.find(class_='RadAjaxPanel') team_name_list_items=team_name_list.find_all('a') for team_name in team_name_list_items: teams=team_name.contents[0] print(teams) winprob_list=soup.find(class_='RadAjaxPanel') winprob_list_items=winprob_list.find_all('td',attrs={'style':'border:1px solid black;'}) for winprob in winprob_list_items: winprobperc=winprob.contents[0] print(winprobperc) f.writerow([teams,winprobperc])
score: 0

http://stackoverflow.com/q/50004739
answer count: 0
has body: I am getting the following error: Python3 : AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d' for the line: sift = cv2.xfeatures2d.SIFT_create() I have tried installing opencv-contrib-python and uninstalling opencv-python and they didn't help get rid of this error. Any help appreciated! Using Mac OSX,Python 3,opencv 3
duplicate of: http://stackoverflow.com/q/42623833
type: Question
has comment: http://stackoverflow.com/comment/87026033
type: UnansweredQuestion
has title: Python3 : AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d'
tagged with: python
linked to: http://stackoverflow.com/q/42623833
has comment: http://stackoverflow.com/comment/87026104
has comment: http://stackoverflow.com/comment/87030373
score: 0
tagged with: opencv3.0

http://stackoverflow.com/comment/87098580
score: 3
type: Comment
comment on: http://stackoverflow.com/q/50041294
type: QuestionComment
has text: You could encapsulate the algorithms into two classes, each with the methods (and possibly state) relevant to that algorithm. Also allows you to make specialized versions of algorithms using inheritance. Or if classes are not an option, you could create helper functions within the algorithms "main entry" function.

http://stackoverflow.com/q/50049920
has comment: http://stackoverflow.com/comment/87117519
has body: UPDATE: this number 48 is showed in "Inspect" in Chrome, but not in "View Page Source". Now understand that it is generated by JavaScript and that is why I can not extract it. This is part of HTML that I am trying to scrape 48 "times" Problem is that I can not get this 48 number. I think that problem is because there are no "" around 48. Because I can get "times" text with no problems, and the only difference that I can see is that there are no "" around 48. This is code that is working for "times": response.xpath('.//span[@class="value"]/text()').extract_first() >>> u'times' For 48: response.xpath('.//span[@class="base-entity-display-count"]').extract_first() >>> u'' As you can see, 48 is missing. Does anybody have some solution or idea?
has comment: http://stackoverflow.com/comment/87134502
has comment: http://stackoverflow.com/comment/87134503
has comment: http://stackoverflow.com/comment/87134557
has comment: http://stackoverflow.com/comment/87130525
has title: Scrapy, scraping text in HTML tag when there are no quotation marks?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50060573
has comment: http://stackoverflow.com/comment/87138549
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/87152050
type: Question
has comment: http://stackoverflow.com/comment/87126636
accepted answer: http://stackoverflow.com/a/50060573
has comment: http://stackoverflow.com/comment/87137343
answer count: 1
tagged with: python

http://stackoverflow.com/q/49965000
downvote count: 0
accepted answer: http://stackoverflow.com/a/49966652
has title: Images opened in Pillow and OpenCV are not equivelant
has comment: http://stackoverflow.com/comment/86946035
has answer: http://stackoverflow.com/a/49966652
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/86946373
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/86946368
has comment: http://stackoverflow.com/comment/86946659
has comment: http://stackoverflow.com/comment/86945979
has comment: http://stackoverflow.com/comment/86946805
has body: I downloaded a test image from Wikipedia (the tree seen below) to compare Pillow and OpenCV (using cv2) in python. Perceptually the two images appear the same, but their respective md5 hashes don't match; and if I subtract the two images the result is not even close to solid black (the image shown below the original). The original image is a JPEG. If I convert it to a PNG first, the hashes match. The last image shows the frequency distribution of how the pixel value differences. As Catree pointed out my subtraction was causing integer overflow. I updated to converting too dtype=int before the subtraction (to show the negative values) and then taking the absolute value before plotting the difference. Now the difference image is perceptually solid black. This is the code I used: from PIL import Image import cv2 import sys import md5 import numpy as np def hashIm(im): imP = np.array(Image.open(im)) # Convert to BGR and drop alpha channel if it exists imP = imP[..., 2::-1] # Make the array contiguous again imP = np.array(imP) im = cv2.imread(im) diff = im.astype(int)-imP.astype(int) cv2.imshow('cv2', im) cv2.imshow('PIL', imP) cv2.imshow('diff', np.abs(diff).astype(np.uint8)) cv2.imshow('diff_overflow', diff.astype(np.uint8)) with open('dist.csv', 'w') as outfile: diff = im-imP for i in range(-256, 256): outfile.write('{},{}\n'.format(i, np.count_nonzero(diff==i))) cv2.waitKey(0) cv2.destroyAllWindows() return md5.md5(im).hexdigest() + ' ' + md5.md5(imP).hexdigest() if __name__ == '__main__': print sys.argv[1] + '\t' + hashIm(sys.argv[1]) Frequency distribution updated to show negative values. This is what I was seeing before I implemented the changes recommended by Catree.
has comment: http://stackoverflow.com/comment/86951670
has comment: http://stackoverflow.com/comment/86946297
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/23565889
has comment: http://stackoverflow.com/comment/86946777
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86946417
answer count: 1

http://stackoverflow.com/a/49987687
accepted answer of: http://stackoverflow.com/q/49987626
answers question: http://stackoverflow.com/q/49987626
type: Answer
has comment: http://stackoverflow.com/comment/87117452
has body: Two parts in that question: "How can I select an item from this list by it's index" Assuming index is the index, and mylist is the list, this is achieved with mylist[index]. Obviously, index has to be (at least) an integer. In your current code, it comes from raw_input that returns a string. So convert that string to an integer using, e.g., index = int(index). "and modify it back to the list with an update?" Assuming x contains the new value: mylist[index] = x. If you want to first remove the item, keep going on with mylist.remove(index), and if you want to insert something new at that same position, use mylist.insert(index, x). More on lists: https://docs.python.org/2/tutorial/datastructures.html (Python 2, as you used print i, list and not print(i, list). I suggest you to move to Python 3 as well).
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86881600
has text: @DanielMöller changed to sigmoid and my accuracy now hovers around 5%. With regards to the weights, I implemented them the same way when solving the mnist example problem and my network functioned correctly so I'm not sure that is the problem
score: 0
comment on: http://stackoverflow.com/q/49932756
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87033185
type: Comment
score: 0
has text: I don't believe so. when I do '```pip show <package>```, i get: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages for both pandas and numpy.
type: QuestionComment
comment on: http://stackoverflow.com/q/50007537

http://stackoverflow.com/q/50033547
downvote count: 1
duplicate of: http://stackoverflow.com/q/8951020
favorite count: 0
has comment: http://stackoverflow.com/comment/87566348
type: Question
answer count: 2
has title: How to loop in a list more times than the list size?
accepted answer: http://stackoverflow.com/a/50033559
possible better answer: http://stackoverflow.com/a/50034088
score: 5
has answer: http://stackoverflow.com/a/50033559
tagged with: python
has answer: http://stackoverflow.com/a/50034088
upvote count: 6
has body: Is there a function or native lib in Python that allows me to loop in a list more times than the number of elements in the list? In other words, when my index of interest is greater than the list size, the next element is the first of the list. For example, I have this list: abc = ['a', 'b', 'c', 'd', 'e'] So, if I have an index with value 10, the result will be 'a'. If the index is with value 18, the result will be 'd'.
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/8951020
tagged with: loops
has comment: http://stackoverflow.com/comment/87083221

http://stackoverflow.com/q/49969834
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: datetime
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has body: I would like to analyze frequency patterns in time series data but there is some technical question. Have a dataframe in Pandas: Date Label 2017-03-22 15:16:45 20 2017-03-22 16:12:00 15 2017-03-22 22:10:23 20 2017-03-23 17:00:03 11 2017-03-24 10:11:13 20 2017-03-25 14:02:54 20 I would like to calculate the difference between the values in 'Date' column between each of two values grouping by the label for label '20'. In my view, it should look like timedelta column with the difference and the label column: DateDiff Label 0 days 06:53:38 20 1 days 12:00:50 20 1 days 03:51:41 20 How can it be possible using pandas groupby options?
tagged with: pandas-groupby
tagged with: pandas
score: 1
has title: Grouping and column difference calculating in Pandas
answer count: 1
has answer: http://stackoverflow.com/a/49969894
accepted answer: http://stackoverflow.com/a/49969894

http://stackoverflow.com/q/49923865
accepted answer: http://stackoverflow.com/a/49923985
tagged with: sympy
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has body: I'm trying to run this simple code block and it keeps throwing a syntax error and it's not pointing out where it's occuring. I'm running python in a console so it won't let me type past the if statement: for p in arange(2,3,0.01): l1 = Line(f(x,p)) l2 = Line(g(x)) if len(intersection(l1,l2) == 1:
answer count: 1
has title: Sympy/Numpy returning syntax error
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86863579
has answer: http://stackoverflow.com/a/49923985

http://stackoverflow.com/a/50057446
has body: In general if you combine the weights / biases entirely after training, this is unlikely to produce good results. However, there are ways to make it work. Intuition about combining weights Consider the following simple example: You have a MLP with one hidden layer. Any two instances of the MLP can produce identical outputs for identical inputs if the nodes in the hidden layer are permuted, the weights input->hidden are permuted the same way, and the weights hidden->output are permuted using the inverse permutation. In other words, even if there was no randomness in what the final network you end up with does, which hidden node corresponds to a particular feature would be random (and determined from the noise of the initializations). If you train two MLPs like that on different data (or random subsets of the same data), they would likely end up with different permutations of the hidden nodes even if the initializations are all the same, because of the noise of the gradients during training. Now, if that a certain property of the input activates most strongly the i-th node of network A and the j-th node of network B (and in general i != j), averaging the weights between the i-th node of A and i-th node of B (which corresponds to a different feature) is likely to decrease performance, or even produce a network that produces nonsense outputs. There are two possible fixes here - you can use either one, or both together. The idea is to either figure out which nodes match between the two networks, or to force the nodes to match. Solution A: Train both networks on different data for a few iterations. Average the weights of both, and replace both networks with the average weights. Repeat. This makes the i-th node of each network learn the same feature as the matching node of the other network, since they can't ever diverge too far. They are frequently re-initialized from the average weights, so once the permutation is determined it is likely to stay stable. A reasonable valu…
type: AcceptedAnswer
downvote count: 0
upvote count: 9
accepted answer of: http://stackoverflow.com/q/49988009
has comment: http://stackoverflow.com/comment/87159606
type: Answer
answers question: http://stackoverflow.com/q/49988009
score: 9

http://stackoverflow.com/a/49969526
upvote count: 3
has body: First: I am not familiar with the array format that you showed in your post. I have never seen an array instantiated in Python using just square brackets. That's not a function call. Second: Your problem may not be fully specified. However: if you have shown us all the possible values that you can have in your input arrays, then only 1, 2, and 3 are possible. In that case, there are only 9 possible pairings of elements from array_1 and array_2, and the values you want as outputs can easily be stored in a 3 x 3 lookup table. Finally: I use Numpy. You seem to want arrays, and Numpy is very common and handles arrays well. import numpy as np from itertools import product arr1 = np.array([[1,2,2],[1,2,3],[1,2,1]], dtype=int) arr2 = np.array([[1,1,2],[2,2,3],[3,1,1]], dtype=int) lookup = np.array(((0,10,15),(5,0,15),(5,10,0)), dtype=int) result = np.zeros_like(arr1) for r, c in product(*[range(x) for x in arr1.shape]): a, b = arr1[r,c], arr2[r,c] result[r,c] = lookup[a-1,b-1] print(arr1, "\n") print(arr2, "\n") print(result) Here's the output: [[1 2 2] [1 2 3] [1 2 1]] [[1 1 2] [2 2 3] [3 1 1]] [[ 0 5 0] [10 0 0] [15 5 0]]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49969215
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/86955707
type: Answer
has comment: http://stackoverflow.com/comment/87012161
accepted answer of: http://stackoverflow.com/q/49969215

http://stackoverflow.com/a/58411728
answers question: http://stackoverflow.com/q/49958287
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: The difference, as noted in the comments, is that print(family) calls the str.__str__ method, while print([family]) calls str.__repr__, which escapes non-printable unicode characters. The print function converts its (non-keyword) arguments using str. Calling str on containers (generally) calls repr on their items. Mostly this is because strings inside a container would too easily disturb the presentation of the container itself (e.g. with newlines). A PEP to change this was raised around the release of Python 3 but quickly rejected. Calling repr on strings escapes any non-printable characters (but, as of Python 3, preserves other non-ASCII Unicode characters): see PEP-3138 and the description of str.isprintable Return true if all characters in the string are printable or the string is empty, false otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.) The CPython implementation can be found here (search for the unicode_repr function).
accepted answer of: http://stackoverflow.com/q/49958287
type: Answer

http://stackoverflow.com/comment/86952870
type: QuestionComment
has text: I think its `CharField()` , using this package [django-jsonfield](https://github.com/dmkoch/django-jsonfield)
score: 0
comment on: http://stackoverflow.com/q/49968183
type: Comment

http://stackoverflow.com/comment/87033169
score: 0
type: QuestionComment
has text: Ah, Is it a list?
comment on: http://stackoverflow.com/q/50008120
type: Comment

http://stackoverflow.com/q/50004980
has body: The following script generates a scatter plot with annotated data points. I'd like remove circle markers from the plot and just show the labels. fig, ax = Plot.subplots() ax.scatter(Y0_mean, Y1_mean) for i, txt in enumerate(features.playerCountry.unique()): country_name = countries_code[countries_code.CountryCode == txt] ['ctr'].values[0].lower() ax.annotate(country_name, (Y0_mean[i], Y1_mean[i]), xytext=(Y0_mean[i], Y1_mean[i]), size=5) ax.legend(fontsize=8) fig.savefig(figPath + 'LocationAwareMeanFeatures_ctr'+str(lr), dpi=300)
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50006040
has answer: http://stackoverflow.com/a/50006040
linked to: http://stackoverflow.com/q/32965180
has title: How remove data points from text annotate?
has comment: http://stackoverflow.com/comment/87028074
tagged with: matplotlib
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87026421
tagged with: annotate
has comment: http://stackoverflow.com/comment/87026555
type: AnsweredQuestion
upvote count: 0
answer count: 1

http://stackoverflow.com/q/49955556
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49955801
tagged with: python
has comment: http://stackoverflow.com/comment/86927832
linked to: http://stackoverflow.com/q/4710067
has comment: http://stackoverflow.com/comment/86927701
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86927542
answer count: 1
tagged with: file
has body: I have a problem with python code and i don't know what to do, because im fairly new in it. date_now1 = datetime.datetime.now() archive_date1 = date_now1.strftime("%d.%m.%Y") f1 = open(archive_date1, "r+") print("What product do you wish to delete ?") delate_product = str(input()) for line in f1.readlines(): if delate_product in line: list = line ready_product = list.split() quantity_of_product = int(ready_product[1]) if quantity_of_product == 1: del line print("Product deleted") else: print("You have {} amounts of this product. How many do you want to delete ?".format(quantity_of_product)) x = int(input()) quantity_of_product = quantity_of_product - x temporary = "{}".format(quantity_of_product) print(type(temporary)) f1.write(temporary) in ready_product[1] I get the message f1.write(temporary) in ready_product[1] TypeError: 'in &lt;string&gt;' requires string as left operand, not int When i do print(type()) in temporary it says string. I also tried str(quantity_of_product), but it doesn't work as well. Maybe somebody could give me the idea of what to do, or what to read to get the answer.
favorite count: 0
has title: Python writing int into file
type: Question

http://stackoverflow.com/comment/86888022
comment on: http://stackoverflow.com/q/49936175
has text: Possible duplicate of [Converting a string to a formatted date-time string using Python](https://stackoverflow.com/questions/2316987/converting-a-string-to-a-formatted-date-time-string-using-python)
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/86980114
comment on: http://stackoverflow.com/a/49981870
type: Comment
score: 0
type: AnswerComment
has text: great answer! for the result possible to list out df2 Cntr_No and the matched / unmatched amount too ?

http://stackoverflow.com/comment/87135620
type: Comment
comment on: http://stackoverflow.com/q/50059451
type: QuestionComment
score: 1
has text: I've reopened the question and removed the beginning code (and replaced it with the more relevant code)

http://stackoverflow.com/q/49931313
has title: Python: using regex on a complicated list of multiple CSS selectors to extract their # and . tags
downvote count: 3
score: 1
has comment: http://stackoverflow.com/comment/86878545
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49931433
has answer: http://stackoverflow.com/a/49931468
has answer: http://stackoverflow.com/a/49931433
tagged with: python
has body: Is there an easier way of checking if a string matches a specific pattern and retrieving the group from that pattern? I want to go through a file of with {readlines} and collect any lines that have stuff between the quotes: **{** **"simpleSelectors": [** "*",** if those are lines in my file, my list should have ['simpleSelectors','*'] in it regexline = re.compile('\"(.*)\"') for i in css: if re.search(regexline, i): x = re.search(regexline, i) inputs.append(x.group(1))
tagged with: regex
accepted answer: http://stackoverflow.com/a/49931468
upvote count: 4
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/50012587
tagged with: python
score: 2
has title: using win32com.shell (python) copying of iphone files
answer count: 0
downvote count: 0
favorite count: 0
has body: I am looking to automate copying of files (photos) from iphone. I got a head start with this python script from github list-photos-on-phone I got it to work and get the file names of the pictures in iphone Then I am stuck with just getting the details.I tried looking up the documentation of win32com.shell and item.BindToHandler. It did not help much. I am using iphone connected to windows 7 by USB and want to copy files. If it works, then I can do a lot more with this. Is there a way to win32com.shell or some other windows package (in python) to copy the files?
type: Question
tagged with: iphone
upvote count: 2
type: UnansweredQuestion
tagged with: win32com

http://stackoverflow.com/q/50003486
type: Question
tagged with: heroku
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87025347
has title: Heroku doesn't recognize the Python version (which is the required one, in this case, 3.6.4)
tagged with: python
has comment: http://stackoverflow.com/comment/87023919
score: 0
has answer: http://stackoverflow.com/a/50004571
has body: I was deploying my code to Heroku with git push heroku master, but the build failed. Here is the output: Counting objects: 316, done. Delta compression using up to 4 threads. Compressing objects: 100% (305/305), done. Writing objects: 100% (316/316), 12.71 MiB | 915.00 KiB/s, done. Total 316 (delta 83), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Python app detected remote: ! The latest version of Python 3 is python-3.6.4 (you are using Python 3.6.4, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.4). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----&gt; Installing Python 3.6.4 remote: ! Requested runtime (Python 3.6.4) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to greensun. remote: To https://git.heroku.com/greensun.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/greensun.git' As you may see, it says: remote: ! The latest version of Python 3 is python-3.6.4 (you are using Python 3.6.4, which is unsupported). How do I make Heroku recognize Python 3.6.4? (it's already installed on this Laptop with Ubuntu and the app has runtime.txt with content: python-3.6.4).
answer count: 1
tagged with: git

http://stackoverflow.com/a/50023472
has comment: http://stackoverflow.com/comment/87100796
has comment: http://stackoverflow.com/comment/87137841
type: Answer
has comment: http://stackoverflow.com/comment/87088697
upvote count: 4
answers question: http://stackoverflow.com/q/50021625
has comment: http://stackoverflow.com/comment/87090643
type: AcceptedAnswer
downvote count: 0
has body: You can calculate a random distribution with loc 14 and scale 12 (+- 12 hours) and then add it as a pandas timedelta of type hours. So given your timestamp it would be import numpy as np import pandas as pd timestamp + pd.Timedelta(np.random.normal(14,12),'h') That should do the trick. Edit If you want to get a value out of the gaussian distribution around the hour of the timestamp you could use something like this: timestamp = pd.Timestamp('20180426140000') np.random.normal(timestamp.hour,12) and if you want to include the minutes timestamp.hour + timestamp.minute/60 Of course, if you need more of one value of the distribution, then you can supply it with the third parameter np.random.normal(timestamp.hour,12,10000)
accepted answer of: http://stackoverflow.com/q/50021625
score: 4

http://stackoverflow.com/comment/87158988
comment on: http://stackoverflow.com/q/50070864
type: Comment
score: 0
type: QuestionComment
has text: I think that's a misleading error. Your earlier builds with `-T` are successful. Your builds started failing after this commit https://github.com/usnistgov/sesame/commit/fce42e5ccc61a94c2eb46b55b98751ce08a03f86 Try reverting previous to that commit.

http://stackoverflow.com/q/49933233
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86883797
answer count: 2
has answer: http://stackoverflow.com/a/49933324
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49933648
has comment: http://stackoverflow.com/comment/86882491
has title: Parse XML data file result in json or dict
downvote count: 0
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
has body: I have data, what is the best way to extra information: Below is the pesudo code. XML data: <nf:data> <__XML__OPT_Cmd_mrib_show_mroute_command> <__XML__BLK_Cmd_mrib_show_mroute_command_source> <__XML__OPT_Cmd_mrib_show_mroute_command_source> <__XML__OPT_Cmd_mrib_show_mroute_command_group> <__XML__PARAM_value>239.16.110.124</__XML__PARAM_value> </__XML__OPT_Cmd_mrib_show_mroute_command_group> </__XML__OPT_Cmd_mrib_show_mroute_command_source> </__XML__BLK_Cmd_mrib_show_mroute_command_source> <__XML__OPT_Cmd_mrib_show_mroute_command_vrf> <__XML__OPT_Cmd_mrib_show_mroute_command___readonly__> <__readonly__> <TABLE_vrf> <ROW_vrf> default <route_count>10623</route_count> <star_g_cnt>4842</star_g_cnt> <sg_cnt>5780</sg_cnt> <star_g_prfx_cnt>1</star_g_prfx_cnt> <TABLE_one_route> <ROW_one_route> (192.168.2.28/32, 239.16.110.124/32) false false 3w6d false <TABLE_mpib> <ROW_mpib> pim 2 false </ROW_mpib> <ROW_mpib> ip 0 false </ROW_mpib> </TABLE_mpib> 625954 31923654 108.800 bps Ethernet2/1 192.168.1.251 Null 0.0.0.0 false 2 false false <TABLE_oif> <ROW_oif> Ethernet2/32 3w6d <TABLE_oif_mpib> <ROW_oif_mpib> pim false false </ROW_oif_mpib> </TABLE_oif_mpib> false </ROW_oif> <ROW_oif> Ethernet1/32 3w6d <TABLE_oif_mpib> <ROW_oif_mpib> pim false false </ROW_oif_mpib> </TABLE_oif_mpib> false </ROW_oif> </TABLE_oif> </ROW_one_route> </TABLE_one_route> </ROW_vrf> </TABLE_vrf> </__readonly__> </__XML__OPT_Cmd_mrib_show_mroute_command___readonly__> </__XML__OPT_Cmd_mrib_show_mroute_command_vrf> </__XML__OPT_Cmd_mrib_show_mroute_command> </nf:data> </nf:rpc-reply> need to parse following: 1. login to switch 2. FIND OUTINT: 3. Loop thru: (nf:data > show > ip > mroute > TABLE_vrf > ROW_vrf > TABLE_one_route > ROW_one_route) 4. pseudo code: for loop ROW_one_route if mcast-addrs startswith (*,) skip if mcast-addrs startswith (\d) parse following information: forloop TABLE_oif > ROW_oif statbps = stats-rate-buf statpkt = stats-pkts if oif-name startswith (vlan*) skip if oif-name startstwith (e…

http://stackoverflow.com/comment/86993772
has text: That's basically algorithm `ff3` in my answer.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49988665
type: Comment

http://stackoverflow.com/comment/87045055
score: 1
has text: The other common reason is much simpler: some server functions just spawn an acceptor function and then return once it's going, so you can `run_until_complete` that server function to get the actual acceptor coro, then do any setup you need, then `run_forever`. (For that design, you can do graceful shutdown with a _third_ `run` call, by having a signal handler just fire `loop.stop`, then call `acceptor.close()` and restart the loop.) Here, you're not doing any setup, or touching the acceptor coro in any way, but (if this is the library's design), it is being returned by `run_until_complete`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50013767

http://stackoverflow.com/comment/87069141
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50026359
has text: sorry, data_segment is a new list

http://stackoverflow.com/comment/88018029
comment on: http://stackoverflow.com/a/50475345
score: 0
type: Comment
type: AnswerComment
has text: openssl ca-certificates? Or just install the 'ca-certificates package' on my macos?

http://stackoverflow.com/q/50035874
tagged with: equals-operator
tagged with: python-2.7
score: 0
answer count: 2
has body: I am trying the following code in Python, using Jupyter Notebooks: import numpy as np i=2 j=0 basis = np.matrix([False,False,True,True,True]) basis_mod = basis print "basis" print basis print "basis_mod" print basis_mod basis_mod[:,i] = False print "basis" print basis print "basis_mod" print basis_mod basis_mod[:,j] = True print "basis" print basis print "basis_mod" print basis_mod The console output / what's printed is: basis False False True True True basis_mod False False True True True basis False False False True True basis_mod False False False True True basis True False False True True basis_mod True False False True True My question is: Why is the variable basis being changed, when I'm making modifications to basis_modified? To be clear, I am modifying the basis_mod variable, so I'd expect the basis variable not to change. However, when I print the basis variable, it is changing to be equal to the basis_mod variable. Note that, if I change the code to: import numpy as np i=2 j=0 basis = np.matrix([False,False,True,True,True]) basis_mod = np.matrix([False,False,True,True,True]) print "basis" print basis print "basis_mod" print basis_mod basis_mod[:,i] = False print "basis" print basis print "basis_mod" print basis_mod basis_mod[:,j] = True print "basis" print basis print "basis_mod" print basis_mod The print-out is as expected: basis False False True True True basis_mod False False True True True basis False False True True True basis_mod False False False True True basis False False True True True basis_mod True False False True True Therefore, I suspect the issue is with the line basis_mod = basis, but I don't understand why. Any help is greatly appreciated! This is majorly messing up an algorithm I'm trying to code.
has title: Python (Jupyter) "equals" assignment is creating changes in RHS variable downstream
type: Question
has answer: http://stackoverflow.com/a/50035916
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50036050

http://stackoverflow.com/comment/87075259
comment on: http://stackoverflow.com/a/50011499
has text: I updated my answer. Hope it is more clear now. Please see note at the end. Is that your situation?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86985762
score: 2
comment on: http://stackoverflow.com/q/49982799
type: Comment
has text: what happens if you open command line window and try telnet 127.0.0.1 5672 Do you get a timeout, connection failed or a successful connection?
type: QuestionComment

http://stackoverflow.com/comment/86931499
has text: @KonstantinNikitin The trouble with wrapping the `bytearray` is that then you pay the price of `__getitem__` and `__setitem__` implemented in Python, in which case you might as well use your `LazyArray` and have instantaneous construction.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49956832

http://stackoverflow.com/a/50063635
has comment: http://stackoverflow.com/comment/87144346
accepted answer of: http://stackoverflow.com/q/50063204
downvote count: 0
has body: This appears to work at the cost of some extra memory: C = ((B[:, :, None] - A.T)**2).sum(axis=1) Testing: import numpy D = 10 N = 20 M = 30 A = numpy.random.rand(N, D) B = numpy.random.rand(M, D) C = numpy.empty((M, N)) Timing: for m in range(M): C[m] = numpy.sum((B[m, :] - A)**2, axis=1) 514 µs ± 13.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) C2 = ((B[:, :, None] - A.T)**2).sum(axis=1) 53.6 µs ± 529 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50063204
has comment: http://stackoverflow.com/comment/87145207
type: AcceptedAnswer

tensor
tags question: http://stackoverflow.com/q/49960875
tags question: http://stackoverflow.com/q/49970141
tags question: http://stackoverflow.com/q/50054453
tag name: tensor
type: Tag
tags question: http://stackoverflow.com/q/49945462
tags question: http://stackoverflow.com/q/49943278

http://stackoverflow.com/q/49947878
tagged with: keras
has body: I am training a neural network with keras in python to predict whether 2 given phrases are paraphrases of each other but am getting some very strange behaviour. when I run something like this (semi pseudo code): for _ in range(10): predictions = train_and_predict_nn(features, test_size) print(predictions) I don't change any of the input parameters, only train and evaluate the neural network several times. Now when I look at the predictions for the test set, most of the time it only predicts one class. Sometimes though it predicts 2 classes (as it should). I am very confused by this behaviour, since I don't change any of the input parameters and still get such high fluctuations. The dataset is roughly balanced with about 60% of instances having the label 1 and the rest having the label 0. The dataset has roughly 10k instances. Can anybody explain this strange behaviour? Edit: I'll try to include some more information. This is the method I use to train the neural network and to classify the test set. def classify(feature_selection, test_size, feature_file_name): features, labels = parse(feature_file_name) X_train, X_test, y_train, y_test = get_features(features, labels, feature_selection, test_size) num_features = len(feature_selection) num_epochs = math.floor(len(X_train)/20) model = Sequential() model.add(Dense(num_features, input_dim=num_features, init='uniform', activation='relu')) model.add(Dense(3, init='uniform', activation='relu')) model.add(Dense(1, init='uniform', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, epochs=num_epochs, batch_size=20, verbose=0) #loss and accuracy score = model.evaluate(X_test, y_test) predictions = model.predict(X_train) rounded = [round(x[0]) for x in predictions] return model, score, rounded The input features are numeric. Printing X_train gives me something like this: [[0.2041 1. 0.0909 0.1667 0.] .... [0.1 1. 0. 0.6972 0.]] And for numpy.shape…
type: Question
has comment: http://stackoverflow.com/comment/86912386
has comment: http://stackoverflow.com/comment/86912455
has title: Neural network sometimes only predicts one label
has comment: http://stackoverflow.com/comment/86912487
tagged with: python
linked to: http://stackoverflow.com/q/41488279
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: neural-network

http://stackoverflow.com/comment/87111000
has text: No, `datetime.now()` returns the date/time when you *call* it. If you only call it when the module starts, well... `now` means *now*. Call it when the module starts and store the results.
comment on: http://stackoverflow.com/q/50045251
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49950568
has comment: http://stackoverflow.com/comment/139879616
downvote count: 0
has comment: http://stackoverflow.com/comment/86918019
upvote count: 4
answers question: http://stackoverflow.com/q/49950412
type: Answer
has body: Here is slightly different way to do it also: z = np.concatenate([x, y[~np.isin(y,x)])
score: 4

http://stackoverflow.com/comment/86942715
has text: Hi @cricket_700, can I ask another question? Now I want to save result into a .txt file, but I want to add a header to the .txt file, how should I do it? I used this statement: my_rdd.repartition(1).saveAsTextFile("sc_result/result.txt")
type: Comment
comment on: http://stackoverflow.com/a/49963324
score: 0
type: AnswerComment

http://stackoverflow.com/q/49972705
answer count: 1
has body: I have a dictionary with tuple keys, like so: (1111, 3454): 34.55555 (1123, 4665): 67.12 (1111, 9797): 5.09 I need to do a list comprehension that grabs the values for all entries with a matching first element. Problem is, I ALSO need that second value of the tuple... interimlist = [v for k,v in mydict.items() if k[0]==item[0]] Is what I've got right now for pulling the values if the first element of the tuple is correct (item is an iterator variable). I'd like the output to be a list of tuples of (value, second tuple number), so with the example points, would be the following output if item[0] is 1111: [(34.55555, 3454), (5.09, 9797)]
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49972763
has answer: http://stackoverflow.com/a/49972763
has title: Need to pull multiple values from python list comprehension?
downvote count: 0
upvote count: 1
tagged with: python
tagged with: list-comprehension
type: AnsweredQuestion
tagged with: python-2.7
tagged with: list
score: 1

http://stackoverflow.com/comment/86958602
has text: That's a 2d array. What's the encoding of this array? I suspect there are some initial characters that read as ''\xef\xbb\xbf'.
score: 0
comment on: http://stackoverflow.com/q/49969840
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50001309
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87122102
has comment: http://stackoverflow.com/comment/87120602
has comment: http://stackoverflow.com/comment/87121064
tagged with: comparison-operators
has comment: http://stackoverflow.com/comment/87018755
tagged with: python
downvote count: 6
has title: Why does the != operator not call my '__neq__' method?
has answer: http://stackoverflow.com/a/50001358
has body: I tried to implement some wildcard class that compares equal to any string, but false to anything else. However, the != operator does not appear to call my __neq__ member as expected: class A(str): def __cmp__(self, o): return 0 if isinstance(o, str) else -1 def __eq__(self, o): return self.__cmp__(o) == 0 def __neq__(self, o): return self.__cmp__(o) != 0 a = A() b = 'a' print(a == b) # Prints True, as expected print(a != b) # Prints True, should print False What am I doing wrong?
has comment: http://stackoverflow.com/comment/87020121
type: AnsweredQuestion
score: 1
upvote count: 7
answer count: 1
has comment: http://stackoverflow.com/comment/87121922
tagged with: methods
accepted answer: http://stackoverflow.com/a/50001358

http://stackoverflow.com/a/50033027
has body: I am still hoping for a magical incantation I can add to my _pth file that says "please put the directory containing any script I run in sys.path" so I do not have to modify all my scripts. However, it is possible that no such magical incantation exists. I have found that the following magical incantation, when added to a Python script, achieves the desired results. And, unlike other solutions you may find out there in the wild, this one will work in the context of cx_Freeze and IDLE and in any other context in which the simple file based solutions will not work. import inspect import os import sys # Add script directory to sys.path. # This is complicated due to the fact that __file__ is not always defined. def GetScriptFile(): """Obtains the full path and file name of the Python script.""" if hasattr(GetScriptFile, "file"): return GetScriptFile.file ret = "" try: # The easy way. Just use __file__. # Unfortunately, __file__ is not available when cx_freeze is used or in IDLE. ret = os.path.realpath(__file__) except NameError: # The hard way. if len(sys.argv) &gt; 0 and len(sys.argv[0]) &gt; 0 and os.path.isabs(sys.argv[0]): ret = os.path.realpath(sys.argv[0]) else: ret = os.path.realpath(inspect.getfile(GetScriptFile)) if not os.path.exists(ret): # If cx_freeze is used the value of the ret variable at this point is in # the following format: {PathToExeFile}\{NameOfPythonSourceFile}. This # makes it necessary to strip off the file name to get the correct path. ret = os.path.dirname(ret) GetScriptFile.file = ret return GetScriptFile.file def GetScriptDirectory(): """Obtains the path to the directory containing the script.""" if hasattr(GetScriptDirectory, "dir"): return GetScriptDirectory.dir module_path = GetScriptFile() GetScriptDirectory.dir = os.path.dirname(module_path) return GetScriptDirectory.dir sys.path.insert(0, GetScriptDirectory()) By the way, if you wish to see this in action, I have implement it my my Python Which project.
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50023869
upvote count: 2
answers question: http://stackoverflow.com/q/50023869
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/86936869
comment on: http://stackoverflow.com/q/49957822
has text: I think this helped, but I think a good portion of the problem is that /generator doesn't refresh the page when it calls itself after you type in a query. So `show.html` calls generator() again which keeps show.html from reloading? But I'm new to Flask and webdev, so I'm not sure if that's right
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50048338
type: Answer
has body: The answer depends on the version of Windows. In the olden days, you had to tinker in the registry. In newer versions, you could change the http protocol association with an interface or two. Then you could only propose an association through a different API and get the user to take action to confirm it. In the newest versions of Windows, they've made it virtually impossible to change certain kinds of defaults to protect the users from a war of defaults being waged by competing applications. If this is a one-off, I would just set it manually through the Default Programs control panel applet that's included in current versions of Windows. If you want to attempt it programmatically, this seems like a good entry point into the documentation.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50043664
score: 2

http://stackoverflow.com/comment/87133333
type: QuestionComment
comment on: http://stackoverflow.com/q/50055916
type: Comment
score: 0
has text: @PhaniKumarYadavilli The target is hive table.its already mentioned in the first line .

http://stackoverflow.com/q/50001562
has body: I have problem at my code I don't know priority of some lines, I want to make (Game guess the number), have user and computer player both have (10) points, so the user input number form 1 to 2, if (user input) == (number of guess), will -1 from computer points(10) = 9, and vice versa, so my problem at the points, after first time user input number it Become as they were automatically(10), sorry about my english so bad. at below my code, I hope any one help me thank you. from random import randint as any_number class Game(): def __init__(self, name, number, points): self.name = name self.number = number self.points = points def score(self, other): guess = any_number(1, 2) if self.number == guess: print('{} your are correct'.format(self.name)) other.points = other.points - 1 else: print('{} your are incorrect'.format(self.name)) print('{} points is ({}) and {} points is ({})'.format(self.name, self.points, other.name, other.points)) while True: user1 = int(input('Guess a number from 1 to 2: ')) computer = any_number(1, 2) p1 = Game('Player1', user1, 10) # &lt;---- my problem here p2 = Game('player2', computer, 10) # &lt;---- my problem here if type(user1) == int: p1.score(p2) print('================================================= ') p2.score(p1) else: print('your input is Error')
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50001722
has comment: http://stackoverflow.com/comment/87019318
upvote count: 0
has answer: http://stackoverflow.com/a/50001722
answer count: 1
downvote count: 3
score: -3
has title: I don't know priority of some lines OOP
favorite count: 0
type: AnsweredQuestion
tagged with: oop
tagged with: python

http://stackoverflow.com/q/49937868
has body: I am creating a sorting application that picks students out of a table and puts them in form groups. Gender should be equal across the groups. It loops through each table inserting random male students. I have used print functions to track what is happening. It seems like the loop is working since print(idMale) is printing rows out. However there hasn't been an insertion at all in the other table. And the program breaks and outputs this error: . Here is my code: # loops through each table for x in range(0,groupNumber): #Adds I to table name to go through each table nameGroupList.append('I') print(nameGroupList) nameGroup = ''.join(nameGroupList) #loop to select a student from the main table (sessionName) and insert them into another group #loop number is subject to the number of males that should be in 1 group for x in range(0, formMaleInt): selectMaleRow = cur.execute("SELECT * FROM " + sessionName + " WHERE Gender='M' ORDER BY random() Limit 1") #-----Find ID of student selected so they can be deleted from sessionName idMale = selectMaleRow.fetchone() print(idMale) idSepChar = list(idMale) idNum = idSepChar[0] idNumStr = str(idNum) #-----Find ID of student selected so they can be deleted from sessionName insertMaleRow = cur.execute("INSERT INTO " + nameGroup + " SELECT * FROM " + sessionName + " WHERE Gender='M' ORDER BY random() Limit 1") deleteMaleRow = cur.execute("DELETE FROM " + sessionName + " WHERE ID='" + idNumStr + "'") Here is my sessionName table: Here is my other table
upvote count: 3
type: UnansweredQuestion
has title: INSERT INTO not working. Unique Constraint Failed (Python SQLite)
tagged with: sqlite
downvote count: 1
favorite count: 0
type: Question
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/q/49937159
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/88370278
tagged with: keras
has comment: http://stackoverflow.com/comment/86893777
has comment: http://stackoverflow.com/comment/86890443
has comment: http://stackoverflow.com/comment/86890001
has comment: http://stackoverflow.com/comment/86889944
score: 1
tagged with: python
favorite count: 0
type: Question
has body: I know that in NN before creating model we should make X_train data between 0 and 1. But what about Y_train in regression NN? Should we keep original values or scale it too?
has title: Scale Y_train in keras?
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: neural-network

http://stackoverflow.com/a/49993904
type: Answer
answers question: http://stackoverflow.com/q/49947946
has body: Got the answer: make use of Matrices. First do a cross tabulation between the SRC and DST and then convert it to a binary matrix. We then do its transpose and then multiply both. The diagonal represents the unique numbers of DST number each SRC called and the non-diagonal represents the intersection of DST between 2 SRC
score: 0

http://stackoverflow.com/a/49936077
answers question: http://stackoverflow.com/q/49934624
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86910460
has body: You can do this by expanding the input and filters for proper automatic shape casting. # Assuming that input.size() is (N, D, W, H) and filters.size() is (F, D, 1, 1) input.unsqueeze_(1) filters.unsqueeze_(0) output = torch.sum((input - filters)**2, dim=2)
accepted answer of: http://stackoverflow.com/q/49934624
has comment: http://stackoverflow.com/comment/86909937
has comment: http://stackoverflow.com/comment/86909424
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86909338
has comment: http://stackoverflow.com/comment/86909776

http://stackoverflow.com/q/49974918
has comment: http://stackoverflow.com/comment/86966114
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86965884
score: 0
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49975060
has comment: http://stackoverflow.com/comment/86966045
has answer: http://stackoverflow.com/a/49975060
has body: Whenever i go to run the program it prompts me to enter the name when i do so it just sends the line where you type to the next line and i cant do anything but when i close it i see whatever i ctrl c the program i see whatever i should have been typing #This program searches for employees by name/prints info #set a boolean value to False found = False #get the search value name search = input("Enter a name to search for: ") #open the employe file in read mode empFile = open('employees.txt','r') #read the first line/the name field in the 1st rec name = empFile.readline() #if field has records, continue processing while name != '': #get id and dept id = empFile.readline() dept = empFile.readline() #strip newline from each string name = name.rstrip('\n') id = id.rstrip('\n') dept = dept.rstrip('\n') #determine if name matches search if name == search: #display record print('Name: ', name) print('ID: ', id) print('Department: ', dept) print() found = True #Read the name in the next record name = empFile.readline() #close the file empFile.close() #If search item not found, print message if found == False: print("The name was not found in the file") Traceback Enter a name to search for: as Traceback (most recent call last): File "C:\Users\adam\Desktop\CIS201\searchRecords.py", line 13, in id = empFile.readline() File "C:\Users\adam\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 22, in decode def decode(self, input, final=False): KeyboardInterrupt as requested the expected result should be it finding the name (or not depending on what you put) and either printing the name id and department or if you put a name that doesnt exist it should display the error message "The name was not found"
tagged with: python
has title: Command prompt goes blank

http://stackoverflow.com/a/51186232
score: 1
downvote count: 0
has body: pyconfig.h is part of the python-dev package. Installing python-dev can also fix your issue. See this question to understand more about what python-dev is: What is python-dev package used for
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89744780
answers question: http://stackoverflow.com/q/50044607

http://stackoverflow.com/a/49998536
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49998463
downvote count: 1
has body: You have a mistake, try: new = [] for i in A: new.append([i]) Here is more beautiful solution: new = [[i] for i in A]
score: 3

http://stackoverflow.com/comment/86962575
comment on: http://stackoverflow.com/q/49968663
score: 0
has text: Should I divide them by their sum?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49969602
has comment: http://stackoverflow.com/comment/86955237
has title: Class inheriting from dict but with element access
has comment: http://stackoverflow.com/comment/86955365
has body: I have classes that inherits from dict which look something like the following class Instance(dict): def __init__(self, element, space): dict.__init__(self, Type='instance', Space=space, Element=element ) I've done this so that I can easily serialise them into a JSON format string. What I'd also like to be able to do is to expose the keys inside the dict as members on the derived type, so that I can do Instance().Type rather than Instance['Type'] Is this possible and if so how can I do it?
has comment: http://stackoverflow.com/comment/86955330
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/86955322
has comment: http://stackoverflow.com/comment/86955254
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/49982843
answer count: 1
accepted answer: http://stackoverflow.com/a/50024045
has answer: http://stackoverflow.com/a/50024045
type: Question
score: 0
tagged with: python
has body: I'm working with a large excel file(30MB+,xlsm). Many of them contain photos in cell comments, so this file takes up so much space. First im open a file to read and get specific column name. Im open that with: self.wb = load_workbook(str(self.directory[0]), read_only=True, keep_vba=True, data_only=False) self.ws = self.wb['BAZA_PRACOWNIKOW'] self.sheet = self.wb.active After finding the appropriate cells, I open it again to add the relevant data to it: self.wb = load_workbook(str(self.directory[0]), read_only=False, keep_vba=True, data_only=False) self.ws = self.wb['BAZA_PRACOWNIKOW'] self.sheet = self.wb.active When I complete this file I would like to save it, so: self.wb.save('new.xlsm') After that i got an error: D:\Anaconda\lib\site-packages\openpyxl\reader\worksheet.py:310: UserWarning: Data Validation extension is not supported and will be removed warn(msg) The file size after saving decrease to 8mb. All photos in comments are not in new.xlsm file. Can someone help me ?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87063860
has title: Python OpenPyxl
tagged with: openpyxl

http://stackoverflow.com/q/49954843
has body: Following is the scenario I am dealing with : There is main process which launches a worker Process using Multiprocessing.Process. The worker process creates tkinter window for rendering. In case I wish to terminate rendering, I simply do process.terminate(). Although this programatically works, I see some artifacts on screen because window destruction is not properly done. My plan is to share the tkinter object with main process, thereby giving it ability to withdraw then destroy window. I tried, Multiprocessing.Queue , Multiprocessing.Manager but none works because of following error : TypeError: can't pickle _tkinter.tkapp objects I think my assumptions are wrong. What is the appropriate python programming technique to achieve this ?
score: 1
has answer: http://stackoverflow.com/a/49955913
favorite count: 0
tagged with: python-multiprocessing
type: Question
tagged with: tkinter
tagged with: multiprocessing-manager
has title: Share tkinter window object between python processes
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49955913

http://stackoverflow.com/a/49961685
has body: This is what you have to do to extract a value from an HTML element import bs4 as bs word = '&lt;ons-list-item id="itembtn" name="itembtn" value="{{ record [0] }}" tappable&gt;' soup = bs.BeautifulSoup(word,'lxml') supa = soup.find('ons-list-item',attrs={'id' : 'itembtn'}) value = supa.get('value') #print(value) #to find all values valuelist = [] supa = soup.find_all('ons-list-item',attrs={'id' : 'itembtn'}) for val in supa: value = val.get('value') valuelist.append(value) print(valuelist)
score: 2
has comment: http://stackoverflow.com/comment/86958432
answers question: http://stackoverflow.com/q/49961349
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/a/50014956
accepted answer of: http://stackoverflow.com/q/50008120
type: Answer
answers question: http://stackoverflow.com/q/50008120
has comment: http://stackoverflow.com/comment/87047684
type: AcceptedAnswer
downvote count: 0
has body: You need to save the CountVectorizer object too just as you are saving the nb. When you call CountVectorizer(analyzer=text_process).fit(x) you are re-training the CountVectorizer on new data, so the features (vocabulary) found by it will be different than at the training time and hence the saved nb which was trained on the earlier features complain about dimension mismatch. Better to pickle them in different files, but if you want you can save them in same file. To pickle both in same object: file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'wb') pickle.dump(bow_transformer, file) &lt;=== Add this pickle.dump(nb, file) To read both in next call: file = open(sentiment_MNB_path + 'sentiment_MNB_model.pickle', 'rb') bow_transformer = pickle.load(file) nb = pickle.load(file) Please look at this answer for more detail: https://stackoverflow.com/a/15463472/3374996
score: 1
upvote count: 1

http://stackoverflow.com/q/50043189
has comment: http://stackoverflow.com/comment/87102414
tagged with: sympy
linked to: http://stackoverflow.com/q/13055884
has answer: http://stackoverflow.com/a/50043951
has comment: http://stackoverflow.com/comment/87103711
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87102923
answer count: 2
has comment: http://stackoverflow.com/comment/87102342
downvote count: 0
possible better answer: http://stackoverflow.com/a/50043951
score: 7
upvote count: 7
tagged with: equation
has answer: http://stackoverflow.com/a/50047781
has body: I have to solve a equation in python, which i get as a string input. I don't know how many symbols are in the equation or what their signature is. A typical Symbol could be "mm", "cm", "x" or something like this. The function should return some kind of array/json with the solved equation. Little Example how it should look like: solve("x/2=4") &gt;&gt; ["x=8"] &gt;&gt; solve("x + 2 = y - 1") &gt;&gt; ["x=y-3", "y=x+3"] I tried to use SymPy-Module for this, but I didn't find a way to enter a dynamic string like above. SymPy seems to only accept "hardcoded" Symbols. Note: String comes from a "sys.argv"-Parameter.
accepted answer: http://stackoverflow.com/a/50047781
favorite count: 0
has title: Solve Equation (String) with Python to every Symbol
type: Question

http://stackoverflow.com/comment/86925341
has text: @ThierryLathuille Taken into consideration - editing now!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49954330

http://stackoverflow.com/comment/87001544
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49991182
type: Comment
has text: It did not work for me because Builder.work() is a static method. So still use @patch.object?

http://stackoverflow.com/q/50001278
linked to: http://stackoverflow.com/q/46688195
linked to: http://stackoverflow.com/q/455612
has comment: http://stackoverflow.com/comment/87019314
tagged with: python
has comment: http://stackoverflow.com/comment/87029482
favorite count: 0
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/87018834
tagged with: list
has comment: http://stackoverflow.com/comment/87021763
downvote count: 1
has answer: http://stackoverflow.com/a/56888037
has comment: http://stackoverflow.com/comment/87020493
has body: No, this is not a duplicate and the link above is specifically what I was referring to as not the correct answer. That link, and my post here specifically ask about producing a Decimal list. But the "answer" produces a float list. The correct answer is to use Decimal parameters with np.arange as in `x_values = np.arange(Decimal(-2.0), Decimal(2.0), Decimal(0.1)) Thanks https://stackoverflow.com/users/2084384/boargules I believe this may be answered elsewhere, but the answers I've found seem wrong. I want a list of decimals (precision = 1 decimal place) from -2 to 2. -2, -1.9, -1.8 ... 1.8, 1.9, 2.0 When I do: import numpy as np x_values = np.arange(-2,2,0.1) x_values I get: array([ -2.00000000e+00, -1.90000000e+00, -1.80000000e+00, ... I tried: from decimal import getcontext, Decimal getcontext().prec = 2 x_values = [x for x in np.around(np.arange(-2, 2, .1), 2)] x_values2 = [Decimal(x) for x in x_values] x_values2 I get: [Decimal('-2'), Decimal('-1.899999999999999911182158029987476766109466552734375'), Decimal('-1.8000000000000000444089209850062616169452667236328125'), ... I'm running 3.6.3 in jupyter notebook. Update: I changed the ranges from 2 to 2.0. This improved the result, but I still get a rounding error: import numpy as np x_values = np.arange(-2.0, 2.0, 0.1) x_values Which produces: -2.00000000e+00, -1.90000000e+00, -1.80000000e+00, ... 1.00000000e-01, 1.77635684e-15, 1.00000000e-01, ... 1.80000000e+00, 1.90000000e+00 Note 1.77635684e-15 may be an incredibly small number, but it's NOT zero. A test for zero will fail. Therefore the output is wrong. My response to the duplicate assertion. As you can see by my results the answer at How to use a decimal range() step value? does not produce the same results I'm seeing with a different range. Specifically floats are still being returned and not rounded and 1.77635684e-15 is not equal to zero.
has title: How to get a list of decimals in python 3
linked to: http://stackoverflow.com/q/477486
has comment: http://stackoverflow.com/comment/87019832
type: Question
tagged with: numpy
tagged with: decimal
has comment: http://stackoverflow.com/comment/87018665
answer count: 2
has comment: http://stackoverflow.com/comment/87018852
has comment: http://stackoverflow.com/comment/87019588
has comment: http://stackoverflow.com/comment/87021832
has answer: http://stackoverflow.com/a/50006748
type: UnansweredQuestion

http://stackoverflow.com/q/49932651
type: AnsweredQuestion
has body: How do you use basic ("default"/"built-in"; don't need to be imported) python methods in pybind11? Lists, dictionaries, and some others do have built-in compatibility, but the method I am looking specifically for (open) is not included via an import. I know that a way around it would be to create a python file with a method wrapping "open" and then calling it as you would any imported method, but I would prefer to do it directly in C++ (using pybind) if possible as otherwise that semi-defeats the purpose. Any assistance/advice would be greatly appreciated.
has comment: http://stackoverflow.com/comment/86968687
has title: Using built-in "open" python method in pybind11 (C++)?
type: Question
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/50070251
answer count: 1
downvote count: 0
tagged with: pybind11
tagged with: python
tagged with: python-3.6
has answer: http://stackoverflow.com/a/50070251
tagged with: c++11
favorite count: 0

http://stackoverflow.com/q/50032465
favorite count: 0
has title: Using list comprehension to print converted string?
has answer: http://stackoverflow.com/a/50296622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87081085
has body: I have been trying to use list comprehension to simplify this code: c = 0 conv_regx = r'(Conv2d).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*' for layer in list(cnn): if "Conv2d" in str(layer): print(re.sub(conv_regx, r'\3 \2 \4 \5', str(layer))) c+=1 if c == len(layerList['C']): break But my attempts result in errors: conv_regx = r'(Conv2d).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*' print_name = [str(re.sub(conv_regx, r'\3 \2 \4 \5', str(i))) if "Conv2d" in str(i) for i in list(cnn)] Like this error: print_name = [str(re.sub(conv_regx, r'\3 \2 \4 \5', str(i))) if "Conv2d" in str(i) for i in list(cnn)] ^ SyntaxError: invalid syntax How do I properly use list comprehension for this task? Edit: I fixed the for and if mix up, but how do I print the string? [print(str(re.sub(conv_regx, r'\3 \2 \4 \5', str(i)))) for i in list(cnn) if "Conv2d" in str(i) ] [print(str(re.sub(conv_regx, r'\3 \2 \4 \5', str(i)))) for i in list(cnn) if "Conv2d" in str(i) ] ^ SyntaxError: invalid syntax
score: 1
has comment: http://stackoverflow.com/comment/87081182
tagged with: list-comprehension
type: Question
has comment: http://stackoverflow.com/comment/87081184
has comment: http://stackoverflow.com/comment/87081264
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50296622

http://stackoverflow.com/a/49958158
answers question: http://stackoverflow.com/q/49956883
upvote count: 13
accepted answer of: http://stackoverflow.com/q/49956883
has comment: http://stackoverflow.com/comment/86938256
has comment: http://stackoverflow.com/comment/86935245
downvote count: 1
has body: The problem is basically generating a random permutation of the integers in the range 0..n-1. Luckily for us, these numbers have a very useful property: they all have a distinct value modulo n. If we can apply some mathemical operations to these numbers while taking care to keep each number distinct modulo n, it's easy to generate a permutation that appears random. And the best part is that we don't need any memory to keep track of numbers we've already generated, because each number is calculated with a simple formula. Examples of operations we can perform on every number x in the range include: Addition: We can add any integer c to x. Multiplication: We can multiply x with any number m that shares no prime factors with n. Applying just these two operations on the range 0..n-1 already gives quite satisfactory results: &gt;&gt;&gt; n = 7 &gt;&gt;&gt; c = 1 &gt;&gt;&gt; m = 3 &gt;&gt;&gt; [((x+c) * m) % n for x in range(n)] [3, 6, 2, 5, 1, 4, 0] Looks random, doesn't it? If we generate c and m from a random number, it'll actually be random, too. But keep in mind that there is no guarantee that this algorithm will generate all possible permutations, or that each permutation has the same probability of being generated. Implementation The difficult part about the implementation is really just generating a suitable random m. I used the prime factorization code from this answer to do so. import random # credit for prime factorization code goes # to https://stackoverflow.com/a/17000452/1222951 def prime_factors(n): gaps = [1,2,2,4,2,4,2,4,6,2,6] length, cycle = 11, 3 f, fs, next_ = 2, [], 0 while f * f &lt;= n: while n % f == 0: fs.append(f) n /= f f += gaps[next_] next_ += 1 if next_ == length: next_ = cycle if n &gt; 1: fs.append(n) return fs def generate_c_and_m(n, seed=None): # we need to know n's prime factors to find a suitable multiplier m p_factors = set(prime_factors(n)) def is_valid_multiplier(m): # m must not share any prime factors with n factors = prime_factor…
score: 12
has comment: http://stackoverflow.com/comment/86937131
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87067538
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50023985
has text: `pip 9.0.1 from /usr/lib/python3.6/dist-packages (python 3.6)` But when I do `python3 -m pip3 install bs4` I get `No module named pip3`
score: 0

http://stackoverflow.com/q/49957950
has comment: http://stackoverflow.com/comment/86932186
answer count: 0
tagged with: apache-spark
type: UnansweredQuestion
upvote count: 3
has body: In pyspark, I have a dataframe that contains a date column with the date truncated to the day # +-------------------+ # |d | # +-------------------+ # |2018-04-07 00:00:00| # +-------------------+ When I do this: df.write.partitionBy('d').parquet('s3://somebucket/out/') ... I expect to find key named like: s3://somebucket/out/d=2018-04-07 00:00:00/part-*-c*.snappy.parquet ... But, instead, I find this: s3://somebucket/out/d=2018-04-07 00%3A00%3A00/part-*-c*.snappy.parquet (note the '%3A' instead of ':') This wreaks havoc on the athena/hive/etc partitions. Is there a way to get pyspark to use a real colon instead of encoding it as %3A?
downvote count: 0
has title: How to get Dataframe partitions to include literal colons instead of encoded (%3A) colons in S3 key names
favorite count: 0
has comment: http://stackoverflow.com/comment/86932574
type: Question
has comment: http://stackoverflow.com/comment/86932483
score: 3
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: python

http://stackoverflow.com/comment/86977019
has text: what I need is the added packages that they have installed manually like `sas7bdat ` in list below
type: AnswerComment
comment on: http://stackoverflow.com/a/49980437
score: 0
type: Comment

http://stackoverflow.com/comment/86882088
has text: Could you please elaborate on what you mean by "wiped out"? I have confirmed that in my case, both the original and the new package are retained.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49932926
type: Comment

http://stackoverflow.com/comment/136503771
type: QuestionComment
comment on: http://stackoverflow.com/q/50006447
has text: learn [Branch-and-bound](https://web.mit.edu/15.053/www/AMP-Chapter-09.pdf) algo (or branch-and-cut to use constraint efficiently)
score: 0
type: Comment

http://stackoverflow.com/a/49969879
answers question: http://stackoverflow.com/q/49966061
score: -1
has body: Try this one: c.execute("INSERT INTO M_Memory(Name, Person, memory, value) SELECT ?, ?, ?, ? EXCEPT SELECT Name, Person, memory, value from M_Memory", (no1, no2, no3, value) ) EXCEPT, which is MINUS in other databases (such as Oracle), makes sure the row will not not be inserted if another row is already there with all values equal.
has comment: http://stackoverflow.com/comment/87019384
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87019510
downvote count: 1

http://stackoverflow.com/comment/86987445
type: AnswerComment
comment on: http://stackoverflow.com/a/49972198
score: 0
type: Comment
has text: I've modified it to support scalars and implemented your suggestion, @Eric.

http://stackoverflow.com/q/50050961
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50071244
tagged with: swig
type: Question
tagged with: python
type: UnansweredQuestion
has body: I am using SWIG to interface between C++ and Python. I want to add some code to the generated wrapper for setting a member variable in a struct. The closest I have found is this: %allowexception TAxis::Min; %exception TAxis::Min %{ $action do_something(); %} struct TAxis { double Min; double Max; }; However, this will call do_something() when TAxis::Min is both read and written. I want it to be called only when TAxis::Min is written. Any suggestions are appreciated.
tagged with: c++
downvote count: 0
has title: Adding custom code to SWIG wrapper
score: 1
upvote count: 1

http://stackoverflow.com/a/50031054
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50030168
score: 0
type: Answer
has body: simply loop through the json object and parse the value: d = { "dict_cars": [{ "model": "toyota", "plate": "A11", "tickets": [{ "amount": 50, "type": "A1" }, { "amount": 34, "type": "A2" } ] }, { "model": "mazda", "plate": "A11", "tickets": [{ "amount": 50, "type": "A1" }, { "amount": 34, "type": "A2" } ] } ] } dict_cars=[] dict_tickets=[] for i,j in d.items(): for k in j: dict_cars.append({k.get('model',''):k.get("plate","")}) for t in k.get('tickets',""): dict_tickets.append(t) print("dict_cars = ",dict_cars) print("dict_tickets = ",dict_tickets) out dict_cars = [{'toyota': 'A11'}, {'mazda': 'A11'}] dict_tickets = [{'amount': 50, 'type': 'A1'}, {'amount': 34, 'type': 'A2'}, {'amount': 50, 'type': 'A1'}, {'amount': 34, 'type': 'A2'}]
answers question: http://stackoverflow.com/q/50030168

http://stackoverflow.com/a/49933937
has comment: http://stackoverflow.com/comment/127030975
accepted answer of: http://stackoverflow.com/q/49933626
has comment: http://stackoverflow.com/comment/86892456
has body: Not surprisingly, the answer is yes. However, there is a much simpler way to do what you want. Let me begin with a bit of background first. plt.text is just a wrapper that creates a mpl.text.Text object on the current axes. Unfortunately, Text anchors itself based on the text alignment properties, and you can't specify an arbitrary point of the text box to anchor. This is unfortunate because there is a whole tutorial on how to position text using the axis transform (coordinate system) instead of the data. Fortunately, there are some helper classes in matplotlib.offsetbox that do exactly what you want. These classes are described in the tutorial, and a couple of relevant examples are shown in the sample gallery here and here. The particular class you are looking for is mpl.offsetbox.AnchoredText. You would set up your text box like this: from matplotlib.offsetbox import AnchoredText ... text_box = AnchoredText(box_text, frameon=True, loc=4, pad=0.5) plt.setp(text_box.patch, facecolor='white', alpha=0.5) plt.gca().add_artist(text_box) frameon=True makes the Patch behind the text visible. loc=4 lines up the bottom right corner of the box with that of the Axes. pad is now in units of fractions of your font size. plt.setp is a utility function to set multiple properties on an bunch of objects at once. The first argument in this case is just a single patch, but normally you would pass in a list of things to operate on. Since you have to add an AnchoredText directly to an Axes, I would recommend switching to the Object Oriented API. Your code would look very similar, but you would have more direct access to the underlying objects. You would create your figure and axes using something like plt.subplots. Then you would plot your data using the methods of Axes that correspond to the usual pyplot methods. Your code would look like this: from matplotlib import pyplot as plt from matplotlib.offsetbox import AnchoredText fig, ax = plt.subplots() ax.plot(...) text_box = AnchoredTe…
has comment: http://stackoverflow.com/comment/86910722
answers question: http://stackoverflow.com/q/49933626
type: Answer
has comment: http://stackoverflow.com/comment/86897729
upvote count: 18
score: 18
has comment: http://stackoverflow.com/comment/86897709
has comment: http://stackoverflow.com/comment/86892608
has comment: http://stackoverflow.com/comment/86907594
has comment: http://stackoverflow.com/comment/127031459
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/127031942
downvote count: 0
has comment: http://stackoverflow.com/comment/86897576

http://stackoverflow.com/comment/86967575
score: 0
has text: You can also subtract the resulting `Counter` objects. Something like `return counter1 - counter2`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49975388

http://stackoverflow.com/q/49967190
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86950638
has answer: http://stackoverflow.com/a/49967449
type: Question
has comment: http://stackoverflow.com/comment/86950687
has comment: http://stackoverflow.com/comment/86950739
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87005136
has comment: http://stackoverflow.com/comment/86951074
has comment: http://stackoverflow.com/comment/86951378
has title: How to extract features from URLs in python?
has body: I have just started work on a classification project which detects phishing websites. I am using uci dataset https://archive.ics.uci.edu/ml/machine-learning-databases/00327/Training%20Dataset.arff. I am trying several models on it like ANN, SVM, logistic regression and I have trained and tested the model. My logistic regression code looks like this #importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset dataset = pd.read_csv("phishcoop.csv") x = dataset.iloc[: , :-1].values y = dataset.iloc[:, -1] #Split the dataset into training and test from sklearn.cross_validation import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, train_size =0.75, random_state = 0) #fitting logistic regression into training set from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state =0) classifier.fit(x_train, y_train) #Predicting values for test data y_pred = classifier.predict(x_test) #checking accurancy using confusion matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) How do I extract the 30 features in my dataset from the url which the user will give as input?
upvote count: 2
tagged with: classification
score: 0
downvote count: 2
tagged with: url
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86951472

http://stackoverflow.com/comment/87064454
score: 0
comment on: http://stackoverflow.com/q/50023771
has text: Thank you so much, problem solved ~
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50065550
has answer: http://stackoverflow.com/a/50065841
has answer: http://stackoverflow.com/a/50065701
possible better answer: http://stackoverflow.com/a/50065701
downvote count: 0
upvote count: 1
tagged with: tensorflow
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50065841
has title: Extracting values from Tensorflow Variable
answer count: 3
score: 1
has body: I'm new to Python and Tensorflow and i'm facing some difficulties getting values from my NN after training phase. import tensorflow as tf import numpy as np import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) n_nodes_hl1 = 50 n_nodes_hl2 = 50 n_classes = 10 batch_size = 128 x = tf.placeholder('float',[None, 784]) y = tf.placeholder('float') def neural_network_model(data): hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,n_nodes_hl1]),name='weights1'), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]),name='biases1')} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2]),name='weights2'), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]),name='biases2')} output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_classes]),name='weights3'), 'biases': tf.Variable(tf.random_normal([n_classes]),name='biases3')} l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) , hidden_1_layer['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases']) l2 = tf.nn.relu(l2) output = tf.add(tf.matmul(l2, output_layer['weights']) , output_layer['biases']) return output def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 100 init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer() ) with tf.Session() as sess: sess.run(init) for epoch in range(hm_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples / batch_size)) : ep_x, ep_y = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer, cost], feed_dict = {x: ep_x, y: ep_y}) epoch_loss += c print('Epoch', epoch+1, 'completed out of', hm_epochs, 'loss:',epoch_loss) correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) prin…
tagged with: python
has answer: http://stackoverflow.com/a/70781655
favorite count: 0
type: Question

http://stackoverflow.com/comment/86866581
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49925045
has text: If that's what you want it to return, then yes.
score: 0

http://stackoverflow.com/a/50057118
answers question: http://stackoverflow.com/q/50055388
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50055388
downvote count: 0
type: Answer
upvote count: 1
has body: [SciPy]: numpy.vstack returns an [SciPy]: numpy.ndarray, while [Python]: random.sample(population, k) expects a sequence ([Python]: class collections.abc.Sequence) Example: &gt;&gt;&gt; import sys &gt;&gt;&gt; import random &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; "Python {:s} on {:s}".format(sys.version, sys.platform) 'Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32' &gt;&gt;&gt; &gt;&gt;&gt; a = np.array([[1], [2], [3]]) &gt;&gt;&gt; b = np.array([[2], [3], [4]]) &gt;&gt;&gt; data = np.vstack((a, b)) &gt;&gt;&gt; data array([[1], [2], [3], [2], [3], [4]]) &gt;&gt;&gt; random.sample(data, 4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "e:\Work\Dev\VEnvs\py35x64_test\lib\random.py", line 320, in sample raise TypeError("Population must be a sequence or set. For dicts, use list(d).") TypeError: Population must be a sequence or set. For dicts, use list(d). &gt;&gt;&gt; random.sample(data.tolist(), 4) [[3], [4], [2], [3]] Fix: Use numpy.ndarray.tolist(). In your code, replace centroids=random.sample(data,num_clust) by centroids = random.sample(data.tolist(), num_clust) or use list(data) (as the exception text instructs (for dicts)).

http://stackoverflow.com/a/49951888
has comment: http://stackoverflow.com/comment/86920348
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49951867
downvote count: 0
has body: Here's your code with spaces replaced by dots: #.-*-.coding:.utf-8.-*- class.OP(object): ..def.RECEIVE_MESSAGE(self): ......print("done") ..def.NOTIFIED_INVITE_INTO_GROUP(self): ....print("done") As you can see, the first print("done") statement is indented by 6 spaces - change it to 4 to fix the problem. Better still, change all indents so they are multiples of 4 spaces (ie 0, 4, 8, 12 etc), as recommended by PEP 8 #.-*-.coding:.utf-8.-*- class.OP(object): ....def.RECEIVE_MESSAGE(self): ........print("done") ....def.NOTIFIED_INVITE_INTO_GROUP(self): ........print("done") More detail, from Python: Myths about Indentation How does the compiler parse the indentation? The parsing is well-defined and quite simple. Basically, changes to the indentation level are inserted as tokens into the token stream. The lexical analyzer (tokenizer) uses a stack to store indentation levels. At the beginning, the stack contains just the value 0, which is the leftmost position. Whenever a nested block begins, the new indentation level is pushed on the stack, and an "INDENT" token is inserted into the token stream which is passed to the parser. There can never be more than one "INDENT" token in a row. When a line is encountered with a smaller indentation level, values are popped from the stack until a value is on top which is equal to the new indentation level (if none is found, a syntax error occurs).
has comment: http://stackoverflow.com/comment/86920232
score: 5

http://stackoverflow.com/a/49967895
answers question: http://stackoverflow.com/q/49948868
type: Answer
score: 0
has body: Installing all the dependencies via Conda solves it.

http://stackoverflow.com/comment/135113422
type: AnswerComment
has text: Avoid code only answer and provide an explanation;
score: 2
type: Comment
comment on: http://stackoverflow.com/a/76619981

http://stackoverflow.com/comment/114894871
has text: did you find any solution to this ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49939860
score: 0
type: Comment

http://stackoverflow.com/comment/86934700
has text: Not related to Python, but [Why `while (!file.eof())` is wrong in C++](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49959094
type: Comment

http://stackoverflow.com/q/49987747
downvote count: 0
has answer: http://stackoverflow.com/a/49987964
upvote count: 1
has title: How to run .sh script in python script and use the output in Python
favorite count: 0
has body: The .sh script contains all the paths and variables which I might need in my python script. I do not want to create a .py file and export it in my program as that will require lot of changes. I tried using subprocess module but not sure how to get the variables for using in py script. Is there any way or I will ultimately have to import a new .py file containing all declarations. Thanks in advance.
score: 1
linked to: http://stackoverflow.com/q/89228
answer count: 1
tagged with: python
type: Question
duplicate of: http://stackoverflow.com/q/89228
type: UnansweredQuestion

http://stackoverflow.com/comment/87047890
has text: Thank you so much, @jezrael, you are correct till making new column headers. And it works fine. However, there is a small cache that not all equities are end with "KS Equity" There are also some "JP Equity" in the data so the result is,
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50015713

http://stackoverflow.com/comment/87541619
type: AnswerComment
has text: You need to learn to separate functions that perform input and output from functions that compute results.
comment on: http://stackoverflow.com/a/50070275
type: Comment
score: 0

http://stackoverflow.com/comment/86934796
type: AnswerComment
comment on: http://stackoverflow.com/a/49956903
type: Comment
has text: Hi Lukisn yes I'm using Python 2.7.13. Do you mean - class Example(Frame): def Frame__init__(self, root): ? Sorry, I still very much a beginner on Python.
score: 0

http://stackoverflow.com/q/49964765
has answer: http://stackoverflow.com/a/49964944
favorite count: 0
type: Question
has body: I have two huge 2d numpy integer arrays X and U, where U is assumed to have only unqiue rows. For each row in X I would like to get the corresponding row index of the matching row in U (if there is one, otherwise -1). E.g., if the following arrays are passed as inputs: U = array([[1, 4], [2, 5], [3, 6]]) X = array([[1, 4], [3, 6], [7, 8], [1, 4]]) the output should be: array([0,2,-1,0]) Is there an efficient way of doing this (or something similar) with Numpy? @ Divakar: Your approach fails for me print(type(rows), rows.dtype, rows.shape) print(rows[:10]) print(search2D_indices(rows[:10], rows[:10])) &lt;class 'numpy.ndarray'&gt; int32 (47398019, 5) [[65536 1 1 1 17] [65536 1 1 1 153] [65536 1 1 2 137] [65536 1 1 3 153] [65536 1 1 9 124] [65536 1 1 13 377] [65536 1 1 13 134] [65536 1 1 13 137] [65536 1 1 13 153] [65536 1 1 13 439]] [ 0 1 2 3 4 -1 -1 -1 -1 9]
tagged with: numpy
tagged with: arrays
linked to: http://stackoverflow.com/q/38674027
tagged with: python
has answer: http://stackoverflow.com/a/49964970
accepted answer: http://stackoverflow.com/a/49964944
possible better answer: http://stackoverflow.com/a/49964810
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49964810
has title: For each row of a 2d numpy array get the index of an equal row in a second 2d array
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/45313301

http://stackoverflow.com/comment/87131230
comment on: http://stackoverflow.com/a/50056788
type: AnswerComment
score: 0
has text: Nice, small suggestion - try rotate labels in x-axis :)
type: Comment

http://stackoverflow.com/q/50006810
has answer: http://stackoverflow.com/a/50018237
has title: Web scraping using selenium and not be able to move on to the next webpage
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has body: So I have been trying to webscrape from ZALORA, it seems selenium keep scraping repeated data....... Here is my codes: from selenium import webdriver import time driver = webdriver.Chrome() url = 'https://www.zalora.com.hk/men/clothing/shirt/?gender=men&dir=desc&sort=popularity&category_id=31&page=1&enable_visual_sort=1' driver.get(url) driver.implicitly_wait(30) brandname='' productTitle='' page=0 while True: info_brandname = '' info_product_title = '' page=page+1 if len(info_brandname) < 99 or len(info_product_title) < 99: info_brandname = driver.find_elements_by_xpath('//span[@class="b-catalogList__itmBrand fsm txtDark uc js-catalogProductTitle"]') info_product_title = driver.find_elements_by_xpath('//em[@class="b-catalogList__itmTitle fss"]') print('info_brandname ' + str(len(info_brandname)) + ' at page ' + str(page)) print('info_product_title ' + str(len(info_product_title)) + ' at page ' + str(page)) else: print('info_brandname ' + str(len(info_brandname)) + ' at page ' + str(page)) print('info_product_title ' + str(len(info_product_title)) + ' at page ' + str(page)) #some manipulation of the scrapped data for i in range(len(info_brandname)): brandname = brandname + '\n' + info_brandname[i].text productTitle = productTitle + '\n' + info_product_title[i].text print(brandname.split('\n')[1:]) print(productTitle.split('\n')[1:]) Here is the part I suspect has gone wrong: #go to the next page before it loops again try: test = driver.find_element_by_xpath("//a[@title='Next']") driver.execute_script("arguments[0].click();", test) except: print('there is no next page man...') time.sleep(2) print(str(driver.current_url)) driver.close() EDIT: At the moment, the very last item's name should be 'Life8' according to the website, but I got 'J.Crew', and I have scraped 1885 items in total, while the website says they have only 1847 items in total. The pages' url were actually changing while the script was running, along with the items on each page, everything behaves norma…
tagged with: python
has comment: http://stackoverflow.com/comment/87049787
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87030500
tagged with: selenium
has answer: http://stackoverflow.com/a/50008430
has comment: http://stackoverflow.com/comment/87030262

http://stackoverflow.com/a/50056476
has comment: http://stackoverflow.com/comment/87277975
has comment: http://stackoverflow.com/comment/87272588
type: Answer
has comment: http://stackoverflow.com/comment/87165232
answers question: http://stackoverflow.com/q/50056380
score: 1
downvote count: 0
has body: You can convert the image to binary, and compute sum of pixel intensities over image rows, and count peaks in it, then compute the sum of pixel intensities over image columns, and count peaks in it. Those would be the number of horizontal and vertical lines found in the image. Then N = (num_of_horizontal_lines - 1) * (num_of_vertical_lines - 1). Example code (using numpy and Pillow): &gt;&gt;&gt; from PIL import Image &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; im = np.array(Image.open('cJyt5.png').convert('L')) &gt;&gt;&gt; threshold = np.histogram(im, 2)[1][1] &gt;&gt;&gt; im2 = im &lt; threshold &gt;&gt;&gt; vert_lines = sum(np.mean(im2, axis=0) &gt; 0.5) &gt;&gt;&gt; horiz_lines = sum(np.mean(im2, axis=1) &gt; 0.5) &gt;&gt;&gt; (vert_lines - 1) * (horiz_lines - 1) 78 If the lines are more than 1 pixel thick, you need to slightly change the code to not take into account multiple consecutive True values in np.mean(...) &gt; 0.5. A simple trick would be to do sum(np.max(0, np.diff(np.mean(...) &gt; 0.5))) to count the number of changes from False to True. (not tested)
upvote count: 1
has comment: http://stackoverflow.com/comment/87278170

http://stackoverflow.com/a/50060395
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87138327
has comment: http://stackoverflow.com/comment/87138373
downvote count: 0
has comment: http://stackoverflow.com/comment/87138120
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50060127
type: Answer
has body: Here is a solution that should cover most cases. from fractions import Fraction from math import ceil def convert_recipe(recipe): weight = {'tbsp': 15, 'tsp': 5} # store the weights for tsp and tbsp ts = 'tbsp' if 'tbsp' in recipe else 'tsp' temp = recipe.split() # convert string to list quantity = float(Fraction(temp[temp.index(ts)-1])) new_recipe = recipe.replace(ts, '{} ({}g)'.format(ts, ceil(quantity*weight[ts]))) # see (1) return new_recipe print(convert_recipe("2 tbsp of butter")) # -&gt; 2 tbsp (30g) of butter print(convert_recipe("1/2 tbsp of butter")) # -&gt; 1/2 tbsp (8g) of butter print(convert_recipe("1/2 tsp of salt")) # -&gt; 1/2 tsp (3g) of salt (1): here are are actually replacing the 'tbsp' part of the sentence with 'tbsp (30g)' for example. The string that is inserted ('tbsp (30g)') is a result of string formating.
has comment: http://stackoverflow.com/comment/87138215
answers question: http://stackoverflow.com/q/50060127

http://stackoverflow.com/a/50001409
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50001168
has body: Maybe this is what you are looking for: d = dict(second_list) flat = [a+[d[a[0]]] for a in first_list] It gives me: flat = [['aaa', 551, 10972, 240], ['bbb', 552, 10872, 120], ['ccc', 553, 11103, 325], ['ddd', 554, 10912, 270]] This way the order of your second list does not matter.
type: Answer
downvote count: 0

http://stackoverflow.com/q/49932863
has body: Implement the ADT double-ended queue. This ADT is similar to a queue, but supports functions to add and remove from either end of the queue. It seems I am struggling with the remove part. This is what I tried: class deq: def __init__(self): self.item = [] def is_empty(self): return self.item == None def size(self): return len(self.item) def add_front(self, item): self.item.insert(0,item) def add_back(self, item): selft.item.append(item) def remove_front(self, item): self.item.remove(item) def remove_back(self, item): self.item.pop() The sample screenshot of output: This is the sample output
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/76619981
type: Question
answer count: 2
has title: python ADT double-ended queue
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49932940

http://stackoverflow.com/q/49949296
score: -2
has body: if I have 2 dict: d1={1:[2,3,str],2:[4,5,str2]} d2={3:[6,7],2:[8,9]} and I want to create a new dictionary that will contain only the keys that appear in both dictionaries new_d={2:[4,5,str2,8,9]}
has comment: http://stackoverflow.com/comment/86915487
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86915498
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86915482
downvote count: 3
has comment: http://stackoverflow.com/comment/86915617
has comment: http://stackoverflow.com/comment/86915693
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49949443
has comment: http://stackoverflow.com/comment/86915110
has answer: http://stackoverflow.com/a/49949443
type: Question
tagged with: python
has title: how to merge two dict to one

http://stackoverflow.com/comment/87048956
type: AnswerComment
has text: try to add more than one user_service and passwords and thin u will find this bug
comment on: http://stackoverflow.com/a/50016087
type: Comment
score: 0

http://stackoverflow.com/comment/87069348
score: 0
type: Comment
has text: @Abhishakegupta I think argparse is pretty overkill for our solution. But thanks for the suggestion
type: QuestionComment
comment on: http://stackoverflow.com/q/50024655

http://stackoverflow.com/comment/87095897
comment on: http://stackoverflow.com/a/50039184
score: 0
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169845/discussion-between-potato-and-blownhither-ma).
type: Comment

http://stackoverflow.com/q/50047349
has body: I am trying to select the first searchbox on this website: https://www.ris.bka.gv.at/Bundesrecht/ This is my code: for ii in testList2: varTitel = ii searchBox = driver.find_element_by_id('MainContent_SuchworteField') searchBox = driver.find_element_by_xpath('//*[@id="MainContent_SuchworteField"]/span') searchBox = driver.find_element_by_name('MainContent_SuchworteField_Value') searchBox.send_keys(varTitel) searchBox.send_keys(Keys.ENTER) time.sleep(1) print("Query link: " + driver.current_url) driver.back() driver.quit() As you can see, I tried three ways of selecting the searchbox. Everytime I am getting NoSuchElement exceptions. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"MainContent_SuchworteField"} selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="MainContent_SuchworteField"]/span"} selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"name","selector":"MainContent_SuchworteField_Value"} Here is a snippet of what is being shown after inspecting the site. I hope you can help me, Cheers
tagged with: web-scraping
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50052167
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50049060
tagged with: python
has title: Python/Selenium Can't find searchbox
tagged with: selenium-webdriver
tagged with: xpath
answer count: 2
downvote count: 0
upvote count: 1
score: 1
tagged with: selenium

http://stackoverflow.com/comment/87104168
type: QuestionComment
comment on: http://stackoverflow.com/q/50043735
has text: I do have those.
score: 0
type: Comment

http://stackoverflow.com/q/49973504
type: UnansweredQuestion
downvote count: 0
tagged with: amazon-ec2
has body: I'm trying to set up a Jupyter Server using AWS EC2 starting with a Deep Learning AMI (Ubuntu) Version 7.0 AMI. It says that it comes with separate virtual environments: Comes with latest binaries of deep learning frameworks pre-installed in separate virtual environments: MXNet, TensorFlow, Caffe, Caffe2, PyTorch, Keras, Chainer, Theano and CNTK. So I ssh into the instance and found an directory ~/anaconda3/envs/ which contains a bunch of folders like tensorflow_p36. But I was unable to find the activate files in them. There doesn't seem to be any other folder that looks remotely like a virtual env so I'm stuck. Can someone help me? Thanks!
tagged with: amazon-web-services
favorite count: 0
type: Question
score: 3
tagged with: virtual-environment
has answer: http://stackoverflow.com/a/60744922
tagged with: python
has answer: http://stackoverflow.com/a/53794263
has comment: http://stackoverflow.com/comment/87034397
has comment: http://stackoverflow.com/comment/86976750
answer count: 2
tagged with: deep-learning
has title: AWS Deep Learning AMI Virtual Environment Activation
upvote count: 3

http://stackoverflow.com/a/49999229
has body: You could for example sub out all the characters other than bbbb2. df = pd.DataFrame(data={"Col1": ["bbbb2"], "Col2": ["Hello I want to removebbbb2"]}) df["Col2"].str.replace("(?:\S*)?(bbbb2)(?:\S*)?", "\\1") Out[29]: 0 Hello I want to bbbb2 Name: Col2, dtype: object Edit: For multiple rows, e.g. import re df = pd.DataFrame(data={"Col1": ["bbbb2", "aaaa1"], "Col2": ["Hello I want to removebbbb2", "Hello I want to remaaaa1"]}) df["out"] = df.apply(lambda x: re.sub("(?:\S*)?(" + x[0] + ")(?:\S*)?", "\\1", x[1]), axis=1) df Out[127]: Col1 Col2 out 0 bbbb2 Hello I want to removebbbb2 Hello I want to bbbb2 1 aaaa1 Hello I want to remaaaa1 Hello I want to aaaa1
type: Answer
has comment: http://stackoverflow.com/comment/87021220
accepted answer of: http://stackoverflow.com/q/49998613
has comment: http://stackoverflow.com/comment/87018901
has comment: http://stackoverflow.com/comment/87020316
has comment: http://stackoverflow.com/comment/87021140
has comment: http://stackoverflow.com/comment/87020119
score: 0
has comment: http://stackoverflow.com/comment/87152520
has comment: http://stackoverflow.com/comment/87022064
has comment: http://stackoverflow.com/comment/87020564
has comment: http://stackoverflow.com/comment/87021011
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87022745
has comment: http://stackoverflow.com/comment/87020904
answers question: http://stackoverflow.com/q/49998613

http://stackoverflow.com/comment/87095875
score: 0
type: Comment
type: QuestionComment
has text: You can run the simulation and the plotting logic in two different threads and update the figure repeatedly. This way the simulation thread won't be blocked.
comment on: http://stackoverflow.com/q/50039928

http://stackoverflow.com/comment/87062316
score: 0
type: Comment
has text: @SumitJha so it's not possible to create the primordially xml with the same representation of empty nodes? Would there be an solution for avoing the character entities?
type: QuestionComment
comment on: http://stackoverflow.com/q/50022116

http://stackoverflow.com/a/49992362
has comment: http://stackoverflow.com/comment/87177368
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/136843616
has comment: http://stackoverflow.com/comment/138009048
has comment: http://stackoverflow.com/comment/110275600
accepted answer of: http://stackoverflow.com/q/49992300
has comment: http://stackoverflow.com/comment/87160283
answers question: http://stackoverflow.com/q/49992300
type: Answer
upvote count: 114
has comment: http://stackoverflow.com/comment/87160449
has comment: http://stackoverflow.com/comment/87179492
has body: Yes, if you use notebook interface. Basically, install Python Extension Pack, it includes Jupyter extension, put your code in the editor, put #%% at the top of your code, you'll get Run cell clickable, click it, and you'll get result in the other window Here is the link to the extension: https://marketplace.visualstudio.com/items?itemName=donjayamanne.jupyter UPDATE Ok, apparently Microsoft hired Don Jayamanne and he's working on Python and Jupyter for VS Code. And last month they (MS) improved their python extension to support Jupyter notebooks right in the Visual Code together with .ipynb import and export. Get extension here and check blog post how to use it with Jupyter notebooks. UPDATE II Another one is Neuron, under development, but looks nice - again, notebooks in VS Code, with graphs, markdown etc. Get it here UPDATE III Using interactive matplotlib graphs works as well in VS Code, check https://matplotlib.org/ipympl/ for details
score: 112
has comment: http://stackoverflow.com/comment/87177507
downvote count: 2

http://stackoverflow.com/comment/86977492
comment on: http://stackoverflow.com/a/49980331
type: Comment
has text: See: [List Comprehensions in Python](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python) They are the most fun part of Python! Basically, it says "Make a list of all Keys of the tags on this instance". In general, there should rarely be a need for a normal `for` command. (Nested for loops hurt my brain, so I kept some here, but there is not need for the last bit.)
score: 2
type: AnswerComment

http://stackoverflow.com/q/50065572
has body: I created a parquet dataset by reading data into a pandas df, using get_dummies() on the data, and writing it to a parquet file: df = pd.read_sql(query, engine) encoded = pd.get_dummies(df, columns=['account']) encoded.to_parquet('encoded.parquet') The pandas df was 2.7M rows and 4,000 columns. Next, I read the parquet data into a dask df and attempted to perform a groupby on it: c = Client() df = dd.read_parquet('encoded.parquet') result = c.compute(df.groupby(df.journal_entry).max()) The resulting df is 600,000 rows and 4,000 columns. I have 32 GB of RAM on my machine. After a small amount of time of attempted calculation, a memory error results. This is the traceback: --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) &lt;ipython-input-29-083067d43616&gt; in &lt;module&gt;() ----&gt; 1 result.result() ~\_installed\anaconda\lib\site-packages\distributed\client.py in result(self, timeout) 156 self._result, raiseit=False, callback_timeout=timeout) 157 if self.status == 'error': --&gt; 158 six.reraise(*result) 159 elif self.status == 'cancelled': 160 raise result ~\_installed\anaconda\lib\site-packages\six.py in reraise(tp, value, tb) 683 value = tp() 684 if value.__traceback__ is not tb: --&gt; 685 raise value.with_traceback(tb) 686 raise value 687 ~\_installed\anaconda\lib\site-packages\zict\buffer.py in __setitem__() 80 self.fast[key] = value 81 else: ---&gt; 82 self.slow[key] = value 83 84 def __delitem__(self, key): ~\_installed\anaconda\lib\site-packages\zict\func.py in __setitem__() 40 41 def __setitem__(self, key, value): ---&gt; 42 self.d[key] = self.dump(value) 43 44 def __contains__(self, key): ~\_installed\anaconda\lib\site-packages\distributed\protocol\serialize.py in serialize_bytelist() 342 343 def serialize_bytelist(x): --&gt; 344 header, frames = serialize(x) 345 frames = frame_split_size(frames) 346 if frames: ~\_installed\anaconda\lib\site-packages\distributed\protocol\serialize…
has comment: http://stackoverflow.com/comment/87152795
tagged with: parquet
has answer: http://stackoverflow.com/a/50068559
answer count: 1
has comment: http://stackoverflow.com/comment/87153187
tagged with: dask-distributed
has comment: http://stackoverflow.com/comment/87153014
accepted answer: http://stackoverflow.com/a/50068559
type: AnsweredQuestion
has title: Dask Memory Error Grouping DF From Parquet Data
tagged with: dask
has comment: http://stackoverflow.com/comment/87153050
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87152868
tagged with: python
type: Question

http://stackoverflow.com/comment/87001688
has text: The problem is nothing to do with `else` or `elif`; it's with `diceI == "D4" or "d4"`. We'll find you a duplicate question with a good answer, but the short version is that you want `diceI in {"D4", "d4"}` or `diceI.lower() == 'd4'` here.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49992556
score: 1

http://stackoverflow.com/comment/87150474
comment on: http://stackoverflow.com/a/50064444
type: Comment
type: AnswerComment
score: 0
has text: (Probably) try to follow the rules that the other users posted. In addition, present a question that is succinct and as limited in scope as possible. For instance, "I can't see for the life of me why [my program isn't functioning correctly]" is not a good question, if it even is a question. Unfortunately, although you did provide all the necessary info to come to a solution, the scope of the problem was too large; debug your program as far as you can, then ask the question about whatever remains that needs explaining. Also, rather than explaining the program here, comment it in your code! :)

http://stackoverflow.com/comment/87069391
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50018415
score: 0
has text: @Mayra Let x = (timestamp minus previous midnight). I don't remember if arithmetic on timestamps is defined in Python; you might have to do something like timestamp.seconds(). I don't remember how to get the previous midnight, but I'm sure you can look it up.

http://stackoverflow.com/comment/87124401
comment on: http://stackoverflow.com/q/50053803
has text: You could determine the min and max during the `for` loops, rather than doing it as a separate step.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/59657830
answers question: http://stackoverflow.com/q/49918479
has body: Try running: conda install -c pytorch pytorch
upvote count: 0
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/comment/86913117
type: QuestionComment
comment on: http://stackoverflow.com/q/49948152
score: 0
type: Comment
has text: One way to think about it is that a python variable doesn't have a type but the object references does. You can assign any object to the variable and then when you use that object, type matters. In a statically typed language, you can only assign some types of objects. Like for intance an string variable can only take a string object.

request
tags question: http://stackoverflow.com/q/49991912
tag name: request
tags question: http://stackoverflow.com/q/50068957
type: Tag
tags question: http://stackoverflow.com/q/50047128
tags question: http://stackoverflow.com/q/50024642
tags question: http://stackoverflow.com/q/49952697

http://stackoverflow.com/comment/86969987
comment on: http://stackoverflow.com/a/49974183
has text: This won't work, it will just give the first image from the generator's filenames list, not the first image that it returns.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87028558
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49948091
has text: The transcoding section also has an inaccuracy, Python 2 allows binary transforms where there isn't implicit conversion. For example, 'base64' codec and 'unicode-escape' codec. And user can register custom codecs, in Python 2 there is no such restriction "str can only be decoded and unicode encoded", it's just convention.
score: 0

http://stackoverflow.com/comment/86869898
has text: It's doing exactly what you told it to do. strip only removes from the ends of the string, maybe you wanted str.replace.
score: 6
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49926934

http://stackoverflow.com/q/50033312
tagged with: keras
linked to: http://stackoverflow.com/q/59017288
tagged with: tensorflow
linked to: http://stackoverflow.com/q/48816873
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/42112260
tagged with: tensorflow-gradient
has body: I would like to monitor the gradient changes in tensorboard with keras to decide whether gradient vanish or explosion. What should I do?
has title: How to monitor gradient vanish and explosion in keras with tensorboard?
tagged with: tensorboard
tagged with: python
accepted answer: http://stackoverflow.com/a/50048179
upvote count: 18
has answer: http://stackoverflow.com/a/50048179
type: AnsweredQuestion
downvote count: 0
score: 18
answer count: 1

http://stackoverflow.com/q/49987244
score: 2
has answer: http://stackoverflow.com/a/51383349
has answer: http://stackoverflow.com/a/66509177
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/86990793
accepted answer: http://stackoverflow.com/a/49987571
tagged with: pyqt5
has title: PyQt5: Find which QPushButton is clicked
has answer: http://stackoverflow.com/a/49987571
possible better answer: http://stackoverflow.com/a/51383349
downvote count: 1
favorite count: 0
type: Question
answer count: 5
has answer: http://stackoverflow.com/a/49987318
has body: I have multiple buttons &amp; want to know which button is clicked. I have found out the error and know that the sender() function has to work with QWidget rather than the class object, but I can't figure out the solution. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): """Widget code here""" self.btn1 = QtWidgets.QPushButton(self.widget) """Button properties here""" self.btn1.setObjectName("btn1") self.btn1.clicked.connect(self.btnListener) self.btn2 = QtWidgets.QPushButton(self.widget) self.btn2.setObjectName("btn2") self.btn2.clicked.connect(self.btnListener) """..... more buttons""" def btnListener(self): sender_button = self.sender() # Error Ui_MainWindow has no attribute sender print(sender_button) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
tagged with: python
has answer: http://stackoverflow.com/a/68108987
linked to: http://stackoverflow.com/q/41133614
tagged with: qpushbutton

http://stackoverflow.com/comment/87010875
type: Comment
comment on: http://stackoverflow.com/a/49997047
has text: it is, but you can't dump it using pickle... that was my problem... doing as @AKX suggests everything is fine..
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86924056
comment on: http://stackoverflow.com/q/49953723
has text: Try running it with e.g. http://pythontutor.com/visualize.html#mode=edit - some *do* get deleted, but your logic is wrong so not all pairs are compared.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49968377
tagged with: python
tagged with: kafka-python
downvote count: 0
score: 7
upvote count: 7
answer count: 1
has comment: http://stackoverflow.com/comment/86965938
has title: How to get the latest offset value from a confluent_python AVRO consumer
has comment: http://stackoverflow.com/comment/86969090
has body: I am pretty new to confluent_kafka but I've gained some experience with kafka-python. What I am trying to do is changing the offset where to start consuming messages. This why I'd like to build a consumer client able to move back to previous messages in order to return data that will populate a dashboard. Said that using the kafka-python package I can use the seek_to_end (https://github.com/dpkp/kafka-python/blob/c0fddbd24269d4333e3b6630a23e86ffe33dfcb6/kafka/consumer/group.py#L788) method in order to get the position value of the latest commit. Having that I can subtract values and get back to the previous messages using the seek method (https://github.com/dpkp/kafka-python/blob/c0fddbd24269d4333e3b6630a23e86ffe33dfcb6/kafka/consumer/group.py#L738) On the other hand, the conflient_kafka seems to have no similar functions and what I've found so far is to use the variables OFFSET_END which has a value of -1 and it doesn't return me the offset numeric value of the latest and largest one. I can use the 'seek' function as well, but I need a way to have the numeric value of the latest offset and not -1. My avro consumer looks like from confluent_kafka.avro import AvroConsumer if __name__ == '__main__': c = AvroConsumer({"bootstrap.servers": "locahost:29092", "group.id":"mygroup",'schema.registry.url': 'http://localhost:8081', 'enable.auto.commit': True,'default.topic.config': {'auto.offset.reset': 'smallest'}}) def my_assign (consumer, partitions): for p in partitions: p.offset = confluent_kafka.OFFSET_END print("offset=",p.offset) print('assign', partitions) print('position:',consumer.position(partitions)) consumer.assign(partitions) c.subscribe(["mytopic"],on_assign=my_assign) while True: m = c.poll(1) if m is None: continue if m.error() is None: print('Received message', m.value(),m.offset()) c.close() which produces the following result: offset= -1 assign [TopicPartition{topic=mytopic,partition=0,offset=-1,error=None}] position: [TopicPartition{topic=mytopic,partitio…
favorite count: 0
type: Question
tagged with: confluent-platform
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56929466

http://stackoverflow.com/a/50049694
has comment: http://stackoverflow.com/comment/87115744
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50046667
accepted answer of: http://stackoverflow.com/q/50046667
type: Answer
has body: Numerical solvers use "probing" values at states that are close but not on the solution trajectory. Loosely speaking, this samples the direction field around the trajectory so that the computed value for the next step may be more accurate. Use the documented paths to obtain the output, in scipy.integrate.ode use the dense output via sol_out or similar, see Using adaptive step sizes with scipy.integrate.ode, for scipy.integrate.odeint use the time list input argument to define the sample points that are reported in the output.
score: 0

http://stackoverflow.com/q/50061845
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87142889
type: UnansweredQuestion
tagged with: scapy
has comment: http://stackoverflow.com/comment/87140101
has title: I am using scapy to get probing information. I am new in python and also scapy
has comment: http://stackoverflow.com/comment/87162024
tagged with: python
has body: #!/usr/bin/env python from scapy.all import * ap_list = [] def PacketHandler(pkt) : if pkt.haslayer(Dot11) : if pkt.type == 0 and pkt.subtype == 8 : if pkt.addr2 not in ap_list : ap_list.append(pkt.addr2) print "AP MAC: %s with SSID: %s " %(pkt.addr2, pkt.info) sniff(iface="mon0", prn = PacketHandler) using above code getting error no such device
type: Question
has comment: http://stackoverflow.com/comment/87346443

http://stackoverflow.com/comment/86964180
type: QuestionComment
comment on: http://stackoverflow.com/q/49973804
score: 0
has text: `I can't define the decoration outside of the class method` Any particular reason for this?
type: Comment

http://stackoverflow.com/comment/87076095
comment on: http://stackoverflow.com/a/50024019
type: Comment
has text: Actually I think you were right to point out this with my answer in case someone else has data with missing intervals. I guess we can add some lines to fill the missing intervals to prevent breaks
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86907005
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49944893
has text: This time I had to sit and toil to fix your question. Please don't leave that work to someone else, not everyone is as forgiving as I am. In future, make sure your questions are self-contained with enough _code_ or textual data to copy and paste to work with. See how to create a [mcve].

java
tags question: http://stackoverflow.com/q/50037645
tags question: http://stackoverflow.com/q/49935645
tags question: http://stackoverflow.com/q/50012174
tags question: http://stackoverflow.com/q/50011221
tags question: http://stackoverflow.com/q/49992880
tags question: http://stackoverflow.com/q/50011932
tag name: java
tags question: http://stackoverflow.com/q/50055849
tags question: http://stackoverflow.com/q/49994816
tags question: http://stackoverflow.com/q/50031690
tags question: http://stackoverflow.com/q/50009514
tags question: http://stackoverflow.com/q/49958256
tags question: http://stackoverflow.com/q/49964017
type: Tag
tags question: http://stackoverflow.com/q/50048806
tags question: http://stackoverflow.com/q/50056268
tags question: http://stackoverflow.com/q/49954083
tags question: http://stackoverflow.com/q/50010548
tags question: http://stackoverflow.com/q/50049962

http://stackoverflow.com/comment/86893907
score: 0
comment on: http://stackoverflow.com/q/49936379
type: QuestionComment
has text: According to the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html), you need to provide `roc_curve` with the probability of the positive class. I don't think you are doing this. What is the shape of `y_test` and `probas`?
type: Comment

http://stackoverflow.com/a/49999060
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49998709
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87014600
type: Answer
answers question: http://stackoverflow.com/q/49998709
score: 2
upvote count: 2
has body: You can do 1 using e.g. np.digitize and 2 using transform(). import pandas as pd import numpy as np df = pd.DataFrame({'A': np.random.random(20), 'B': np.random.random(20)}) bins = np.arange(0, 1.05, 0.05) df["bins"] = np.digitize(df["B"], bins) df["count"] = df.groupby("bins")["bins"].transform("count") df["weight"] = df["count"].max()/df["count"] df Out[32]: A B bins count weight 0 0.032735 0.948836 19 1 3.0 1 0.728310 0.671117 14 2 1.5 2 0.307804 0.328636 7 1 3.0 3 0.794719 0.257233 6 3 1.0 4 0.137138 0.480473 10 1 3.0 5 0.145847 0.754164 16 2 1.5 6 0.929552 0.187502 4 1 3.0 7 0.700309 0.655163 14 2 1.5 8 0.590829 0.561370 12 1 3.0 9 0.236366 0.814549 17 2 1.5 10 0.409573 0.444851 9 1 3.0 11 0.611366 0.842374 17 2 1.5 12 0.184661 0.725729 15 1 3.0 13 0.643751 0.299513 6 3 1.0 14 0.421400 0.294158 6 3 1.0 15 0.293585 0.112387 3 1 3.0 16 0.790870 0.609906 13 1 3.0 17 0.980155 0.757171 16 2 1.5 18 0.733151 0.393027 8 2 1.5 19 0.512966 0.398919 8 2 1.5

http://stackoverflow.com/a/50068273
has body: Regex is great, but for this you could also use .split() test_string = "9 - Saturday, 19 May 2012" splt_string = test_string.split(",") out_String = splt_string[1] print(out_String) Outputs: 19 May 2012 If the leading ' ' is a propblem, you can remedy this with out_String.lstrip()
answers question: http://stackoverflow.com/q/50068183
upvote count: 1
downvote count: 1
score: 0
type: Answer

http://stackoverflow.com/comment/87022634
type: QuestionComment
has text: @RafaelC a dictionary and csv arent very similar at all..
score: 1
comment on: http://stackoverflow.com/q/50003007
type: Comment

http://stackoverflow.com/q/50017962
tagged with: javascript
tagged with: python
has title: How to get labels of clicked position in Bokeh heatmap
type: AnsweredQuestion
score: 0
tagged with: visualization
has answer: http://stackoverflow.com/a/50022102
answer count: 1
tagged with: bokeh
type: Question
has body: I have Bokeh heatmap. I register callback and able to get x and y coordinates of clicked position. Is there way to get x and y labels for the same positions? It seems that cb_data doesn't contain any useful information. source = ColumnDataSource(data=dict(xname=xname, yname=yname, colors=color, alphas=alpha, means=means.flatten(), stds=stds.flatten(),)) callback = CustomJS(args=dict(source=source), code="""alert(JSON.stringify(cb_obj));""") p = figure(title="Plot", x_axis_location="above", tools="pan,hover,save,wheel_zoom,box_zoom,reset", x_range=labels, y_range=list(reversed(labels))) p.js_on_event('tap', callback)
accepted answer: http://stackoverflow.com/a/50022102

http://stackoverflow.com/comment/88239466
comment on: http://stackoverflow.com/q/50032227
type: Comment
type: QuestionComment
score: 0
has text: It sounds like you should be using a real database, at least SQLite. It's okay for a rarely-changing SQL table to have many indexes.

http://stackoverflow.com/comment/87084773
comment on: http://stackoverflow.com/a/50015181
score: 0
type: Comment
has text: It looks weird，if I use action="{% url 'operation:update_comment' 1 %}",it works.I can opend the detail page without errors.It seems that,I didn't pass the new.id to the template sucessfully.
type: AnswerComment

http://stackoverflow.com/comment/86895054
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49921128
has text: Thanks DebanjanB! In the end nr.5 did it! `wait.until(EC.invisibility_of_element_located((By.XPATH, "//div[@class='blockUI blockOverlay']")))` and then `el_xp("//input[@value='Save']").click()`.

http://stackoverflow.com/q/50003978
downvote count: 1
has body: Here is list of tasks imported imported from kaggle homepage in pandas dataframe. import pandas as pd df=pd.read_csv('https://s3.amazonaws.com/todel162/kaggle_unicode1.txt', encoding='utf8', sep='`', header=None) sample=df.head(5).T sample.columns=['task_name', 'task_description', 'task_date', 'task_prize', 'task_teams'] The sample dataframe will generate the first row correctly. I need to loop through rest of the data. How do I repeat the transpose method for every 5 rows?
accepted answer: http://stackoverflow.com/a/50004681
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50004681
has title: repeat a pandas method after every N rows
has comment: http://stackoverflow.com/comment/87024432
score: -1
favorite count: 0
type: Question
upvote count: 0
possible better answer: http://stackoverflow.com/a/50004184
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/50004184

http://stackoverflow.com/comment/86913356
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49947856
type: Comment
has text: You should probably post the full stack trace of the error. I had assumed it was caused by this: `(self.time_out - self.time_in)`

http://stackoverflow.com/q/49932787
duplicate of: http://stackoverflow.com/q/354038
has answer: http://stackoverflow.com/a/49932959
downvote count: 0
linked to: http://stackoverflow.com/q/1265665
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/642154
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86881472
duplicate of: http://stackoverflow.com/q/75666408
tagged with: python
score: 4
has body: Possible Duplicate: How to convert strings into integers in Python? Hello guys, I am trying to convert this string integers from a nested list to integers. This is my list: listy = [['+', '1', '0'], ['-', '2', '0']] I trying to convert to this: [['+', 1, 2], ['-', 2, 0]] This what I have tried so far, but my second line of code is taken from one of the answers in the question How to convert strings into integers in Python? listy = [['+', '1', '0'], ['-', '2', '0']] T2 = [list(map(int, x)) for x in listy] print(T2) But it gives me an error: ValueError: invalid literal for int() with base 10: '+' Is there any possible way to fix this in Python 3?
linked to: http://stackoverflow.com/q/354038
possible better answer: http://stackoverflow.com/a/49932872
upvote count: 4
accepted answer: http://stackoverflow.com/a/49932844
type: AnsweredQuestion
has title: How to convert a list of string numbers into int number in Python3?
has answer: http://stackoverflow.com/a/49932872
answer count: 3
has answer: http://stackoverflow.com/a/49932844

http://stackoverflow.com/q/49970526
tagged with: data-analysis
tagged with: data-visualization
tagged with: python
has title: Need help to solve the Unnamed and to change it in dataframe in pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49970566
tagged with: pandas
has body: how set my indexes from "Unnamed" to the first line of my dataframe in python import pandas as pd df = pd.read_excel('example.xls','Day_Report',index_col=None ,skip_footer=31 ,index=False) df = df.dropna(how='all',axis=1) df = df.dropna(how='all') df = df.drop(2)
has answer: http://stackoverflow.com/a/49970566
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87153696
type: QuestionComment
has text: there is no problem with the path. I'm sure about that. because this function works for a while. but after some time I get this error. Anyway updated the code.
comment on: http://stackoverflow.com/q/50068613
type: Comment
score: 0

http://stackoverflow.com/a/50027238
score: 0
has body: You can query with ... df.query: res = df.query('Finish == Finish.min()') You can get names of these province(s) by chaining .index.
type: Answer
answers question: http://stackoverflow.com/q/50027047

http://stackoverflow.com/q/50070739
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/87159079
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87159141
accepted answer: http://stackoverflow.com/a/50071271
possible better answer: http://stackoverflow.com/a/50071228
has comment: http://stackoverflow.com/comment/87158088
type: AnsweredQuestion
tagged with: numpy
has answer: http://stackoverflow.com/a/50071271
has body: let's say I have a file that looks like this text a bla bla 1 2 3 4 5 6 text b bla 7 8 9 10 11 12 text c bla bla bla 13 14 15 16 17 18 I am trying to extract only the number arrays and place them into a numpy array: array([[ 1, 2, 3, 4, 5, 6,], [ 7, 8, 9, 10, 11, 12], [ 13, 14, 15, 16, 17, 18]]) I tried using np.genfromtxt('test.txt',usecols=[0,1,2],invalid_raise=False) array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.], [ 10., 11., 12.], [ nan, nan, nan], [ 13., 14., 15.], [ 16., 17., 18.]]) but it doesn't create sub-arrays and converts the text into nans. Is there a better way of doing this?
has answer: http://stackoverflow.com/a/50071228
has comment: http://stackoverflow.com/comment/87160220
score: 1
has title: read number arrays in text file into numpy array - python
has comment: http://stackoverflow.com/comment/87158238
linked to: http://stackoverflow.com/q/50065295
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87158519

http://stackoverflow.com/q/49979707
answer count: 1
type: Question
has title: Compare document pairs within corpus using TF-IDF - Python
tagged with: tf-idf
type: UnansweredQuestion
has body: I managed to calculate the TF-IDF and matrix using the following code: from sklearn.feature_extraction.text import TfidfVectorizer #define vectorizer parameters tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000, min_df=0.2, stop_words='english', use_idf=True, ngram_range=(1,3)) tfidf_matrix = tfidf_vectorizer.fit_transform(paragraphs) #fit the vectorizer to paragraphs However, I would now like to compare the similarity of different paragraphs, my end result should look like this: Pair# | Paragraph1 | Paragraph2 | Similarity score 1 --------xyz --------xyz --------- 30.2% 2 --------xyz --------xyz --------- 22.3% 3 --------xyz --------xyz --------- 4.3% How can I use the TF-IDF matrix to compare the different paragraph pairs?
has answer: http://stackoverflow.com/a/50574927
tagged with: python
score: 0
tagged with: pandas

http://stackoverflow.com/q/50048786
accepted answer: http://stackoverflow.com/a/50048915
type: Question
has answer: http://stackoverflow.com/a/50048915
tagged with: python
has title: Apply property pandas.DataFrame.shape to multiple dataframe stored in a tuple
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: I have a function which returns as output a tuple containing multiple pd.DataFrame objects. Take the example: import pandas as pd def myfunction(): x = pd.DataFrame(data = [1,2,3]) y = pd.DataFrame(data = [[1,2,3],[4,5,6]]) return x, y myfunction() I am looking for a concise way to apply the property pandas.DataFrame.shape to each of the object stored in the tuple resulting from the call myfunction(). The solution must not include a cycle!
answer count: 1

http://stackoverflow.com/comment/88370278
type: QuestionComment
comment on: http://stackoverflow.com/q/49937159
score: 0
type: Comment
has text: @Perfavore you should transform BoxCox so that Y_train will have a normal distribution

http://stackoverflow.com/q/49970407
has title: Unable to use multiple proxies within Scrapy spider
has answer: http://stackoverflow.com/a/49973550
downvote count: 0
tagged with: web-scraping
tagged with: scrapy
answer count: 1
favorite count: 0
tagged with: python-3.x
score: 8
upvote count: 8
type: Question
tagged with: python
type: UnansweredQuestion
has body: I've written a script in python using Scrapy to send a request to a webpage through proxy without changing anything in the settings.py or DOWNLOADER_MIDDLEWARES. It is working great now. However, the only thing I can't make use of is creating a list of proxies so that If one fails another will be in use. How can I twitch this portion os.environ["http_proxy"] = "http://176.58.125.65:80" to get list of proxies one by one as it supports only one. Any help on this will be highly appreciated. This is what I've tried so far (working one): import scrapy, os from scrapy.crawler import CrawlerProcess class ProxyCheckerSpider(scrapy.Spider): name = 'lagado' start_urls = ['http://www.lagado.com/proxy-test'] os.environ["http_proxy"] = "http://176.58.125.65:80" #can't modify this portion to get list of proxies def parse(self, response): stat = response.css(".main-panel p::text").extract()[1:3] yield {"Proxy-Status":stat} c = CrawlerProcess({ 'USER_AGENT': 'Mozilla/5.0', }) c.crawl(ProxyCheckerSpider) c.start() I do not want to change anything in the settings.py or create any custom middleware to serve the purpose. I wish to achieve the same (externally) like I did above with a single proxy. Thanks.

http://stackoverflow.com/comment/86993356
score: 0
type: Comment
type: QuestionComment
has text: Thanks @davedwards, that worked! It gave me the text but it only did so for a single tweet despite the limit being set to 5 tweets. `with open('tweets.json', 'w', encoding='utf8') as file: for tweet in tweets: json.dump(tweet._json['text'], file)`
comment on: http://stackoverflow.com/q/49986251

http://stackoverflow.com/comment/87271113
has text: Hi there: what do you mean by the "best" population?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49978307

http://stackoverflow.com/a/50010975
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50010932
score: -2
has body: The problem lies within while True This continuously repeats the code under it, so it checks after 5 times if the gamescene is 0 again, repeat is another 5 times etc. You should change the gamescene to be nonzero within the while loop, or remove the while loop.
downvote count: 3

http://stackoverflow.com/comment/87097677
type: AnswerComment
score: 0
type: Comment
has text: Added another version to my answer in light of this comment
comment on: http://stackoverflow.com/a/50031061

http://stackoverflow.com/comment/86941955
score: 0
comment on: http://stackoverflow.com/q/49962973
has text: why am i getting downvoted, this question is legit not answered under [python-requests] tag search if you dont believe me
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87036362
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50008141
has text: The values for each key are stored in its associated list, so `lstdct.get('AM')` (or `lstdct['AM']`) is the list of them. Individual items within those can be accessed by specifying an integer index. e.g. `lstdct['AM'][0]`, `lstdct['AM'][1]`, etc. You could also loop through them all with something like `for flight in lstdct.get('AM', []): ...`. You can also easily check to see if a key is in the dictionary (and avoid creating an unneeded empty list) by using a conditional like `if 'AM' in lstdct: ...`.
type: Comment

http://stackoverflow.com/comment/87088870
has text: Do you want to submit this form? https://screenshots.firefox.com/Ft4QQvSpWb4TPYxj/www.findlatitudeandlongitude.com
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50033646

http://stackoverflow.com/q/50058414
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50058945
has body: How can I make intervals from two lists under conditions in Python? Logic behind this problem is a little bit of odd: Numbers in start list can get skipped when they in an interval. Like 2011 in example 1, because 2011 is in [2010, 2012]. But numbers in end list can not get skipped, and raise an error. Like 2019 in example 2, because the last interval is [2015, 2016], 2019 is larger than 2016. And if the last few numbers in start list are larger than the last number in end list, there will be an interval from the least number of last few numbers in start to infinity. Like 2017, 2018 in example 3, so there will be an interval [2017, float("inf")]. Example 1: start = [2010, 2011, 2015, 2017, 2018] end = [2012, 2016, 2019] Expected outcome 1: [[2010, 2012], [2015, 2016], [2017, 2019]] Example 2: start = [2010, 2011, 2015] end = [2012, 2016, 2019] Expected outcome 2: Error, because there are more numbers in end list after intervals created. (2019) Example 3: start = [2010, 2011, 2015, 2017, 2018] end = [2012, 2016] Expected outcome 3: [[2010, 2012], [2015, 2016], [2017, float("inf")]]
has title: Make intervals from two lists under conditions in Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50058728
possible better answer: http://stackoverflow.com/a/50058728
has comment: http://stackoverflow.com/comment/87133453
has comment: http://stackoverflow.com/comment/87133336
accepted answer: http://stackoverflow.com/a/50058945
tagged with: python
has comment: http://stackoverflow.com/comment/87133454
has comment: http://stackoverflow.com/comment/87133750
has comment: http://stackoverflow.com/comment/87133561
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50051799
accepted answer: http://stackoverflow.com/a/50051914
tagged with: pandas
has body: I have a large table with a couple of thousands of origin points (column A) and a couple of thousands of destination points (column B) and another columns with a value. I need an efficient algorithm in python to make sure that there is a row for each pair of origin to destination, and if not, create it. For example, imagine I have three origin points (1,2,3) and Three destination points (1,2,3). Currently, my data does not have a row for each possible pair between origins (column A) and destinations (column B) and is like: Index A B Value 0 1 1 V11 1 1 3 V13 2 2 1 V21 3 2 2 V22 4 2 3 V23 5 3 1 V31 6 3 3 V33 I want a python script to make it look like: Index A B Value 0 1 1 V11 1 1 2 NA 2 1 3 V13 3 2 1 V21 4 2 2 V22 5 2 3 V23 6 3 1 V31 7 3 2 NA 8 3 3 V33
upvote count: 3
has answer: http://stackoverflow.com/a/50051914
downvote count: 0
has title: Check if a row with certain values exist, and create if it does not exist
possible better answer: http://stackoverflow.com/a/50051965
favorite count: 0
type: Question
score: 3
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50052087
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50051965
answer count: 3

http://stackoverflow.com/comment/86907592
has text: When read exactly how you told me, filepath = 'https://raw.githubusercontent.com/gabrielacaesar/studyingPython/master/ceap-sf-new-12-04-2018.csv', it still doesn't recognize the dataset. Later it says it could not find the file.. Or that "'str' object has no attribute 'head'", for example. :( Thank you for the help
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49935675
type: AnswerComment

http://stackoverflow.com/a/49918832
has comment: http://stackoverflow.com/comment/86853222
accepted answer of: http://stackoverflow.com/q/49918095
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49918095
has body: Try this: select 'Income' AS ` `, MAX(CASE WHEN Year= 2010 THEN income END)`2010` ,MAX(CASE WHEN Year= 2011 THEN income END)`2011` ,MAX(CASE WHEN Year= 2012 THEN income END)`2012` from( SELECT A.*,(A.income/B.income)increase_ratio FROM My_Table A LEFT JOIN My_Table B ON B.id = A.id-1 WHERE A.company_name = 'A' )D UNION select 'increase_ratio' AS ` `,MAX(CASE WHEN Year= 2010 THEN increase_ratio END)`2010` ,MAX(CASE WHEN Year= 2011 THEN increase_ratio END)`2011` ,MAX(CASE WHEN Year= 2012 THEN increase_ratio END)`2012` from( SELECT A.*,(A.income/B.income)increase_ratio FROM My_Table A LEFT JOIN My_Table B ON B.id = A.id-1 WHERE A.company_name = 'A' )D Check this in the #SQL Fiddle Output: 2010 2011 2012 Income 10 20 30 increase_ratio (null) 2 1.5
score: 1
type: Answer

http://stackoverflow.com/comment/86921657
type: QuestionComment
comment on: http://stackoverflow.com/q/49952480
has text: Your problem isn't the python code, your problem is the html. You can't use `th` like that
score: 0
type: Comment

http://stackoverflow.com/comment/87053302
type: AnswerComment
has text: is your form a ModelForm or normal Form?
comment on: http://stackoverflow.com/a/50018323
type: Comment
score: 0

http://stackoverflow.com/comment/87064633
has text: @Tie_24 - just realised it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50024138
type: Comment

http://stackoverflow.com/a/49968569
score: 0
answers question: http://stackoverflow.com/q/49967364
has body: Assume your dataframe have numeric values, here 'u' refer to first row of dataframe, import pandas as pd import numpy as np u = df.iloc[0] cos_sim_list = [] norm_u = np.linalg.norm(u) for i in range(1, df.shape[0]): v = df.iloc[i] dot = np.dot(u, v) norm_v = np.linalg.norm(v) cos_sim = (dot/norm_u * norm_v) cos_sim_list.append(cos_sim) cos_sim_list
type: Answer

http://stackoverflow.com/q/49940899
tagged with: memory-management
answer count: 0
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Efficient way to clear memory while removing DF python 3 pandas
has body: Hi! Is there any efficient way in python 3 to release memory after removing object? del DF DF = pd.DataFrame() gc.collect() None of those is working properly. Only working approach is to DF.to_csv after working on it, restart the script and read_csv - that is really annoying. from SecureString import clearmem - works fine in python 2, however it is not supported in python 3 Do you know any similiar method to SecureString that works in python 3? Thanks in advance!
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15455048
tagged with: python
has comment: http://stackoverflow.com/comment/86897790

http://stackoverflow.com/comment/86899535
type: QuestionComment
has text: @chrisz you mean "average_loss += l"? It's lowercased "L" for loss :)
type: Comment
comment on: http://stackoverflow.com/q/49933056
score: 0

http://stackoverflow.com/a/49939891
upvote count: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/49939810
downvote count: 0
type: AcceptedAnswer
score: 6
answers question: http://stackoverflow.com/q/49939810
has body: As a Django user, def get_context_data(self, *args, **kwargs): and def get_object(self, *args, **kwargs): look unusual to me. The code will work because the same args and kwargs are passed to super(). You could argue that it makes the code more robust because it will still work if Django changes the signature in a future version. However I would prefer to use the same signatures as the parent class. You are correct that you could use pk_url_kwarg instead of overriding get_object. The pk_url_kwarg should be the name of the kwarg in the URL pattern, so in this case it should be pk_url_kwarg = 'rest_id'. The advantage of pk_url_kwarg is that it simplifies the code. The disadvantage is that it's less obvious how the object is being fetched if you're not familiar with Django's class-based-views. There's a couple more changes you could make. Instead of queryset = Restaurant.objects.all() you can simply set model, because get_queryset defaults to self.model.objects.all(). Finally, the get_context_data method doesn't do anything apart from printing, so I would remove it entirely once I'd finished debugging. Putting that together, you get: class RestaurantDetailView(DetailView): model = Restaurant pk_url_kwarg = 'rest_id'

http://stackoverflow.com/q/50034601
tagged with: if-statement
score: -2
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/50035045
tagged with: python-3.x
has title: Python 3, Calling a Function Properly
has answer: http://stackoverflow.com/a/50035045
upvote count: 0
downvote count: 2
possible better answer: http://stackoverflow.com/a/50034714
has comment: http://stackoverflow.com/comment/87085490
tagged with: loops
has answer: http://stackoverflow.com/a/50034799
has comment: http://stackoverflow.com/comment/87085472
favorite count: 0
has answer: http://stackoverflow.com/a/50034714
has comment: http://stackoverflow.com/comment/87085697
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87085515
has body: I'm quite new to Python, kind of new to programming and I'm having trouble creating a proper "loop". def gameLoop(): print('1') if ageInt == 2: gamePlay = '{}'.format(input("Would you like to play a game?\n")) else: sys.exit(0) time.sleep(1) if any([gamePlay == 'yes', gamePlay == 'sure']): print('you are playing a game') elif gamePlay == 'maybe': gamePlay = '{}'.format(input("C'mon, let,'s play...\n")) time.sleep(1) gameLoop() I realize a lot of this code may be sloppy, but I'm trying to call gameLoop, so if they answer "maybe" it returns to gameLoop. Why doesn't the last line of the code return to the first line? Edit to include full code: import time import sys name = input('What is your name?\n') print('Hello, %s!' % name) age = int (input('how old are you?\n')) print('Your age is: %s' % age, ' and your name is: %s' % name) ageInt = int (1) def gameLoop(): print('gameloopworks') if ageInt == 2: gamePlay = '{}'.format(input("Would you like to play a game?\n")) else:sys.exit(0) time.sleep(1) if any([gamePlay == 'yes', gamePlay == 'sure']): print('you are playing a game') elif gamePlay == 'maybe': gamePlay = '{}'.format(input("C'mon, let,'s play...\n")) time.sleep(1) print('elif works') gameLoop() if age &lt; 18: print(name, 'sorry you\'re too young') ageInt = 1 else: print(name, 'you are totally blankable') ageInt = 2 gameLoop()
answer count: 3

http://stackoverflow.com/a/50035958
answers question: http://stackoverflow.com/q/50035932
has body: It is expected behaviour, in datetimes the year, month and day arguments are required. If want remove days need month period by to_period: df['Date'] = df['Date'].dt.to_period('M') df['Date'] = pd.to_datetime(df['Date'],format= '%Y-%m').dt.to_period('M') Sample: df = pd.DataFrame({'Date':pd.to_datetime(['1988-01-01','1999-01-15'])}) print (df) Date 0 1988-01-01 1 1999-01-15 df['Date'] = df['Date'].dt.to_period('M') print (df) Date 0 1988-01 1 1999-01
downvote count: 0
upvote count: 3
score: 3
type: Answer

http://stackoverflow.com/q/50039242
has body: So the basis of my question is given here. After all I need to add elements of the lists. In the simplest example: first = [1,2] second = [6,7] Then [x + y for x, y in zip(first, second)] which gives: #[7,9] However my problem is that I am producing number of lists via a for loop. In the for loop the lists are not being stored and so to see them one uses print(list) at the end of the loop and it prints the lists. Now how can I write a code to look at the produced lists and sum the elements in the given manner above? Example: l = [] for i in range(2): l= list(range(5)) print(l) the above produces: #[0, 1, 2, 3, 4] #[0, 1, 2, 3, 4] How can I add a line in the for loop to sum the one-by-one elements of the lists to get: #[0, 2, 4, 6, 8]
tagged with: python
has comment: http://stackoverflow.com/comment/87094711
accepted answer: http://stackoverflow.com/a/50039524
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
linked to: http://stackoverflow.com/q/14050824
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87094808
has title: Summing up the elements of lists in a for loop
possible better answer: http://stackoverflow.com/a/50039696
has comment: http://stackoverflow.com/comment/87094786
has answer: http://stackoverflow.com/a/50039524
type: Question
has comment: http://stackoverflow.com/comment/87094685
has answer: http://stackoverflow.com/a/50039696
has comment: http://stackoverflow.com/comment/87094564
has comment: http://stackoverflow.com/comment/87094547

http://stackoverflow.com/q/50004337
type: Question
tagged with: qt
score: 1
has body: In my PyQt GUI, I've got a couple of relatively short (readOnly) QLineEdits containing some text. As the contained text is longer than the widget itself, only part of it can be shown. The QLineEdit widget typically shows the last part (by default): As the figure shows, I'd like to make the first part of the text visible (by default). How do I do that? I have added some code below to help you to setup a test-case quickly. Just copy-paste the code into a *.py file, run it, and you should get a QLineEdit in a window. import sys import os from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * '''================================================================================''' '''| CUSTOM MAIN WINDOW |''' '''================================================================================''' class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # -------------------------------- # # Window setup # # -------------------------------- # # 1. Define the geometry of the main window # ------------------------------------------ self.setGeometry(100, 100, 800, 200) self.setWindowTitle("QLineEdit test") # 2. Create frame and layout # --------------------------- self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffffff }") self.__lyt = QVBoxLayout() self.__lyt.setAlignment(Qt.AlignTop) self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) # 3. Create QLineEdit # ------------------- self.__myQLineEdit = QLineEdit("This is a very long line") self.__myQLineEdit.setFixedWidth(100) self.__myQLineEdit.setReadOnly(True) self.__lyt.addWidget(self.__myQLineEdit) self.show() '''=== end Class ===''' if __name__ == '__main__': app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Fusion')) myGUI = CustomMainWindow() sys.exit(app.exec_()) '''''' Last but not least, I'd like to describe my system for completeness: Windows 10, 64-bit Python 3.6 PyQt5
tagged with: python
has answer: http://stackoverflow.com/a/50004613
has title: How do I change visible part of the text in a (short) QLineEdit?
type: AnsweredQuestion
tagged with: python-3.x
tagged with: pyqt
upvote count: 1
answer count: 1
downvote count: 0
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/50004613
favorite count: 0

http://stackoverflow.com/comment/87116718
type: Comment
score: 0
has text: Thanks @jbch ! I added your link to my answer
type: AnswerComment
comment on: http://stackoverflow.com/a/50049902

http://stackoverflow.com/comment/87133269
type: Comment
type: QuestionComment
has text: ah I see, I read my own code as abs(X)**2 instead of abs(X)*2.... So what is an appropriate Mx function so that I get the proper power function normalized ? Mx=abs(X)**2 -with what else multiplied by it?
comment on: http://stackoverflow.com/q/50038747
score: 0

http://stackoverflow.com/a/50046640
has comment: http://stackoverflow.com/comment/124666672
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/124666718
has body: The following is for PyTorch (fully on GPU) # abs_cosine should be a Tensor of shape (m, m) mask = torch.ones(abs_cosine.size()[0]) mask = 1 - mask.diag() sim_vec = torch.nonzero((abs_cosine &gt;= threshold)*mask) # sim_vec is a tensor of shape (?, 2) where the first column is the row index and second is the column index The following works in numpy mask = 1 - np.diag(np.ones(abs_cosine.shape[0])) sim_vec = np.nonzero((abs_cosine &gt;= 0.2)*mask) # sim_vec is a 2-array tuple where the first array is the row index and the second array is column index
upvote count: 7
score: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50045202
has comment: http://stackoverflow.com/comment/133354055
answers question: http://stackoverflow.com/q/50045202

http://stackoverflow.com/a/49989758
score: 1
answers question: http://stackoverflow.com/q/49989616
has body: I don't really know about elegance, but I needed to do that and I just created a function on the class like so: def as_simple_dict(self): simple_dict = {} simple_dict['id'] = str(self.id) simple_dict['name'] = self.name simple_dict['attribute'] = self.attribute simple_dict['foo'] = self.foo simple_dict['bar'] = self.bar And call it whenever I need it. Hope it helps.
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49916885
downvote count: 0
has body: you could try this: c.execute("INSERT INTO batch VALUES(?, ?, ?)", (a,b,d)) make sure you don't use c again, since you are using it as a cursor as well. This changes your c = connection.cursor() to c = ("input")
answers question: http://stackoverflow.com/q/49916861
type: Answer
accepted answer of: http://stackoverflow.com/q/49916861
upvote count: 2
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49922911
type: AnsweredQuestion
score: 0
answer count: 2
has body: I would like to have a dict like: dict_a= { 'abc' : {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}, 'efg' : {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]}, 'hij' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]} } so I separate into 2 dict dict_b = { 'a': [], 'b': [], 'c': [] } dict_a= { 'abc': {}, 'efg': {}, 'hij' } When I put data by using for loop, the last data will cover earlier data. The following is my code: for x in sorted(dict_a): for y in sorted(dict_b): list= [] ... dict_b[y] = list dict_a[x] = dict_b and the result is: dict_a= { 'abc' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]}, 'efg' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]}, 'hij' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]} } My expected result is: dict_a= { 'abc' : {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}, 'efg' : {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]}, 'hij' : {'a':[21,22,23], 'b':[24,25,26], 'c':[27,28,29]} } How can I solve it? Update full code: for market in sorted(MARKET_LUT): for type in sorted(STOCK_TYPE_LUT): try: list = [] data = pd.read_csv(file_path, sep=' ', header=None, names=['code', 'name']) list = data.code.tolist() dict_b [type] = list except Exception as e: traceback.print_exc() err = sys.exc_info()[1] LOG_write_log(LOG_ERROR, str(err)) dict_a[x] = dict_b
possible better answer: http://stackoverflow.com/a/49924070
has title: How can I add multiple dict to one multiple?
has comment: http://stackoverflow.com/comment/86863255
type: Question
has answer: http://stackoverflow.com/a/49924070
has answer: http://stackoverflow.com/a/49923860
has comment: http://stackoverflow.com/comment/86863424
has comment: http://stackoverflow.com/comment/86863209
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86861872
has comment: http://stackoverflow.com/comment/86861469
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49923860
has comment: http://stackoverflow.com/comment/86863310
has comment: http://stackoverflow.com/comment/86862877
has comment: http://stackoverflow.com/comment/86861644

http://stackoverflow.com/comment/86981091
type: QuestionComment
comment on: http://stackoverflow.com/q/49981942
has text: No, that sounds good.
score: 0
type: Comment

http://stackoverflow.com/comment/87265295
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50070275
has text: yep i have a prime function
type: AnswerComment

http://stackoverflow.com/q/49997050
upvote count: 1
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87013920
type: UnansweredQuestion
downvote count: 0
has title: Regex pattern to find plus and equal sign
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/87010576
tagged with: regex
has answer: http://stackoverflow.com/a/50000842
has comment: http://stackoverflow.com/comment/87013936
has answer: http://stackoverflow.com/a/49997427
has comment: http://stackoverflow.com/comment/87010676
has body: Hey I'm looking for a regex pattern to search through a string example: ++t+==+z++== and return true if a letter is surrounded by a + on both sides. Otherwise its false ++t++z== will return false. ++z+p++ will return true. t++z+ will return false. A code sample of the function in js function check_str_pos(str){ ///(\+|=|[a-zA-Z])|(\+[a-zA-Z]\+)|(\+|=|[a-zA-Z])$/ if(/^(\+[a-zA-Z]\+)$/.test(str)) { return true; } else{ return false; } }
score: 1

http://stackoverflow.com/q/50037096
has answer: http://stackoverflow.com/a/50225979
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87090271
tagged with: twilio
accepted answer: http://stackoverflow.com/a/50225979
has title: Transfer a live call in twilio to another secondary number that is not in twilio - Python
has body: I am using the python SDK for handling twilio incoming calls. I have created a flask application for this. All calls coming in to my twilio number get routed through the flask application URL(Webhook). Now, when the call is in progress, I want to transfer the caller to a secondary number (which is not in twilio) and then disconnect my call with the caller once the connection is established between the caller and the secondary number. Can someone tell me how this can be done in python? I already tried calling a number but was not able to achieve the required functionality.
tagged with: python
has comment: http://stackoverflow.com/comment/87203889
tagged with: flask
has comment: http://stackoverflow.com/comment/87091702
type: AnsweredQuestion
upvote count: 2
score: 2

http://stackoverflow.com/a/49920280
answers question: http://stackoverflow.com/q/49920150
type: Answer
has comment: http://stackoverflow.com/comment/86856123
score: 0
has body: k = s.split(',') this is where the error occours. s.split(',') in your case returns 3 strings. Buy on the left hand side theres only one variable k. You cannot assign 3 variables to only one variable. changing it to k1, k2, k3 = s.split(',') will work
has comment: http://stackoverflow.com/comment/86856745
has comment: http://stackoverflow.com/comment/86856032

http://stackoverflow.com/comment/140066132
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50070958
has text: right, but this way you cannot parameterize the value of `prec`, right?
score: 0

http://stackoverflow.com/a/49993988
has body: Here is a quick solution. Edited to include genexpr instead of list comprehension mySet = {(1, 3), (3, 4), (3, 5)} mySet = (set(tup) for tup in mySet) print(set.intersection(*mySet)) # {3}
upvote count: 6
answers question: http://stackoverflow.com/q/49993936
has comment: http://stackoverflow.com/comment/87005357
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/87004701
has comment: http://stackoverflow.com/comment/87005025
has comment: http://stackoverflow.com/comment/87004966
accepted answer of: http://stackoverflow.com/q/49993936
type: Answer

http://stackoverflow.com/comment/131049387
type: AnswerComment
comment on: http://stackoverflow.com/a/49943187
type: Comment
has text: BTW, this answer does not answer the question. Because the intention was to read the data as [[],[],...,[]]. The code is right, the terminal wasn't.
score: 0

http://stackoverflow.com/comment/87039416
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50011246
type: Comment
has text: Yes - line _numbers_ - not _number and line content_ as his does.

http://stackoverflow.com/q/50066396
tagged with: keras
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50066568
has answer: http://stackoverflow.com/a/50066568
tagged with: python
has title: Tensorflow Set Graph/Session Context on Class Method Call
tagged with: class
score: 2
type: AnsweredQuestion
upvote count: 2
answer count: 1
downvote count: 0
has body: I am running two tensorflow models in parallel. Each has its own graph and session. To ensure there are no graph/op conflicts I have created a wrapper class that maintains the two models' respective graph and session: class ModelWrapper: def __init__(self): self.graph = None self.sess = None self.model = None def load_model(self, pth_model=None): # load graph, session, and model here On call I then set the context using with: def predict(self, np_x): with self.graph.as_default(): with self.sess.as_default(): np_y_preds = self.model.predict(np_x) return np_y_preds Is there a more elegant way to set the context every time I call the predict method?
tagged with: tensorflow

http://stackoverflow.com/comment/86946321
score: 0
type: Comment
has text: :), the answer we're trying to get is "4 5 17 6 14 16 7 5 13 5 13 9 8 10 10 2 10 13 27 15 2 4 0 3 22 6 22 14"
type: AnswerComment
comment on: http://stackoverflow.com/a/49965238

file-type
tag name: file-type
tags question: http://stackoverflow.com/q/49950710
type: Tag

http://stackoverflow.com/comment/122531681
comment on: http://stackoverflow.com/a/49950891
has text: Well spotted, thank you.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50069470
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87156014
accepted answer: http://stackoverflow.com/a/50069828
tagged with: algorithm
has answer: http://stackoverflow.com/a/50069703
has comment: http://stackoverflow.com/comment/87156253
has comment: http://stackoverflow.com/comment/87156129
has answer: http://stackoverflow.com/a/50069828
tagged with: python
has comment: http://stackoverflow.com/comment/87155835
tagged with: decimal
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/50069703
has title: Algorithm to reduce decimals in the pattern of 0.2 -> 0.1 -> 0.09 -> 0.08 -> ... -> 0.02 -> 0.01 -> 0.009
answer count: 2
has comment: http://stackoverflow.com/comment/87155526
upvote count: 1
has body: I am attempting to automate the decaying of a neural network's learning rate. I would like to write a function that is called if the neural net's loss does not reduce over n epochs. This function will take the current learning rate as a parameter and then will reduce it by 0.1, 0.01, 0.001, etc, depending on it's current value (the number of significant figures it currently has). This would give the decaying pattern of 0.2 -> 0.1 -> 0.09 -> 0.08 -> ... -> 0.02 -> 0.01 -> 0.009 As a guideline, I currently have the learning rate decaying as below, starting at 0.1: def decayLearningRate(learningRate): return learningRate ** 2 However, these jumps are too big. What is an elegant way to achieve what I have proposed? Note: The learning rate will always begin at 0.1 or less.
has comment: http://stackoverflow.com/comment/87155631
has comment: http://stackoverflow.com/comment/87156046

http://stackoverflow.com/a/56481855
score: 2
has comment: http://stackoverflow.com/comment/99554287
has body: This is the code example how to put in a cell value with a leading single quote: from openpyxl import load_workbook xlFilePath = "testquote.xlsx" #put your path here wb = load_workbook(filename=xlFilePath) ws = wb.worksheets[0] _cell = ws.cell(1, 1) _cell.quotePrefix = 1 _cell.value = "your_value" wb.save(xlFilePath) In the cell "A1" you get the value with a leading single quote: 'your_value. What is more, single quote is not displayed when viewing a workbook (but it is visible when editing cell content).
has comment: http://stackoverflow.com/comment/113936251
answers question: http://stackoverflow.com/q/50027429
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/99566564
upvote count: 2

http://stackoverflow.com/comment/87085327
type: QuestionComment
comment on: http://stackoverflow.com/q/50034590
has text: Apply will work. See this answer: https://stackoverflow.com/questions/26886653/pandas-create-new-column-based-on-values-from-other-columns
score: 0
type: Comment

http://stackoverflow.com/q/50050486
score: 0
has body: Suppose I have a data structure composed of objects in Python like this: class Planet: def __init__(self, name): self.name = name self.continents = [] class Continent: def __init__(self, name): self.name = name self.countries = [] class Country: def __init__(self, name): self.name = name self.states = [] class State: def __init__(self, name): self.name = name self.cities = [] class City: def __init__(self, name): self.name = name Now suppose I was to create a function that would be able to take an object and an attribute "path" as parameters and output a list of all the objects that "match" that path. Since I don't really know how to describe very well what I'm thinking of and most likely I'm using the wrong terminology, here is an idea of what it might look like in practice (let's call the function collect, and assume that the data structure is populated with data, with planet being the "root" object of the data structure): planet = Planet("Earth") ... Code for populating data structure ... collect(planet, "continents.countries.states.cities") This function call would return a list of every cities in every state in every country in every continent on the planet. Or if I wanted all the states in the data model I would do: collect(planet, "continents.countries.states") Hopefully you get the idea. The problem is that I just have no clue how I would accomplish this. Here's what I've come up with so far: def collect(obj, attr_path): attrs = attr_path.split(".") current_attr = obj items = [] for attr in attrs: current_attr = getitem(current_attr, attr) # Not sure what to do here... return items Does anyone know how I can make this work?
has answer: http://stackoverflow.com/a/50050648
type: Question
tagged with: python-3.x
has title: Recursive listing of all objects at an arbitrary depth in a data model?
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: recursion
has comment: http://stackoverflow.com/comment/87117448

http://stackoverflow.com/q/49922385
has comment: http://stackoverflow.com/comment/86861183
linked to: http://stackoverflow.com/q/47770144
favorite count: 0
type: Question
has title: Unable to locate element Selenium webdriver || Python
has answer: http://stackoverflow.com/a/49924536
accepted answer: http://stackoverflow.com/a/49924536
tagged with: python
has body: Go to Search Am trying to locate the Search box by switching into iframe and selecting by search_box = driver.find_element_by_xpath('//*@id="ca660735dba5d3003d7e5478dc9619b2_text"]') But i get error unable to locate Message: no such element: Unable to locate element: Even thought I find one matching node.
tagged with: selenium-webdriver
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: selenium

http://stackoverflow.com/q/49941192
has answer: http://stackoverflow.com/a/49941304
has title: `+=` leads to `none` with class instance
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49941307
type: Question
linked to: http://stackoverflow.com/q/4841436
tagged with: python-3.x
upvote count: 1
duplicate of: http://stackoverflow.com/q/4841436
has body: I just want to use the __add__ modifier, to use '+=' to easily add to elements of a classinstance: class Problem: def __init__(self): self.lItems = [] def __add__(self, other): self.lItems.append(other) problem = Problem() problem += 'text' print(problem) The resulting problem will equal Noneafter the +=. Why? And how can I prevent that from happening? P.S.: I have also tried implementing __iadd__ with no effect...
has answer: http://stackoverflow.com/a/49941280
accepted answer: http://stackoverflow.com/a/49941280
has comment: http://stackoverflow.com/comment/86898322
has comment: http://stackoverflow.com/comment/86898557
favorite count: 0
possible better answer: http://stackoverflow.com/a/49941307
has comment: http://stackoverflow.com/comment/86898269
tagged with: class
tagged with: operator-overloading
type: AnsweredQuestion
score: 0
answer count: 3

http://stackoverflow.com/q/49974030
has comment: http://stackoverflow.com/comment/87031994
tagged with: google-cloud-ml
has body: I have created a ml model for fraud detection as: A little snippet of the actual model code as: from sklearn.metrics import classification_report, accuracy_score from sklearn.ensemble import IsolationForest from sklearn.neighbors import LocalOutlierFactor # define a random state state = 1 # define the outlier detection method classifiers = { "Isolation Forest": IsolationForest(max_samples=len(X), contamination=outlier_fraction, random_state=state), "Local Outlier Factor": LocalOutlierFactor( n_neighbors = 20, contamination = outlier_fraction) } import pickle # fit the model n_outliers = len(Fraud) for i, (clf_name, clf) in enumerate(classifiers.items()): # fit te data and tag outliers if clf_name == "Local Outlier Factor": y_pred = clf.fit_predict(X) # Export the classifier to a file with open('model.pkl', 'wb') as model_file: pickle.dump(clf, model_file) scores_pred = clf.negative_outlier_factor_ else: clf.fit(X) scores_pred = clf.decision_function(X) y_pred = clf.predict(X) # Export the classifier to a file with open('model.pkl', 'wb') as model_file: pickle.dump(clf, model_file) # Reshape the prediction values to 0 for valid and 1 for fraudulent y_pred[y_pred == 1] = 0 y_pred[y_pred == -1] = 1 n_errors = (y_pred != Y).sum() # run classification metrics print('{}:{}'.format(clf_name, n_errors)) print(accuracy_score(Y, y_pred )) print(classification_report(Y, y_pred )) I have created a storage bucket, ml model, and a version successfully on Google Cloud Platform. But as a beginner to ml world, I'm confused, how I can pass the input to this model to get a real prediction as this model is deployed on Google's ML-Engine now. Update: As stated in the N3da's answer, now I'm using this code for online prediction: import os from googleapiclient import discovery from oauth2client.client import GoogleCredentials PROJECT_ID = "PROJECT_ID" VERSION_NAME = "VERSION" MODEL_NAME = "MODEL_NAME" credentials = GoogleCredentials.get_application_default() service = discovery.build('ml'…
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/87041093
favorite count: 0
accepted answer: http://stackoverflow.com/a/49986285
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Prediction from a Deployed SCIKITLEARN model at Google Cloud ML-Engine
has comment: http://stackoverflow.com/comment/87043939
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49986285
type: Question
linked to: http://stackoverflow.com/q/50013828
tagged with: prediction

http://stackoverflow.com/a/49948218
type: Answer
answers question: http://stackoverflow.com/q/49948029
accepted answer of: http://stackoverflow.com/q/49948029
has comment: http://stackoverflow.com/comment/86913113
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86913605
score: 1
has body: you are trying to read an enum there: https://developers.google.com/protocol-buffers/docs/reference/python-generated#enum Converting to a string might not be the most elegant way to proceed. I think that this should return True: print str(cq.V1LayerParameter.LayerType.DESCRIPTOR.values_by_name["CONVOLUTION"].number == net_txt.layers[0].type)

http://stackoverflow.com/a/49958052
score: 0
has comment: http://stackoverflow.com/comment/86932869
has comment: http://stackoverflow.com/comment/86932777
type: Answer
answers question: http://stackoverflow.com/q/49957918
has body: For example: temp = [] for site in sites: checker = pyping.ping(site) # The site status changed from it's last value, so send an email if checker.ret_code == 0: # The site is UP body = "%s This Server is up %s" % (site, st) temp.append(body) else: # The site is Down body = "%s This Server is down %s" % (site, st) temp.append(body) body = '\n'.join(temp) session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
has comment: http://stackoverflow.com/comment/86932801
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49957918

http://stackoverflow.com/q/50027943
tagged with: python
has answer: http://stackoverflow.com/a/52355203
has body: I have a project with the following structure -project --src --test when i run pytest inside project folder from python2 (python2 -m pytest), it works fine, however, with python 3 (python3 -m pytest), i have an error in the test files as it cant find the imports in the src folder I have an __init__.py in both folders Is there any reason why it should be different in python2 and python3? How could i make it work in python3? Thanks
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87074121
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87072331
upvote count: 1
favorite count: 0
type: Question
has title: Pytest in python2 and python3 - different behaviour
tagged with: pytest
score: 1

http://stackoverflow.com/q/49982804
type: Question
upvote count: 4
tagged with: numpy
tagged with: python-3.x
downvote count: 0
accepted answer: http://stackoverflow.com/a/49983452
tagged with: python
tagged with: sorting
score: 4
has answer: http://stackoverflow.com/a/49983452
tagged with: quicksort
type: AnsweredQuestion
answer count: 1
has title: Numpy argsort instability
has body: Lately, I have been experimenting np.argsort and I have realized something weird. If you run the following code, you will get the result: In [0]: np.argsort([3]*16) Out[0]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], dtype=int64) But if you make just a little change: In [1]: np.argsort([3]*17) Out[1]: array([ 0, 14, 13, 12, 11, 10, 9, 15, 8, 6, 5, 4, 3, 2, 1, 7, 16], dtype=int64) I know the default method for numpy argsort is quicksort, which is an unstable sorting algorithm. But, there is an reasonably explanation about the differents behavior above? Is this related to quicksort's choice of pivot? If so, why?
favorite count: 0

http://stackoverflow.com/comment/98322317
score: 1
has text: @Abhishek... You can find the IP address of the camera using some network scanning utility such as `arp-scan` on linux. Further details of the URL i.e. `Protocol`, `Credentials` and `Channel` should be found in the camera manual or the software/mobile app shipped with the camera.
type: Comment
comment on: http://stackoverflow.com/a/49979186
type: AnswerComment

http://stackoverflow.com/comment/87167184
type: AnswerComment
has text: @Tulika Asthana. In order to find propoer approach for your work, you should examine different solutions. There is no method that fits to all probelms. make more experiments with different algorithms and parameters. Also, you can try to use ensemble systems.
type: Comment
comment on: http://stackoverflow.com/a/50072702
score: 0

http://stackoverflow.com/a/50025959
has comment: http://stackoverflow.com/comment/87079066
has comment: http://stackoverflow.com/comment/87114776
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87107165
upvote count: 1
has comment: http://stackoverflow.com/comment/87078619
has comment: http://stackoverflow.com/comment/87112088
answers question: http://stackoverflow.com/q/50008122
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87114395
accepted answer of: http://stackoverflow.com/q/50008122
has body: Depending on your input and your expected output (three time the same couple of values in your list for each key?), at least you can replace your for p in plots by: for p in plots: # Select the data you want df = bigger_df.filter([p['x'], p['y'], 'S', 'F', 'C']) # selects the minimum of columns needed df = df[df['F'].isin([2, 3, 4, 9]) &amp; df[p['x']].notnull() &amp; df[p['y']].notnull() &amp; (df.S == 123)] # I have used 123 to simplify, actually the value is an integer variable df.sort_values(['C'], ascending=[True], inplace=True) # fill the dictionary d['xs{}'.format(n)] = [list(df[p['x']]) for x in range(N)] d['ys{}'.format(n)] = [list(df[p['y']]) for x in range(N)] n += 1 At least you save the for index in range(3) and doing the same operation on your bigger_df 3 times. With timeit I dropped from 210 ms with your code to 70.5 ms (around a third) with this one. EDIT: with the way you redefine your question, I think this might do the job you want: # put this code after the definition of plots s_list = [123, 145, 35] # create an empty DF to add your results in the loop df_output = pd.DataFrame(index=s_list, columns=['xs0','ys0', 'xs1', 'ys1', 'xs2', 'ys2']) n = 0 for p in plots: # Select the data you want and sort them on the same line df_p = bigger_df[bigger_df['F'].isin([2, 3, 4, 9]) &amp; bigger_df[p['x']].notnull() &amp; bigger_df[p['y']].notnull() &amp; bigger_df['S'].isin(s_list)].sort_values(['C'], ascending=[True]) # on bigger df I would do a bit differently if the isin on F and S are the same for the three plots, # I would create a df_select_FS outside of the loop before (might be faster) # Now, you can do groupby on S and then you create a list of element in column p['x'] (and same for p['y']) # and you add them in you empty df_output in the right column df_output['xs{}'.format(n)] = df_p.groupby('S').apply(lambda x: list(x[p['x']])) df_output['ys{}'.format(n)] = df_p.groupby('S').apply(lambda x: list(x[p['y']])) n += 1 Two notes: first if in your s_lis…
has comment: http://stackoverflow.com/comment/87079723
has comment: http://stackoverflow.com/comment/87079142

http://stackoverflow.com/comment/87094100
score: 0
type: Comment
type: QuestionComment
has text: Tks Mat, but does does not make a difference, I've tried with 'A' and got the same result. Additionally, in other queries, with double quotes, it runs.
comment on: http://stackoverflow.com/q/50038805

http://stackoverflow.com/q/49996416
has comment: http://stackoverflow.com/comment/87020132
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87010718
has body: System information OS Platform and Distribution: Linux Ubuntu 16.04 TensorFlow version: tensorflow-gpu (1.7.0) Python version: Python 3.5.2 CUDA/cuDNN version: CUDA 9.0 cuDNN 7 Describe the problem I have a cuda lib build from C++ for post-processing after predict result by tensorflow model. I use following way to make python able to use cuda code from C++ lib = ctypes.cdll.LoadLibrary(my.so) result = lib.post_process(tensorflow_result) If I test the cuda code alone without tensorflow, it work fine. (I save the result from tensorflow then use cv2.imread to feed into my cuda code) But when tensorflow is used in my project, my cuda code become 10 times slower.... My time log is in cuda .so lib, so it's no way that the gap come from python to .so wrap. I have try to set the fraction of GPU memory to be allocated in tensorflow by: # Assume that you have 12GB of GPU memory and want to allocate ~4GB: gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) but useless.... so I wonder does tensorflow take all resource from GPU, making other CUDA code slow ? the only solution is make my cuda code as a tensorflow OP by register? Any suggestion? Thanks~~~ ----------------------Update---------------------- I have tested what @AnandCU say. config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) but it doesn't make my cuda code speed up like I test it alone without tensorflow.
has comment: http://stackoverflow.com/comment/87014113
has comment: http://stackoverflow.com/comment/87012346
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87014490
tagged with: c++
has title: does tensorflow take all resource from GPU, making other CUDA code slow?
tagged with: ctypes
score: 0
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87012316

http://stackoverflow.com/a/50210717
answers question: http://stackoverflow.com/q/49936803
score: 0
has body: I'm done with Googling. Just using registry and set decimal value.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49936803
type: Answer

http://stackoverflow.com/q/49990229
favorite count: 0
type: Question
tagged with: keylogger
tagged with: sockets
score: 1
has answer: http://stackoverflow.com/a/49990410
has comment: http://stackoverflow.com/comment/86997196
tagged with: python
has title: Adding socket to a keylogger
has comment: http://stackoverflow.com/comment/86997227
type: UnansweredQuestion
answer count: 1
has body: For fun purposes, I'm building a keylogger. What I want is the keylogger will act like a chat client and will send every key stroke to the other party. However, when I try to do it, it only sends the first key I pressed, not the others that follow it. import socket import pythoncom import pyHook HOST = "192.168.2.103" PORT = 5000 s = socket.socket() s.connect((HOST, PORT )) def OnKeyboardEvent(event): global s keylog = chr(event.Ascii) s.send(keylog.encode("utf-8")) return True h_m = pyHook.HookManager() h_m.KeyDown =OnKeyboardEvent h_m.HookKeyboard() pythoncom.PumpMessages()
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50021635
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50013311
accepted answer of: http://stackoverflow.com/q/50013311
has body: In fact, your recursive method also used postorder's idea. It's kind like the same idea but you try to implement it with different ways. Your main problem is like what jasonharper said. For example: a = [[1], [2]] for list in a: list = [] a will still be [[1], [2]], but remember, list is not an immutable object. Therefore, if you code like this: a = [[1], [2]] for list in a: list.append(1) a will then be [[1, 1], [2, 1]]. This is why your node.val may change the value but not node.
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/50013927
type: Answer
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50013854
has body: In python, using re.findall exhibits the following behavior: If one or more groups are present in the pattern, return a list of groups; Since .* (anything found after your numbers) is not contained in a group, it will not be in the final result. Either remove the groups altogether, or add a group for the text following your number: s = """ 2008-11-08 06:32:46.354761500 26318 logging::logterse plugin: ` 89.223.216.72 apn-89-223-216-72.vodafone.hu apn-89-223-216-72.vodafone.hu &lt;toshiter@donin.com&gt; rhsbl 901 Not supporting null originator (DSN) msg denied before queued 2008-11-08 06:33:17.924158500 26331 logging::logterse plugin: ` 208.99.214.236 mx22.ecreditchoices7.com mx22.ecreditchoices7.com &lt;moneydiet2@mx22.ecreditchoices7.com&gt; dnsbl 903 http://www.spamhaus.org/SBL/sbl.lasso?query=SBL69049 msg denied before queued 2008-11-08 06:34:53.318459500 26358 logging::logterse plugin: ` 84.58.57.150 dslb-084-058-057-150.pools.arcor-ip.net rpemgmu.arcor-ip.net &lt;sundered@ancientinc.com&gt; dnsbl 903 http://www.spamhaus.org/query/bl?ip=84.58.57.150 msg denied before queued 2008-11-08 06:35:41.724563500 26375 logging::logterse plugin: ` 58.126.113.198 Unknown [58.126.113.198] &lt;benny@surecom.com&gt; rhsbl 901 Not supporting null originator (DSN) msg denied before queued 2008-11-08 06:37:31.730609500 26398 logging::logterse plugin: ` 87.103.146.91 pmsn.91.146.103.87.sable.dsl.krasnet.ru pmsn.91.146.103.87.sable.dsl.krasnet.ru &lt;dwweem@wee.com&gt; dnsbl 903 http://www.spamhaus.org/query/bl?ip=87.103.146.91 msg denied before queued 2008-11-08 06:37:41.211401500 26409 logging::logterse plugin: ` 87.103.146.91 pmsn.91.146.103.87.sable.dsl.krasnet.ru pmsn.91.146.103.87.sable.dsl.krasnet.ru &lt;dwtrupsm@trups.com&gt; dnsbl 903 http://www.spamhaus.org/query/bl?ip=87.103.146.91 msg denied before queued """ import re print(re.findall(r'(90[13])(.*)', s)) Output: [('901', ' Not supporting null originator (DSN) msg denied before queued'), ('903', ' http://www.spamhaus.or…
score: 1

http://stackoverflow.com/q/50043308
has answer: http://stackoverflow.com/a/50043503
has title: Function to sum multiple numbers
answer count: 5
has body: I'm new to python and I started learning to execute function. And I started adding numbers but I could only sum two numbers and if I wanted to sum more, it would require I edit the program. Here's my code def sum(num1,num2): return num1+num2 a=5 b=7 c=sum(a,b) print (c) Now I want to create a function to sum any amount of number you want without Editting the codes. Here was what I did: def sum(num1,num2): return num1+num2 a=int(input("what is the number you want to add?: ")) ask="yes" while(ask=="yes"): b=int(input("what is the number you want to add?: ")) c=sum(a,b) a=c ask=input("do you want to add another number?: ") else: c=a print (c) This worked but i think there should be an easier way to do this with a function... right? Thanks for your help!
tagged with: function
accepted answer: http://stackoverflow.com/a/50043393
linked to: http://stackoverflow.com/q/919680
tagged with: python
has answer: http://stackoverflow.com/a/50043580
possible better answer: http://stackoverflow.com/a/50043504
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50043504
duplicate of: http://stackoverflow.com/q/919680
has answer: http://stackoverflow.com/a/50043374
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50043393
favorite count: 0
type: Question

http://stackoverflow.com/comment/87036045
type: QuestionComment
comment on: http://stackoverflow.com/q/50009029
score: 0
has text: Ooops. Apparently, the arguments passed to function were csr sparse matrices, not numpy arrays. That was my problem. After creating numpy arrays with `A=A.toarray()` it works several times faster (and `numpy.count_nonzero()` also works correctly). I suppose question should be deleted (I can't think of a way to edit it, since the problem was in completely different area than my question).
type: Comment

http://stackoverflow.com/a/50049294
has body: You'll want to use the subprocess.Popen() function, which keeps the process alive. Related S.O. question for reference: Keep a subprocess alive and keep giving it commands? Python
has comment: http://stackoverflow.com/comment/87115196
has comment: http://stackoverflow.com/comment/87115053
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50048780

http://stackoverflow.com/comment/87101502
type: AnswerComment
comment on: http://stackoverflow.com/a/50024385
has text: Completely agree. I think I had this problem a while back and resorted to using this method as a bodge... But I needed the code to work and the bodge meant it worked in time - not ideal but good enough as last resort
score: 0
type: Comment

http://stackoverflow.com/comment/120922820
type: Comment
has text: the already-answered stackoverflow thread does not have any solution related to temporary files (especially `SpooledTemporaryFile`), this post should be reopened
comment on: http://stackoverflow.com/q/49934598
type: QuestionComment
score: 0

http://stackoverflow.com/q/50030944
has comment: http://stackoverflow.com/comment/87078681
score: 0
has comment: http://stackoverflow.com/comment/87081207
has comment: http://stackoverflow.com/comment/87078523
has title: Efficient way of dealing with MongoDB objects in Python
tagged with: python
has comment: http://stackoverflow.com/comment/87078244
has body: I'm trying to build a very simple MongoDB extraction script but I stumbled upon this problem of most keynames and strings being recorded as unicode. So, when I try to just print a document it comes out with a bunch of keys and values like this u'username':u'christian' etc. And my documents in this database are rather large and complex, so I have several nested levels. I searched around a bit to make this conversion from unicode keys and values to ASCII but came up with nothing. I'm trying to convert all keys and values like so def convert2ascii: for k, v in mydict.iteritems(): newk = k.encode('ascii','ignore') mydict[newk] = mydict.pop(k) if isinstance(v, unicode): mydict[newk] = v.encode('ascii','ignore') elif isinstance(v, dict): convert2ascii(v) #elif isinstance(v, list): // todo # convert2ascii(v) But I keep running into some uncovered scenario (like a list of dictionaries, or just a plain list of strings) and having to add all of those to to that function, and by now it is rather ugly. Any ideas on how I can make that simpler?
linked to: http://stackoverflow.com/q/21752259
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/87087189
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50031045
answer count: 1
tagged with: bson
tagged with: unicode

http://stackoverflow.com/q/50061518
has comment: http://stackoverflow.com/comment/87139509
score: 0
has comment: http://stackoverflow.com/comment/87140112
has comment: http://stackoverflow.com/comment/87139852
has comment: http://stackoverflow.com/comment/87140015
tagged with: pyqt
answer count: 1
has title: Custom widget does not appear on Main Window
upvote count: 1
has comment: http://stackoverflow.com/comment/87140148
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87139705
has comment: http://stackoverflow.com/comment/87139775
has comment: http://stackoverflow.com/comment/87139647
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87139350
has comment: http://stackoverflow.com/comment/87140067
has comment: http://stackoverflow.com/comment/87140695
has body: I've trying to create a custom widget and make it appear on Grid Layout on the main window. class MyCustomWidget(QtGui.QWidget): def __init__(self): super(MyCustomWidget, self).__init__() self.setupUi() def setupUi(self): self.testText = QtGui.QLabel() font = QtGui.QFont() font.setPointSize(8) font.setBold(True) font.setWeight(75) self.testText.setFont(font) self.testText.setAlignment(QtCore.Qt.AlignCenter) self.testText.setObjectName(_fromUtf8("patientText")) self.testText.setText("Test") class UIMainWindow(object): def setupUi(self, MainWindow): ... self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) ... self.test = MyCustomWidget() self.gridLayout.addWidget(self.test) When I run this code, main window appears but there is nothing about the widget that I created. If I simply add an QLabel to grid layout, it appears.
accepted answer: http://stackoverflow.com/a/50062026
tagged with: pyqt4
tagged with: python
has answer: http://stackoverflow.com/a/50062026
has comment: http://stackoverflow.com/comment/87139537
has comment: http://stackoverflow.com/comment/87139961
type: Question
has comment: http://stackoverflow.com/comment/87140191

http://stackoverflow.com/a/78035878
type: Answer
answers question: http://stackoverflow.com/q/50008296
score: 0
has body: Based on Martijn Pieters's answer here is the solution written in Node.js import { readFileSync } from 'node:fs' import { Buffer } from 'node:buffer' let data = JSON.parse(readFileSync('message_1.json'),(key, value) => { if (typeof value === "string") { let buff = Buffer.from(value,'latin1') return buff.toString('utf-8') } else { return value} })

http://stackoverflow.com/comment/87024556
has text: Should the input be `names=[' HE XF, Wei W, Liu ZZ, Shen XL',' STARK LE, AARON FIN, LEO DE CAP, ADAM FORTH, KARAN SINGH',' ELSWICK RICK Jr, ASTO FON, SAM MARLON, KIM ZENG']` or `names=[' HE XF, Wei W, Liu ZZ, Shen XL STARK LE, AARON FIN, LEO DE CAP, ADAM FORTH, KARAN SINGH , ELSWICK RICK Jr, ASTO FON, SAM MARLON, KIM ZENG']` - Why are there extra ',' in your example?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50003922
type: QuestionComment

http://stackoverflow.com/comment/86993164
score: 0
type: Comment
type: QuestionComment
has text: Should `"Easily apply"` be present in link text or in description? I see no `"Easily apply"` at all...
comment on: http://stackoverflow.com/q/49988239

http://stackoverflow.com/comment/87038159
has text: @TheMan result is `[1, 2, 3, 2, 1, 2, 3] 14` -why is that wrong? Its 7 results and you undulate between 1 and 3 and back , inc/dec by 1...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50010332
type: Comment

http://stackoverflow.com/comment/86912695
type: Comment
comment on: http://stackoverflow.com/a/49947979
type: AnswerComment
has text: You can look for a solution online, I don't think it's possible though.
score: 0

http://stackoverflow.com/a/49955913
type: AcceptedAnswer
has body: You cannot share tkinter objects between processes. Tkinter widgets depend on an embedded tcl interpreter, and that embedded interpreter cannot be shared between threads or processes.
type: Answer
accepted answer of: http://stackoverflow.com/q/49954843
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49954843

http://stackoverflow.com/a/49938830
answers question: http://stackoverflow.com/q/49938766
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86893464
upvote count: 0
has comment: http://stackoverflow.com/comment/86895049
has comment: http://stackoverflow.com/comment/86893525
downvote count: 1
has body: Try to select the field with unform = browser.find_element_by_xpath("//input[@name='username']") unform.send_keys(&lt;username&gt;) and for password browser.find_element_by_xpath("//input[@name='password']")
has comment: http://stackoverflow.com/comment/86893680
has comment: http://stackoverflow.com/comment/86893612

http://stackoverflow.com/comment/86930954
score: 2
type: Comment
has text: The task of generating ASCII land art is incredibly broad, and does not admit a 10 line answer. I have copied and pasted the code from one link to address your concern, but 3 times this much code is required to implement a robust solution, and stackoverflow is not a code-writing service.
type: AnswerComment
comment on: http://stackoverflow.com/a/49947039

http://stackoverflow.com/q/50011078
has answer: http://stackoverflow.com/a/50011131
has answer: http://stackoverflow.com/a/50011193
type: Question
tagged with: shorthand
has body: I have a deeply nested dictionary in python thats taking up a lot of room. Is there a way to abbreviate something like this master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name][color] = blue to this for example nested_child_info[color] = blue And still have it edit the dictionary ? I hope that makes sense.
downvote count: 0
answer count: 7
tagged with: nested
has comment: http://stackoverflow.com/comment/87038764
has answer: http://stackoverflow.com/a/71395911
accepted answer: http://stackoverflow.com/a/50011131
favorite count: 0
has title: Convenient way to handle deeply nested dictionary in Python
has answer: http://stackoverflow.com/a/50011136
type: AnsweredQuestion
upvote count: 7
score: 7
has answer: http://stackoverflow.com/a/50011897
possible better answer: http://stackoverflow.com/a/50011897
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50011182
has answer: http://stackoverflow.com/a/50011202

http://stackoverflow.com/q/50031506
has comment: http://stackoverflow.com/comment/87079363
has comment: http://stackoverflow.com/comment/87101927
has comment: http://stackoverflow.com/comment/87079232
has title: Multiple subprocess pipes python
type: Question
has comment: http://stackoverflow.com/comment/87079268
has body: This is my first time on here so please bear with me. I am working through some python code and having trouble with one block in particular so I will post my code from the test script I have been working on. I have even used print debugger statements to find out what's wrong and it appears the 3rd pipe is not getting stdin from the 2nd one even though the 2nd one is piping out the output. If I comment out output3 and use output2 the file gets created and populated but once I include output3 the file is completely empty. Any help is greatly appreciated! #!/usr/bin/python import subprocess try: output = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE) output2 = subprocess.Popen(['egrep', '/usr/'], stdin=output.stdout, stdout=subprocess.PIPE); output.stdout.close() output3 = subprocess.Popen(['egrep', '"sbin|lib"'], stdin=output2.stdout, stdout=subprocess.PIPE); output2.stdout.close() with output3.stdout, open('some file name', 'ab') as file: for line in iter(output3.stdout.readline, b''): file.write(line) except OSError as message: print "Display bad things {}!".format(message) I had to hand jam this so sorry if I missed some typos!
has comment: http://stackoverflow.com/comment/87079343
has comment: http://stackoverflow.com/comment/87079462
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87079424
tagged with: pipe
tagged with: python
has comment: http://stackoverflow.com/comment/87079242
has comment: http://stackoverflow.com/comment/87079193
has comment: http://stackoverflow.com/comment/87079286
tagged with: subprocess
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/87079299
has comment: http://stackoverflow.com/comment/87079189
has comment: http://stackoverflow.com/comment/87079158

http://stackoverflow.com/comment/87101952
score: 0
comment on: http://stackoverflow.com/q/50037063
type: Comment
type: QuestionComment
has text: The video compiles and runs properly and gives the proper console o/p when i insert `print` statements but the o/p i get cannot be read it gives `"Could not demultiplex stream."`

http://stackoverflow.com/a/50069461
type: Answer
answers question: http://stackoverflow.com/q/50069340
downvote count: 0
upvote count: 1
score: 1
has body: df['new_col'] = [[1,2,3] for j in range(df.shape[0])]

http://stackoverflow.com/comment/87045409
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50014568
has text: I have created my model version with `Python 3.5 ` and also my model's code written in `python 3.6`
type: Comment

http://stackoverflow.com/a/49933021
has body: Use a try except to handle non-digit inputs. To keep prompting the user for a valid age until they have inputted one just keep your loop on true and only break it when you get a valid age: print("Please input a valid age") while True: try: age = int(input()) assert 0 &lt; age &lt; 130 break except (AssertionError, ValueError): print("Please input a valid age") print(age) If you don't want to use try/excepts you can use .isdigit(): print("Please input a valid age") while True: age = input() if age.isdigit() and (0 &lt;int(age)&lt; 130): break else: print("Please input a valid age") print(int(age)) #age is valid and you can safely convert to int
answers question: http://stackoverflow.com/q/49932975
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49932975

input
tags question: http://stackoverflow.com/q/50044416
tags question: http://stackoverflow.com/q/49940647
tags question: http://stackoverflow.com/q/49970413
tags question: http://stackoverflow.com/q/50065610
tags question: http://stackoverflow.com/q/49925595
tags question: http://stackoverflow.com/q/50063455
tags question: http://stackoverflow.com/q/50063493
tags question: http://stackoverflow.com/q/50038514
tag name: input
type: Tag
tags question: http://stackoverflow.com/q/50073254
tags question: http://stackoverflow.com/q/49961179

http://stackoverflow.com/a/50053726
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50053585
has comment: http://stackoverflow.com/comment/87124347
score: 2
answers question: http://stackoverflow.com/q/50053585
has comment: http://stackoverflow.com/comment/87124458
has body: You can use a dictionary comprehension: foo = {1: {'f1': 'c1'}, 2: {'f2': 'c2'}} bar = {k: v for d in foo.values() for k, v in d.items()} {'f1': 'c1', 'f2': 'c2'} You were close, but the order of your nesting is incorrect. This is tricky and not intuitive to everyone. Read your comprehension as you would write a normal for loop. There is also no need to make a list out of your dictionary values. Related: Understanding nested list comprehension.
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/87016097
type: Comment
type: QuestionComment
has text: @ak_slick I edited the title so it adapts to an `mpl` method as well. Thanks for the comment.
comment on: http://stackoverflow.com/q/49999636
score: 0

http://stackoverflow.com/comment/86915601
has text: @MarioAgolli What *error* are you getting? It works perfectly fine on my end.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49930475
score: 0

http://stackoverflow.com/a/49930617
type: Answer
accepted answer of: http://stackoverflow.com/q/49929940
downvote count: 0
answers question: http://stackoverflow.com/q/49929940
upvote count: 1
type: AcceptedAnswer
has body: try replacing: driver.find_element_by_xpath("//span[@data-qaid='txt-lowest-price']").text with: driver.find_element_by_xpath("//span[@data-qaid='txt-lowest-price']").get_attribute('textContent')
score: 1

http://stackoverflow.com/q/49941302
tagged with: flask
has title: can I know which CLI command is being executed in Flask?
accepted answer: http://stackoverflow.com/a/49941544
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/75815991
favorite count: 0
has body: I want to call a function only if a certain command is being used to start the flask app. I.e. I do not want to call the function if CLI command is 'initdb': flask initdb but I want to call it when command is 'run': flask run --host=0.0.0.0 Is there a way of knowing what command flask was called with? PS. I'm looking at flaskr code and trying to start a Process() only if flask is called with 'run'.
type: Question
score: 5
upvote count: 5
possible better answer: http://stackoverflow.com/a/75815991
has answer: http://stackoverflow.com/a/49941544
tagged with: python

http://stackoverflow.com/q/49929374
has answer: http://stackoverflow.com/a/69627848
has title: NotADirectoryError: [WinError 267] The directory name is invalid error while invoking Firefox through Selenium Python
has answer: http://stackoverflow.com/a/75257015
answer count: 5
tagged with: geckodriver
has comment: http://stackoverflow.com/comment/86874896
tagged with: python
upvote count: 16
tagged with: selenium-webdriver
type: Question
has answer: http://stackoverflow.com/a/66015669
has body: I'm trying to invoke a firefox browser using Selenium webdriver from below python code.. from selenium import webdriver # Initializing the WebDriver for Firefox browser driver = webdriver.Firefox("C:\\selenium\\mozilla\\geckodriver.exe") driver.set_page_load_timeout(30) driver.maximize_window() driver.get("https://www.google.com/") # Closing the reference driver.quit() but it is always throwing an error like below, however this is working for Chrome browser. Traceback (most recent call last): File "C:/Python/Practice/FirefoxSample.py", line 8, in &lt;module&gt; driver = webdriver.Firefox("C:\\selenium\\mozilla\\geckodriver.exe") File "C:\Python\venv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 139, in __init__ firefox_profile = FirefoxProfile(firefox_profile) File "C:\Python\venv\lib\site-packages\selenium\webdriver\firefox\firefox_profile.py", line 78, in __init__ ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock")) File "C:\Python\Python36-32\lib\shutil.py", line 309, in copytree names = os.listdir(src) NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\selenium\\mozilla\\geckodriver.exe' Process finished with exit code 1 What am I missing here? I have also tried upgrading the selenium package using the pip pip install -U selenium Additional info: running the Firefox latest version (59.0.2), Python (3.6.5) and Selenium Gecko webdriver (0.20.0). Not sure if anything is needed to help on this.
has comment: http://stackoverflow.com/comment/86875142
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49930067
tagged with: firefox
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/72462018
has comment: http://stackoverflow.com/comment/120805901
favorite count: 0
score: 16
linked to: http://stackoverflow.com/q/55012755

http://stackoverflow.com/comment/86900344
has text: @VivekKumar You might have misread the question: this one is talking about [One-Class SVM](http://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html#sklearn.svm.OneClassSVM), which is a modified version of a standard SVM used for outlier detection, and which does not offer the ability to convert the classification into a probability score based on the distance from the separating hyperplane as in other types of SVM classifiers. This is very unique to the One-Class SVM.
score: 0
comment on: http://stackoverflow.com/q/49931965
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86909338
has text: When I try to access my convolutional layers weight using "w = self.conv2.weight.unsqueeze_(0)" I am getting the following error: "a leaf Variable that requires grad has been used in an in-place operation". If I unsqueeze will autogradients will work?
type: AnswerComment
comment on: http://stackoverflow.com/a/49936077
score: 0
type: Comment

http://stackoverflow.com/comment/87147219
type: Comment
type: QuestionComment
score: 0
has text: Where do I find the cert path
comment on: http://stackoverflow.com/q/50064950

pymodm
tags question: http://stackoverflow.com/q/49969301
type: Tag
tag name: pymodm

http://stackoverflow.com/q/50024378
tagged with: garbage-collection
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50024641
answer count: 1
tagged with: python
has title: Python 2D array and loop
tagged with: memory
type: Question
accepted answer: http://stackoverflow.com/a/50024641
has body: I'm new to Python and am attempting to set up a script to check the status of specific wifi connected IOT devices on my local network. Essentially, the script takes the mac hardware IDs I want to check; pings the network to trigger ARPs's; searches the response to arp-a for the relevant mac ID's which are printed with the date and time if located successfully. Two questions- 1) At the moment I am just searching this for 2 mac addresses however going forward it's more likely to be 20. How can I amend my detect_mac function to take a two-dimensional array (or similar) and loop through the results to avoid having to repeat the if any(address in str_output for address in input_address_list1): line 20 times. 2) If I leave this script running constantly (it has a 10 minute timer between runs) will this python eventually crash? Is there some sort of garbage collection, log overflow etc I would need to consider? import pdb, os import subprocess import re import time from subprocess import Popen, PIPE, DEVNULL lower=1 upper=25 MAC_address_list1 = ["58:e2:zz:xx:28:d7"] MAC_address_list2 = ["08:05:xx:zz:75:c5"] MAC_address_list3 = ["##:##:##:##:##:##"] MAC_address_list4 = ["##:##:##:##:##:##"] p = {} # Get The Current Date and Time def getdatetime(): import time return time.strftime("%H:%M %d/%m/%Y ") def detect_mac(input_address_list1, input_address_list2): # Assign list of devices on the network to "output" output = subprocess.check_output("arp -a", shell=True) str_output = output.decode("utf-8") if any(address in str_output for address in input_address_list1): print(getdatetime() + str(input_address_list1)) if any(address in str_output for address in input_address_list2): print(getdatetime() + str(input_address_list2)) #sleep 10 minutes time.sleep(600) return True while 1: # ping all IPs in range to make ARP available for i in range(lower,upper): ip = "192.168.1.%d" % i p[ip] = Popen(['ping', '-n', '-w5', '-c3', ip], stdout=DEVNULL) detect_mac(MAC_address_list1, MAC_address…
tagged with: arrays

http://stackoverflow.com/a/49959687
score: 4
has comment: http://stackoverflow.com/comment/86935838
accepted answer of: http://stackoverflow.com/q/49959648
has body: In your description, level 787 maps to 98% while in your code level 787 maps to 97%. Assuming that this is a typo and level 787 should map to 98%, 788 to 97% etc, the code below should do the trick. I also assume that pool_level_perentage can take values less than 69 (something which is not reflected in your code) so I won't include any further conditions. def get_pool_level_percentage(level): if (level &gt; 785): return (100 - (level - 785)) return 100
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86935875
has comment: http://stackoverflow.com/comment/86982346
has comment: http://stackoverflow.com/comment/86935750
answers question: http://stackoverflow.com/q/49959648
type: Answer
upvote count: 4

http://stackoverflow.com/a/50005712
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50004087
has body: After fighting with python for over an hour, I decided to look for a solution in another language. This is how my goal can be achieved in C#: var s = "\u00c4\u008d"; var newS = Encoding.UTF8.GetString(Encoding.Default.GetBytes(s)); File.WriteAllText(@"D:\tmp\test.txt", newS, Encoding.UTF8); Finally! The file now contains č. I therefore got inspired by this approach in C# and managed to come up with the following (seemingly) equivalent solution in Python: &gt;&gt;&gt; s = u"\u00c4\u008d" &gt;&gt;&gt; arr = bytearray(map(ord, s)) &gt;&gt;&gt; print arr.decode("utf-8") č I'm not sure how good this solution is but it seems to work in my case.
score: 0
accepted answer of: http://stackoverflow.com/q/50004087
downvote count: 1
type: Answer

http://stackoverflow.com/q/49951850
has comment: http://stackoverflow.com/comment/86922158
answer count: 1
accepted answer: http://stackoverflow.com/a/49951897
tagged with: python
has answer: http://stackoverflow.com/a/49951897
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86920249
has body: I am writing a regex to preprocess some tweets. Many a times I come across spellings like hiiiii or looove etc. I am trying to clean them to hi or love to clean usage of multiple consecutive characters. My code is as follows: w = re.sub(r'[^\w\s]|(.)(?=\1)', '', w) This does most of the job but it also cleans words like book to bok or deep to dep. I want to exclude oo and ee from this pattern. Tried doing this: w = re.sub(r'(?!oo)[^\w\s]|(.)(?=\1)', '', "book") But this didn't work. Please help.
tagged with: regex
has title: Regex exclude a specific pattern
has comment: http://stackoverflow.com/comment/86920365
type: Question
has comment: http://stackoverflow.com/comment/86920161

http://stackoverflow.com/comment/87087991
type: QuestionComment
has text: You shouldn't write to row while iterating through it. This can lead to unexpected results.
comment on: http://stackoverflow.com/q/50035827
score: 0
type: Comment

http://stackoverflow.com/q/50008800
has title: Handling nested JSON in Python
has comment: http://stackoverflow.com/comment/87034169
has body: I'm attempting to retrieve data from within a nested JSON data using Python. Abbreviated example of the JSON data: { "daily" : { "1524182400000" : 438, "1524268800000" : 438, "1524355200000" : 437, "1524441600000" : 437, "1524528000000" : 432 } } As you see, each of the above keys is a unix timestamp and the overall object is constantly updated with new key/value pairs. While I am easily able to retrieve the data if I know the timestamp I don't know how I get the value of the latest timestamp. I would usually complete this in PHP with the below code and selecting the array position: foreach ($data["daily"] as $timedate =&gt; $value) { array_push($ValueArray, $value); array_push($ValueDate, $timedate); } How do I get this in Python? Any help would be appreciated!
has answer: http://stackoverflow.com/a/50009401
answer count: 3
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50008881
tagged with: python
possible better answer: http://stackoverflow.com/a/50008865
has answer: http://stackoverflow.com/a/50008881
has answer: http://stackoverflow.com/a/50008865

google-drive-api
tags question: http://stackoverflow.com/q/50030526
tags question: http://stackoverflow.com/q/49998528
type: Tag
tag name: google-drive-api

http://stackoverflow.com/comment/86863510
comment on: http://stackoverflow.com/q/49922327
type: Comment
score: 0
type: QuestionComment
has text: @t.m.adam: Even better!

http://stackoverflow.com/a/50079435
type: Answer
answers question: http://stackoverflow.com/q/50051425
score: 0
has body: You can't use a standard HTTP client such as requests to talk to a Socket.IO server. You need a Socket.IO client instead. For Python, you can use SocketIO-Client.

http://stackoverflow.com/a/49963324
answers question: http://stackoverflow.com/q/49962987
score: 0
has body: the expected result is sum and max of value In that case, you are looking for x[1] + y[1], and not use the built-in sum() function. my_rdd.reduceByKey( lambda x,y: ( max(x[0],y[0]), x[1] + y[1] ) )
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86942768
accepted answer of: http://stackoverflow.com/q/49962987
has comment: http://stackoverflow.com/comment/86942715
type: Answer

http://stackoverflow.com/a/49991263
downvote count: 0
type: Answer
score: 3
has body: Try printing out what's in self.level. If you've entered lines 123, 456, 789, what you want is presumably this: [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] … but what you have is this: [['1', '2', '3', '4', '5', '6', '7', '8', '9'], [], []] Why? Because you add them with this: self.level[self.currentLine] += self.line[i] … and you never increment self.currentLine anywhere. You probably want to add this line to the end of newLine: self.currentLine += 1 However, it might be simpler to just build the new line and add it, and not even bother with that currentLine variable. And, for that matter, you don't need a line attribute; that's just a local variable. Plus, you don't need a loop to convert a string into a list of characters one by one. So, you can replace the whole thing with: line = input('\n') self.level += list(line) As a side note, you probably don't want to use [] as a default value for self.level. If you do that, and create two separate LevelEditor instances with default arguments, they're going to end up sharing the same list. To fix that, either do this: def __init__(self, level=[]): self.level = list(level) … or, if you want to allow explicitly sharing lists, but not accidentally: def __init__(self, level=None): self.level = [] if level is None else level … or, is there really any reason to allow passing in a value at all? If not: def __init__(self): self.level = []
upvote count: 3
answers question: http://stackoverflow.com/q/49991192
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49991192

http://stackoverflow.com/a/50005681
has body: row['PIC_1'] returns a Pandas series so you need to access the values before you can slice them. You're looking to slice a string so you can use pandas.Series.str vectorised string methods: row['PIC_1'].str[PIC_loc:PIC_loc+15]
score: 1
has comment: http://stackoverflow.com/comment/87028339
has comment: http://stackoverflow.com/comment/87028750
has comment: http://stackoverflow.com/comment/87029003
has comment: http://stackoverflow.com/comment/87028880
answers question: http://stackoverflow.com/q/50005293
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50005293
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87027853
upvote count: 1
has comment: http://stackoverflow.com/comment/87029511
has comment: http://stackoverflow.com/comment/87029555
has comment: http://stackoverflow.com/comment/87029286

http://stackoverflow.com/comment/87326124
score: 0
type: Comment
type: QuestionComment
has text: I need to execute python code in c# and this python code uses XML and JSON. Isnt IronPython a good solution to do this? Is there other better solution? Sorry to be so late on the response, i was working on somthing else and forgot this post.
comment on: http://stackoverflow.com/q/50042951

http://stackoverflow.com/a/50071143
has comment: http://stackoverflow.com/comment/87159084
has comment: http://stackoverflow.com/comment/87159530
has comment: http://stackoverflow.com/comment/87159543
has body: You were close. The trick is to use ValueError as e and compare your strings against str(e). It's also good practice to use if / elif rather than repeated if statements. Here's a working example: import calendar, datetime try: print(datetime.date(int(birthYear), int(birthMonth), int(birthDay))) except ValueError as e: if str(e) == 'month must be in 1..12': print('Month ' + str(birthMonth) + ' is out of range. The month must be a number in 1...12') elif str(e) == 'year {0} is out of range'.format(birthYear): print('Year ' + str(birthMonth) + ' is out of range. The year must be a number in ' + str(datetime.MINYEAR) + '...' + str(datetime.MAXYEAR)) elif str(e) == 'day is out of range for month': print('Day ' + str(birthDay) + ' is out of range. The day must be a number in 1...' + str(calendar.monthrange(birthYear, birthMonth)))
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87159003
has comment: http://stackoverflow.com/comment/87175905
accepted answer of: http://stackoverflow.com/q/50071040
answers question: http://stackoverflow.com/q/50071040
type: Answer
has comment: http://stackoverflow.com/comment/87159047
score: 11
has comment: http://stackoverflow.com/comment/87159128
upvote count: 11

http://stackoverflow.com/comment/86987298
comment on: http://stackoverflow.com/a/49977615
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169606/discussion-between-naveen-and-will-keeling).
type: AnswerComment

http://stackoverflow.com/comment/87011627
type: QuestionComment
comment on: http://stackoverflow.com/q/49975227
has text: Sorry for the delay, selecting relevant code and formatting took time.
score: 0
type: Comment

http://stackoverflow.com/q/50010580
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/50010718
answer count: 2
has comment: http://stackoverflow.com/comment/87037804
has answer: http://stackoverflow.com/a/50010628
tagged with: python-3.x
has body: I am using the Spyder IDE. I wanted to calculate the value and for that, I used the if else condition. but I can't see the calculated value in variable explorer. please suggest me the solution. p = pd.read_excel('Data1.xlsx') p.head() a = p.iloc[:12,0].values b = p.iloc[:12,1].values c = 200.00 d = 150.00 s = int() def s(a, b): if a + b &lt; c: s = c elif a + b &gt; d: s = d else: s = a + b return s print(s)
type: Question
tagged with: python
type: UnansweredQuestion
has title: if else no printing in variable explorer

http://stackoverflow.com/comment/87098779
comment on: http://stackoverflow.com/q/50041402
type: Comment
has text: also, can you clarify what the technical reason is that you want to get rid of the for loop ?
score: 0
type: QuestionComment

http://stackoverflow.com/q/49963510
has answer: http://stackoverflow.com/a/49965369
has body: Django = 2.0 I want this app to add to my project - https://github.com/pythonsd/test-driven-django-development/tree/master/myblog It works for me, but I don't need comments. And I can't figure out how to delete these comments. In HTML I know how to remove it, but I want to remove comments from models and views, I want to have clean code in my project. https://github.com/pythonsd/test-driven-django-development/blob/master/myblog/blog/models.py - I am to delete class Comment(models.Model) , right? I think yes. https://github.com/pythonsd/test-driven-django-development/blob/master/myblog/blog/views.py - But what I need to remove from the file, if I do not have the comments in my blog-app? Thank you very much.
accepted answer: http://stackoverflow.com/a/49965369
answer count: 1
tagged with: django
type: AnsweredQuestion
score: 0
has title: Add application blog to my Django project
tagged with: python
type: Question

http://stackoverflow.com/a/49977327
score: -1
answers question: http://stackoverflow.com/q/49977283
upvote count: 0
downvote count: 1
has body: Suggest you to work with pandas library. Pandas
type: Answer

geocoding
tags question: http://stackoverflow.com/q/50008546
tags question: http://stackoverflow.com/q/49922601
tag name: geocoding
type: Tag
tags question: http://stackoverflow.com/q/50026147

http://stackoverflow.com/q/49968274
tagged with: python
tagged with: qpushbutton
has body: I am having trouble maintaining previously drawn lines after I draw a new line. Right now if I click one button it will draw a line but once I click the second button a new line is drawn and the initial one is removed. I would like that both remain. import sys from PyQt5.QtWidgets import QMainWindow,QPushButton, QApplication from PyQt5.QtCore import QSize, Qt, QLine, QPoint from PyQt5.QtGui import QPainter, QPen class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(300, 300)) pybutton = QPushButton('button', self) pybutton.clicked.connect(self.draw_line) pybutton.resize(100,100) pybutton.move(0, 0) pybutton2 = QPushButton('button2', self) pybutton2.clicked.connect(self.draw_line) pybutton2.resize(100,100) pybutton2.move(200, 0) self.line = QLine() def draw_line(self): button = self.sender() x = int(button.x()) + int(button.width())/2 y = int(button.y())+100 self.line = QLine(x, y, x, y+100) self.update() def paintEvent(self,event): QMainWindow.paintEvent(self, event) if not self.line.isNull(): painter = QPainter(self) pen = QPen(Qt.red, 3) painter.setPen(pen) painter.drawLine(self.line) if __name__ == "__main__": app = QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_())
tagged with: drawing
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49972928
accepted answer: http://stackoverflow.com/a/49972928
favorite count: 0
type: Question
has title: PyQt5: Maintain previously drawn drawings/line when new ones are drawn

http://stackoverflow.com/comment/86989727
score: 0
type: Comment
has text: and also the checkbox
type: AnswerComment
comment on: http://stackoverflow.com/a/49986145

http://stackoverflow.com/comment/87090877
type: QuestionComment
score: 0
has text: @SIKing: thanks, I can indeed do that, but since in my real code this is being done in a recursive way, the outer code then loses track of the selenium session, which makes it a bit complicated, so I wanted to triage before going down that route. Another option would be to open a new window before .get()ing the pages, then closing the window if it hangs.
type: Comment
comment on: http://stackoverflow.com/q/50031290

http://stackoverflow.com/comment/87037538
comment on: http://stackoverflow.com/q/50009034
has text: @LordNeckbeard : I added my code now. Is there something that I am missing in my code?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86995223
type: Comment
comment on: http://stackoverflow.com/a/49989364
has text: I have to use the method named __next__ to compute and print the odd numbers
type: AnswerComment
score: 0

http://stackoverflow.com/a/52085031
score: 1
type: Answer
has body: Maryam seems to have identified the cause of your spurious loss values(i.e. summing the generator and discriminator losses). Just wanted to add that you should probably opt for the Stochastic Gradient Descent optimizer for the discriminator in lieu of Adam - doing so provides stronger theoretical guarantees of the network's convergence when playing the minimax game(source: https://github.com/soumith/ganhacks).
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49988496

http://stackoverflow.com/comment/87080635
type: Comment
has text: DP2's last card is always 8 of spades, so it always wins another 2 cards
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50032238

http://stackoverflow.com/comment/86947405
type: QuestionComment
comment on: http://stackoverflow.com/q/49965781
has text: What do you want as output?
score: 0
type: Comment

http://stackoverflow.com/a/49947936
has body: Python datetime.datetime objects can be subtracted, but datetime.time objects can't. You can subtract them by combining them into datetime objects using the current date (see, e.g., https://stackoverflow.com/a/5259921/2715819). Specifically, try changing worked_hours = (self.time_out - self.time_in).total_seconds() / 60 / 60 to: datetime_in = datetime.combine(date.min, self.time_in) datetime_out = datetime.combine(date.min, self.time_out) worked_hours = (datetime_out - datetime_in).total_seconds() / 60 / 60 You'll also have to add from datetime import datetime, date at the top of your file. You'll have to change the calculation of overtime_hours to use datetime_out instead of self.time_out, too.
has comment: http://stackoverflow.com/comment/86913808
type: Answer
answers question: http://stackoverflow.com/q/49947856
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49947856
has comment: http://stackoverflow.com/comment/86914383
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87000335
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86913555

http://stackoverflow.com/comment/86917575
comment on: http://stackoverflow.com/a/49928442
type: Comment
type: AnswerComment
has text: A couple of sentences to explain the concept is not the same as a line by line explanation. I agree that the latter is excessive.
score: 0

http://stackoverflow.com/comment/87052210
comment on: http://stackoverflow.com/q/50018013
type: QuestionComment
has text: Where in your code do you use these characters? `sys.argv[3:]`?
score: 2
type: Comment

http://stackoverflow.com/q/50042403
tagged with: string
has answer: http://stackoverflow.com/a/50042549
type: Question
has title: subprocess python passing files as arguments
score: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87102463
has comment: http://stackoverflow.com/comment/87100742
answer count: 1
tagged with: subprocess
has body: I have to run a simple exernal programm inside a python script, passing some arguments and some files. I tried outside of the script and it is working corretly. The problem is that I don't know why the external programm is not working correctly when I run inside a python script. I think that the problem is in how I'm writing the name of the files inside the arguments. I tried every different combinations. I'm using subprocess, Python 3.6 and Windows &gt; import subprocess &gt; &gt; software=str(r"C:\Program Files\aa\bin\aa.exe") &gt; &gt; c=subprocess.call([software,'-db', '–if "File_assembly.cxm"', '–of &gt; "File_assembly_dec.cxm"'], shell=True) Thanks a lot for any suggestions. I'm destroyed! Cheers, Carlo
tagged with: arguments

http://stackoverflow.com/a/49979059
answers question: http://stackoverflow.com/q/49977258
has comment: http://stackoverflow.com/comment/86975214
type: Answer
has body: Perhaps you could use itertools.zip_longest which will zip the longest sequence and will substitute None for the missing values in the shorter sequence. That way you won't lose the April data. If you wish to use a value other than None, specify the fillvalue argument. From https://docs.python.org/3/library/itertools.html#itertools.zip_longest itertools.zip_longest(*iterables, fillvalue=None) Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Note that the function is called itertools.izip_longest in Python 2.
accepted answer of: http://stackoverflow.com/q/49977258
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87074187
has comment: http://stackoverflow.com/comment/87005451
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87064723
has comment: http://stackoverflow.com/comment/87009024
has comment: http://stackoverflow.com/comment/87062646

http://stackoverflow.com/comment/86935396
comment on: http://stackoverflow.com/a/49959358
type: AnswerComment
score: 2
has text: You probably meant `exec` and not `eval`
type: Comment

http://stackoverflow.com/comment/87035659
type: Comment
type: QuestionComment
has text: This is not opinion based, I disagree with the hold. There is scientific reasoning behind the answer to this question.
comment on: http://stackoverflow.com/q/49968000
score: 0

http://stackoverflow.com/comment/86863209
score: 0
has text: @Sylvain Biehler so, do you means that i need to add `dict={}` for each `x` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49922911
type: Comment

http://stackoverflow.com/comment/87145862
has text: I will work on this later when I get home. thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50063093
score: 0

http://stackoverflow.com/comment/87058466
has text: Both functions work and do the same thing, but the 2nd one has a horrible time complexity and should be avoided.
type: Comment
comment on: http://stackoverflow.com/q/50021381
score: 3
type: QuestionComment

http://stackoverflow.com/q/50055849
tagged with: python
has comment: http://stackoverflow.com/comment/87128314
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/5998245
accepted answer: http://stackoverflow.com/a/50055914
has answer: http://stackoverflow.com/a/50055942
has answer: http://stackoverflow.com/a/50055914
has body: I have 2 modules, the first one is generating ingestion_time as shown below Long ingestion_time = System.currentTimeMillis(); The sample output of this ingestion_time is ingestion_time = 446453570778734 Now I have the second module in python which is generating detection_time for the same event as shown below detection_time = time.time() The sample output of this detection_time is detection_time = 1524807106.92 I want to have them in the same format so that I can get latency as latency = detection_time - ingestion_time Both modules are on the same system. Please help! Edit 1 by using now = long(time.time()) print "detection_time = %s "%now I get detection_time as detection_time = 1524808352 which is still not comparable with generation_time as the number of digits is different generation_time = 1524808352170 Answer using below-mentioned code solved my issue now = int(round(time.time() * 1000)) print "detection_time = %s "%now
has comment: http://stackoverflow.com/comment/87128220
tagged with: timestamping
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/50055942
has title: use same time format in Java and Python
tagged with: java

http://stackoverflow.com/comment/87104086
comment on: http://stackoverflow.com/q/50043603
score: 0
type: Comment
has text: @ScottBoston That's not really what I want, kinda in the opposite direction. I want the x in the lambda to be the dataframe, not a component of it. I will try to make my question clearer.
type: QuestionComment

http://stackoverflow.com/comment/86927003
type: AnswerComment
comment on: http://stackoverflow.com/a/49951561
has text: Don't just blurt out code! Adding some text to explain how this best answers the question will improve the long-term value of the answer and help to prevent it from being deleted during review.
type: Comment
score: 0

http://stackoverflow.com/comment/86942806
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49963323
has text: Please show the page as displayed to the end user, showing the double quotes problem.

http://stackoverflow.com/q/50033695
tagged with: python
has title: Is it possible to duplicate a rectangle and both being in different positions?
has answer: http://stackoverflow.com/a/50046160
score: 0
answer count: 1
tagged with: pygame
has comment: http://stackoverflow.com/comment/87083567
has body: I have tried to use .copy() and .move_ip() to duplicate the rectangle but all that does is move the original rectangle without creating two. I have also tried calling in pygame.rect.draw twice yet all it does is move the original image without leaving anything behind. import pygame pygame.init() dis = pygame.display.set_mode((500, 500)) x = 0 y = 500-40 height = 40 width = 100 run = True vel = 10 clock = pygame.time.Clock() direction = 'Right' ran = True game = 0 def animate(ran, x, y, height, width, direction)#Pygasm: if ran: if x &lt; vel: direction = 'Right' elif x &gt; 500-width-vel: direction = 'Left' if direction == 'Right': x += vel elif direction == 'Left': x -= vel dssz = pygame.draw.rect(dis, (255, 0, 0), pygame.Rect(x, y, width, height)) return x, y, width, height, direction while run: for ev in pygame.event.get(): if ev.type == pygame.QUIT: run = False if ev.type == pygame.KEYDOWN: if ev.key == pygame.K_UP: game+=1 ran = False if ev.key == pygame.K_DOWN: game = 0 pygame.draw.rect(dis, (255,0,0), pygame.Rect(x,y,width,height)) y -= 40 ran = True dis.fill((0, 0, 0)) keys = pygame.key.get_pressed() x, y, height, width, direction = animate(ran, x, y, height, width, direction) pygame.display.flip() clock.tick(60) pygame.quit()
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87100238

http://stackoverflow.com/q/49953723
favorite count: 0
has answer: http://stackoverflow.com/a/49953866
type: Question
has comment: http://stackoverflow.com/comment/86924187
has comment: http://stackoverflow.com/comment/86924300
linked to: http://stackoverflow.com/q/480214
linked to: http://stackoverflow.com/q/8312829
has body: I want to delate the duplicated elements in a list using this structure but the list remains unchanged when I use this code. Could anyone help me please? e.g.,item=[1,2,3,4,5,6,7,8,9,1,2,6,7] def duplicated(item): i=0 j=0 while i&lt;len(item): while j&lt;len(item): if item[j]==item[i] and i!=j: del item[j] j+=1 i+=1 return item
tagged with: python
has comment: http://stackoverflow.com/comment/86924178
has comment: http://stackoverflow.com/comment/86924013
answer count: 4
has comment: http://stackoverflow.com/comment/86924037
type: AnsweredQuestion
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/49953868
downvote count: 0
accepted answer: http://stackoverflow.com/a/49953829
has comment: http://stackoverflow.com/comment/86924259
has title: Why I get the list unchanged when using this code?
has answer: http://stackoverflow.com/a/49953777
has comment: http://stackoverflow.com/comment/86924056
has answer: http://stackoverflow.com/a/49953868
linked to: http://stackoverflow.com/q/1207406
has answer: http://stackoverflow.com/a/49953829

http://stackoverflow.com/q/49981303
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
type: Question
has body: I'm not very experienced in programming. What I'm trying to do is to randomly shuffle the pages of a pdf and output it to another pdf. Searching online I found the following two solutions (source 1, source 2): #!/usr/bin/env python2 import random, sys from PyPDF2 import PdfFileWriter, PdfFileReader input = PdfFileReader(sys.stdin) output = PdfFileWriter() pages = range(input.getNumPages()) random.shuffle(pages) for i in pages: output.addPage(input.getPage(i)) output.write(sys.stdout) And this one: #!/usr/bin/python import sys import random from pyPdf import PdfFileWriter, PdfFileReader # read input pdf and instantiate output pdf output = PdfFileWriter() input1 = PdfFileReader(file(sys.argv[1],"rb")) # construct and shuffle page number list pages = list(range(input1.getNumPages())) random.shuffle(pages) # display new sequence print 'Reordering pages according to sequence:' print pages # add the new sequence of pages to output pdf for page in pages: output.addPage(input1.getPage(page)) # write the output pdf to file outputStream = file(sys.argv[1]+'-mixed.pdf','wb') output.write(outputStream) outputStream.close() I tried both (and both with PyPDF2 and pyPdf) and both indeed create a new pdf file, but this file is simply empty (and has 0KB) (when I enter, let's say "shuffle.py new.pdf"). I'm using PyCharm and one problem I encounter (and not really understand) is that it says: "Cannot find reference 'PdfFileWriter'". PyCharm tells me that it cannot find the reference I would appreciate any help understanding what I'm doing wrong :) EDIT: As suggested by Tom Dalton, I'm posting what happens when I run the first one: C:\Users\Anwender\AppData\Local\Temp\shuffle.py\venv\Scripts\python.exe "E:/Shuffle PDF/shuffle.py" PdfReadWarning: PdfFileReader stream/file object is not in binary mode. It may not be read correctly. [pdf.py:1079] Traceback (most recent call last): File "E:/Shuffle PDF/shuffle.py", line 5, in &lt;module&gt; input = PdfFileReader(sys.stdin) File "C:\Python2…
tagged with: random
answer count: 0
tagged with: pypdf
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87012228
has comment: http://stackoverflow.com/comment/87007523
has comment: http://stackoverflow.com/comment/87021626
has comment: http://stackoverflow.com/comment/87022504
favorite count: 0
has title: Randomly shuffle the pages of a PDF file using pyPDF or PyPDF2
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86979009

http://stackoverflow.com/a/49995596
type: Answer
has body: This line: future = loop.run_in_executor(executor, run(blocking)) Will actually run the blocking function and give its result to the executor. According to the documentation, you need to pass the function explicitly followed by its arguments. future = loop.run_in_executor(executor, run, blocking)
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49978320
answers question: http://stackoverflow.com/q/49978320

http://stackoverflow.com/q/49987271
has body: i have the following model: class Purchases(models.Model): p_id = models.IntegerField(primary_key=True, default=0) date = models.DateField(default=datetime.now) def __str__(self): return self.date.strftime('%Y-%m-%d') class Meta: verbose_name_plural = "Purchases" class Purchased_Items(models.Model): p_id = models.ForeignKey(Purchases, on_delete=models.CASCADE) item = models.CharField(max_length=80) size = models.IntegerField(max_length=2) quantity = models.IntegerField(max_length=3) price = models.IntegerField(max_length=4) total = models.IntegerField(default=0) def __str__(self): return self.item class Meta: verbose_name_plural = "Purchased Items" I am trying to retrieve using inner join: pur = Purchased_Items.objects.all().select_related() But i am not getting the required result. Basically I want the following sql: select * from finance_purchases as fp inner join finance_purchased_items pi ON (fp.p_id = pi.p_id_id); another question is although the foreign key in Purchased_Items is p_id but in the column in sql table is p_id_id! why? What is the logic behind it? Thanks
has comment: http://stackoverflow.com/comment/86990982
tagged with: sql
linked to: http://stackoverflow.com/q/97197
type: UnansweredQuestion
answer count: 1
tagged with: django
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86990838
tagged with: python
has title: Django retrieve data from two tables
linked to: http://stackoverflow.com/q/4125379
has answer: http://stackoverflow.com/a/49987565

http://stackoverflow.com/comment/87041819
score: 0
has text: Well, you haven't told us what website you're using, so there's no way anyone can read what they've said there. But meanwhile, what about all of the other questions?
comment on: http://stackoverflow.com/q/50012624
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49965395
accepted answer of: http://stackoverflow.com/q/49964327
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49964327
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86948245
score: 1
has body: Use: df['E'] = df['D'].pct_change().mul(100).replace(0,np.nan).ffill().fillna(0).round(2) s = df[df['B'].eq(time(12))].drop_duplicates(subset=['A']).set_index('A')['D'] df['F'] = (df['D'].div(df['A'].map(s.shift()))).sub(1).mul(100).round(2).fillna(0) print (df) A B C D E F 0 2002-01-12 10:00:00 John 19 0.00 0.00 1 2002-01-12 11:00:00 Africa 15 -21.05 0.00 2 2002-01-12 12:00:00 Mary 30 100.00 0.00 3 2002-01-13 09:00:00 Billy 5 -83.33 -83.33 4 2002-01-13 11:00:00 Mira 6 20.00 -80.00 5 2002-01-13 12:00:00 Hillary 50 733.33 66.67 6 2002-01-13 12:00:00 Romina 50 733.33 66.67 7 2002-01-14 10:00:00 George 30 -40.00 -40.00 8 2002-01-14 11:00:00 Denzel 12 -60.00 -76.00 9 2002-01-14 11:00:00 Michael 12 -60.00 -76.00 10 2002-01-14 12:00:00 Bisc 25 108.33 -50.00 11 2002-01-16 10:00:00 Virgin 16 -36.00 -36.00 12 2002-01-16 11:00:00 Antonio 10 -37.50 -60.00 13 2002-01-16 12:00:00 Sito 5 -50.00 -80.00 Explanation: For column E is used pct_change, then replace 0 to NaN and forward filling NaNs. For column F is used formula with mapping column A by rows with 12:00:00 in column B
type: Answer

http://stackoverflow.com/comment/89978727
has text: My case was weirder because "sudo" still gave me the same error. I had to switch to root (sudo su on ubuntu) to be able to do pip3.5 list and pip3.5 install :|
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51182092

http://stackoverflow.com/comment/87142716
type: AnswerComment
has text: @Vladyslav yeah, is it worked for you ?
comment on: http://stackoverflow.com/a/50062759
score: 0
type: Comment

http://stackoverflow.com/q/49921552
score: 1
answer count: 1
tagged with: pos-tagger
tagged with: nlp
favorite count: 0
type: Question
has title: Giving your own custom tags to tokenize data in nltk?
linked to: http://stackoverflow.com/q/33717131
tagged with: spacy
tagged with: nltk
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49942605
downvote count: 0
upvote count: 1
tagged with: python
has body: While running the below code from nltk import word_tokenize, pos_tag, ne_chunk sentence = "Antacids is given to Jhon,Sodium Bicarbonate is given to Carl,Folic Acid to Jeery all works at Google " print(ne_chunk(pos_tag(word_tokenize(sentence)))) i am getting this output (S (GPE Antacids/NNP) is/VBZ given/VBN to/TO (PERSON Jhon/NNP) ,/, (PERSON Sodium/NNP Bicarbonate/NNP) is/VBZ given/VBN to/TO (GPE Carl/NNP) ,/, (PERSON Folic/NNP Acid/NNP) to/TO (GPE Jeery/NNP) all/DT works/NNS at/IN (ORGANIZATION Google/NNP)) I want to assign the medicines like (Antacid,Sodium, Folic) to same category. Which library I can use for this purpose ?
has comment: http://stackoverflow.com/comment/86967113

http://stackoverflow.com/comment/87078299
type: Comment
has text: It does but in its proper situation. I'd recommend you to read https://docs.python.org/3/reference/import.html#the-import-system and https://www.python.org/dev/peps/pep-0366/ so that you can find the answer of your question thoroughly.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50019435

http://stackoverflow.com/a/49950788
type: Answer
has comment: http://stackoverflow.com/comment/86918342
has comment: http://stackoverflow.com/comment/87367687
answers question: http://stackoverflow.com/q/49950747
has body: This is both implementation-dependent and hardware-dependent. Without knowing your target machine and specific distribution, I couldn't say for sure. However, I strongly suspect that the underlying hardware, like most, has memory block instructions. Among other things, this can compare a pair of arbitrarily long strings (up to addressing limits) in parallel and pipelined fashion. For instance, it may compare 8-byte slices at one slice per clock cycle. This is a lot faster than fiddling with byte-level indices.
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/86985044
upvote count: 5

http://stackoverflow.com/q/49951964
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49952069
type: UnansweredQuestion
downvote count: 0
tagged with: python
upvote count: 2
score: 2
answer count: 1
tagged with: shelve
has title: Python shelve able to create but not open shelf
has body: I'm having a strange experience. I'm running python3.5.3 on debian, installed through the official repositories. I have a few objects that I store in a shelf as follows with shelve.open(filename,'c') as shelf: shelf['lists'] = (bus1,bus2) shelf['N'] = N shelf['wtfun'] = mywtfun.__name__ shelf['g'] = g shelf['svs'] = mysvs It saves it as filename.db when I do this. Running file on this in the unix prompt tells me it is a Berkeley database. I do have the bsddb module installed. Then when I try: s1 = shelve.open(filename) I get the following error: &lt;ipython-input-100-171f41c7dda0&gt; in &lt;module&gt;() ----&gt; 1 s1 = shelve.open('busemanns-runs-30000-N-1000-absnormal-2018-04-20T22:14:18.439245.shelf.db') /usr/lib/python3.5/shelve.py in open(filename, flag, protocol, writeback) 241 &lt;ipython-input-100-171f41c7dda0&gt; in &lt;module&gt;() ----&gt; 1 s1 = shelve.open('busemanns-runs-30000-N-1000-absnormal-2018-04-20T22:14:18.439245.shelf.db') /usr/lib/python3.5/shelve.py in open(filename, flag, protocol, writeback) 241 """ 242 --&gt; 243 return DbfilenameShelf(filename, flag, protocol, writeback) /usr/lib/python3.5/shelve.py in __init__(self, filename, flag, protocol, writeback) 225 def __init__(self, filename, flag='c', protocol=None, writeback=False): 226 import dbm --&gt; 227 Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) 228 229 /usr/lib/python3.5/dbm/__init__.py in open(file, flag, mode) 86 elif result == "": 87 # db type cannot be determined ---&gt; 88 raise error[0]("db type could not be determined") 89 elif result not in _modules: 90 raise error[0]("db type is {0}, but the module is not " error: db type could not be determined """ 242 --&gt; 243 return DbfilenameShelf(filename, flag, protocol, writeback) /usr/lib/python3.5/shelve.py in __init__(self, filename, flag, protocol, writeback) 225 def __init__(self, filename, flag='c', protocol=None, writeback=False): 226 import dbm --&gt; 227 Shelf.__init__(self, dbm.open(filename, flag), pro…

http://stackoverflow.com/q/49955429
has body: I am confused about the right approach I should take I am creating a sort of game and in this game the main character has accessories. So I was thinking about an abstract class named Item. Inheriting from Item are also abstract class such as Glasses, Shirt etc... The reason I think it should be abstract is that I never create glasses for example, I create an instance of "Green Shades". Green Shades is also a class and I think it should inherit from glasses of course. I was thinking about making Item an abstract class and also Glasses an abstract class for example but they have a factory method that generates the types of glasses(Green Shades, Blue Shades and so on). Each Item has a worth property (basic or rare). I've started to write something but I am getting confused on the implementation details. Item: from enum import Enum from abc import ABCMeta, abstractmethod class Worth(Enum): BASIC = 0 RARE = 1 class Item(object): __metaclas__ = ABCMeta def __init__(self, worth): self.worth = worth @property @abstractmethod def type_factory(self,type): pass Glasses and an example of a glasses: from abc import ABCMeta, abstractmethod import importlib Enums = importlib.import_module('Enums') Item = importlib.import_module('Item') class Glasses(Item): __metaclas__ = ABCMeta def __init__(self,worth,type): super().__init__(worth) # self.type = self.type_factory() @property @abstractmethod def type_factory(self,type): if type == Enums.GlassesType.BLACK_SHADES: return BlackShades() # so on.. class BlackShades(Glasses): def __init__(self,worth): super().__init__(worth) What would be the best way to do it? Is there a better example of a factory I should use? Maybe it will be better to use type class creation? To clarify: I am not looking just to improve this code. I wouldn't mind implementing it from scratch using the right way to do so, which I am not sure what it is due to my lack of experience in Python. Thanks
tagged with: oop
has comment: http://stackoverflow.com/comment/86927329
has comment: http://stackoverflow.com/comment/86927349
has comment: http://stackoverflow.com/comment/86927452
tagged with: python
has comment: http://stackoverflow.com/comment/86927363
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86927328
answer count: 0
type: UnansweredQuestion
has title: Abstract Classes, Inheritance and Factory Method in Python
upvote count: 1
tagged with: inheritance
downvote count: 1
tagged with: factory
score: 0
tagged with: abstract-class

http://stackoverflow.com/q/50072328
tagged with: python-3.x
type: UnansweredQuestion
tagged with: datetime
linked to: http://stackoverflow.com/q/12070193
tagged with: python
has comment: http://stackoverflow.com/comment/87165133
tagged with: datetime-format
has body: Trying to convert this date format Thu Apr 26 22:51:49 PDT 2018 to UTC 2018-04-26T22:51:49Z I dont care about the day part and can be excluded. type(results[0].create_date) returns &lt;class 'str'&gt; So far I have tried this print (datetime.strptime((results[0].create_date), "%Y-%m-%dT%H:%M:%SZ")) but failing with this error ValueError: time data 'Thu Apr 26 22:51:49 PDT 2018' does not match format '%Y-%m-%dT%H:%M:%SZ'
score: 0
has title: Convert datetime to UTC in different order
has answer: http://stackoverflow.com/a/50113364
answer count: 1
type: Question

http://stackoverflow.com/q/50048920
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: instagram-api
has comment: http://stackoverflow.com/comment/87114053
tagged with: instagram
has answer: http://stackoverflow.com/a/54136300
type: UnansweredQuestion
has body: I'm using the InstagramAPI for a Python project which requires me to add an instagram post, a story and also tag people on the photo using something like x and y coordinates . All using code! i use this for uploading: InstagramAPI.uploadPhoto(photo_path, caption=caption) but can't figureout a way to tag people in the post!
tagged with: python
has comment: http://stackoverflow.com/comment/87114307
score: 1
has title: Is there a way to tag someone on instagram post and story using InstagramAPI?

http://stackoverflow.com/comment/86989547
has text: All required DLLs appear to be present. Please open an issue on the TensorFlow GitHub page: https://github.com/tensorflow/tensorflow/issues An exception has occurred, use %tb to see the full traceback.
score: 0
comment on: http://stackoverflow.com/a/49975776
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86901690
type: Comment
type: QuestionComment
has text: I need the countArray for every j&k. I use it to compute few other parameters and then it can be reset. Which is why I need faster computing only for the innermost for-loop.
comment on: http://stackoverflow.com/q/49942690
score: 0

http://stackoverflow.com/a/50063220
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50063089
has comment: http://stackoverflow.com/comment/87143197
has comment: http://stackoverflow.com/comment/87143504
answers question: http://stackoverflow.com/q/50063089
type: Answer
has body: You could call cumsum on the output of get_dummies on the column of interest: &gt;&gt;&gt; pd.get_dummies(df["f2"]) a b c 0 1 0 0 1 1 0 0 2 0 1 0 3 0 0 1 &gt;&gt;&gt; pd.get_dummies(df["f2"]).cumsum() a b c 0 1 0 0 1 2 0 0 2 2 1 0 3 2 1 1 If you want the equivalent of normalize=True for value_counts, you can simply do it manually: &gt;&gt;&gt; x = pd.get_dummies(df["f2"]).cumsum() &gt;&gt;&gt; x.div(x.sum(axis=1), axis=0) a b c 0 1.000000 0.000000 0.00 1 1.000000 0.000000 0.00 2 0.666667 0.333333 0.00 3 0.500000 0.250000 0.25 This is probably the best format for further data processing. While you could force this into a dict-like format, pandas doesn't have good support for non-scalar elements, and so apart from being slow it can lead to mysterious bugs. That said: &gt;&gt;&gt; pd.get_dummies(df["f2"]).cumsum().apply(dict, axis=1) 0 {'a': 1, 'b': 0, 'c': 0} 1 {'a': 2, 'b': 0, 'c': 0} 2 {'a': 2, 'b': 1, 'c': 0} 3 {'a': 2, 'b': 1, 'c': 1} dtype: object
has comment: http://stackoverflow.com/comment/87143514
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87143357

http://stackoverflow.com/comment/86966131
score: 0
type: Comment
type: QuestionComment
has text: @e.s. No change even when I do `from __future__ import division`
comment on: http://stackoverflow.com/q/49973586

http://stackoverflow.com/comment/86950255
has text: I think you need an sql request on sale_order table join with sale_order_line join with product_template where sale_order state is done and date order between start_date and end_date
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49965402
type: Comment

http://stackoverflow.com/comment/86899109
comment on: http://stackoverflow.com/q/49941417
score: 0
type: Comment
type: QuestionComment
has text: It definitely can. You need to look for href values on each page(be careful with externel urls). There's a great course at Udacity that'll teach you how to build a web crawler using Beautiful Soup(Intro to Computer Science). Personally I like lxml.html for that.

http://stackoverflow.com/comment/87058765
has text: @CZoellner anyway Thank you:)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50017118

http://stackoverflow.com/a/49959422
has comment: http://stackoverflow.com/comment/86935697
type: Answer
has comment: http://stackoverflow.com/comment/86939687
has comment: http://stackoverflow.com/comment/86939748
has comment: http://stackoverflow.com/comment/86939764
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49956945
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49956945
has comment: http://stackoverflow.com/comment/86938656
has body: "...it forgets the first wave to learn the next one..." This makes me think... are you training one sequence, then another one, then another?? That will fail, naturally, for any kind of problem with any model. You must train lots of sequences in the same batch, or, if one sequence at a time, never more than once per epoch. freqs = list_of_frequencies sinusoids = [] for freq in freqs: sinusoids.append(create_a_sinusoid(freq)) training_data = np.array(sinusoids).reshape((freqs,timesteps,features)) Possible tricks to help the model: Add the frequency as a feature (for all steps) in the input data (if you know it as input) Make the model output the frequency (if you know it as output) and train it on frequencies. You may combine a model that identifies frequences with a model that will read these frequencies for predicting the desired outputs

http://stackoverflow.com/q/50023736
has comment: http://stackoverflow.com/comment/87069303
upvote count: 3
score: 3
tagged with: random
has comment: http://stackoverflow.com/comment/87068858
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87067830
linked to: http://stackoverflow.com/q/12915177
has comment: http://stackoverflow.com/comment/87093214
has comment: http://stackoverflow.com/comment/111148012
tagged with: random-seed
has comment: http://stackoverflow.com/comment/87069069
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87077463
has body: I have a project in which I cannot reproduce random numbers when I use numpy in combination with tensorflow. In the beginning of all my tests, I set tf.set_random_seed(seed) np.random.seed(seed) I have been debugging, and when I use numpy and no TF, all results are reproducible. When I add the TF code, the random numbers stop being reproducible. When I use both TF and numpy, I get the following results: TF variables are initialized to the same value every time (OK) When I use np.random.RandomState() with a set seed instead of direct calls to np.random.uniform(), np.random.normal(), etc, results are reproducible (OK) When I use direct calls to np.random.uniform(), np.random.normal(), etc, results are not reproducible (NOT OK) The difference between 2 and 3 makes me think that TF must be using numpy internally somewhere in order to generate random numbers. This sounds a bit strange and unexpected. I have only 1 main thread, so the difference is definitely not caused because of race conditions. Furthermore, even if TF uses np.random, this should not change the random numbers that I observe between runs in my project since the sequence of querying the random number generation is always the same. What is even more strange is that the particular piece of TF code which makes results non-reproducible is computing and applying gradients, where I would not expect any random number generation to be needed. Note that I am comparing only the sampled random numbers rather than results from the network (since TF has some non-deterministic operations) and these random numbers are not affected in any way by results produced from training the net. Sorry I am unable to post my code, but it is just too big and reducing it to a smaller sample will likely make the problem go away. Thus any suggestions how to debug further are welcome. EDIT: I discovered that this happens only on GPU and does not occur on CPU.
has title: Unable to reproduce randomness with tensorflow and numpy combined?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87067946
tagged with: python

http://stackoverflow.com/a/50029705
answers question: http://stackoverflow.com/q/50029667
type: Answer
upvote count: 0
downvote count: 1
score: -1
has body: For reading in just one column use the keyword usecols: data = pd.read_csv("/Users/Desktop/EQR_Data/EQR_Transactions_1.csv", usecols=['seller_company_name']) Then you can groupby seller names: grpd = df.groupby('seller_company_name') In grpd.groups is then a dict, which contains the list of occurence indices for each seller. Turn it into a dict with the lengths of these lists: result = {d: len(grpd.groups[d]) for d in grpd.groups}

http://stackoverflow.com/comment/86937476
comment on: http://stackoverflow.com/q/49953345
type: Comment
type: QuestionComment
has text: Well, you change the projection matrix in-between the objects. SO what do you expect? None of that does make any sense.
score: 0

http://stackoverflow.com/comment/87122207
type: Comment
type: QuestionComment
score: 0
has text: You only assign to `text` once.
comment on: http://stackoverflow.com/q/50052820

http://stackoverflow.com/q/49951041
score: 0
has answer: http://stackoverflow.com/a/49951163
has body: I'm learning python and I've made a quick grade calculator that checks if the first letter is D for daily grade, or M for major grade (Major is weighed differently than daily). However I need to actually remove the D and M once I move it to their respective lists. How would I go about doing this? Do me a favor and keep it simple :D. grades = ['D 85', 'D 100', 'M 20', 'D 70'] I have code that puts the Daily grades in the proper list and vice versa for major. Daily = ['D 85', 'D 100', 'D 70'] Major = ['M 20'] Now I need to remove the D and the M from each item in the list. daily.replace didn't work and I tried a for i in list: for c in i: newdaily.replace('D',"") And same for the major list. How would I go about this?
tagged with: list
has answer: http://stackoverflow.com/a/50422196
has answer: http://stackoverflow.com/a/49951069
has answer: http://stackoverflow.com/a/49951113
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86918676
favorite count: 0
has answer: http://stackoverflow.com/a/49951066
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86918824
answer count: 5
type: UnansweredQuestion
tagged with: python
has title: How can I delete a character in an item in a list (Python)

http://stackoverflow.com/a/49936550
has body: If all files have the same pattern, you can use this: import os list_of_files = os.listdir() # returns list of current directory files file_to_be_deleted = sorted(list_of_files)[0] Now you have the name of the file that should be deleted in file_to_be_deleted, then use os.remove() to delete the file.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49936414

jupyter
tags question: http://stackoverflow.com/q/49961374
tags question: http://stackoverflow.com/q/50058396
type: Tag
tags question: http://stackoverflow.com/q/49995624
tags question: http://stackoverflow.com/q/49964038
tags question: http://stackoverflow.com/q/49952341
tags question: http://stackoverflow.com/q/50015665
tags question: http://stackoverflow.com/q/49948868
tags question: http://stackoverflow.com/q/49925555
tags question: http://stackoverflow.com/q/49952317
tag name: jupyter

http://stackoverflow.com/comment/86949478
has text: Thanks ayhan. It works
score: 0
comment on: http://stackoverflow.com/q/49966770
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87085439
score: 0
has text: There are tons of duplicates for reading a CSV file in pandas and computing column average. Please close.
type: QuestionComment
comment on: http://stackoverflow.com/q/50034477
type: Comment

http://stackoverflow.com/comment/87091863
has text: Sorry, your regex works well. But if the path contains `_`, it doesn't work. E.g. `/Users/analyze_geronimo/histogram/offline-deployer-list_b7bacc7fdb-0e0e08077c_GERONIMO-2886_635_histogrambuglines_635.diff`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50037791
score: 0

http://stackoverflow.com/comment/87215935
comment on: http://stackoverflow.com/a/50046511
type: AnswerComment
score: 0
has text: Made a new question :https://stackoverflow.com/questions/50099105/dynamic-location-count-in-pandas-array
type: Comment

http://stackoverflow.com/q/50019417
has answer: http://stackoverflow.com/a/50025996
tagged with: apache-spark
tagged with: pyspark
has title: Error doing .show() in spark sql SELECT query
has comment: http://stackoverflow.com/comment/87057375
has body: I created a Hive container with docker, I created poke table and I have this error when I do a Select query a after call show() function. The code: from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession, HiveContext spark = SparkSession \ .builder \ .appName("Python Spark SQL Hive integration example") \ .config("hive.metastore.uris", "thrift://localhost:9083") \ .enableHiveSupport() \ .getOrCreate() spark.sql("SELECT * FROM pokes").show() The error is: 18/04/25 11:58:34 INFO SparkContext: Created broadcast 0 from Traceback (most recent call last): File "/Users/xxxxx/scripts/hive/hive.py", line 12, in spark.sql("SELECT * FROM pokes").show() File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/pyspark.zip/pyspark/sql/dataframe.py", line 336, in show File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in call File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/pyspark.zip/pyspark/sql/utils.py", line 79, in deco pyspark.sql.utils.IllegalArgumentException: u'java.net.UnknownHostException: namenode' Thanks!
has comment: http://stackoverflow.com/comment/87058233
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/60803619
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87062246
tagged with: hive
type: Question
score: 0

http://stackoverflow.com/comment/86913434
score: 0
type: AnswerComment
has text: I definitely will. Today is the mark of my first month in coding, so I haven't knew much for sure. I was just trying to do a practical study side by side with theoretical reading, so I can see practically how it will behave. Thanks for stopping by to help, I won't waste anymore of your time for now :)
comment on: http://stackoverflow.com/a/49948010
type: Comment

http://stackoverflow.com/comment/86930876
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49957157
has text: `[i+1:]` is not necessarily the last value in a list, which would be `[-1]`. What exactly to you mean?

http://stackoverflow.com/comment/87145849
has text: you can get three channels as red = img[:,:,2] and green = img[:,:,1] and blue = img[:,:,0] and use your range to get colors
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50009438

http://stackoverflow.com/q/49953379
type: UnansweredQuestion
downvote count: 0
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/109983592
favorite count: 0
type: Question
has title: Tensorflow: Multiple loss functions vs Multiple training ops
has answer: http://stackoverflow.com/a/52053172
upvote count: 33
has answer: http://stackoverflow.com/a/49955623
has answer: http://stackoverflow.com/a/51157386
tagged with: python
has answer: http://stackoverflow.com/a/52228323
has body: I am creating a Tensorflow model which predicts multiple outputs (with different activations). I think there are two ways to do this: Method 1: Create multiple loss functions (one for each output), merge them (using tf.reduce_mean or tf.reduce_sum) and pass it to the training op like so: final_loss = tf.reduce_mean(loss1 + loss2) train_op = tf.train.AdamOptimizer().minimize(final_loss) Method 2: Create multiple training operations and then group them like so: train_op1 = tf.train.AdamOptimizer().minimize(loss1) train_op2 = tf.train.AdamOptimizer().minimize(loss2) final_train_op = tf.group(train_op1 train_op2) My question is whether one method is advantageous over the other? Is there a third method I don't know? Thanks
has answer: http://stackoverflow.com/a/65112694
score: 33
answer count: 5

http://stackoverflow.com/comment/87034256
type: AnswerComment
comment on: http://stackoverflow.com/a/50008360
has text: @GeorgeSanger Your program has a few issue. 1st you need to show what imports are needed for this code. 2nd you are sending three arguments to a function that can only take one. I think you need to change `popupmsg('You have a discount of', str(percentage*100), '%')` to this: `popupmsg('You have a discount of {}%'.format(percentage*100))`. 3rd your example uses `Tk()` however the main program will be using `Tk()` so you should be using `Toplevel()` here instead.
score: 0
type: Comment

http://stackoverflow.com/a/50011009
answers question: http://stackoverflow.com/q/50010858
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: What you're asking for in your description doesn't match anything in your sample input, or even come close to it. None of your lines starts with ). One of your lines starts with some whitespace and a ), but the line before that is a blank line, and the last non-blank line before that doesn't have a comma anywhere to remove. But I'll ignore the sample input and explain how to do what you were asking for in the description. The simplest way is to just keep track of the previous line while iterating the lines: lastline = None for line in infile: line = line.rstrip() if line.startswith(")"): if lastline is not None: lastline = lastline.rstrip(",") if lastline is not None: outfile.write(lastline + '\n') lastline = line if lastline is not None: outfile.write(lastline + '\n') You can make this a little cleaner and more compact by using a pairwise iterator wrapper like the one in the itertools recipes, but slightly modified to include the "extra" pair at the end: def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.zip_longest(a, b, fillvalue='') stripped = (line.rstrip() for line in infile) for line, nextline in pairwise(stripped): if nextline.startswith(")"): line = line.rstrip(",") if line is not None: outfile.write(line + '\n')
type: Answer
accepted answer of: http://stackoverflow.com/q/50010858

http://stackoverflow.com/comment/86984680
comment on: http://stackoverflow.com/q/49983966
type: Comment
type: QuestionComment
has text: Use Toplevel instead.
score: 0

http://stackoverflow.com/comment/86947502
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49964044
has text: Thanks for the detailed answer. Greatly appreciated, could you also please explain why a number would be easier than a list? Thanks again :)
score: 0

qfilesystemmodel
tag name: qfilesystemmodel
tags question: http://stackoverflow.com/q/50068802
type: Tag

http://stackoverflow.com/q/49974379
tagged with: python
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/49981064
has title: Using ScreenshotKeywords from SeleniumLibrary
favorite count: 0
type: Question
tagged with: robotframework
has body: I'm trying to create a custom python library that I can use with RobotFramework to run my tests. So far, I've only had issues with using the capture_page_screenshot() method from within my code. I can't seem to figure out the right way to call the function. How do I get around this? from SeleniumLibrary import ScreenshotKeywords def screenshot(): ScreenshotKeywords.capture_page_screenshot()
type: UnansweredQuestion

http://stackoverflow.com/comment/86973568
has text: I have a personal (probably unfair/irrational) dislike of using `or` for that purpose. Possibly due to childhood exposure to C constructs that use `or` alongside functions with side-effects :-)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49978179
type: Comment

http://stackoverflow.com/q/50049309
linked to: http://stackoverflow.com/q/394809
has answer: http://stackoverflow.com/a/61647854
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/75167957
has answer: http://stackoverflow.com/a/50049392
has comment: http://stackoverflow.com/comment/87114940
type: Question
has comment: http://stackoverflow.com/comment/87114737
has title: Alternating letter in python
answer count: 12
has answer: http://stackoverflow.com/a/62112956
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59464152
has body: def myfunc(word): result = "" index = 0 for letter in word: if index % 2 == 0: result += letter.lower() else: result += letter.upper() return result index +=1 I am trying to return a matching string where every even letter is uppercase and every odd letter is lowercase. But the code doesn't show this exact result, any solution?
has answer: http://stackoverflow.com/a/50049609
has answer: http://stackoverflow.com/a/65046693
has answer: http://stackoverflow.com/a/54049659
score: 2
has answer: http://stackoverflow.com/a/61901958
upvote count: 3
linked to: http://stackoverflow.com/q/36247173
has answer: http://stackoverflow.com/a/61079550
has answer: http://stackoverflow.com/a/50049359
has answer: http://stackoverflow.com/a/62060517
has comment: http://stackoverflow.com/comment/87114735

http://stackoverflow.com/q/50008418
upvote count: 1
accepted answer: http://stackoverflow.com/a/50008774
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50008774
favorite count: 0
has comment: http://stackoverflow.com/comment/87033475
type: Question
has comment: http://stackoverflow.com/comment/87033334
tagged with: python
has title: How to setup Python directory structure for Jenkins?
has body: I have a python project I'm working on and am trying to implement tests with pytest and Jenkins. My directory structure is like this: project/ src/ __init__.py hello.py input.py person.py test/ test_hello.py When I run pytest from the project directory it works fine. But when I use Jenkins I keep getting the following error: [-1_10-finish-basic-ci-setup-IIB3G6YENVYIQDST5MPMDBNVOZLYD6VSLP5ZCT6VUVQSNZJKGYEA] Running shell script + python src/hello.py true Traceback (most recent call last): File "src/hello.py", line 1, in &lt;module&gt; import src.person as person ImportError: No module named 'src' I run Jenkins inside a docker container and it spins up another docker container for testing my project. Can anyone please clue me in to how I can get it to recognize the src directory for running the test?
tagged with: jenkins
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/50065427
tagged with: graph
tagged with: python
has answer: http://stackoverflow.com/a/50069632
has title: Bokeh: Span when plotting multiple graphs
type: AnsweredQuestion
score: 1
has body: I'm fairly new to Bokeh so still probably missing something with it, but I keep running into issues when trying to use Span on multiple plots if I'm generating the plots in a loop. Here's what I'm trying: titleString = 'Test Plot' plotVals = [1, 2] upperLimit = Span(location=6, dimension='width', line_color='red', line_dash='dashed', line_width=1) lowerLimit = Span(location=-6, dimension='width', line_color='red', line_dash='dashed', line_width=1) xVals = [0,1,2,3,4] yVals = [2,4,3,4,2] for t in enumerate(plotVals): print(t[1]) imgTitle = 'Span Test ' + str(t[0]) p = figure(title=imgTitle, plot_width=800, plot_height=450, y_range=(-8, 8), x_range=(-4,8)) p.add_layout(upperLimit) p.add_layout(lowerLimit) p.circle(xVals,yVals, size=5) show(p) reset_output() The first graph comes out as expected, but the second fails with the following message: ValueError: object to be added already has 'plot' attribute set I assume I'm doing something stupid. Can someone point me in the right direction?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50069632
tagged with: bokeh
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87816108
type: Comment
score: 0
type: AnswerComment
has text: Thanks, just to clarify, I am not using the version with +1 since it adds one element that is too many. I always get `i>j` anyway. In your new update, does the `a[j-1:]` have anything to do with the `i-j+1`, in other words, if I do `i-j` instead, do I need the -1 part?
comment on: http://stackoverflow.com/a/49982967

http://stackoverflow.com/a/50063244
upvote count: 1
answers question: http://stackoverflow.com/q/50063206
downvote count: 0
type: Answer
has body: Convert your input to int. Ex: choice = int(input()) and then replace if choice == 2: with elif choice == 2: Edit as per comments def game(): health = 100 revive = 0 print("You are greeted by a monster...") print("1 = Fight") print("2 = Take a chance at running") choice = int(input("")) if choice == 1: damage = randint(1,100) health = health - damage print("You killed the monster!") print("But you took "+str(damage)+" damage") #--&gt;Convert int to str before concatenation print("Your new health is: "+str(health)) #--&gt;Convert int to str before concatenation elif choice == 2: print("You tried to run but failed.") damage = randint(70,100) health = health - damage print("Your new health is: "+str(health)) #--&gt;Convert int to str before concatenation else: print("Wrong choice. You died.")
has comment: http://stackoverflow.com/comment/87143029
has comment: http://stackoverflow.com/comment/87143212
score: 1

http://stackoverflow.com/comment/106767684
comment on: http://stackoverflow.com/a/49998082
type: Comment
has text: @JoelB Yes, this is an old story. Now it is not what you want any more. What a sad story.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49946833
type: Answer
downvote count: 0
upvote count: 1
has body: Without using Pandas &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; pprint(d) {('domestic', 'cat', 'siamese', 'young'): array([10, 11, 12]), ('domestic', 'dog', 'collie', 'old'): array([1, 2, 3]), ('domestic', 'dog', 'golden', 'old'): array([4, 5, 6]), ('domestic', 'dog', 'golden', 'young'): array([7, 8, 9]), ('stray', 'dog', 'golden', 'old'): array([13, 14, 15])} Filter the dictionary &gt;&gt;&gt; keys = ('old','dog') &gt;&gt;&gt; q = [v for k,v in d.items() if all(thing in k for thing in keys)] &gt;&gt;&gt; q [array([1, 2, 3]), array([4, 5, 6]), array([13, 14, 15])] &gt;&gt;&gt; &gt;&gt;&gt; #or with keys as a set &gt;&gt;&gt; keys = set(('old','dog')) &gt;&gt;&gt; q = [v for k,v in d.items() if len(keys.intersection(k)) == len(keys)] Create a 2-d array from the results and get the mean of the columns: &gt;&gt;&gt; np.vstack(q) array([[ 1, 2, 3], [ 4, 5, 6], [13, 14, 15]]) &gt;&gt;&gt; np.vstack(q).mean(1) array([ 2., 5., 14.]) &gt;&gt;&gt; np.vstack(q).mean(0) array([ 6., 7., 8.]) &gt;&gt;&gt; Using the in operator, this solution does Not test for values in specific positions of the dictionary keys.
answers question: http://stackoverflow.com/q/49930401
score: 1

concurrent.futures
tags question: http://stackoverflow.com/q/49992329
type: Tag
tag name: concurrent.futures

http://stackoverflow.com/comment/86991226
has text: This printed out all of the relative file paths of the parent directory, WinterResearch.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49975637
score: 0

http://stackoverflow.com/a/49964950
has comment: http://stackoverflow.com/comment/86999772
has body: This is how you define and acess the instance and calss attributes: class YourClass: another_preset = 0 # the class attributes are defined here, and accessed the same way as instance attributes (plus can be accessed in the class itself like this: ‘YourClass.another_preset’), but are shared among all instances def __init__(self): self.preset = 0 # instance variable - will be unique for every instance def set_preset_to(self, x): self.preset = x # this is how you access the instance or class attributes inside a method def do_something_with_preset(self): self.preset += 2 # they can also be modified
type: Answer
has comment: http://stackoverflow.com/comment/86996804
has comment: http://stackoverflow.com/comment/86999888
answers question: http://stackoverflow.com/q/49964759
score: 0

http://stackoverflow.com/comment/86967071
has text: Thanks for answer. I tried to remove "$" at point you mentioned. It worked fine at both cases(with $ and without $) But I found question for this case.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49975258
type: AnswerComment

http://stackoverflow.com/comment/87113745
type: QuestionComment
has text: It should work if the filter one line above returns something.
comment on: http://stackoverflow.com/q/50044825
score: 1
type: Comment

http://stackoverflow.com/comment/86943892
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49963862
has text: what are the errors?

http://stackoverflow.com/comment/86994156
has text: `[data[k], data[k+1], data[k+2]] == data[k:k+3]`
comment on: http://stackoverflow.com/a/49988665
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50023660
has body: Here's a quick way to create the confusion matrix, using numpy.add.at. First, here's some sample data: In [93]: y_label Out[93]: array([2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]) In [94]: y_predict Out[94]: array([2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]) Create the array cm containing zeros, and then add 1 at each index (y_label[i], y_predict[i]): In [95]: cm = np.zeros((3, 3), dtype=int) In [96]: np.add.at(cm, (y_label, y_predict), 1) In [97]: cm Out[97]: array([[4, 1, 2], [3, 0, 2], [1, 2, 1]]) In SciPy 1.7.0, the function scipy.stats.contingency.crosstab was added, which provides a nice wrapper for the same calculation. It is like a pared down version of the Pandas crosstab function. In [55]: from scipy.stats.contingency import crosstab In [56]: y_label = np.array([2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]) In [57]: y_predict = np.array([2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]) In [58]: (labels, _), table = crosstab(y_label, y_predict) In [59]: table Out[59]: array([[4, 1, 2], [3, 0, 2], [1, 2, 1]])
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50021928
upvote count: 8
answers question: http://stackoverflow.com/q/50021928
type: Answer
score: 8

http://stackoverflow.com/comment/86896016
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49939859
has text: how are you accessing video camera?
type: Comment

http://stackoverflow.com/a/49997151
answers question: http://stackoverflow.com/q/49997094
type: Answer
has body: You can not use python 2 syntax if you are using python 3 compiler. Missing parentheses should give you a clear clue about how you should use print.
score: 0
accepted answer of: http://stackoverflow.com/q/49997094
type: AcceptedAnswer

http://stackoverflow.com/a/49971978
has body: You can filter your data to do this. A simple option would just be a mean filter. For example, I have the following data. I then filter it with a length 5 mean filter. I use scipy's convolve function to do this. from scipy.signal import convolve smoothed = convolve(data, [1/5] * 5, mode='valid') Which results in this signal.
type: Answer
answers question: http://stackoverflow.com/q/49971723
score: 0

http://stackoverflow.com/a/49964533
has body: It takes a shell to interpret operators like |. You can ask Python to run a shell, and pass your command as the thing to execute: cmd = "cat test.py | tail -n3" process = subprocess.Popen(['bash', '-c', cmd], stdout=subprocess.PIPE) out, err = process.communicate() print out
type: Answer
answers question: http://stackoverflow.com/q/49964453
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86954779
downvote count: 0

http://stackoverflow.com/comment/87058736
comment on: http://stackoverflow.com/q/50020279
type: QuestionComment
type: Comment
has text: Why you need `for f in formset:` for loop ?
score: 0

http://stackoverflow.com/q/49944797
type: Question
possible better answer: http://stackoverflow.com/a/49944936
has answer: http://stackoverflow.com/a/49944936
accepted answer: http://stackoverflow.com/a/49944852
has title: Add non-lamda function to self of Python class
tagged with: python
has comment: http://stackoverflow.com/comment/86907250
tagged with: lambda
has answer: http://stackoverflow.com/a/49944852
tagged with: class
type: AnsweredQuestion
answer count: 3
score: 0
has body: Adding lambda expression to self of a Python class is easy: class Foo(object): def __init__(self, x): if x &gt; 0: self.eval = lambda x: x else: self.eval = lambda x: x**2 return def compute(self, y): return self.eval(y) In my case, self.eval is somewhat more complex such that it doesn't fit into a one-line lambda. I need def. How can I assign self.eval with a defined function though? For performance reasons, I would like to not store self.x = x and not move the if into compute.
has answer: http://stackoverflow.com/a/49945074

http://stackoverflow.com/q/50044926
tagged with: automation
type: UnansweredQuestion
has title: Send message from python to Google Chrome on Windows and tell it to export or import bookmarks
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/87661049
answer count: 0
upvote count: 1
score: 1
downvote count: 0
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/87106106
favorite count: 0
type: Question
has body: I am running on Windows. I want to have a Python program send a message to Google Chrome and tell it to import or export bookmarks. This can be done through the Chrome user interface, but I don't know how to do it programmatically.

http://stackoverflow.com/q/50007054
has title: Using an image in django/python
possible better answer: http://stackoverflow.com/a/50007245
has answer: http://stackoverflow.com/a/50007245
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: image
has body: I want to add an image for every post and I already tried setting the static link: &lt;img src="{% static {{ post.img }}"&gt; I also tried uploading the img by writing in the models.py: image = models.ImageField(upload_to=.....) But it still does not work. models.py from django.db import models from django.urls import reverse from PIL import Image # Create your models here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) content = models.TextField(default="---") img = models.CharField(max_length=125, default='--') class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.title def get_absolute_url(self): return reverse('Products.views.post', args=[self.slug]) Views.py from django.shortcuts import render, render_to_response , get_object_or_404 from .models import Post # Create your views here. def index(request): posts=Post.objects.all() return render(request, 'Index.html', {"posts": posts}) def post(request, slug): return render(request, 'post.html', {'post': get_object_or_404(Post, slug=slug)})
answer count: 2
has comment: http://stackoverflow.com/comment/87030654
tagged with: django
accepted answer: http://stackoverflow.com/a/51364328
has answer: http://stackoverflow.com/a/51364328
type: Question
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50067974
has body: There is no "quality" setting in JPEG. Some encoders use quality as a simplified interface method for selecting quantization tables. You mentioned PNG. You can control the compression settings. The difference is that in JPEG compression setting trade off variations from the original against the output stream size. In PNG the compression settings trade off the time to do the compression against the output stream size. You are unlikely to find compression values analogous to encoder-specific quality settings among various compression formats.
score: 0
answers question: http://stackoverflow.com/q/50062696
type: Answer

http://stackoverflow.com/comment/86926172
type: AnswerComment
has text: So this is the 1st method which I have written.
comment on: http://stackoverflow.com/a/49948351
type: Comment
score: 0

http://stackoverflow.com/comment/86932643
score: 0
comment on: http://stackoverflow.com/q/49957984
type: Comment
has text: I have updated the question with an example. I hope it is more understandable now.
type: QuestionComment

http://stackoverflow.com/q/49998860
has body: A certain error message in a script is currently being caught in a try except block. For the intended use, this is going to let an error happen too often and I am wondering if there is a neat and tidy way to create a subclass from an error which counts how many times it happens before triggering. The following illustrates the desired behaviour. Without any handling: from random import randint for i in range(100): print(1 / randint(0, 10)) outputs: 0.1111111111111111 0.1 0.25 0.3333333333333333 0.1 0.2 0.16666666666666666 1.0 0.1 0.5 1.0 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) &lt;ipython-input-11-bfba3ff98af3&gt; in &lt;module&gt;() 1 from random import randint 2 for i in range(100): ----&gt; 3 print(1 / randint(0, 10)) ZeroDivisionError: division by zero Can you do this somehow: class MoreThanFiveZeroDiv(ZeroDivisionError): pass such that when you run this: from random import randint for i in range(100): try: print(1 / randint(0, 10)) except MoreThanFiveZeroDiv it only triggers when it happens for the fifth time?
downvote count: 0
tagged with: error-handling
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50005766
answer count: 2
accepted answer: http://stackoverflow.com/a/49999557
upvote count: 2
has answer: http://stackoverflow.com/a/49999557
tagged with: python
possible better answer: http://stackoverflow.com/a/50005766
linked to: http://stackoverflow.com/q/34566806
has title: subclass of error which counts how many times it gets raised
score: 2
type: AnsweredQuestion

c++
tags question: http://stackoverflow.com/q/50012909
tags question: http://stackoverflow.com/q/49995905
tags question: http://stackoverflow.com/q/49984220
tags question: http://stackoverflow.com/q/50009202
tags question: http://stackoverflow.com/q/49988922
tags question: http://stackoverflow.com/q/49928983
tags question: http://stackoverflow.com/q/49981835
tags question: http://stackoverflow.com/q/49976741
tags question: http://stackoverflow.com/q/50011561
tags question: http://stackoverflow.com/q/50020112
tags question: http://stackoverflow.com/q/49921185
tags question: http://stackoverflow.com/q/50032746
tags question: http://stackoverflow.com/q/49925945
tags question: http://stackoverflow.com/q/50050961
tags question: http://stackoverflow.com/q/49978208
tags question: http://stackoverflow.com/q/50054334
tags question: http://stackoverflow.com/q/49973982
tags question: http://stackoverflow.com/q/49941327
tags question: http://stackoverflow.com/q/49958256
type: Tag
tags question: http://stackoverflow.com/q/50034149
tags question: http://stackoverflow.com/q/50052192
tags question: http://stackoverflow.com/q/49972909
tags question: http://stackoverflow.com/q/49996416
tag name: c++
tags question: http://stackoverflow.com/q/50056859
tags question: http://stackoverflow.com/q/49937031
tags question: http://stackoverflow.com/q/50033276
tags question: http://stackoverflow.com/q/49919951

http://stackoverflow.com/comment/87012612
type: AnswerComment
has text: I cant add transformations since column names can be anything and data can be of any type just that only string values will be enclosed within quotes.@ilim
type: Comment
comment on: http://stackoverflow.com/a/49995881
score: 0

http://stackoverflow.com/q/49990586
upvote count: 9
has body: I have couple of date columns, I want to convert them to month/day/year format. Let's say test is one of the date columns - below code works. dfq['test1'] = dfq['test1'].apply(lambda x: x.strftime('%m/%d/%Y')) But when there are missing value in the column as 'NaT' it shows error ValueError: NaTType does not support strftime . I have created a sample data set and intentionally kept one missing value as ' ' . In that case also it shows error. I want to keep the missing or NaT values, so can't remove them. Is there any other way around ? Another question, if I want to convert all my date columns (say test1, test, test3) at the same time, - is there a way to do it while using lambda/strftime ?
tagged with: missing-data
tagged with: python
accepted answer: http://stackoverflow.com/a/49990664
tagged with: date
possible better answer: http://stackoverflow.com/a/65020357
score: 9
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65020357
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49990664
type: Question
tagged with: python-3.x
has title: How to convert date format when there are missing/NaT values in the column

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/49944041
tags question: http://stackoverflow.com/q/49917663
tags question: http://stackoverflow.com/q/49996856
tags question: http://stackoverflow.com/q/49938071
tags question: http://stackoverflow.com/q/50016982
tags question: http://stackoverflow.com/q/50057820
tags question: http://stackoverflow.com/q/49932791
tags question: http://stackoverflow.com/q/50025099
tags question: http://stackoverflow.com/q/49949764
tags question: http://stackoverflow.com/q/50025441
tags question: http://stackoverflow.com/q/50038651
tags question: http://stackoverflow.com/q/50038514
tags question: http://stackoverflow.com/q/49974936
tags question: http://stackoverflow.com/q/50012062
type: Tag
tags question: http://stackoverflow.com/q/49971556
tags question: http://stackoverflow.com/q/50053955

http://stackoverflow.com/comment/87139485
has text: for that reason post the entire stack dump (so we see where the error is coming from). Good edit so far.
score: 0
comment on: http://stackoverflow.com/q/50060781
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50046647
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50046920
tagged with: regex
accepted answer: http://stackoverflow.com/a/50046852
has body: I'm trying to split a file that contains 'string = float' format repeatedly. Below is how the file looks like. +name1 = 32 name2= 4 +name3 = 2 name4 = 5 +name5 = 2e+23 ... And I want them to put it a dictionary. Like... a={name1:32, name2:4, name3:2, name4:5, name5:2e+23} I'm new to regular expression and having a hard time figuring out what to do. After some googling, I tried to do as below to remove "+" character and white space.. p=re.compile('[^+\s]+') splitted_list=p.findall(lineof_file) But this gave me two problems.. 1. when there is no space btw name and "=" sign, it doesn't spilit. 2. for numbers like 2e+23, it split the + sign in between. I managed to parse the file as I wanted after some modification of depperm's code. But I'm facing another problem. To better explain my problems. Below is how my file can look like. After + sign multiple parameter and value pair can appear with '=' sign. The parameter name can contain alphabet and number in any position. Also value can contain +- sign with scientific notification(E/e-+). And sometimes value can be a math expression if it is single quoted. + abc2dfg3 = -2.3534E-03 dfe4c3= 2.000 + abcdefg= '1.00232e-1*x' * bdfd=1e-3 I managed to parse the above using the below regex. re.findall("(\w+)\s*=\s*([+-]?[\d+.Ee+-]+|'[^']+')",eachline) But now my problem is sometimes like "* bdfd=1e-3", there could be some comment. Anything after *(asterisk) in my file should be treated as comment but not if * present inside single quoted string. With above regex, it parses "bdfd=1e-3" as well but I want it to be not parsed. I tried to find solution for hours but I couldn't find any solution so far.
has answer: http://stackoverflow.com/a/50046904
has answer: http://stackoverflow.com/a/50046852
type: AnsweredQuestion
tagged with: python-2.7
has title: Python regular expression to split parameterized text file
answer count: 3
score: 1
downvote count: 0
possible better answer: http://stackoverflow.com/a/50046904
upvote count: 1

opencv
tags question: http://stackoverflow.com/q/50060952
type: Tag
tags question: http://stackoverflow.com/q/49979931
tags question: http://stackoverflow.com/q/49924470
tags question: http://stackoverflow.com/q/49965000
tags question: http://stackoverflow.com/q/50029546
tags question: http://stackoverflow.com/q/50051916
tags question: http://stackoverflow.com/q/50071326
tags question: http://stackoverflow.com/q/49999564
tags question: http://stackoverflow.com/q/49929581
tags question: http://stackoverflow.com/q/49949639
tags question: http://stackoverflow.com/q/49986150
tags question: http://stackoverflow.com/q/49936444
tags question: http://stackoverflow.com/q/49977034
tags question: http://stackoverflow.com/q/50043573
tags question: http://stackoverflow.com/q/49979680
tags question: http://stackoverflow.com/q/50039172
tags question: http://stackoverflow.com/q/49972165
tags question: http://stackoverflow.com/q/49921185
tags question: http://stackoverflow.com/q/50035895
tags question: http://stackoverflow.com/q/50029906
tags question: http://stackoverflow.com/q/50064045
tags question: http://stackoverflow.com/q/50032600
tags question: http://stackoverflow.com/q/49917778
tags question: http://stackoverflow.com/q/50049219
tags question: http://stackoverflow.com/q/49946918
tags question: http://stackoverflow.com/q/49993864
tags question: http://stackoverflow.com/q/49983013
tags question: http://stackoverflow.com/q/49931964
tags question: http://stackoverflow.com/q/49973982
tags question: http://stackoverflow.com/q/49971980
tags question: http://stackoverflow.com/q/50004208
tags question: http://stackoverflow.com/q/49969550
tags question: http://stackoverflow.com/q/49989032
tags question: http://stackoverflow.com/q/49932344
tags question: http://stackoverflow.com/q/49946528
tags question: http://stackoverflow.com/q/50027490
tags question: http://stackoverflow.com/q/49957788
tags question: http://stackoverflow.com/q/50050744
tags question: http://stackoverflow.com/q/49918828
tags question: http://stackoverflow.com/q/49979804
tags question: http://stackoverflow.com/q/49998281
tags question: http://stackoverflow.com/q/49940099
tags question: http://stackoverflow.com/q/49943665
tags question: http://stackoverflow.com/q/49994760
tags question: http://stackoverflow.com/q/49978705
tags question: http://stackoverflow.com/q/49989714
tags question: http://stackoverflow.com/q/49939859
tags question: http://stackoverflow.com/q/50061579
tags question: http://stackoverflow.com/q/49971484
tags question: http://stackoverflow.com/q/49992372
tags question: http://stackoverflow.com/q/49981538
tags question: http://stackoverflow.com/q/49958640
tags question: http://stackoverflow.com/q/49929482
tags question: http://stackoverflow.com/q/49966522
tags question: http://stackoverflow.com/q/50009037
tags question: http://stackoverflow.com/q/50008022
tags question: http://stackoverflow.com/q/50013794
tags question: http://stackoverflow.com/q/49970147
tags question: http://stackoverflow.com/q/50063506
tags question: http://stackoverflow.com/q/49957431
tags question: http://stackoverflow.com/q/50025280
tags question: http://stackoverflow.com/q/49969044
tags question: http://stackoverflow.com/q/49983339
tags question: http://stackoverflow.com/q/50029986
tags question: http://stackoverflow.com/q/50061634
tags question: http://stackoverflow.com/q/50020130
tags question: http://stackoverflow.com/q/49941299
tags question: http://stackoverflow.com/q/50038263
tags question: http://stackoverflow.com/q/50037063
tags question: http://stackoverflow.com/q/49938739
tag name: opencv
tags question: http://stackoverflow.com/q/50058811
tags question: http://stackoverflow.com/q/49963494
tags question: http://stackoverflow.com/q/50003297
tags question: http://stackoverflow.com/q/50003036
tags question: http://stackoverflow.com/q/50012528
tags question: http://stackoverflow.com/q/49991998
tags question: http://stackoverflow.com/q/50014697
tags question: http://stackoverflow.com/q/50056645

http://stackoverflow.com/q/49942090
tagged with: ldap
score: 3
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/86907157
has title: How to call a management.call_command in remote serve with Django?
has comment: http://stackoverflow.com/comment/86900191
has comment: http://stackoverflow.com/comment/86902508
has comment: http://stackoverflow.com/comment/86903366
has body: I have a job script in Python that call a command to update AD users. When I run this command in my local machine, it works fine. But in our Remote Server, with Linux and Apache, the same script doesn't work and give me a error: "Unknown command: 'ldap_sync_users'... I tried to use other common commands like migrate (just to test) and it gives the same problem... This is the command that I'm trying to run and works fine in my local: # https://github.com/etianen/django-python3-ldap management.call_command('ldap_sync_users') I'm using Python 3.6, Django 2.0.4. In localserver I'm using virtualenv and in remote server Apache 2. What I'm doing wrong? Someone can help me? view.py ... from apps.iumob.utilities import sync_hr_with_ldap def cron_job_to_sync(request): print(request.GET.get('token')) if request.GET.get('token') == "mytoken": if sync_hr_with_ldap() is True: return HttpResponse("Records synchronization finished.") else: return HttpResponse("Records synchronization finished with errors.") else: return HttpResponse("Access forbidden.") utilities.py: from django.core import management def sync_hr_with_ldap(): """ This method will be called to synchronize AD users and workers. If some worker that have a user and he was fired, it will check all users and, if it is still active, it will save in database this record. Every time that the user is deactivate from AD, this record will also be updated. """ # This method call a library that call LDAP and check all users, inactivating if necessary # https://github.com/etianen/django-python3-ldap management.call_command('ldap_sync_users')` Traceback Environment: Request Method: GET Request URL: myurl.../pt-br/iumob/cron-job-sync?token=sometoken Django Version: 2.0.3 Python Version: 3.5.2 Installed Applications: ['apps.iumob.apps.IumobConfig', 'apps.hrmob.apps.HrmobConfig', 'apps.cimob.apps.CimobConfig', 'apps.users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.…
has comment: http://stackoverflow.com/comment/86903949
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86900243
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86901942

http://stackoverflow.com/a/50019034
accepted answer of: http://stackoverflow.com/q/50018955
downvote count: 0
type: Answer
score: 6
has body: Python dictionnaries have keys and values accessed using those keys. You can access the keys as follows, your dict key will be stored in the key variable: my_dict = {"a" : 1, "b" : 2} for key in my_dict: print(key) This will print: a b You can then do any comparisons you want: my_dict = {"a" : 1, "b" : 2} for key in my_dict: if key == "a": return True else: return False which can be improved to: my_dict = {"a" : 1, "b" : 2} print("a" in my_dict.keys()) You can then access the values for each key in your dict as follows: my_dict = {"a" : 1, "b" : 2} for key in my_dict: print(my_dict[key]) This will print: 1 2 I suggest you read more about dictionaries from the official Python documentation: https://docs.python.org/3.6/tutorial/datastructures.html#dictionaries
upvote count: 6
has comment: http://stackoverflow.com/comment/87054329
has comment: http://stackoverflow.com/comment/87054221
has comment: http://stackoverflow.com/comment/87054694
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50018955

http://stackoverflow.com/comment/87162498
score: 0
type: Comment
has text: `itertools.combinations` looks like the correct function.
comment on: http://stackoverflow.com/a/50071615
type: AnswerComment

http://stackoverflow.com/q/49943691
has body: I am trying to load a csv file as a dataframe import pandas as pd import numpy as np # loading csv files map1 = pd.read_csv('data001.csv') print(map1) However, the dataframe's column names are provided from the first's row *.csv file values. Any ideas how can I obtain a dataframe with column names that are sequentially numbered instead? Thanks!
answer count: 1
has answer: http://stackoverflow.com/a/49943774
has title: how to load *.csv file as dataframe with columns with sequential numbering?
has comment: http://stackoverflow.com/comment/86904076
duplicate of: http://stackoverflow.com/q/29287224
has comment: http://stackoverflow.com/comment/86903535
linked to: http://stackoverflow.com/q/29287224
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86903543
type: Question
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52567664
type: Answer
has body: I met exactly the same error. It's fixed after the extension "VS Code Jupyter Notebook Previewer" is installed and reloaded.
answers question: http://stackoverflow.com/q/50045733
score: 1
downvote count: 0
upvote count: 1

aes
tag name: aes
tags question: http://stackoverflow.com/q/49945709
type: Tag

http://stackoverflow.com/q/49950041
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49950314
accepted answer: http://stackoverflow.com/a/49950314
tagged with: meta
favorite count: 0
type: Question
tagged with: beautifulsoup
type: AnsweredQuestion
has title: BeautifulSoup not picking up meta tag
score: 3
has answer: http://stackoverflow.com/a/49950146
linked to: http://stackoverflow.com/q/18134318
tagged with: python
upvote count: 3
has body: I have a simple script that gets an html page and tries to output the contents of the meta tag for keywords. Somehow, it is not picking up the content of the keywords meta tag even through the html contains the tag. Any help is appreciated. url = “https://www.mediapost.com/publications/article/316086/google-facebook-others-pitch-in-app-ads-brand-s.html” req = urllib2.Request(url=url) f = urllib2.urlopen(req) mycontent = f.read() soup = BeautifulSoup(mycontent, 'html.parser') keywords = soup.find("meta", property="keywords") print keywords
has answer: http://stackoverflow.com/a/49950485
possible better answer: http://stackoverflow.com/a/49950485

http://stackoverflow.com/a/49980108
has comment: http://stackoverflow.com/comment/86976284
score: 4
has comment: http://stackoverflow.com/comment/86978438
has body: Try the explicit flag: conda list --explicit
has comment: http://stackoverflow.com/comment/86978209
type: Answer
answers question: http://stackoverflow.com/q/49979904
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50036712
has answer: http://stackoverflow.com/a/50200956
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87094004
has comment: http://stackoverflow.com/comment/87276280
tagged with: airflow
has comment: http://stackoverflow.com/comment/87092398
has body: I have this code for airflow to execute python script inside docker : a02_retrieve_2 = SSHExecuteOperator( task_id='a02_retrieve_2', ssh_hook=sshHook, dag=dag, bash_command= 'docker exec myDocker -i bash -c " /opt/conda/bin/python aretrieve_2.py --myarg 45 --myarg 35 " ' ) Unfortunately, it does not work. But, the version with no argument works. a02_retrieve_2 = SSHExecuteOperator( task_id='a02_retrieve_2', ssh_hook=sshHook, dag=dag, bash_command= 'docker exec myDocker -i bash -c " /opt/conda/bin/python aretrieve_2.py " ' ) Error is : Python script starts to run but Airflow is unable to catch up the python script parameters... How to make the version with python script arguments works ? Is this related to jinja template ? BashOperator doen&#39;t run bash file apache airflow
tagged with: python
has comment: http://stackoverflow.com/comment/87290998
tagged with: docker
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87107849
answer count: 1
favorite count: 0
type: Question
upvote count: 2
has title: Run python script inside docker inside Airflow
linked to: http://stackoverflow.com/q/42259298

http://stackoverflow.com/q/50065432
tagged with: anaconda
has title: Python 2.7.6: "No module named etree.ElementTree" when using pip install
tagged with: python
accepted answer: http://stackoverflow.com/a/50065676
tagged with: elementtree
has answer: http://stackoverflow.com/a/50065676
tagged with: http://stackoverflow.com/tag/xml
score: 2
has comment: http://stackoverflow.com/comment/87148971
upvote count: 2
answer count: 1
downvote count: 0
tagged with: pip
favorite count: 0
type: Question
has body: I somehow messed up my python and am running out of ideas how to fix it. I am using Python 2.7.6. on a Windows computer. Basically anything connected to xml stopped working. Meaning: it worked fine before, then the console crashed, and now I get the error described. When I write pip install numpy in the console I get the following error: Traceback (most recent call last): File "C:\Python27\Scripts\pip-script.py", line 9, in &lt;module&gt; load_entry_point('pip==1.5.2', 'console_scripts', 'pip')() File "C:\Python27\lib\site-packages\pkg_resources.py", line 351, in load_entry _point return get_distribution(dist).load_entry_point(group, name) File "C:\Python27\lib\site-packages\pkg_resources.py", line 2363, in load_entr y_point return ep.load() File "C:\Python27\lib\site-packages\pkg_resources.py", line 2088, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "C:\Python27\lib\site-packages\pip\__init__.py", line 11, in &lt;module&gt; from pip.vcs import git, mercurial, subversion, bazaar # noqa File "C:\Python27\lib\site-packages\pip\vcs\subversion.py", line 4, in &lt;module &gt; from pip.index import Link File "C:\Python27\lib\site-packages\pip\index.py", line 18, in &lt;module&gt; import html5lib File "C:\Python27\lib\site-packages\html5lib\__init__.py", line 16, in &lt;module &gt; from .html5parser import HTMLParser, parse, parseFragment File "C:\Python27\lib\site-packages\html5lib\html5parser.py", line 6, in &lt;modu le&gt; from . import inputstream File "C:\Python27\lib\site-packages\html5lib\inputstream.py", line 10, in &lt;mod ule&gt; from . import utils File "C:\Python27\lib\site-packages\html5lib\utils.py", line 8, in &lt;module&gt; import xml.etree.ElementTree as default_etree ImportError: No module named etree.ElementTree What I did so far: I tried to reinstall the xml package (which was suggested in the forum). I also installed Anaconda with various environments. There, the problem is visible when I want to use packages lik…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87149499

http://stackoverflow.com/a/49993376
upvote count: 0
type: Answer
downvote count: 1
has body: Definitely Many-to-One relationship as Many Animal to One Species. You can use relationship to achieve this: http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html
score: -1
answers question: http://stackoverflow.com/q/49992768

http://stackoverflow.com/comment/87228845
has text: ah i see. glad you got it working!
score: 0
comment on: http://stackoverflow.com/a/50049515
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49989861
favorite count: 0
type: Question
has body: In python 3.3 I can do the following def _gen(): for i in range(3): yield i def gen(): yield from _gen() for i in gen(): print(i) &gt;&gt;&gt; 0 &gt;&gt;&gt; 1 &gt;&gt;&gt; 2 Can I do the same within a python 3.6 asyncio coroutine? (Warning, contrived example) async def _gen(): for i in range(3): yield await get_num(i) # get_num is a coroutine async def gen(): yield from _gen() # Syntax error! for i in gen(): print(i) I need to define gen as async def gen(): async for i in _gen(): yield i But it seems there should be a way to delegate to the other coroutine as we could with yield from
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/86997084
tagged with: python
tagged with: python-3.6
has title: Delegate to a generator in python 3.6+ asyncio coroutine
score: 2
upvote count: 3
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49990310
has comment: http://stackoverflow.com/comment/87026175
downvote count: 1
has comment: http://stackoverflow.com/comment/87025762

pyspark
tags question: http://stackoverflow.com/q/50043101
tags question: http://stackoverflow.com/q/49946283
tags question: http://stackoverflow.com/q/49981833
tags question: http://stackoverflow.com/q/50063668
tags question: http://stackoverflow.com/q/50037057
tags question: http://stackoverflow.com/q/49957950
tags question: http://stackoverflow.com/q/50070775
tags question: http://stackoverflow.com/q/50063685
tags question: http://stackoverflow.com/q/49981649
tags question: http://stackoverflow.com/q/49973200
tags question: http://stackoverflow.com/q/50004017
tags question: http://stackoverflow.com/q/49930657
tags question: http://stackoverflow.com/q/49980242
tags question: http://stackoverflow.com/q/49947159
tags question: http://stackoverflow.com/q/50047493
tags question: http://stackoverflow.com/q/50054693
tags question: http://stackoverflow.com/q/50054427
tags question: http://stackoverflow.com/q/49962987
tags question: http://stackoverflow.com/q/49933172
tags question: http://stackoverflow.com/q/50061577
tags question: http://stackoverflow.com/q/49971903
tags question: http://stackoverflow.com/q/50068131
tags question: http://stackoverflow.com/q/50055916
type: Tag
tags question: http://stackoverflow.com/q/49940084
tags question: http://stackoverflow.com/q/49967984
tags question: http://stackoverflow.com/q/49934648
tags question: http://stackoverflow.com/q/49983555
tags question: http://stackoverflow.com/q/50019417
tags question: http://stackoverflow.com/q/50038842
tags question: http://stackoverflow.com/q/49936190
tag name: pyspark
tags question: http://stackoverflow.com/q/49917974
tags question: http://stackoverflow.com/q/50009413
tags question: http://stackoverflow.com/q/49917936
tags question: http://stackoverflow.com/q/49923921
tags question: http://stackoverflow.com/q/49917008
tags question: http://stackoverflow.com/q/49926504
tags question: http://stackoverflow.com/q/50034351
tags question: http://stackoverflow.com/q/50028730

http://stackoverflow.com/q/49953627
type: Question
tagged with: numpy
tagged with: dbscan
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49959803
has body: Could someone guide me how could i cluster twitter data using DBSCAN in python? I am totally new to DBSCAN. Also, how to determine the eps value and the iloc or loc value. import numpy as np import pandas as pd from sklearn.cluster import DBSCAN from sklearn.preprocessing import StandardScaler def clusterEvaluate(cluster): count_cluster = np.bincount(cluster) count_cluster = np.argmax(count_cluster) same_clusters = np.count_nonzero(cluster == count_cluster)/np.size(cluster) return same_clusters dataset = np.loadtxt('tweetdata.csv') # not sure if this works X = StandardScaler().fit_transform(dataset) y_valid = dataset.iloc[:6].values() dbscan = DBSCAN(eps= 0.5,min_samples=5,metric='euclidean') y = dbscan.fit_predict(X) cluster_labels = np.unique(y) same_clusters = [] i = 0 for index in cluster_labels: cluster = y_valid[y == index] same_clusters.insert((i, clusterEvaluate(cluster)))
has title: How to input twitter data (csv/txt) into DBSCAN python?
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/50049560
answer count: 3
has comment: http://stackoverflow.com/comment/87136855
score: 1
has title: Choose every nth subset of a list/ columns/ array
upvote count: 1
has answer: http://stackoverflow.com/a/50049932
accepted answer: http://stackoverflow.com/a/50049932
has comment: http://stackoverflow.com/comment/87115420
possible better answer: http://stackoverflow.com/a/50049637
favorite count: 0
linked to: http://stackoverflow.com/q/18665873
type: Question
has body: From a list of following elements how to choose by index, so index 1,2, then 5,6 then 9,10? Numbers and text are not relevant, the order is relevant. The basic idea behind is as follows: Suppose you have feature a,b,c,d and for all of them you have mean, standard deviation, min and max. If you only interested in showing feature b and c, how to show them? column=[] for i in range(1,4): for j in list('abcd'): column.append(str(j)+str(i)) column ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2', 'a3', 'b3', 'c3', 'd3'] How can I extract the values at the indices 1, 2, 5, 6, 9, 10 so the result is ['b1', 'c1', 'b2', 'c2', 'b3', 'c3']
downvote count: 0
has comment: http://stackoverflow.com/comment/87115407
has comment: http://stackoverflow.com/comment/87115386
has comment: http://stackoverflow.com/comment/87115238
has comment: http://stackoverflow.com/comment/87115595
tagged with: python
has comment: http://stackoverflow.com/comment/87115355
has answer: http://stackoverflow.com/a/50049828
has comment: http://stackoverflow.com/comment/87134640
linked to: http://stackoverflow.com/q/2621674
has comment: http://stackoverflow.com/comment/87115254
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50049637

http://stackoverflow.com/a/50069494
answers question: http://stackoverflow.com/q/50052999
has comment: http://stackoverflow.com/comment/87694511
has comment: http://stackoverflow.com/comment/87710033
score: 0
has comment: http://stackoverflow.com/comment/87192242
has comment: http://stackoverflow.com/comment/87191037
has comment: http://stackoverflow.com/comment/87709644
has comment: http://stackoverflow.com/comment/87194323
has body: The error says that the first argument of final_output = tf.matmul(first_output, A2) is not a matrix. So first_output is not okay. It comes from the previous line: first_output = tf_gaussian_function(euclid_dist) So we'd need to review that function tf_gaussian_function() but that's not in the posted code. I've checked if it's a typo and it should be tf.gaussian_function() but there is no such a thing. So please post the definition of the function tf_gaussian_function(). So now that we have that, it turns out that you're trying to map the function math.exp( -SC * math.pow( input_layer, 2 ) ) (generally called rho or &rho;) onto euclid_dist; I take that would be your radial basis function. Side note: looks like you're trying to do some serious heavy lifting by implementing your own gradient, and everything, going through np.vectorize() and all that. I'd suggest you implement something much simpler, like this code (untested): first_output = tf.exp( -SC * euclid_dist * euclid_dist ) (I use x * x instead of the equivalent tf.pow( x, 2 ) because the first is more efficient.) This should create its own gradient and take care of all you're trying to achieve. But anyway, you sound confident that your implementation works, which might very well be the case as I found here; you can also double check if it yields the same results as this one-liner. In terms of what euclid_dist is, tf.norm( x, ord = "euclidean", axis = None ) is returning the 2nd norm (or Euclidean norm, otherwise also known as the square root of the sum of squares), so that is definitely a scalar. (It does exactly what the commented out line above says: euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.subtract(inputs_with_weights, c), 2))).) Not sure what you're trying to achieve there? If you just want the squares of distances, then you should do it like this: euclid_dist = ( inputs_with_weights - c ) * ( inputs_with_weights - c ) But as far as I understand, in a radial basis function network first you apply the…
has comment: http://stackoverflow.com/comment/87709162
has comment: http://stackoverflow.com/comment/87727664
has comment: http://stackoverflow.com/comment/87697813
has comment: http://stackoverflow.com/comment/87714382
has comment: http://stackoverflow.com/comment/87178993
has comment: http://stackoverflow.com/comment/87692581
has comment: http://stackoverflow.com/comment/87708371
type: Answer
has comment: http://stackoverflow.com/comment/87708974

http://stackoverflow.com/q/50064333
tagged with: python
has body: I'm trying to classify MRI images of brain tumor as normal,malignant or benign.For this ,I want to run two neural networks in a single program. first network classifies whether the brain MRI i mage is tumorous or non tumorous. If tumorous ,The second network classifies whether the brain MRI image is malignant or benign.The code is as follows: # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense import sys from PIL import Image sys.modules['Image'] = Image #import PIL as pillow #from PIL import Image # Initialising the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Conv2D(32, (3, 3), input_shape = (100, 100, 3), activation = 'relu')) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) # Compiling the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Part 2 - Fitting the CNN to the images from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('C:\\Users\\Admin\\Desktop\\tumor_non_tumour\\training', target_size = (100, 100), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('C:\\Users\\Admin\\Desktop\\tumor_non_tumour\\testing', target_size = (100, 100), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, steps_per_epoch = 10, e…
tagged with: conv-neural-network
answer count: 0
has comment: http://stackoverflow.com/comment/87145497
type: UnansweredQuestion
downvote count: 0
tagged with: neural-network
upvote count: 1
favorite count: 0
type: Question
has title: raise ImportError('Could not import PIL.Image. ' 'The use of `array_to_img` requires PIL.')
score: 1

http://stackoverflow.com/comment/94988582
comment on: http://stackoverflow.com/a/50202280
type: Comment
has text: Thank a lot for your answer! I went a bit through the docs and tried your examples. Seems like a lot of fun. Do I understand correctly, that Hy is meant to be used with it's own lisp-based syntax? Either way it seems to me, that generating code with Hy is in itself not very readable (in the Python sense). Is that observation correct? If yes, it would make it more difficult to maintain the resulting library. Since I am working in a scientific context, simplicity/readability of syntax is a rather important feat.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49952520
answers question: http://stackoverflow.com/q/49952409
type: Answer
has body: If I understand correctly: pd.merge_asof(df, \ df.assign(floored_price=df.price.apply(np.floor)). \ groupby('floored_price')'sales', 'visits'.sum(). \ rename(columns={'sales':'total_sales', 'visits':'total_visits'}). \ reset_index(), \ left_on='price', right_on='floored_price') # product price visits sales conversion floored_price total_sales total_visits # 0 12345678 74.98 225 14 0.0622 74.0 14 225 # 1 12345678 79.98 302 12 0.0397 79.0 31 748 # 2 12345678 79.99 446 19 0.0426 79.0 31 748 # 3 12345678 81.98 17 1 0.0588 81.0 1 17 # 4 12345678 84.98 11 0 0.0000 84.0 52 856
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49952409
upvote count: 1

http://stackoverflow.com/comment/86894332
type: AnswerComment
comment on: http://stackoverflow.com/a/49939169
score: 0
type: Comment
has text: @TalhaIrfan - I add solution for it, but `map` here is better.

http://stackoverflow.com/q/49942050
answer count: 3
has body: In python3, following works: print(3); print(5) However following gives a syntax error due to semicolon: (lambda key: (print(3); print(5))) Why is that, and is there a way to write a lambda function in single line (I intend to pass it as a short argument, without defining the function elsewhere)
has answer: http://stackoverflow.com/a/53996463
accepted answer: http://stackoverflow.com/a/49942602
has answer: http://stackoverflow.com/a/49942602
has title: define a lambda function in single line using semicolons in python 3
has comment: http://stackoverflow.com/comment/86900282
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86900114
has comment: http://stackoverflow.com/comment/86900336
has comment: http://stackoverflow.com/comment/86900533
upvote count: 5
has comment: http://stackoverflow.com/comment/86900405
has answer: http://stackoverflow.com/a/49942209
tagged with: python
score: 4
tagged with: lambda
has comment: http://stackoverflow.com/comment/86900488
has comment: http://stackoverflow.com/comment/86900694
has comment: http://stackoverflow.com/comment/86900429
possible better answer: http://stackoverflow.com/a/53996463
type: AnsweredQuestion
tagged with: syntax-error

http://stackoverflow.com/q/49992234
type: Question
has title: Table extraction: BeautifulSoup vs. Pandas.read_html
tagged with: python
possible better answer: http://stackoverflow.com/a/49992452
has answer: http://stackoverflow.com/a/49992452
accepted answer: http://stackoverflow.com/a/49994809
tagged with: html-table
has answer: http://stackoverflow.com/a/49994809
tagged with: pandas
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: web-scraping
tagged with: beautifulsoup
has body: I have an html file taken from this <a href="http://&#39;https://physics.nist.gov/cgi-bin/ASD/lines1.pl?spectra=C%20I%2C%20Ti%20I&amp;limits_type=0&amp;low_w=190&amp;upp_w=250&amp;unit=1&amp;de=0&amp;format=0&amp;line_out=0&amp;no_spaces=on&amp;remove_js=on&amp;en_unit=1&amp;output=0&amp;bibrefs=0&amp;page_size=15&amp;show_obs_wl=1&amp;unc_out=0&amp;order_out=0&amp;max_low_enrg=&amp;show_av=2&amp;max_upp_enrg=&amp;tsb_value=0&amp;min_str=&amp;A_out=1&amp;A8=1&amp;max_str=&amp;allowed_out=1&amp;forbid_out=1&amp;min_accur=&amp;min_intens=&amp;conf_out=on&amp;term_out=on&amp;enrg_out=on&amp;J_out=on&amp;g_out=on&amp;submit=Retrieve%20Data&#39;" rel="nofollow noreferrer">link, but I am not being able to extract any sort of table neither with bs4.BeautifulSoup() nor with pandas.read_html. I understand that each row of my desired table starts with &lt;tr class='odd'&gt;. Despite that, something is not working when I pass soup.find({'class': 'odd'}) or pd.read_html(url, attrs = {'class': 'odd'}). Where is the mistake or what should I do instead? The beginning of the table apparently starts in requests.get(url).content[8359:]. &lt;table style="background-color:#FFFEEE; border-width:thin; border-collapse:collapse; border-spacing:0; border-style:outset;" rules="groups" &gt; &lt;colgroup&gt; &lt;colgroup&gt; &lt;colgroup&gt; &lt;colgroup&gt; &lt;colgroup span="3"&gt; &lt;colgroup span="3"&gt; &lt;colgroup span="3"&gt; &lt;colgroup span="3"&gt; &lt;colgroup&gt; &lt;tbody&gt; &lt;tr style="vertical-align:middle; background-color:#177A9C"&gt; &lt;th scope="col" style="text-align:center"&gt;Ion&lt;/th&gt; &lt;th scope="col" style="text-align:center"&gt;&amp;nbsp;Observed&amp;nbsp;&lt;br /&gt;&amp;nbsp;Wavelength&amp;nbsp;&lt;br /&gt;&amp;nbsp;Vac (nm)&amp;nbsp;&lt;/th&gt; &lt;th scope="col" style="text-align:center; white-space:nowrap"&gt;&amp;nbsp;&lt;i&gt;g&lt;sub&gt;k&lt;/sub&gt;A&lt;sub&gt;ki&lt;/sub&gt;&lt;/i&gt;&lt;br /&gt;&amp;nbsp;(10&lt;sup&gt;8&lt;/sup&gt; s&lt;sup&gt;-1…

http://stackoverflow.com/q/49955905
tagged with: python
score: 8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86928930
has title: Django JSONField filtering Queryset
answer count: 1
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/86928565
has body: For project I'm using Python 3.6.3, Django 2.0 and Postgre 9.4. In my class Ticket, a have JSONField passenger passenger = JSONField(blank=True) and my passenger JSON looks like this: { "email": null, "mobile": "21312", "passport": "2141241", "sms_sent": false, "full_name": "something" }, { "email": null, "mobile": null, "passport": "1231231", "sms_sent": false, "full_name": "Irfan" }, { "email": null, "mobile": null, "passport": "1231231", "sms_sent": true, "full_name": "Irfan" } Now I have django command where I want to filter tickets that have mobile that is not null or None, and sms_sent is False. tickets = Ticket.objects.filter( date=tomorrow, trip__bus_company=bus_company, passenger__sms_sent=False ).not_cancelled() Now passenger__sms_sent=False filter is working, and is giving my only Tickets with sms_sent=False. But passenger__mobile filter is not working. I tried everyone of this: tickets = tickets.exclude(passenger__mobile=None) tickets = tickets.exclude(passenger__mobile=None).exclude(passenger__mobile='') tickets = tickets.exclude(passenger__mobile__isnull=True) tickets = tickets.exclude(passenger__exact={'mobile': None}) tickets = tickets.exclude(passenger__mobile__isnull=True).exclude(passenger__mobile='') tickets = tickets.exclude(passenger__mobile__isnull=False).exclude(passenger__mobile='') tickets = tickets.exclude(Q(passenger__mobile__isnull=True) | Q(passenger__mobile='')) and also puting passenger__mobile in first filter, but I can not filter out(exclude) tickets where passenger__mobile is null, I either get all tickets, or empty queryset. Now I can do this: for ticket in tickets: if ticket.passenger['mobile'] is not None: print(ticket.passenger['mobile']) but that is not what I'm looking for. I want to use filter or exclude to get those tickets. What I'm I doing wrong? P.S. not_cancelled() is my manager and it does not have anything to do with passenger field.
accepted answer: http://stackoverflow.com/a/49956053
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49956053
tagged with: postgresql
upvote count: 8

http://stackoverflow.com/q/50018264
upvote count: 1
has title: pyinstaller failed to process no matter how I try
downvote count: 1
favorite count: 0
type: Question
tagged with: pyinstaller
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50018487
tagged with: python
has body: c:\program files\python35\scripts> pyinstaller.exe --onefile "path\whatever\main.py" c:\program files\python35\scripts> pyinstaller --onefile "path\whatever\main.py" fails to process also tried running pyinstaller from the path where main.py is located and still nothing. working with python 3.5.2, 64bit Thank you
has comment: http://stackoverflow.com/comment/87053827
score: 0
answer count: 1

http://stackoverflow.com/a/50033491
type: AcceptedAnswer
has body: Start out with a list, and append or concat based on a condition. A temporary string is not needed: workingList = ... #assume its a list of strings. If its not just split it by newlines. result = [] for i in workingList: if '&lt;p&gt;' == i[:3]: result.append(i) #start new if &lt;p&gt; found as start else: result[-1] += ' ' + i #add it to the end of the last one for i in result: print(i) And you get these results when the code is run: &lt;p&gt;University Press, Inc.The Game of Hearts: Harriette Wilson &amp;amp; Her Memoirs edited by Lesley Blanch. Copyright © 1955 by&lt;p&gt; &lt;p&gt;7&lt;p&gt; &lt;p&gt;Acknowledgments&lt;p&gt; &lt;p&gt;First, I would like to thank Anna Biller for her countless contributions tothis book: the research, the many discussions, her invaluable help with thetext itself, and, last but not least, her knowledge of the art of seduction, ofwhich I have been the happy victim on numerous occasions.&lt;p&gt; &lt;p&gt;To the memory of my father&lt;p&gt; &lt;p&gt;8&lt;p&gt; &lt;p&gt;I must thank my mother, Laurette, for supporting me so steadfastlythroughout this project and for being my most devoted fan.`&lt;p&gt;` &lt;p&gt;I would like to thank Catherine Léouzon, who some years ago intro-duced me to Les Liaisons Dangereuses and the world of Valmont.&lt;p&gt;
accepted answer of: http://stackoverflow.com/q/50033353
type: Answer
answers question: http://stackoverflow.com/q/50033353
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/comment/87126343
has text: That's an specific case of your implementation, but most of the cases it's not like that, E.g.: Utils modules that are used from across the system then to have a lot of staticmethods because they are intended to be used a lot
comment on: http://stackoverflow.com/a/50054926
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/50062936
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50063200
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50063198
has answer: http://stackoverflow.com/a/50063198
tagged with: dataframe
tagged with: python
has body: I'm working on a Dataframe with 1116 columns, how could I select just the columns in a period of 17 ? More clearly select the 12th, 29th,46th,63rd... columns
type: AnsweredQuestion
has title: Select columns periodically on pandas DataFrame
answer count: 2
possible better answer: http://stackoverflow.com/a/50063200

http://stackoverflow.com/a/49936951
upvote count: 1
has body: You have to use the dumpdata command. The following command will dump the whole database to a db.json file. ./manage.py dumpdata &gt; db.json After that, you can restore the data into db with loaddata command. But, if you have made any critical change you might get the IntegrityError. To fix this issue you have to make sure to backup the database by excluding contenttypes and auth.permissions tables by running this command when dumping data: ./manage.py dumpdata --exclude auth.permission --exclude contenttypes &gt; db.json After that you can safely run loaddata command with a fresh database. ./manage.py loaddata db.json Here you can find Django documentation on dumpdata command.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49936742
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49936742
downvote count: 0

http://stackoverflow.com/q/50008759
tagged with: default-value
has comment: http://stackoverflow.com/comment/87034238
tagged with: parameters
tagged with: python-2.7
score: 0
has body: The following code def score_track(details, result_details, top_score=200): if top_score &lt; 120: # do smth return None works in Python 2 but throws exception in Python 3: Traceback (most recent call last): File "function.py", line 280, in &lt;module&gt; search_result.get('score')) File "ImportList.py", line 131, in score_track if top_score &lt; 120: TypeError: '&lt;' not supported between instances of 'NoneType' and 'int' If I initialize top_score explicitly it goes fine. score_track function is called like this: add_song(details,score_track(details,details)) search_result list is constructed like this: search_results = [] dlog('search details: '+str(details)) lib_album_match = False if details['artist'] and details['title'] and search_personal_library: lib_results = [item for item in library if s_in_s(details['artist'],item.get('artist')) and s_in_s(details['title'],item.get('title'))] dlog('lib search results: '+str(len(lib_results))) for result in lib_results: if s_in_s(result['album'],details['album']): lib_album_match = True item = {} item[u'track'] = result item[u'score'] = 200 search_results.append(item) What is wrong? I didn't find any information about different behavior of default parameter values in Python3 vs Python2.
has comment: http://stackoverflow.com/comment/87034209
tagged with: python
has comment: http://stackoverflow.com/comment/87035542
has title: Default function parameter is not initialized in Python 3
has comment: http://stackoverflow.com/comment/87035613
type: Question
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/87034070
type: UnansweredQuestion

http://stackoverflow.com/a/49954608
downvote count: 0
has body: It appears that the src attributes are added due to the JavaScript running in the browser. You can use Requests-HTML to achieve your goal: from requests_html import HTMLSession session = HTMLSession() url = 'https://www.google.pl/search?q=python&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=0ahUKEwif6Zq7i8vaAhVMLVAKHUDkDa4Q_AUICigB&amp;biw=1280&amp;bih=681' r = session.get(url) r.html.render() first_image = r.html.find('.rg_ic.rg_i', first=True) link = first_image.attrs['src']
answers question: http://stackoverflow.com/q/49952518
upvote count: 2
has comment: http://stackoverflow.com/comment/86936196
type: Answer
has comment: http://stackoverflow.com/comment/86947357
score: 2

http://stackoverflow.com/q/49958396
linked to: http://stackoverflow.com/q/11830980
has comment: http://stackoverflow.com/comment/86945172
has comment: http://stackoverflow.com/comment/86937159
tagged with: sql
linked to: http://stackoverflow.com/q/3750118
answer count: 1
downvote count: 0
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86937190
has title: SQLAlchemy get max value
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53196714
has comment: http://stackoverflow.com/comment/86945177
tagged with: python
score: 4
has body: Im trying to get the max value in a table for an attribute, the attribute is risk: I am running: func.max(HostsModel.risk) I get back: &lt;sqlalchemy.sql.functions.max at 0x10f0721d0; max&gt; How do I actually get the value from this? I see these as the available functions: dir(func.max(HostsModel.risk)) ['__add__', '__and__', '__bool__', '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__or__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__rshift__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__visit_name__', '__weakref__', '_allow_label_resolve', '_alt_names', '_annotate', '_annotations', '_bind', '_bind_param', '_clone', '_cloned_set', '_cols_populated', '_compare_name_for_result', '_compiler', '_compiler_dispatch', '_constructor', '_copy_internals', '_deannotate', '_execute_on_connection', '_execution_options', '_from_objects', '_generate', '_hide_froms', '_init_collections', '_is_clone_of', '_is_from_container', '_is_join', '_is_lexical_equivalent', '_is_select', '_key_label', '_label', '_make_proxy', '_memoized_property', '_negate', '_order_by_label_element', '_params', '_populate_column_collection', '_refresh_for_new_column', '_render_label_in_columns_clause', '_reset_exported', '_resolve_label', '_select_iterable', '_textual', '_translate_schema', '_with_annotations', 'alias', 'all_', 'anon_label', 'any_', 'asc', 'base_columns', 'between', 'bind', 'bool_op', 'c', 'cast', 'clause_expr', 'clauses', 'coerce_arguments', 'collate', 'columns', 'comparator', 'compare', 'compile', 'concat', 'contains', 'correspond_…
upvote count: 4

http://stackoverflow.com/comment/87054718
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50019006
has text: @Alechan Yes, that's what I pointed. If your intention is to test importing in concrete case, then place `import` inside *test case*. But in most cases you can place it at beginning of your *module* because if whole module will fail **doing import** then you probably have installed your code wrong and it shouldn't run at all. In most cases tests are intended to check if you wrote your code properly, not if you installed every dependency.
type: AnswerComment

http://stackoverflow.com/q/50005341
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50005804
tagged with: pandas
tagged with: python
has title: Display all columns after running df.columns
tagged with: python-3.6
score: 2
upvote count: 2
has body: I currently have 120 columns in my DataFrame. When I execute df.columns I get a truncated list, where I only see 20 instead of 120 columns: Index(['Reporting_FI', 'Reporting_FI_identification', 'Reporting_FI_identification_type', 'Reporting_FI_street_address_1', 'Reporting_FI_street_address_2', 'Reporting_FI_city', 'Reporting_FI_state', 'Reporting_FI_postal_code', 'Reporting_FI_country_code', 'Transaction_date', ... 'FI_country_code_3', 'FI_name_4', 'FI_branch_4', 'FI_identification_4', 'FI_identification_type_4', 'FI_account_number_4', 'FI_city_4', 'FI_state_4', 'FI_country_code_4', 'Additional_infomation_2'], dtype='object', length=120) How do I adjust this to display all 120? I am not looking for: pd.set_option('display.max_columns', 120) Thanks
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50005804
downvote count: 0
answer count: 1
tagged with: label

webdriver
tags question: http://stackoverflow.com/q/50031290
tags question: http://stackoverflow.com/q/49978486
tags question: http://stackoverflow.com/q/49955629
tags question: http://stackoverflow.com/q/49937997
tags question: http://stackoverflow.com/q/49999407
tags question: http://stackoverflow.com/q/50069625
type: Tag
tags question: http://stackoverflow.com/q/49985726
tags question: http://stackoverflow.com/q/49919214
tags question: http://stackoverflow.com/q/50047392
tags question: http://stackoverflow.com/q/49972306
tags question: http://stackoverflow.com/q/50060755
tag name: webdriver
tags question: http://stackoverflow.com/q/49974708
tags question: http://stackoverflow.com/q/49967652

http://stackoverflow.com/comment/87139792
type: QuestionComment
comment on: http://stackoverflow.com/q/50061599
score: 1
has text: So basically you want to convert `CNF` (Conjunctive Normal Form) into `DNF` (Disjunctive Normal Form)? Even just considering `and`, `or` and `not`, then you might want to read [this](http://www.daimi.au.dk/~bromille/Papers/cnfdnfmfcs.pdf) about its complexity. Having said this, there should be an extensive literature of algorithms for doing it, possibly even implementations in `python`. The duplicate link above proves what I just said, upvoted. :-)
type: Comment

http://stackoverflow.com/comment/87142792
score: 1
type: Comment
type: QuestionComment
has text: Okay, good, we're getting somewhere. Now, why are you trying to produce a specific encrypted value? That doesn't really make sense. As long as you can encrypt plain-text and then decrypted the encrypted text back to the original, why do you care what the encrypted value is?
comment on: http://stackoverflow.com/q/50062663

http://stackoverflow.com/comment/86851607
comment on: http://stackoverflow.com/q/49917796
has text: @DanielRoseman - With due respect, you're being too chatty. This is how I've designed it and I know what I'm doing. The question is not `why`, the question is `how`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49928787
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49928680
score: 7
type: Answer
answers question: http://stackoverflow.com/q/49928680
type: AcceptedAnswer
has body: Write the function to accept increments as parameters. def add_edges(aincr, bincr): for i in range(0,300): a += aincr; b += bincr if a!=0 and b!=0: edges.add((a, b)) Then pass in the appropriate increments when calling: add_edges(1, 1) add_edges(-1, -1) add_edges(1, -1) add_edges(-1, 1) There is no need to pass the concept of "add" or "subtract", since you can do that numerically. You could (as other answers show), but try not to overcomplicate things.
downvote count: 0

http://stackoverflow.com/comment/86883292
type: AnswerComment
comment on: http://stackoverflow.com/a/49933822
has text: As you have the days listed in function. The above code if you execute you will get console output as "Please enter the number: 5 Friday"
type: Comment
score: 0

http://stackoverflow.com/a/49928259
has body: You are getting this error because when you call results.items(), it returns a list which is not a hashable. A simple way to make your code work would be to iterate through each dict item and check for it's equality for i in results: if(results[i] != expectedResults[i]): print('different key : value pair') print('key : ' + i) print('Value in results : ' + str(results[i])) print('Value in expectedResults : ' + str(expectedResults[i])) Your can't get a solution as simple as this.
accepted answer of: http://stackoverflow.com/q/49927573
has comment: http://stackoverflow.com/comment/86873237
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49927573
score: 0
has comment: http://stackoverflow.com/comment/86874435

http://stackoverflow.com/q/49969735
score: 0
has comment: http://stackoverflow.com/comment/86955554
tagged with: sqlite
answer count: 1
has answer: http://stackoverflow.com/a/49982819
tagged with: web
type: Question
has comment: http://stackoverflow.com/comment/86994848
type: UnansweredQuestion
tagged with: django
has body: I am creating a simple result processing system using django. I made this class: class Course(models.Model): Course_Code = models.CharField(max_length=50,unique=True,primary_key = True) Course_Name = models.CharField(max_length=50) Dept = models.CharField(max_length=50) Credit_Lecture = models.IntegerField() Credit_Tutorial = models.IntegerField() Credit_Practical = models.IntegerField() Max_Marks_MidTerm = models.IntegerField() Max_Marks_Theory = models.IntegerField() Max_Marks_Pr = models.IntegerField() Now I want to make a new column that stores the total credit value of a course i.e. : Credit_Total = Credit_Lecture + Credit_Tutorial + Credit_Practical How should I do so? I found the following possibilities but failed: Total_Credit =Credit_Lec + Credit_Tut + Credit_Pr Total_credit = SELECT CAST(Credit_lec AS VARCHAR(255)) AS credit_lec FROM Course;
tagged with: python
has title: How to create new columns from existing columns in django sqlite models.py files?

sudo
tags question: http://stackoverflow.com/q/49986887
type: Tag
tags question: http://stackoverflow.com/q/49992390
tag name: sudo
tags question: http://stackoverflow.com/q/50057695

http://stackoverflow.com/q/50013150
has comment: http://stackoverflow.com/comment/87042790
answer count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87042734
type: UnansweredQuestion
tagged with: list
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87119337
tagged with: client
has title: Why does my output vary when sending lists over a TCP socket in Python 3.6?
tagged with: server
has body: Could someone please explain why my socket program outputs the message in a strange way everytime I run the code. I am supposed to receive the server results from a list sent from the client as follows: Sending request 'E1.0 -945 1689 -950 230 -25 1' Received response: Sending request 'S0 2 -945 1689 -950 230 -25 1 1e-15' Received response: ... Instead, I get this: Sending request 'E1.0 -945 1689 -950 230 -25 1' Received response: Sending request 'S0 2 -945 1689 -950 230 -25 1 1e-15' Received response: Sending request 'G4.1 0 0'Received response: XIncorrect command type Sending request '4 1 0' Received response: XIncorrect command type Sending request 'E1.0' Received response: Sending request 'S1.0'Received response: Sending request 'S0 2 -945 1689 -950 230 -25 1 -1e-15'Received response: Sending request 'Not a number'Received response: XIncorrect command type This happens all the time, sometimes it works as it should most time the received data is out of place. This is my code... server.py import socket port = 12345 mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mySocket.bind(('localhost', port)) mySocket.listen(0) clientsocket, addr = mySocket.accept() print("Connection from: {}\n".format(str(addr))) while True: encoded_message = clientsocket.recv(2048) data = encoded_message.decode() print(data) if not data: break else: acknowledge = "Sending request \'{}\'".format(data) clientsocket.sendall(acknowledge.encode()) request_code = data[0] if request_code == 'E': messageO = "Received response: \n\r" clientsocket.sendall(messageO.encode()) elif request_code == 'S': messageO = "Received response: \n\r" clientsocket.sendall(messageO.encode()) else: messageO = "Received response: XIncorrect command type\n\r" clientsocket.sendall(messageO.encode()) clientsocket.close() client.py import socket host = 'localhost' port = 12345 mySocket = socket.socket() mySocket.connect((host, port)) testing_strings = ["E1.0 -945 1689 -950 230 -25 1", "S0 2 -945 1689 -950 230 -…
tagged with: sockets

http://stackoverflow.com/q/50071563
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50359175
has body: I am using SQLAlchemy's declarative API to build my models and tables for my application. However, I'm unable to use Base.metadata.create_all(engine) command to build a new table in my database because of error NoReferencedTableError: Foreign key associated with column 'org_prediction.company_id' could not find table 'organization' with which to generate a foreign key to target column 'id' The reason this is happening is because the class Organization I am trying to reference for a ForeignKey does not exist in my models.py file. So, when I call Base.metadata.create_all(engine), SQLAlchemy chokes because class Organization is not present in Base... I have tried reflecting my database, which will return the table for Organization which exists, but has no corresponding Class written for it in my models.py file. But when I reflect the DB tables and try to create my new dependent class on top of Organization, I get an error like: InvalidRequestError: Table 'user' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object., which is caused because the reflected MetaData and my models.py class for User overlap, and SQLAlchemy isn't sure what to do. But where do I apply extend_existing=True? I have no Table objects to pass this parameter into. How can I create my FK dependent table when my FK dependent table doesn't exist in my models.py file? Or how can I reflect my existing tables, but append or update only the classes which do not exist yet in the database? models.py from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) username = Column(String(50)) class OrgPrediction(Base): __tablename__ = 'org_prediction' id = Column(Integer, primary_key=True) company_id = Column(String(255), ForeignKey('organization.id'), nullable=True) prediction = Column(String(255) Base.metadata.create_all(engine)…
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: How to Create New Tables without Defined Classes in SQLAlchemy 1.2.7
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/50359175
favorite count: 0

http://stackoverflow.com/comment/86935864
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49959546
has text: Thanks for the suggestion @unutbu - added those as edits.

http://stackoverflow.com/q/49993359
score: 0
has answer: http://stackoverflow.com/a/49998080
answer count: 1
has body: I have json data in format {"issue_number": 1, "created_at": "2016-03-13", "closed_at": "2016-04-13", "labels": ["Category: Bug", "Latitude:41.925573", "Longitude:-87.649249", "OriginationPhase:Requirements"], "State": "closed"} I need to write an elastic search query that retrieves all locations that got atleast 3 issues created for same location i.e latitude and longitude. To my understanding i need to retrieve the data where issues are more than 3 for same location. So i need to groupby latitude and longitude , and count should be greater than or equal to 3 I dont have much understanding on elastic search. i have referred couple of sites and tried the below code. q = { 'aggregations':{ 'labels':{ 'nested':{ 'path':'labels' }, 'aggs':{ 'latitude':{ 'terms':{ 'field':'labels.Latitude', 'min_doc_count':3 }, 'aggs':{ 'by_top_hits':{ 'top_hits':{ 'size':3 } } } } } } } } But i didn't get the expected result and query doc_count is 0.
has title: ElasticSearch query on json data
type: Question
type: UnansweredQuestion
tagged with: elasticsearch
tagged with: python
tagged with: jupyter-notebook
tagged with: elasticsearch-5

http://stackoverflow.com/a/50065469
upvote count: 1
score: 1
type: Answer
has body: You are correct that reticulate doesn't handle the automatic typecasting. There is no way to programmatically determine this unless knowing specifically whether a particular Python parameter needs to be an integer or a float and then intercede, which is impossible in Python since Python is a typeless language. You can get around it by explicitly casting your arguments as integers using as.integer(25) or you can use 25L instead of 25.
answers question: http://stackoverflow.com/q/50046643
downvote count: 0

http://stackoverflow.com/comment/87148952
has text: https://stackoverflow.com/questions/39936869/matplotlib-pick-event-not-working-in-embedded-graph-with-figurecanvastkagg
comment on: http://stackoverflow.com/q/50065911
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91121811
type: AnswerComment
comment on: http://stackoverflow.com/a/52084766
score: 1
type: Comment
has text: Hi, could you improve the code formatting to clarify your answer — see https://stackoverflow.com/help/formatting

http://stackoverflow.com/a/49974861
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49972507
has body: The Google Calendar API is a rest API. It returns data in Json format. It will be up to you as the developer to create a nice calendar to display to your users. You are not going to find any link to the web view in the API. Solution create the web view from the data returned by the api.
has comment: http://stackoverflow.com/comment/86980292
score: 0
has comment: http://stackoverflow.com/comment/86982505
type: Answer
accepted answer of: http://stackoverflow.com/q/49972507
has comment: http://stackoverflow.com/comment/86982813

http://stackoverflow.com/a/50026799
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49980380
downvote count: 0
has comment: http://stackoverflow.com/comment/87070429
has body: This is an answer stub as my simulations will be finished in a second and then I need to get back to work. ;-) According to Lemma 1 here The Gabriel graph on a vertex set V is a subgraph of the Delaunay triangulation for V. Furthermore, the edge AB of the Delaunay triangulation is an edge of the Gabriel graph iff the straight line joining A to B intersects the boundary line segment common to the Thiessen polygons for A and B at a point other than the endpoints of that boundary line segment. A Delaunay triangulation can be computed in O(n log n) time. There is a Delaunay triangulation in scipy.spatial. You can then filter the edges using the cited criterion by 1) computing the Voronoi diagram (also in scipy.spatial), and 2) asserting that edge end points are not in set of Voronoi points.
type: Answer

http://stackoverflow.com/q/49943938
tagged with: python
tagged with: boto3
has body: I am using unittest to test a function that makes a call to AWS using boto3. The function looks like this: import boto3 def my_function(): client = boto3.client('athena') res = client.start_query_exeuction( QueryString='SELECT * FROM logs', ResultConfiguration={'OutputLocation': 's3://mybucket'} ) return res['QueryExecutionId'] I am using botocore stubber to stub this request in my unit tests like this: from botocore.stub import Stubber import botocore.session def test_my_function(): client = botocore.session.get_session().create_client('athena') client_res = {'QueryExecutionId': 'testid'} exp_params = { 'QueryString': 'SELECT * FROM logs', 'ResultConfiguration': { 'OutputLocation': 's3://mybucket' } } with Stubber(client) as stubber: stubber.add_response('start_query_execution', client_res, exp_params) res = my_function() self.assertEqual(res, 'testid') This test is failing with botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the StartQueryExecution operation: The security token included in the request is invalid. Why would this be failing? Is it because I am creating a new client in my_function() which is different from the client used in the stubber? If so, how can I test this? Any help is much appreciated.
has answer: http://stackoverflow.com/a/58397551
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 3
has answer: http://stackoverflow.com/a/69833276
possible better answer: http://stackoverflow.com/a/69833276
downvote count: 0
has answer: http://stackoverflow.com/a/49944176
has title: UnrecognizedClientException when using botocore stubber
tagged with: python-unittest
tagged with: botocore
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49944176

http://stackoverflow.com/comment/87107643
has text: @D.Redmond Ah. That's because you have the `root.bind` call outside the class definition. So you need to reorganize your code a little. Either put that call inside your class, and change it to `self.root.bind`, or save a reference to the `Adder` instance eg, `adder = Adder(root); root.bind('<Return>', adder.calculate)`
comment on: http://stackoverflow.com/a/50045602
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87142964
type: Comment
type: QuestionComment
has text: can you show us the entire code rather than a portion of it?
comment on: http://stackoverflow.com/q/50063093
score: 1

http://stackoverflow.com/a/50063580
has comment: http://stackoverflow.com/comment/87146357
has comment: http://stackoverflow.com/comment/87144253
upvote count: 1
has body: There is no need to iterate over pairs of dictionaries, as set().union() operation can take multiple arguments: def merge_dictionaries(*args): result = {} for key in set().union(*args): # let's convert the value union to set before sorting to get rid of the duplicates result[key] = sorted(set.union(*[set(d.get(key, [])) for d in args]), key=int) return result
answers question: http://stackoverflow.com/q/50063292
type: Answer
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50063292
downvote count: 0

http://stackoverflow.com/q/50063668
tagged with: amazon-s3
upvote count: 3
has body: I want to run a pyspark session on my local machine and I want to use the data I've stored in an AWS s3 bucket. So far I'm trying to do import pyspark as ps fp = "s3n://my-bucket/some/data/file.csv" spark = ps.sql.SparkSession.builder.master("local[*]").getOrCreate() df = spark.read.csv(fp, schema=SCHEMA, sep="\t") df.show(10, False) where the schema is correctly defined elsewhere. However, I receive some weird warnings and a weird error: (Notice that the first part is just a warning and doesn't prevent the code from running, even if it explicitly says java/util.ServiceConfigurationError.) 2018-04-27 15:04:59 WARN NativeCodeLoader:62 - Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 2018-04-27 15:05:01 WARN FileSystem:2639 - Cannot load filesystem java.util.ServiceConfigurationError: org.apache.hadoop.fs.FileSystem: org.apache.hadoop.fs.s3a.S3AFileSystem Unable to get public no-arg constructor Caused by: java.lang.NoClassDefFoundError: com/amazonaws/AmazonServiceException Caused by: java.lang.ClassNotFoundException: com.amazonaws.AmazonServiceException 2018-04-27 15:05:02 WARN FileStreamSink:66 - Error while looking for metadata directory. py4j.protocol.Py4JJavaError: An error occurred while calling o32.csv. : org.apache.hadoop.fs.s3.S3Exception: org.jets3t.service.ServiceException: Request Error: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty Caused by: org.jets3t.service.ServiceException: Request Error: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterExcept…
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50080830
has title: Accessing s3 data locally with pyspark - trustAnchors parameter must be non-empty
has answer: http://stackoverflow.com/a/50080830
favorite count: 0
type: Question
tagged with: pyspark
tagged with: python
tagged with: amazon-web-services
type: AnsweredQuestion
score: 3
tagged with: apache-spark

http://stackoverflow.com/comment/86901419
comment on: http://stackoverflow.com/a/49942407
has text: @AstroBen I've edited. If you are not satisfied with this, then xs and loc are your only other options.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49947588
score: 0
has body: The first question to ask is why the tasks are actually failing. If you have certain tasks that can fail without any negative impact you can run them with "ignore_errors: yes" that way it Ansible will just continue to the next task as if the current module hadn't failed and the output won't indicate a failure. Another solution would be to use a callback plugin which is the part of Ansible which handles the actual output from a playbook. By default, the "default" callback plugin is used. There are however a lot of callback plugins included in Ansible. You can see a list of them in the source code: https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/callback You could either try different callback plugins which you can set in ansible.cfg using the "stdout_callback" parameter. Depending on what you want to do you could use the null callback which won't print out anything. If you need the number of tasks which were ok, changed and unreachable you might need to create your own callback. This could be done by creating a copy of the default callback and editing out the section which prints the number of failed tasks.
type: Answer
answers question: http://stackoverflow.com/q/49945127

http://stackoverflow.com/comment/86939687
has text: see a sequence and try to extend it
comment on: http://stackoverflow.com/a/49959422
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49979804
has comment: http://stackoverflow.com/comment/86978621
downvote count: 1
has comment: http://stackoverflow.com/comment/87003767
has comment: http://stackoverflow.com/comment/87040929
tagged with: opencv
has comment: http://stackoverflow.com/comment/86978870
tagged with: opengl
linked to: http://stackoverflow.com/q/26700719
has body: I was looking for a basic python program which will display webcam feed using OpenCV and PyOpenGL. I did some searches, and came up with a code posted in stackoverflow import cv2 from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import numpy as np import sys #window dimensions width = 1280 height = 720 nRange = 1.0 global capture capture = None def cv2array(im): h,w,c=im.shape a = np.fromstring( im.tostring(), dtype=im.dtype, count=w*h*c) a.shape = (h,w,c) return a def init(): #glclearcolor (r, g, b, alpha) glClearColor(0.0, 0.0, 0.0, 1.0) glutDisplayFunc(display) glutReshapeFunc(reshape) glutKeyboardFunc(keyboard) glutIdleFunc(idle) def idle(): #capture next frame global capture _,image = capture.read() cv2.cvtColor(image,cv2.COLOR_BGR2RGB) #you must convert the image to array for glTexImage2D to work #maybe there is a faster way that I don't know about yet... #print image_arr # Create Texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 720,1280, 0, GL_RGB, GL_UNSIGNED_BYTE, image) cv2.imshow('frame',image) glutPostRedisplay() def display(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_TEXTURE_2D) #glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) #glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) #glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) #this one is necessary with texture2d for some reason glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) # Set Projection Matrix glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, width, 0, height) # Switch to Model View Matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Draw textured Quads glBegin(GL_QUADS) glTexCoord2f(0.0, 0.0) glVertex2f(0.0, 0.0) glTexCoord2f(1.0, 0.0) glVertex2f(width, 0.0) glTexCoord2f(1.0, 1.0) glVertex2f(width, height) glTexCoord2f(0.0, 1.0) glVertex2f(0.0, height) glEnd() glFlush() glutSwapBuffers() def reshape(w, h): if h == 0: h = 1 glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() # a…
has comment: http://stackoverflow.com/comment/86978290
score: 1
linked to: http://stackoverflow.com/q/32210107
has comment: http://stackoverflow.com/comment/87085900
tagged with: pyopengl
favorite count: 0
has comment: http://stackoverflow.com/comment/87046835
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87085858
has comment: http://stackoverflow.com/comment/86979582
has comment: http://stackoverflow.com/comment/87052129
answer count: 0
has title: Using PyOpenGL to display OpenCV image
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86978281
has comment: http://stackoverflow.com/comment/87097172
has comment: http://stackoverflow.com/comment/87041011
has comment: http://stackoverflow.com/comment/86979850
tagged with: python

http://stackoverflow.com/comment/87175062
type: Comment
comment on: http://stackoverflow.com/a/50047515
has text: Thank you so much for the thoughtful reply! I'll look into it :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87139201
has text: Python is not Java; when you import a module you get a reference to the module itself, not the class it contains. (Especially as modules can contain multiple classes.)
type: Comment
comment on: http://stackoverflow.com/q/50061352
score: 0
type: QuestionComment

http://stackoverflow.com/q/50067934
possible better answer: http://stackoverflow.com/a/50068004
accepted answer: http://stackoverflow.com/a/50068046
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50068046
score: 0
has answer: http://stackoverflow.com/a/50068004
answer count: 2
has title: Using callbacks inside a function callback
tagged with: callback
has comment: http://stackoverflow.com/comment/87152405
type: Question
has comment: http://stackoverflow.com/comment/87152411
tagged with: arguments
tagged with: python
has body: Given the following three functions: def return_arg( *arg ): return arg[0] def an_expression( x, y, **kwargs ): return x*x + y*y def sub_function( x, y, F ): return x + y + F(**locals()) I can call the following sub_function( 1, 2, an_expression ) to obtain 8. I can also call: T = 5 return_arg(T) How can I call sub_function( 1, 2, return_arg) in the case that I want to have return_arg(T)?

http://stackoverflow.com/q/49966534
tagged with: iteration
favorite count: 0
type: Question
has title: Changing working directory in a loop in Python 2.7
type: UnansweredQuestion
score: 1
tagged with: python
tagged with: active-directory
has body: Good morning, I am currently working on a code that reads files in several directories, but I don't really know how to do that. I've searched here before but didn't found the answer. The folder structure inside a path(eg: /home/Documents/foamOutput) is like: 0,1,2,3,4,5,6, and I need to access each of those folders, operate with the files inside them, and change to the following folder. I'm pretty new with python, so any help is very welcome. Kind regards, Javier
tagged with: for-loop
answer count: 0
has comment: http://stackoverflow.com/comment/86955252
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86948688

http://stackoverflow.com/a/49995339
has comment: http://stackoverflow.com/comment/87008197
has body: Here's one with np.lib.stride_tricks.as_strided that gives us views into a zeros-padded array and as such are very efficient, both memory-wise and performance-wise - def sliding_windows(a, n=4): length = len(a) + n width = n + 1 z_pad = np.zeros(n,dtype=a.dtype) ac = np.r_[z_pad, a, z_pad] s = ac.strides[0] strided = np.lib.stride_tricks.as_strided return strided(ac[n:], shape=(width, length), strides=(-s,s),writeable=False) If you need a writable version, simply make a copy with sliding_windows(a, n=4).copy(). Sample runs - In [42]: a Out[42]: array([1, 2, 3]) In [43]: sliding_windows(a, n=4) Out[43]: array([[1, 2, 3, 0, 0, 0, 0], [0, 1, 2, 3, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0], [0, 0, 0, 1, 2, 3, 0], [0, 0, 0, 0, 1, 2, 3]]) In [44]: sliding_windows(a, n=5) Out[44]: array([[1, 2, 3, 0, 0, 0, 0, 0], [0, 1, 2, 3, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0, 0], [0, 0, 0, 1, 2, 3, 0, 0], [0, 0, 0, 0, 1, 2, 3, 0], [0, 0, 0, 0, 0, 1, 2, 3]]) One more with array-assignment, which should be good if you need a writable version - def sliding_windows_arrassign(a, n=4): pad_length = len(a) + n + 1 width = n + 1 p = np.zeros((width,pad_length),dtype=a.dtype) p[:,:len(a)] = a return p.ravel()[:-n-1].reshape(width,-1) Benchmarking on larger arrays 1) 100 elements and similar n : In [101]: a = np.arange(1,101) In [102]: %timeit sliding_windows(a, n=len(a)+1) 100000 loops, best of 3: 17.6 µs per loop In [103]: %timeit sliding_windows_arrassign(a, n=len(a)+1) 100000 loops, best of 3: 8.63 µs per loop # @Julien's soln In [104]: %%timeit ...: n = len(a)+1 ...: m = np.tile(np.hstack((a,np.zeros(n+1))),n+1)[:(n+len(a))*(n+1)] ...: m.shape = (n+1, n+len(a)) 100000 loops, best of 3: 15 µs per loop 2) ~5000 elements and similar n : In [82]: a = np.arange(1,5000) In [83]: %timeit sliding_windows(a, n=len(a)+1) 10000 loops, best of 3: 23.2 µs per loop In [84]: %timeit sliding_windows_arrassign(a, n=len(a)+1) 10 loops, best of 3: 28.9 ms per loop # @Julien's soln In [91]: %%timeit ...: n = len(a)+1 ...: …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87008022
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87007937
type: Answer
accepted answer of: http://stackoverflow.com/q/49995237
has comment: http://stackoverflow.com/comment/87008132
has comment: http://stackoverflow.com/comment/87007652
answers question: http://stackoverflow.com/q/49995237

http://stackoverflow.com/q/49949418
has answer: http://stackoverflow.com/a/49949893
has answer: http://stackoverflow.com/a/49954607
tagged with: jsonnet
favorite count: 0
type: Question
tagged with: python-import
answer count: 2
score: 5
possible better answer: http://stackoverflow.com/a/49949893
downvote count: 0
tagged with: python
has body: I'm using jsonnet to build json objects that will be used by Python code, calling jsonnet from Python using the bindings. I want to set up my directory structure so that the jsonnet files are in a subdirectory or subdirectories relative to where the Python code is run, something like: foo.py jsonnet/ jsonnet/bar.jsonnet jsonnet/baz.libsonnet Running foo.py should then be able to use _jsonnet.evaluate_snippet() on strings read from files in jsonnet/ that import other files from jsonnet/. What's the best way to do this?
type: AnsweredQuestion
has title: How to correctly call jsonnet with imports from Python
accepted answer: http://stackoverflow.com/a/49954607
upvote count: 5

http://stackoverflow.com/a/49976540
score: 6
accepted answer of: http://stackoverflow.com/q/49976353
answers question: http://stackoverflow.com/q/49976353
type: Answer
has comment: http://stackoverflow.com/comment/86969491
has body: The error comes from the event binding statements: when using self.routine() the callback is called when the bind statement is executed, not when the event is triggered. To get the correct behavior, the second argument of bind should be the name of a function not a call to this function, so simply remove the parentheses. Another error: when using bind, the callback function is expected to have a first argument (traditionnaly called event) storing the event parameters. So you should define your callback as: def routine(self, event): ...
downvote count: 0
type: AcceptedAnswer
upvote count: 6

http://stackoverflow.com/comment/87124626
type: Comment
comment on: http://stackoverflow.com/a/50053847
type: AnswerComment
has text: He has missed parenthesis after `split`.
score: 0

http://stackoverflow.com/q/50070397
tagged with: list
downvote count: 2
has title: Extract value given key for a single dictionary inside list
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: So I have a list like the following [{'id': '290910533794791424', 'invite': 'KEY', 'orderid': 'YMHBK8', 'order': 'specified value'}] How would I obtain a certain value such as the orderid?
tagged with: indexing
linked to: http://stackoverflow.com/q/7271482
has comment: http://stackoverflow.com/comment/87157350
has answer: http://stackoverflow.com/a/50070502
accepted answer: http://stackoverflow.com/a/50070502
duplicate of: http://stackoverflow.com/q/7271482
tagged with: python
score: -1
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/comment/86914417
score: 0
has text: @RobertCrovella the code I use to populate the ecc and incl values is long and based on a number of read files - how best should I deal with posting that to SE? The fix of changing i> ecc... to i>= ecc... hasn't solved the issue.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49941231

http://stackoverflow.com/a/50071012
answers question: http://stackoverflow.com/q/50018194
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: This StackOverflow link may at least partly address the question: Save D3 chart as image It mentions a GitHub package called saveSvgAsPng (https://github.com/exupero/saveSvgAsPng) and how to use it to translate the D3 charts into a .png file. The JavaScript-side mpld3 code basically takes the JSON specification that mpld3.fig_to_dict() generates for a matplotlib plot and it renders it in the DOM as D3 elements (&lt;svg&gt; and other nested elements). There is no raster-based image that is stored in the browser, so you can't directly download a png from this. But a tool such as saveSvgAsPng can allow you to translate that element of the DOM into a downloadable .png file. I don't know if there are other tools for PDFs, jpegs, etc. We have websites we've created which allow the user to click on a button in the browser to download the figures, but the way they work is by telling the Python code on the server-side (through an HTTP-based remote procedure call) to replot the figure and save a file on the server to be downloaded. So there the server renders the plot, which I suppose might be the best option if you want your saved plot files to look like the original matplotlib figures rather than their D3 translations/approximations. (In one of our sites, https://github.com/optimamodel/optima/blob/develop/client/source/js/modules/charts/charts.js#L218 has the JavaScript-side RPC call, which calls https://github.com/optimamodel/optima/blob/develop/client/source/js/modules/common/rpc-service.js#L74 , and the following RPC Python server code is ultimately called: https://github.com/optimamodel/optima/blob/develop/server/webapp/dataio.py#L1103 )

http://stackoverflow.com/comment/87342639
comment on: http://stackoverflow.com/a/50121735
type: Comment
score: 0
type: AnswerComment
has text: While in the notebook I have the line `pretrained_model = load_model('final_model')` when I last evaluated the model I actually didn't save/load the model, I just kept it in memory. So I don't think it's that either :/

http://stackoverflow.com/comment/87120312
has text: I do `python bin/limitbook-tseries.py sample_data/XOM_BATS_2010-06-16.csv sample_data/XOM_BATS_2010-06-162.csv ` and got the error above
type: QuestionComment
comment on: http://stackoverflow.com/q/50051359
score: 0
type: Comment

http://stackoverflow.com/a/50033161
answers question: http://stackoverflow.com/q/50032779
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50032779
upvote count: 1
has body: I would bind the properties of both switches, inverted and sync'ed on creation: #!/usr/bin/python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject class SwitcherWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Alt Switch Demo") self.set_border_width(10) hbox = Gtk.Box(spacing=10) self.add(hbox) switch1 = Gtk.Switch() switch1.set_active(True) hbox.pack_start(switch1, True, True, 0) switch2 = Gtk.Switch() switch2.set_active(False) hbox.pack_start(switch2, True, True, 0) switch1.bind_property("active", switch2, "active", GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE | GObject.BindingFlags.INVERT_BOOLEAN) win = SwitcherWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main() The solution resides on this line of code: switch1.bind_property("active", switch2, "active", GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE | GObject.BindingFlags.INVERT_BOOLEAN) Here you bind the "active" property of switch1 and switch2 with the binding flags: bidirectional, sync on create and invert boolean
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87111311
comment on: http://stackoverflow.com/a/50047098
type: Comment
has text: Because you need `conn.commit()` to push the changes.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87012778
has text: What is in .pythonstartup? What's craze here is that it's looking in very much the wrong location for sitecustomize... so it seems like a path is off somewhere. Like the location is being added through some mechanism (such as your .pythonstartup) or PYTHONPATH is being set directly (though I doubt this is the problem because of the KeyError you are seeing).
comment on: http://stackoverflow.com/q/49991416
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49974001
possible better answer: http://stackoverflow.com/a/49974197
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49974197
has title: Converting a datframe into a list of column retaining the column names -python
accepted answer: http://stackoverflow.com/a/49974164
has body: I have a dataframe a b --------- 1 xyz 2 pqr 3 mno I need to convert into something like (a=[1,2,3],b=[xyz,pqr,mno]) How can I achieve this?
tagged with: python
has answer: http://stackoverflow.com/a/49974164
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 0
tagged with: dataframe

http://stackoverflow.com/q/49954439
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50074219
answer count: 2
has title: Low Accuracy with static image on TFLite demo model
type: UnansweredQuestion
tagged with: android
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/53483553
has body: I'm trying the TFLite implementation for Image Classification using Mobile Net Transfer Learning example from TensorFlow for Poets 2 I'm able to succesfully complete the transfer learning using the four flower samples in the code lab and got the below screen This is a continuous stream of images that's being classified. I need to classify the image after taking the picture instead of stream and then take some action based on the result. Below is my approach for this. Create a basic camera app Take a picture and save it to storage The uri of the image is saved and then a drawable is created from the URI. This drawable is then converted to a bitmap. The bitmap size transformed to 224 x 224 to match the input of the Mobile Net model I'm receiving the accuracy in the ranges of 0.05 and 0.06 against the continuous stream sample from the Code Labs which gives accuracy in the range of 0.80 - 0.90 in the trained flower classes Below is the code where I transform the bitmap to 224 x 224 size private static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, boolean isNecessaryToKeepOrig) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // CREATE A MATRIX FOR THE MANIPULATION Matrix matrix = new Matrix(); // RESIZE THE BIT MAP matrix.postScale(scaleWidth, scaleHeight); // "RECREATE" THE NEW BITMAP Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); if(!isNecessaryToKeepOrig){ bm.recycle(); } return resizedBitmap; } The results turn out to be same even when I pass down the original bitmap to classifier which itself is converting the image to 224 x 224. Should I be doing some more additional processing on the images or do I need to change any configuration in the model ?
tagged with: tensorflow-lite
score: 1

http://stackoverflow.com/comment/86944186
type: QuestionComment
comment on: http://stackoverflow.com/q/49964017
has text: That which creates the self-hosted bootstrap version (let's call it genesis) is written in another language. This is often C or Assembler.
score: 0
type: Comment

http://stackoverflow.com/q/50032122
tagged with: http://stackoverflow.com/tag/svg
downvote count: 4
linked to: http://stackoverflow.com/q/67873157
has title: Calculate area of complex shaped SVG
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87080715
answer count: 1
has body: I want to be able to calculate the area of a given SVG by defining the width, therefor the length too in cm. It's a not only height*width because it's the SVG is complex shape. Let's say I have this SVG: How can I calculate it's surface area with HTML/JavaScript, or Python, or Node.JS?
tagged with: javascript
has comment: http://stackoverflow.com/comment/87080835
favorite count: 0
has comment: http://stackoverflow.com/comment/87081002
type: Question
has answer: http://stackoverflow.com/a/50032154
score: 1
tagged with: math
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/120447745
tagged with: node.js

http://stackoverflow.com/comment/87112360
has text: Use `==` instead of `is` to check for equality
score: 0
comment on: http://stackoverflow.com/q/50048105
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87178873
comment on: http://stackoverflow.com/q/50071515
has text: @hpaulj since you know your way around `argparse` what do you think of my solution? Could you please leave some feedback?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50524852
has body: Answer my own question, what I found is have three python files. Main.py, CallUI.py and MainWindow.py. (Named as you want.) So you can keep regenerate UI and override MainWindow.py without clear button event you wrote. 1.Main.py is the one to launch everything, name == "main". Call CAllUI.py's setup function. #Main.py from PyQt5 import QtCore, QtGui, QtWidgets import sys import CallUI def setUp(): CallUI.setUpWindow() raw_input() if __name__ == "__main__": setUp() 2.CallUI.py is the one to use "QtWidgets.QApplication(sys.argv)" to show UI and add button click functions. #CallUI.py import sys from MainWindow import Ui_Dialog from PyQt5 import QtCore, QtGui, QtWidgets import os class CallUI(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(self) self.ui = Ui_Dialog() self.ui.setupUi(self) self.setUpBtnconnect() def setUpBtnconnect(self): self.ui.pushButton.clicked.connect(self.myFunction) def myFunction(self): os.system("ipconfig") raw_input() def setUpWindow(): app = QtWidgets.QApplication(sys.argv) nowWindow = CallUI() nowWindow.show() sys.exit(app.exec_()) 3.MainWindow.py is the one you converted from pyuic5, it's describe all the UI layout. #MainWindow.py from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("MainWindow") Dialog.resize(466, 417) self.centralwidget = QtWidgets.QWidget(Dialog) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(160, 260, 75, 23)) self.pushButton.setObjectName("pushButton") self.menubar = QtWidgets.QMenuBar(Dialog) self.menubar.setGeometry(QtCore.QRect(0, 0, 466, 21)) self.menubar.setObjectName("menubar") self.statusbar = QtWidgets.QStatusBar(Dialog) self.statusbar.setObjectName("statusbar") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate self.pushButton.s…
answers question: http://stackoverflow.com/q/50060030
downvote count: 1
upvote count: 5
type: Answer
score: 4

http://stackoverflow.com/comment/87137325
type: QuestionComment
comment on: http://stackoverflow.com/q/50059699
score: 0
type: Comment
has text: @Lupanoide: can you give me some code examples for this?

http://stackoverflow.com/q/49922032
has answer: http://stackoverflow.com/a/49945079
score: 1
has title: Python module in tensorflow anaconda installation
tagged with: tensorflow
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0
has body: I am working in anaconda environment I used conda install tensorflow to install tensorflow In the code I : import tensorflow as tf from tensorflow.python.data import Dataset The first command passes but the second command does not (Import error) I looked In the github of tensorflow and saw that the tensorflow.python.data module exists but probably changed Is there a way to get Dataset class from the anaconda installation? If not is there a workaround ? Ilan

http://stackoverflow.com/comment/87053070
comment on: http://stackoverflow.com/q/50017118
score: 0
type: QuestionComment
has text: I'm afraid it is not possible to use many-to-many relations in pivot. You can't group by such relations.
type: Comment

http://stackoverflow.com/comment/86990300
has text: SyntaxError: unexpected EOF while parsing its getting error
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49986145

http://stackoverflow.com/a/50023457
upvote count: 1
has body: Use DataFrame.duplicated for boolean mask by 2 columns and keep=False for return all dupes and filter by boolean indexing: df = df[df.duplicated(['B', 'C'], keep=False)] print (df) A B C 0 b1 1 0 1 b2 1 0 3 b1 2 1 4 b2 2 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50023121
accepted answer of: http://stackoverflow.com/q/50023121
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/87042267
comment on: http://stackoverflow.com/q/50012895
score: 1
type: QuestionComment
has text: It doesn't need to remember all of the previous entries; it just needs the information necessary to compute the average.
type: Comment

http://stackoverflow.com/comment/86858554
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49921094
has text: Possible duplicate of [How to store empty value as an Integerfield](https://stackoverflow.com/questions/20399717/how-to-store-empty-value-as-an-integerfield)

http://stackoverflow.com/q/50014616
favorite count: 0
type: AnsweredQuestion
tagged with: heroku
has answer: http://stackoverflow.com/a/50021068
answer count: 3
upvote count: 5
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/50432276
has title: OSError: [Errno 30] Read-only file system in Django on Heroku
type: Question
has body: I'm using Django 2.0 and Heroku to host the application. My media directory settings are like App/settings/production.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root') I'm using gTTS to convert text to speech and save .mp3 file in the media directory: tts_file_name = str(int(time.time())) + '.mp3' joined_path = os.path.join(settings.MEDIA_ROOT, 'tts') joined_path_with_file = os.path.join(joined_path, tts_file_name) # create directory if does not exists if not os.path.exists(joined_path): os.makedirs(joined_path) tts = gTTS(text='Good morning', lang='en') tts.save(joined_path_with_file) # tts path to send to template tts_media_url = os.path.join(settings.MEDIA_URL, 'tts', tts_file_name) It is working fine on local system as I can change file permissions manually also. But It is not working on Heroku and giving error: OSError: [Errno 30] Read-only file system: '/static_cdn' I tried to locate static_cdn by running heroku shell, but could not even found static_cdn in application path and root path. But it seems to be working as other uploading through form is working perfectly. using Django model's upload_to is working and even directory is created in static_cdn. How can I create directory in static_cdn on Heroku the same way Django does using model's upload_to?
tagged with: django
has answer: http://stackoverflow.com/a/50432276
has answer: http://stackoverflow.com/a/69462638
possible better answer: http://stackoverflow.com/a/69462638
downvote count: 1

http://stackoverflow.com/comment/131553355
type: Comment
type: AnswerComment
has text: As Alasdair said the other solution it's to use the `mock` decorator as: `@mock.patch('boto3.client')`, it's important to make sure that the `return_value` for that mocking returns the same `boto3.client` instance that you define inside your unit test.
comment on: http://stackoverflow.com/a/49944176
score: 0

http://stackoverflow.com/q/49953785
has answer: http://stackoverflow.com/a/49955945
has comment: http://stackoverflow.com/comment/87471991
tagged with: npm
tagged with: python-packaging
score: 12
linked to: http://stackoverflow.com/q/11842444
has comment: http://stackoverflow.com/comment/87471970
has comment: http://stackoverflow.com/comment/87479191
linked to: http://stackoverflow.com/q/14680733
downvote count: 1
has comment: http://stackoverflow.com/comment/87464257
favorite count: 0
has answer: http://stackoverflow.com/a/50045057
linked to: http://stackoverflow.com/q/19183720
linked to: http://stackoverflow.com/q/44185843
type: Question
has title: Which options do exist for defining a Python package with node.js dependencies?
answer count: 2
tagged with: javascript
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87467451
tagged with: node.js
upvote count: 13
has comment: http://stackoverflow.com/comment/87465006
has body: Currently, I have a few (unpublished) Python packages in local use, which I install (for development purposes) with a Bash script on Linux into an activated (otherwise "empty") virtual environment in the following manner: cd /root/of/python/package pip install -r requirements_python.txt # includes "nodeenv" nodeenv -p # pulls node.js and integrates it into my virtual environment npm i -g npm # update npm ... cat requirements_node.txt | xargs npm install -g pip install -e . The background is that I have a number of node.js dependencies, JavaScript CLI scripts, which are called by my Python code. Pros of current approach: dead simple: relies on nodeenv for all required plumbing can theoretically be implemented within setup.py with subprocess.Popen etc Cons of current approach: Unix-like platforms with Bash only "hard" to distribute my packages, say on PyPI requires a virtual environment has potentially "interesting" side effects if a package is installed globally potentially interferes with a pre-existing configuration / "deployment" of nodeenv in the current virtual environment What is the canonical (if there is any) or just a sane, potentially cross-platform approach of defining node.js dependencies for a Python package, making it publishable? Why is this question even relevant? JavaScript is not just for web development (any more). There are also interesting (relevant) data processing tools out there. If you do not want to miss / ignore them, well, welcome to this particular form of hell. I recently came across calmjs, which appears to be what I am looking for. I have not experimented much with it yet and it also appears to be a relatively young project. I started an issue there asking a similar question. EDIT (1): Interesting resource: JavaScript versus Research Computing - A Brief Guide for Those Who Regret That This Has Become Necessary EDIT (2): I started an issue against nodeenv, asking how I could make a project depend on it.

http://stackoverflow.com/comment/87160671
type: Comment
score: 0
type: AnswerComment
has text: when I do that I get AssertionError: A blueprint's name collision occurred between <flask.blueprints.Blueprint object at 0x000001EB35D2D240> and <flask.blueprints.Blueprint object at 0x000001EB35A59198>. Both share the same name "admin". Blueprints that are created on the fly need unique names.
comment on: http://stackoverflow.com/a/50071082

http://stackoverflow.com/comment/86862810
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49923488
type: QuestionComment
has text: You need to put the for-loop between the opening and the closing of the file.

http://stackoverflow.com/q/50040496
accepted answer: http://stackoverflow.com/a/50045211
has answer: http://stackoverflow.com/a/50045211
has body: I have two csv files shown below. First file: abTestGroup,platform,countryCode,userId group_control,ios,GB,aaaaaaaaaaa group_control,ios,GB,aaaaaaaaaaa group_control,ios,GB,aaaaaaaaaaa group_control,ios,GB,aaaaaaaaaaa group_test,android,GB,ccccccccccc Second file: dateActivity,productId,cost,userId 2018-03-02,specialpack,0.198,aaaaaaaaaaa 2018-03-03,specialpack,0.498,aaaaaaaaaaa 2018-03-02,specialpack,0.398,bbbbbbbbbbb 2018-03-02,specialpack,0.998,ccccccccccc and they have one common thing in this case which is the userId. I want to merge those files and create a parent-child relationship using Python (Pandas). I have used the script below: import pandas as pd a = pd.read_csv('PARENT.csv', encoding = "UTF-8", mangle_dupe_cols=True, usecols=['abTestGroup','platform','countryCode','userId']) b = pd.read_csv("CHILD.csv") merged = b.merge(a, on='userId', how='inner') merged = merged.drop_duplicates() merged.to_csv("final_output.csv", index=False) in order to get the following output: dateActivity,productId,cost,userId,abTestGroup,platform,countryCode 2018-03-02,specialpack,0.198,aaaaaaaaaaa,group_control,ios,GB 2018-03-03,specialpack,0.498,aaaaaaaaaaa,group_control,ios,GB 2018-03-02,specialpack,0.998,ccccccccccc,group_test,android,GB The userId 'bbbbbbbbbbb' does not appear in the final output because it doesn't exist in both files. How can I include the unmatched rows (unmatched userIds) and assign the 'Other' value to the cells?
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50045288
tagged with: python
has answer: http://stackoverflow.com/a/50045288
has title: Include unmatched rows in Python script that merges two files based on one column
tagged with: merge
has comment: http://stackoverflow.com/comment/87106807
type: AnsweredQuestion
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/49982537

http://stackoverflow.com/comment/87149876
has text: You might have to install it (but note that it is `pandas`, not `panda`)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50065513

http://stackoverflow.com/comment/87097048
type: Comment
type: QuestionComment
score: 0
has text: Where is the bytestring coming from? I.E: Why can't you just do `r'...'` and not `b'...'`
comment on: http://stackoverflow.com/q/50040285

http://stackoverflow.com/q/50066902
answer count: 1
tagged with: imshow
has answer: http://stackoverflow.com/a/50075183
has body: A dataframe, which should be considered a matrix, contains values 0, 1, 2. With imshow, I get a nice image. I can use a cmap with 3 discrete colors. I want to highlight few rows, so visually I want to have those rows with alpha=1 and the other with alpha=0.1 . Should I create the image myself, creating a matrix with RGBA entries? Is there a more straight-forward way? With Kind Regards, Oren
score: 0
tagged with: python
type: Question
has title: masking an imshow, or imshow with RGBA
type: UnansweredQuestion

http://stackoverflow.com/q/50031277
tagged with: python-3.x
answer count: 2
score: 5
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/50031316
upvote count: 5
has body: I am using if in a conditional statement like the below code. If address is NJ then the value of name column is changed to 'N/A'. df1.loc[df1.Address.isin(['NJ']), 'name'] = 'N/A' How do I do the same, if I have 'nested if statements' like below? # this not code just representing the logic if address isin ('NJ', 'NY'): if name1 isin ('john', 'bob'): name1 = 'N/A' if name2 isin ('mayer', 'dylan'): name2 = 'N/A' Can I achieve above logic using df.loc? Or is there any other way to do it?
downvote count: 0
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50032861
has title: Nested if statements with .loc in pandas / python
has answer: http://stackoverflow.com/a/50031316
has answer: http://stackoverflow.com/a/50032861
favorite count: 0
type: Question

http://stackoverflow.com/comment/87074300
type: QuestionComment
has text: You'll need to mount the file share on the Mac and Linux machines. I believe MacOS automatically creates mount points under `/Volumes` when you connect using Finder. In a Linux machine you'll need to set up a `cifs` point mount and entry in `/etc/fstab`. You'll also need to figure out how the share should be authenticated. In a single-user system you can connect as the current user, but for an automated process you'll need to embed credentials somehow.
score: 0
comment on: http://stackoverflow.com/q/50026412
type: Comment

http://stackoverflow.com/q/50049619
type: Question
upvote count: 2
has title: How to stop pip overwriting its cacert.pem file on upgrade
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87115514
tagged with: pip
tagged with: ssl
linked to: http://stackoverflow.com/q/35032780
tagged with: python
has body: I'm stuck behind a company firewall and to let pip through it I add some certificates to lib/pythonX.X/site-packages/pip/_vendor/certifi/cacert.pem. I noticed that on upgrade it overwrites this file with a different certificate bundle. Is there something I can set to stop this behavior? I'm running on Mac OS X I'm running pip inside a virtualenv. If there's some way I can specify a certificate bundle for the whole virtualenv that would be best as I occasionally run into issues like this for other programs too.
score: 2
answer count: 0
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/87125298
favorite count: 0

http://stackoverflow.com/comment/87018834
comment on: http://stackoverflow.com/q/50001278
score: 0
type: Comment
type: QuestionComment
has text: I don't understand what's wrong with the array you get? The precision you want is one decimal place and you get a precision of a dozen decimals...

http://stackoverflow.com/comment/87129465
has text: Thank you! I added to the top of my code: "import copy" and changed "basis_mod = basis" to "basis_mod = copy.deepcopy(basis)" and it worked. I think "basis_mod = copy.copy(basis)" or "basis_mod = basis.copy()" would have also worked.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50035916
type: Comment

http://stackoverflow.com/comment/87107816
type: AnswerComment
has text: I'm getting a new error now.It says TypeError: calculate() takes 1 positional argument but 2 were given.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50045602

http://stackoverflow.com/comment/87021321
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50002444
has text: @Patricia on the plus side though, it looks like it gave you the solution to your problem!

http://stackoverflow.com/comment/87038878
comment on: http://stackoverflow.com/q/50011143
type: Comment
type: QuestionComment
has text: Are the "Blank line" actually blank lines?
score: 1

http://stackoverflow.com/q/50070458
has comment: http://stackoverflow.com/comment/87157973
type: Question
tagged with: python-3.x
tagged with: min
upvote count: 2
accepted answer: http://stackoverflow.com/a/50070661
has body: Can you please help me understand what is going on in this line of code? def push(self, x): self.stack.append(x) if len(self.minStack): if x &lt; self.minStack[-1][0]: self.minStack.append([x, 1]) elif x == self.minStack[-1][0]: self.minStack[-1][1] += 1 else: self.minStack.append([x, 1]) it is taken from the line of this code: class MinStack2: def __init__(self): self.stack, self.minStack = [], [] # @param x, an integer # @return an integer def push(self, x): self.stack.append(x) if len(self.minStack): if x &lt; self.minStack[-1][0]: self.minStack.append([x, 1]) elif x == self.minStack[-1][0]: self.minStack[-1][1] += 1 else: self.minStack.append([x, 1]) You can also find it at this GitHub account: https://github.com/kamyu104/LeetCode/blob/master/Python/min-stack.py Thank you in advance Please, dont just mark it down if there is any misunderstanding for you. Leave a feedback rather. This is a plattform to learn and I feel like marking post down without an explanantion is very uneducated
has title: Retrieving the minimum element in a stack at a constant time
has comment: http://stackoverflow.com/comment/87157876
tagged with: python
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87158414
tagged with: stack
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/50070661

http://stackoverflow.com/comment/98684300
type: Comment
type: AnswerComment
has text: how can I pass in the delay time to this fixture from within a test case?
comment on: http://stackoverflow.com/a/50048692
score: 0

http://stackoverflow.com/comment/86940498
type: AnswerComment
has text: how can i make it so that the integer values are ints and not strings? for example instead of '30', i want 30
comment on: http://stackoverflow.com/a/49962031
type: Comment
score: 0

http://stackoverflow.com/comment/87005599
comment on: http://stackoverflow.com/q/49994703
score: 0
has text: Can you post a sample of your data?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86866432
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49925187
has text: yaml uses a dict container to move data around so they will not be saved in the order you want.
type: Comment

http://stackoverflow.com/comment/86863795
score: 0
comment on: http://stackoverflow.com/q/49923960
type: Comment
type: QuestionComment
has text: Can you create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)

http://stackoverflow.com/comment/87249358
comment on: http://stackoverflow.com/a/50086632
has text: Could you please enhance your question with code examples that reflect that context?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86925327
score: 0
has text: parent_mcu_data_id is in the mcu_data_ids
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49941745

http://stackoverflow.com/comment/87049079
has text: Because the loss of accuracy occurs for non-zero values of x.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49995901

http://stackoverflow.com/comment/86926730
type: AnswerComment
has text: Oh, Yes. You are right. `related_name` should have been something related to `Product`.
type: Comment
comment on: http://stackoverflow.com/a/49949554
score: 0

http://stackoverflow.com/comment/87029762
type: AnswerComment
has text: Awesome. This edited code works perfectly fine with my list, Thanks a lot. Much appreciate your help.
type: Comment
comment on: http://stackoverflow.com/a/50004680
score: 0

http://stackoverflow.com/a/49967934
has comment: http://stackoverflow.com/comment/97176003
type: Answer
has comment: http://stackoverflow.com/comment/86969899
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49967909
has comment: http://stackoverflow.com/comment/86969742
has comment: http://stackoverflow.com/comment/86968098
has comment: http://stackoverflow.com/comment/86960105
has comment: http://stackoverflow.com/comment/86967123
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/86970188
has body: '' doesn't mean any string, it means no string (aka, the empty string, or the 0-length string). There are, strictly speaking, an infinite number of 0-length strings in a string, but practically, len(string) + 1 is returned - one for just before first character, and one each for after every character. This scenario has been explicitly special-cased in count.h: if (sub_len == 0) return (str_len &lt; maxcount) ? str_len + 1 : maxcount; When the search string is the empty string, len(string) + 1 is returned by default.
answers question: http://stackoverflow.com/q/49967909

http://stackoverflow.com/q/49961179
type: AnsweredQuestion
has body: In my guess the number program it gives me the error: '>' not supported between instances of 'str' and 'int' on line 26 in main. I would be grateful if someone helped me with this, Thank you. import random guesses = 0 def higher(guesses): print("Lower") gueeses += 1 def lower(guesses): print("Higher") guesses += 1 def correct(guesses): print("You got it correct!") print("It was {0}".format(number)) guesses += 1 def _main_(guesses): print("Welcome to guess the number") number = random.randint(1, 100) while True: guess = input("Guess a number: ") if guess &gt; number: lower(guesses) elif guess &lt; number: higher(guesses) elif guess == number: correct(guesses) while True: answer = input("Would you like to play again? Y or N: ") if answer == "Y": break elif answer == "N": exit() else: exit() _main_(guesses)
score: 0
linked to: http://stackoverflow.com/q/23294658
tagged with: input
tagged with: python
accepted answer: http://stackoverflow.com/a/49961196
has title: '>' not supported between instances of 'str' and 'int' in my guess the number game
answer count: 1
has answer: http://stackoverflow.com/a/49961196
type: Question

http://stackoverflow.com/q/50015804
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50015876
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87172344
tagged with: python-3.x
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/87048038
tagged with: regex
accepted answer: http://stackoverflow.com/a/50015876
has title: error while using re.findall() to find all letters from A to Z
has body: My code is: import re key, val = ' ', 2 self._l[key] = re.findall(r"[A-Z]+", val) Error: return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/86935892
has text: The default optimization method `newton` breaks in this case. method='bfgs' works, but there is perfect prediction, so the parameters are not identified.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49954406

http://stackoverflow.com/comment/87158295
type: AnswerComment
comment on: http://stackoverflow.com/a/50070805
type: Comment
has text: Thank's for the suggestions! Unfortunately, this also leads to an error: `TypeError: coercing to Unicode: need string or buffer, list found`
score: 0

http://stackoverflow.com/comment/87071709
comment on: http://stackoverflow.com/q/50027585
has text: I am `researching` Python. Can't learn all at once :) Step by step
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50069063
downvote count: 0
has body: This is one way with itertools: from itertools import chain, zip_longest a = "12345" b = "6789XYZ" res = ''.join(list(chain.from_iterable(zip_longest(a, b, fillvalue='')))) # '162738495XYZ' Note the list conversion is not required, but improves performance.
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50068837
upvote count: 3

http://stackoverflow.com/comment/87093207
has text: @BcK No, before you decide to avoid that or not you should know how it performs and see if identity check is necessary in your case or not. When you use a high level language like Python with so much abstraction you always need to be aware of these unexpected behavior.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50037786

http://stackoverflow.com/a/49985001
score: 0
answers question: http://stackoverflow.com/q/49984791
has body: According to [Python]: Format examples, you should use (templates like): &lt;a href={links[one]}&gt;&lt;/a&gt; as html format specifier (since [Python]: json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) returns a dict). Example: &gt;&gt;&gt; json_dict {'links': {'one': 'www.one.com', 'two': 'www.two.com'}} &gt;&gt;&gt; href_text '&lt;a href={links[one]}&gt;&lt;/a&gt;' &gt;&gt;&gt; href_text.format(links=json_dict["links"]) '&lt;a href=www.one.com&gt;&lt;/a&gt;'
type: Answer

http://stackoverflow.com/comment/86916906
type: QuestionComment
has text: The currently provided CW answer has been updated to reflect this. You're welcome to accept that one if you wish.
comment on: http://stackoverflow.com/q/49941231
type: Comment
score: 1

http://stackoverflow.com/q/49945999
has body: Suppose I have a multi-level dictionary like this mydict = { 'first': { 'second': { 'third': { 'fourth': 'the end' } } } } I'd like to access it like this test = get_entry(mydict, 'first.second.third.fourth') What I have so far is def get_entry(dict, keyspec): keys = keyspec.split('.') result = dict[keys[0]] for key in keys[1:]: result = dict[key] return result Are there more efficient ways to do it? According to %timeit the runtime of the function is 1.26us, while accessing the dictionary the standard way like this foo = mydict['first']['second']['third']['fourth'] takes 541ns. I'm looking for ways to trim it to 800ns range if possible. Thanks
has answer: http://stackoverflow.com/a/50057045
linked to: http://stackoverflow.com/q/2352181
score: 32
has comment: http://stackoverflow.com/comment/86908752
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49946428
has answer: http://stackoverflow.com/a/50075991
has comment: http://stackoverflow.com/comment/86908511
linked to: http://stackoverflow.com/q/14692690
linked to: http://stackoverflow.com/q/938733
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87140352
downvote count: 2
has title: Efficiently accessing arbitrarily deep dictionaries
has answer: http://stackoverflow.com/a/50074290
has answer: http://stackoverflow.com/a/49947100
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49946181
answer count: 7
upvote count: 34
favorite count: 0
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/86908541
has answer: http://stackoverflow.com/a/49949382
has comment: http://stackoverflow.com/comment/87069052

http://stackoverflow.com/comment/87094811
type: QuestionComment
has text: you cannot use collect inside UDF. Can't you do that using `join` ?
comment on: http://stackoverflow.com/q/50038842
score: 0
type: Comment

http://stackoverflow.com/q/50045202
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50046510
has title: Quickly find indices that have values larger than a threshold in Numpy/PyTorch
accepted answer: http://stackoverflow.com/a/50046640
has answer: http://stackoverflow.com/a/50046640
type: AnsweredQuestion
has body: Task Given a numpy or pytorch matrix, find the indices of cells that have values that are larger than a given threshold. My implementation #abs_cosine is the matrix #sim_vec is the wanted sim_vec = [] for m in range(abs_cosine.shape[0]): for n in range(abs_cosine.shape[1]): # exclude diagonal cells if m != n and abs_cosine[m][n] &gt;= threshold: sim_vec.append((m, n)) Concerns Speed. All other computations are built on Pytorch, using numpy is already a compromise, because it has moved computations from GPU to CPU. Pure python for loops will make the whole process even worse (for small data set already 5 times slower). I was wondering if we can move the whole computation to Numpy (or pytorch) without invoking any for loops? An improvement I can think of (but got stuck...) bool_cosine = abs_cosine > threshold which returns a boolean matrix of True and False. But I cannot find a way to quick retrieve the indices of the True cells.
favorite count: 0
has answer: http://stackoverflow.com/a/50046510
type: Question
tagged with: numpy
answer count: 2
score: 5
tagged with: pytorch
upvote count: 5

http://stackoverflow.com/q/50062780
has comment: http://stackoverflow.com/comment/87142345
type: Question
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/87142436
has title: Reprint options if invalid input
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87142546
has body: I'm trying to code a simple python script which takes the input from user and continues, for now it has 3 options and just exit's if there's an invalid input. My question is what should I add to reprint the options if the user input's anything other then the numbers 1-3 ? def select(): option = raw_input("\nSelect an option:\n [1]First\n [2]Second\n [3]Third\n") if option == '1': print('Hello') elif option == '2': print('Hi') elif option == '3': print('Hey') else: exit(0) (Code just for example)

http://stackoverflow.com/comment/87026251
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50002926
has text: Right! Will check this out. Many thanks for elaborating.
type: AnswerComment

http://stackoverflow.com/q/50026341
answer count: 1
has body: This code is working but not the way I wanted: vor_merged_to_dad_pivot = pd.pivot_table( vor_merged_to_dad, index=['ID'], values=['MDD_Y', 'ADMITDATE'], aggfunc={ 'MDD_Y':np.sum, 'ADMITDATE':np.min } ) I want to get the minimal ADMITDATE but only when MDD_Y is equal to one, I tried this but doesn't work: vor_merged_to_dad_pivot = pd.pivot_table( vor_merged_to_dad, index=['ID'], values=['MDD_Y', 'ADMITDATE'], aggfunc={ 'MDD_Y':np.sum, 'ADMITDATE':np.min if 'MDD_Y'==1 } ) SyntaxError: invalid syntax
favorite count: 0
type: Question
has title: How to give conditional statements within Pandas' pivot_table function?
tagged with: aggregate
tagged with: pivot-table
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50026667
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50026667

http://stackoverflow.com/comment/87104923
type: Comment
type: QuestionComment
has text: Just one of them
comment on: http://stackoverflow.com/q/50044349
score: 0

http://stackoverflow.com/a/49953833
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/87017963
has comment: http://stackoverflow.com/comment/87070307
has comment: http://stackoverflow.com/comment/87071426
has comment: http://stackoverflow.com/comment/87023961
answers question: http://stackoverflow.com/q/49950865
type: Answer
has comment: http://stackoverflow.com/comment/87023782
has comment: http://stackoverflow.com/comment/87025535
accepted answer of: http://stackoverflow.com/q/49950865
upvote count: 6
has comment: http://stackoverflow.com/comment/87068070
has comment: http://stackoverflow.com/comment/87015698
has body: As already shown in Primusa's answer, it is helpful to allow the recurrent layer to output its hidden state using return_sequences=True, together with a Bidirectional layer which has been shown to better capture temporal patterns. Additionally, I would argue that you need to have some sort of an intuition towards the kind of function you're trying to approximate- trying to decompose it into a number of functions and constructing a sub-network for each usually speeds up the learning process, especially so when using appropriate activation combinations. Applying weight regularization is also relevant as it may stop the extreme divergence due to error accumulation. Note also that unless you use stateful=True, you will need to provide the network with a long enough time frame to inspect long-range patterns (i.e. the parabola is easy to approximate as a line if the time-window is small). Concretely, the below alterations achieve a (still rapidly decreasing) MSE of (1.0223e-04/0.0015 ) after 20 epochs and (2.8111e-05/3.0393e-04) after 100 epochs, with a lookback of 100 (note that I have also changed your optimizer to Adam which I simply prefer): from keras import Model, Input from keras.layers import (LSTM, Dense, Activation, BatchNormalization, Dropout, Bidirectional, Add) inputs = Input(shape=(look_back, 1)) bd_seq = Bidirectional(LSTM(128, return_sequences=True, kernel_regularizer='l2'), merge_mode='sum')(inputs) bd_sin = Bidirectional(LSTM(32, return_sequences=True, kernel_regularizer='l2'), merge_mode='sum') (bd_seq) bd_1 = Bidirectional(LSTM(1, activation='linear'), merge_mode='sum')(bd_seq) bd_2 = Bidirectional(LSTM(1, activation='tanh'), merge_mode='sum')(bd_sin) output = Add()([bd_1, bd_2]) model = Model(inputs=inputs, outputs=output) model.compile(optimizer='adam', loss='mean_squared_error')

http://stackoverflow.com/comment/87021511
has text: why dont you split it to two datasets one for fraud, one for non-fraud and sample 260 each?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50002579

http://stackoverflow.com/q/49990881
type: Question
has comment: http://stackoverflow.com/comment/86998553
has comment: http://stackoverflow.com/comment/86998948
tagged with: python
linked to: http://stackoverflow.com/q/11309739
tagged with: type-conversion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50015030
score: 0
has body: This is different from other question such as this Store different datatypes in one NumPy array?. I could not see the matrix in that 'possible duplicate question'. The question did not look like a matrix. I am interested in changing the specific data types of within a matrix. I would like to have a matrix with a mix of datatypes. That is would like to change the individual columns datatypes: I will illustrate with the original matrix and what I would like to do. The original matrix is of type float64. mymatrix array([[17. , 27. , 19.62120627, 21. , 0. ], [10. , 1. , 18.94042755, 0. , 0. ], [11. , 53. , 13.96885424, 29. , 0. ], [ 8. , 1. , 19.36688898, 0. , 1. ], [ 8. , 44. , 19.26500703, 29. , 1. ], [16. , 2. , 27.31823044, 0. , 1. ]]) But I would like the individual columns to be of different types: i2,i2,f8,i2,? That is the columns in the matrix are of type int16, int16, float64, int16 and binary. See reference half way down https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html. Also the suggested answer Store different datatypes in one NumPy array? does not relate to my need. For example: I have the first row in the original matrix array([[17. , 27. , 19.62120627, 21. , 0. ] but I would like array([[17,27,19.62120627,21, False] That is my columns to respectively be of type: i2, i2, f8, i2, ? That is I would like my whole matrix as shown above to have columns of type int16, int16, float64, int16 and binary. Recall, the reference is half way down See reference half way down https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html Sum: how to change individual columns to specific datatypes?
accepted answer: http://stackoverflow.com/a/50015030
linked to: http://stackoverflow.com/q/27431390
tagged with: matrix
tagged with: types
tagged with: arrays
answer count: 1
has title: Python changing individual data types within a matrix/array - eg int, float, binary

http://stackoverflow.com/comment/124829199
comment on: http://stackoverflow.com/a/70553095
has text: Yes on closer inspection, I now see what you mean. Presumably my answer wouldn't solve the problem at all, as the questioner would still be told that lxml was already installed...probably shouldn't have posted the answer. I'll leave it in if you think I should, though obviously it answers a far more basic problem scenario.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86858984
type: Comment
type: QuestionComment
has text: Look at `help(Connection)`. But now I am worried that this undocumented property might not be part of the intended API. Also, `Pipe()` returns instances of the undocumented class `PipeConnection` which is a sibling, not a descendant of `Connection`. I don't think they are going anywhere but you might want to look for more qualified advice, maybe in the python users mailing list.
comment on: http://stackoverflow.com/q/49921214
score: 0

parallel-coordinates
tags question: http://stackoverflow.com/q/49917313
tag name: parallel-coordinates
type: Tag

http://stackoverflow.com/comment/87119269
type: AnswerComment
score: 1
has text: To be honest, I dont quite see the point of this benchmark anyway. pandas is built on top of numpy, so I would be surprised to see any numpy solution slower than the pandas solution, as pandas involves additional functional overhead.
comment on: http://stackoverflow.com/a/49968504
type: Comment

http://stackoverflow.com/comment/87162747
has text: You need to rewind to the beginning of the file before the second loop.
type: QuestionComment
comment on: http://stackoverflow.com/q/50073110
score: 2
type: Comment

http://stackoverflow.com/q/49967457
type: Question
tagged with: numpy
has title: Create a map of images in python numpy
has body: I have a numpy array of size image_stack 64x28x28x3 which correspond to 64 images of size 28x28x3. What I want is to construct an image of size 224x224x3 which will contain all my images that are in the initial array. How can I do so in numpy? So far I have the code for stacking the images in the same line, however I want 8 lines of 8 columns instead. My code so far: def tile_images(image_stack): """Given a stacked tensor of images, reshapes them into a horizontal tiling for display.""" assert len(image_stack.shape) == 4 image_list = [image_stack[i, :, :, :] for i in range(image_stack.shape[0])] tiled_images = np.concatenate(image_list, axis=1) return tiled_images
has answer: http://stackoverflow.com/a/49967686
accepted answer: http://stackoverflow.com/a/49967686
tagged with: python
tagged with: image
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/comment/87025140
has text: `memcpy` is a C function and generally can't handle anything beyond simple references to C++ objects. I'm not sure what would happen to a `std::vector` for instance.
comment on: http://stackoverflow.com/q/50003851
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50058330
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87151136
has body: For Python 2.7 , the following approach works. full_dict = {} full_dict_list = [] for index,val in enumerate(foobar_list): full_dict = dict(default_params_list[index],**val) # merge dictionaries from both the lists map(full_dict.pop, ['junk','type']) # remove the unwanted keys full_dict_list.append(full_dict) update: approach without using for loops. full_dict_list = map(lambda d1,d2:dict(d1.items()+d2.items()),foobar_list,default_params_list) map(lambda d1:map(d1.pop,['junk','type']), full_dict_list)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50055652

http://stackoverflow.com/comment/86884172
score: 0
type: AnswerComment
has text: @roadstorm Ah, I assumed that the elements of `B` may occur only once. `maxcoeff` is the same as `i`. (Here I assumed that `A` is always of the form `0, 1, 2, 3, ..., i`).
type: Comment
comment on: http://stackoverflow.com/a/49931980

http://stackoverflow.com/comment/86882255
type: QuestionComment
comment on: http://stackoverflow.com/q/49932096
score: 0
has text: Thank you Pavel for the formating, sorry about that.
type: Comment

http://stackoverflow.com/comment/86942532
has text: Can you also post the output of the script?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49963241
type: QuestionComment

http://stackoverflow.com/q/50013207
type: Question
type: UnansweredQuestion
tagged with: python
has body: I am doing a project to solve captcha using python.I am using pytesseract module for that.This script works well it also creates new image file by modifying it but always creates an error while interpretation of line text = pytesseract.image_to_string(Image.open(filename)) to extract text from new temporary created image file.I'm using the following script temporary image created for extraction of text # import the necessary packages from PIL import Image import pytesseract import argparse import cv2 import os # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image to be OCR'd") ap.add_argument("-p", "--preprocess", type=str, default="thresh", help="type of preprocessing to be done") args = vars(ap.parse_args()) # load the example image and convert it to grayscale image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # check to see if we should apply thresholding to preprocess the # image if args["preprocess"] == "thresh": gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # make a check to see if median blurring should be done to remove # noise elif args["preprocess"] == "blur": gray = cv2.medianBlur(gray, 3) # write the grayscale image to disk as a temporary file so we can # apply OCR to it filename = "{}.png".format(os.getpid()) cv2.imwrite(filename, gray) # load the image as a PIL/Pillow image, apply OCR, and then delete # the temporary file text = pytesseract.image_to_string(Image.open(filename)) os.remove(filename) print(text) # show the output images cv2.imshow("Image", image) cv2.imshow("Output", gray) cv2.waitKey(0) C:\Users\LENOVO\Desktop\ocr&gt;python test.py -i image.jpg Traceback (most recent call last): File "test.py", line 44, in &lt;module&gt; text = pytesseract.image_to_string(Image.open(filename)) File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 193, in image_to_string return…
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50014065
has title: pytesseract.image_to_string() always creates an error

python-3.4
tags question: http://stackoverflow.com/q/49946273
tag name: python-3.4
tags question: http://stackoverflow.com/q/50010814
type: Tag
tags question: http://stackoverflow.com/q/50008091
tags question: http://stackoverflow.com/q/50042673
tags question: http://stackoverflow.com/q/50033119

http://stackoverflow.com/comment/86997308
has text: I suppose `str.__repr__` (which is called for `print([family])`, but not `print(family)`) has a predefined set of characters that are shown as escape sequences. They seem to be mostly hard-to-see characters like blank and zero-width characters. `200D` is apparently one of them, but modifiers are usually printed literally. This is all based on observation, I haven't found a written source for this.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49958287
type: Comment

http://stackoverflow.com/q/49947856
has body: My code is working perfectly working fine but due to my change in requirements I had to make DateTimeField to TimeField but after making the changes in my code I faced following error. Exception Value: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' My code is about salary calculation. class salary(models.Model): #employee = models.ForeignKey('employee', on_delete=models.CASCADE) base_salary = models.IntegerField(default=0) time_in = models.DateTimeField(default=tz.now, null=True, blank=True) time_out = models.DateTimeField(default=tz.now, null=True, blank=True) total_salary = models.CharField(max_length=20, default='0') def calculate_salary(self): worked_hours = (self.time_out - self.time_in).total_seconds() / 60 / 60 overtime_hours = 0 # make sure you use timezone aware objects # https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#naive-and-aware-datetime-objects same_day_8pm = self.time_out.replace(hour=16, minute=0, second=0, microsecond=0) if self.time_out &gt; same_day_8pm: overtime_hours = (self.time_out - same_day_8pm).total_seconds() / 60 / 60 salary_1 = worked_hours * self.base_salary salary_2 = overtime_hours * self.base_salary * 0.2 total_salary = salary_1 + salary_2 # careful: this will be a 'float', not an 'int' # with round() using 0 decimal digits you get an 'int' # total_salary = round(total_salary, 0) return total_salary def save(self,*args,**kwargs): # are you really sure that you want to save a string ??? self.total_salary = str(self.calculate_salary()) super().save(*args, **kwargs)
type: AnsweredQuestion
tagged with: django-views
has comment: http://stackoverflow.com/comment/86912415
score: 1
has title: DateTimeField & TimeField Error
linked to: http://stackoverflow.com/q/5259882
tagged with: django-models
tagged with: python
tagged with: django-templates
has comment: http://stackoverflow.com/comment/86913004
has comment: http://stackoverflow.com/comment/86913483
has comment: http://stackoverflow.com/comment/86913412
accepted answer: http://stackoverflow.com/a/49947936
has comment: http://stackoverflow.com/comment/86913356
has comment: http://stackoverflow.com/comment/86913207
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49947936
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/86913487
favorite count: 0
has comment: http://stackoverflow.com/comment/86913076
type: Question
has comment: http://stackoverflow.com/comment/86913468

http://stackoverflow.com/q/49983853
score: 0
tagged with: gdal
answer count: 0
has body: I am trying to count features that have the text "Fehler" in a certain field. This only works, when using the OGRSQL-dialect, but returns None when using SQLITE. I want to use the SQLITE-dialect, because I am looping over several SQL-Strings, and some of them contain SUM(LENGTH)/1000, which only works in SQLITE, and not with OGRSQL. I am using Python 2.7.5 an gdal 2.1.3 Here is the code that I am using: import os try: from osgeo import ogr from osgeo import gdal except: sys.exit("Failed to import OGR-module. Please check the GDAL-Installation!") srcFile = r"D:\Didi\Tmp\OGR_Select_Bug\Export.shp" driver = ogr.GetDriverByName('ESRI Shapefile') destFileDS = driver.Open(srcFile, 0) sql = u"SELECT COUNT(*) as Anzahl from %s WHERE rstatus like '%%Fehler'" % (os.path.basename(srcFile)[:-4]) #Works actLayer = destFileDS.ExecuteSQL(statement=sql.encode('utf-8'), dialect='OGRSQL') actFeat = actLayer.GetNextFeature() destFileDS.ReleaseResultSet(actLayer) #Returns none actLayer = destFileDS.ExecuteSQL(statement=sql.encode('utf-8'), dialect='SQLITE') actFeat = actLayer.GetNextFeature() destFileDS.ReleaseResultSet(actLayer)
tagged with: sql
has comment: http://stackoverflow.com/comment/87006095
tagged with: sqlite
type: Question
has comment: http://stackoverflow.com/comment/86985171
has title: Why is "...like '%Wert'" not working with ogr.ExecuteSQL and dialect = SQLITE?
has comment: http://stackoverflow.com/comment/87206261
tagged with: ogr
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/50026477
downvote count: 0
has comment: http://stackoverflow.com/comment/87073886
has comment: http://stackoverflow.com/comment/87069316
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87071717
has body: Update: Using eq(==) and sumwith axis=1, if that is more than 1 it should be some columns repeat the columns T 's value df[df.eq(df['T'],0).sum(1).gt(1)] Out[84]: A B C D E T 0 2 3 5 10 21 5
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/50026272
type: Answer
accepted answer of: http://stackoverflow.com/q/50026272

http://stackoverflow.com/comment/86987410
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49972562
has text: It converted to float just fine but in the api helper function the float I created was subtracted from a date which caused the error. `datetime.datetime.now()` alone worked perfectly. Apparently `datetime.datetime.now()` is dateInt format.
type: Comment

http://stackoverflow.com/a/49940373
accepted answer of: http://stackoverflow.com/q/49940099
has body: def identify(number): sht = gc.open("Test") wks3 = sht.worksheet("NAMES") b = wks3.acell('B'+str(number)).value a = wks3.acell('A'+str(number)).value #because you did, Id = ? if(Id == a and conf&lt;65): print(Id, conf) Id = str(b) Time = time.ctime() hour(number) elif(conf&gt;64): print(conf) Id = "Unknown" Because you did, variable Id isn't passed as any parameter or global/local variable or as an argument to existing class. If Id was parameter: def identify(number,Id): If Id was global variable: def identify(number): global Id If Id was local variable: def identify(number): id = None # or some other data type And if Id was argument from some class: some_class.Id In short you referenced Id before it was initialised. This is rookie mistake and there is some stuff where you can actually init a variable in if elif else statement but you need to trow a none of above logic of the rule. if True: Id = 2; elif False: Id = 3; else: Id =0 #this is pseudocode, don't paste it in. Also have in mind that next variable is also Unbound conf EDIT: Often to avoid this problem we write code like this: def somefunction(parm1,parm2... ): # global variables : description for variable stack is optional global var1,var2 # if needed #local variables var3,var4 = None; var5 = 'something else' #in body functions : functions inside functions or just general program functions def a(... ): return ... #body : actually what function/program does. # returning , finishing statement.
type: Answer
answers question: http://stackoverflow.com/q/49940099
score: 3
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86896532
downvote count: 0
has comment: http://stackoverflow.com/comment/86896358

http://stackoverflow.com/comment/86927613
type: Comment
has text: Yes bro, it is a confirmed SO.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49952955

http://stackoverflow.com/a/49942929
has body: There's no reason to create a bunch of classes or frames in a loop. Just store your questions and answers in a simple array, and refresh the display based on the data in that array. You just need a single frame to display one question at a time. Start by creating a class to hold your questions and other data. I'm assuming this is a multiple choice quiz, so you need a list of choices and a pointer to which one is correct. class Question(): def __init__(self, question, choices, answer_index): self.question = question self.choices=choices self.answer_index = answer_index Next, define your questions: questions = ( Question("Question 1?", choices=("A. ...", "B. ...", "C. ...", answer_index=0)), Question("Question 2?", choices=("A. ...", "B. ...", "C. ...", answer_index=3)), Question("Question 3?", choices=("A. ...", "B. ...", "C. ...", answer_index=2)), Question("Question 4?", choices=("A. ...", "B. ...", "C. ...", answer_index=2)), } Finally, create a function that given an index will render that question: def show_question(index): """Show the question at the given index in 'questionFrame'""" # destroy old widgets # (you can skip if all questions have the same number of choices) for child in questionFrame.children(): child.destroy() question - questions[index] # create widgets for current question # (or configure existing widgets if all questions have the same # number of choices) question_label = tk.Label(questionFrame, text=question.question) for choice in question.choices: radiobutton = tk.Radiobutton(...)
accepted answer of: http://stackoverflow.com/q/49942172
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49942172
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86902999
type: Answer
score: 1

http://stackoverflow.com/a/49926823
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86869934
has body: This was already answer here. This is because numpy.matlib is an optional sub-package of numpy that must be imported separately. When you import just numpy without the sub-package matlib, then Python will be looking for .matlib as an attribute of the numpy package. This attribute has not been assigned to numpy without importing numpy.matlib
answers question: http://stackoverflow.com/q/49926751
has comment: http://stackoverflow.com/comment/86869629
type: Answer
accepted answer of: http://stackoverflow.com/q/49926751
has comment: http://stackoverflow.com/comment/86869669
upvote count: 12
score: 12
downvote count: 0

http://stackoverflow.com/comment/87151195
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50064950
has text: `Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),))`

http://stackoverflow.com/q/49997560
has comment: http://stackoverflow.com/comment/87011725
tagged with: wordnet
has comment: http://stackoverflow.com/comment/87013305
type: Question
answer count: 0
tagged with: nltk
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27943396
has comment: http://stackoverflow.com/comment/87011668
has comment: http://stackoverflow.com/comment/87057272
has body: I'm trying to use Affect WordNet to use the different emotions that are implemented within, like: anger, dislike, fear negative-fear, joy, sad etc. I found a code sample for that on the library: https://github.com/clemtoy/WNAffect from wnaffect import WNAffect import nltk nltk.download('dict') wna = WNAffect('wordnet-1.6/', 'wn-domains-3.2/') emo = wna.get_emotion('angry', 'JJ') print(emo) I tested it and I got this error: Resource dict not found. Please use the NLTK Downloader to obtain the resource: import nltk nltk.download('dict') I tried to use NLTK downloader to download it, but nothing there ! A similar question was asked before here: Extract “emotion words” / affect words from english corpus? but they solved it by using sentiwordNet to retrieve the negative and the positive scores !
tagged with: python
has title: Extract different emotions for words Affect WordNet
score: 0
has comment: http://stackoverflow.com/comment/87015248
linked to: http://stackoverflow.com/q/9653815

http://stackoverflow.com/comment/86937719
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49960015
has text: I'm not sure I know what you mean by "account", but maybe [django-allauth](https://github.com/pennersr/django-allauth) can help you.

http://stackoverflow.com/a/50021353
score: 0
has comment: http://stackoverflow.com/comment/87060020
type: Answer
has comment: http://stackoverflow.com/comment/87058752
answers question: http://stackoverflow.com/q/50020949
has comment: http://stackoverflow.com/comment/87060559
has comment: http://stackoverflow.com/comment/87060218
has comment: http://stackoverflow.com/comment/87059928
accepted answer of: http://stackoverflow.com/q/50020949
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87059243
has comment: http://stackoverflow.com/comment/87060340
has body: You got the memory address, because the () is missing at the end. print(e2.get_name) -&gt; &lt;bound method s.get_name of ... print(e2.get_name()) -&gt; Bill The other q: class s(object): def __init__(self, name): self._name = name def get_name(self): return str(self._name) def __repr__(self): return str(self._name) def val(x): #This used in place of a lambda return x[0]._name.lower() e1 = s("Fred") e2 = s("Bill") list1 = [(e1, 3), (e2, 4)] for n in list1: print(val(n)) list2 = sorted(list1, key = val) print(list2[0] == e2) Out: fred bill [(Bill, 4), (Fred, 3)] False The False is because the compare check the tuple for the object. If you change it to list2[0][0] == e2, it will return True
has comment: http://stackoverflow.com/comment/87059363

http://stackoverflow.com/q/50070410
favorite count: 0
type: AnsweredQuestion
tagged with: ordereddictionary
score: 1
tagged with: mysql
accepted answer: http://stackoverflow.com/a/50070440
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50070440
has body: I am trying to insert an ordered dict into mysql and think I am missing one simple item. sql_command = """CREATE TABLE asdf ( id INTEGER PRIMARY KEY, description TEXT(100), data_value TEXT(100));""" cursor.execute(sql_command) for id, p in enumerate(info): format_str = """INSERT INTO asdf (id, description, data_value) VALUES ({id}, '{description}', '{data_value}');""" sql_command = format_str.format(id=id, description=p[0], data_value=p[1]) print(sql_command) this actually does 95% of what I want however, for some reason it is only printing the first two letters of the first 'item' so if 'info' is the data below OrderedDict([('name', 'bob'), ('favorite food', 'pizza')]) it prints out the following INSERT INTO asdf (id, description, data_value) VALUES (0, 'n', 'a'); INSERT INTO asdf (id, description, data_value) VALUES (1, 'f', 'a'); but I want it to print the following INSERT INTO asdf (id, description, data_value) VALUES (0, 'name', 'bob'); INSERT INTO asdf (id, description, data_value) VALUES (1, 'favorite food', 'pizza'); thoughts?
has title: When formatting my sql-insert statement from ordereddict, the data is only 1 char, not the key/value from ordereddict
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87157495
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87183877
comment on: http://stackoverflow.com/a/50074720
type: Comment
score: 0
type: AnswerComment
has text: @QuantumEnergy AFAIK, it _uses_ Windows named pipes (and UNIX sockets on Unix) to provide a much simpler abstraction than generic named pipes. Am I wrong? Can you actually access any of the features of named pipes with a `Listener`? Because if so, that would be pretty cool.

http://stackoverflow.com/comment/86858659
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49921289
type: AnswerComment
has text: The answer which jpp has provided below works and so does your answer this : **pd.to_numeric(df['deposit_amount'].replace(',','', regex=True), errors='coerce', downcast='float')**

http://stackoverflow.com/comment/86930946
type: AnswerComment
score: 0
has text: @ArthurQ Not directly, but you could create two arrays, one for all x's and one for all y's. If done right, this could be encapsulated in a `PointArray` class that hides the gory details. But please ask a separate question about details of that, because adding this new requirement renders all existing answers obsolete.
type: Comment
comment on: http://stackoverflow.com/a/49956832

http://stackoverflow.com/comment/87033372
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50008364
type: Comment
has text: In Python, violating the LSP often makes sense—but violating it with an ABC almost never does. You’re going out of your way to say “This class really is a subtype that implements this interface”. So, I think the answer should focus more on ABC and abstractmethod and what they’re intended to mean, rather than generalities.

http://stackoverflow.com/comment/87126242
score: 1
has text: @PeterKirby Whether it's more or less Pythonic than if-else ultimately comes down to how decoupled the generic "stuff" is from everything else. Which is impossible to guess from the OP's toy example. But there are definitely uses for both designs (not to mention for a subclass-based design)—if not, PEP 443 would never have been accepted (and then used in the stdlib).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50054871

http://stackoverflow.com/a/49949322
answers question: http://stackoverflow.com/q/49949239
type: Answer
has comment: http://stackoverflow.com/comment/86915196
upvote count: 3
downvote count: 0
has body: Put a * before the argument. def my_sum(*args): total = 0 for arg in args: total += arg return total Now you can call it like my_sum(1, 2, 3, 4, 5).
score: 3

http://stackoverflow.com/q/50071189
tagged with: wiringpi
answer count: 1
has title: WiringPi ODROID C2 Python reading analogue input
type: Question
has body: The ODROID C2 is a board similar to the Raspberry PI. I have installed and configured WiringPi as specified by the website for my board. Running gpio readall returns the table: +------+-----+----------+------+ Model ODROID-C2 +------+----------+-----+------+ | GPIO | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | GPIO | +------+-----+----------+------+---+----++----+---+------+----------+-----+------+ | | | 3.3v | | | 1 || 2 | | | 5v | | | | | 8 | SDA.1 | | | 3 || 4 | | | 5V | | | | | 9 | SCL.1 | | | 5 || 6 | | | 0v | | | | 249 | 7 | GPIO.249 | IN | 1 | 7 || 8 | | | TxD1 | 15 | | | | | 0v | | | 9 || 10 | | | RxD1 | 16 | | | 247 | 0 | GPIO.247 | IN | 1 | 11 || 12 | 1 | IN | GPIO.238 | 1 | 238 | | 239 | 2 | GPIO.239 | IN | 1 | 13 || 14 | | | 0v | | | | 237 | 3 | GPIO.237 | IN | 1 | 15 || 16 | 1 | IN | GPIO.236 | 4 | 236 | | | | 3.3v | | | 17 || 18 | 1 | IN | GPIO.233 | 5 | 233 | | 235 | 12 | GPIO.235 | IN | 1 | 19 || 20 | | | 0v | | | | 232 | 13 | GPIO.232 | IN | 1 | 21 || 22 | 1 | IN | GPIO.231 | 6 | 231 | | 230 | 14 | GPIO.230 | IN | 1 | 23 || 24 | 1 | IN | GPIO.229 | 10 | 229 | | | | 0v | | | 25 || 26 | 1 | OUT | GPIO.225 | 11 | 225 | | | 30 | SDA.2 | | | 27 || 28 | | | SCL.2 | 31 | | | 228 | 21 | GPIO.228 | IN | 1 | 29 || 30 | | | 0v | | | | 219 | 22 | GPIO.219 | IN | 1 | 31 || 32 | 1 | IN | GPIO.224 | 26 | 224 | | 234 | 23 | GPIO.234 | IN | 0 | 33 || 34 | | | 0v | | | | 214 | 24 | GPIO.214 | IN | 1 | 35 || 36 | 1 | IN | GPIO.218 | 27 | 218 | | | 25 | AIN.1 | | | 37 || 38 | | | 1v8 | 28 | | | | | 0v | | | 39 || 40 | | | AIN.0 | 29 | | +------+-----+----------+------+---+----++----+---+------+----------+-----+------+ I am attempting to read input from the analogue pin #25 for the wiring pi column (second from the bottom on the left). Here is the code for the script: #!/usr/bin/python import wiringpi2 as wpi import time wpi.wiringPiSetup() while True: print(wpi.analogRead(25)) #use pin 25 for analogue input Why is it only returning 0? My phone is connect…
has answer: http://stackoverflow.com/a/50184054
tagged with: python
tagged with: odroid
accepted answer: http://stackoverflow.com/a/50184054
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49949508
has comment: http://stackoverflow.com/comment/86915636
has comment: http://stackoverflow.com/comment/86915714
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49950117
has answer: http://stackoverflow.com/a/49951853
has body: Below is my stab at it, but it is not getting it right. There is a lot more in my "text" file, but I would like to get the vlan and ports: Attempt for Python: ([\d])+\W+[a-zA-Z]+\W+[A-Za-z]+\W+|[\w+]+([\d])/([\d]) Output: Vlan 1 Et0/1 Vlan 1 Et0/3 Vlan 1 Et0/4 Vlan 1 Et0/5 Vlan 1 Et0/6 Vlan 1 Et0/7 Vlan 2 Et0/0 Vlan 3 Et0/2 From this...... asa# Show switch vlan VLAN Name Status Ports ---- -------------------------------- --------- ----------------------------- 1 inside up Et0/1, Et0/3, Et0/4, Et0/5 Et0/6, Et0/7 2 outside up Et0/0 3 dmz up Et0/2
has comment: http://stackoverflow.com/comment/86915660
has title: How to write a reg ex for show vlan
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: regex

http://stackoverflow.com/q/49967727
type: UnansweredQuestion
has title: Cannot resolve keyword 'slug' into field. Choices are: body, comments, date, id, title
tagged with: django
has answer: http://stackoverflow.com/a/49967859
type: Question
has comment: http://stackoverflow.com/comment/86951256
has body: HI I have a problem with writing a comment on a post pls help me. Here is my urls from django.conf.urls import url from django.views.generic import ListView, DetailView from forum.models import Post from . import views from .views import createPost urlpatterns = [ url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="forum/forum.html")), url(r'^(?P&lt;pk&gt;\d+)$', DetailView.as_view(model=Post, template_name='forum/post.html')), url(r'^createPost/', createPost.as_view(), name='createPost'), url(r'^(?P&lt;slug&gt;[-\w]+)/comment/$', views.add_comment, name='add_comment') ] And here is my views from django.shortcuts import render, redirect from .forms import PostForm from django.views.generic import TemplateView from .forms import CommentForm from django.shortcuts import get_object_or_404 from .models import Post class createPost(TemplateView): template_name = 'forum/createPost.html' def get(self, request): form = PostForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = PostForm(request.POST) if(form.is_valid()): form.save() return redirect('/forum') def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) if(request.method == "Post"): form = CommentForm(request.Post) if(form.is_valid()): comment = form.save(commit=False) comment.post = post comment.save() return redirect('/forum/createPost', slug=post.slug) else: form = CommentForm() template = 'forum/addComment.html' context = {'form': form} return render(request, template, context) And lastly here is my models from django.db import models class Post(models.Model): title = models.CharField(max_length=140) body = models.CharField(max_length=500) date = models.DateTimeField() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=None) com_title = models.CharField(max_length=140) com_body = models.CharField(max_length=500) def __str__(self)…
linked to: http://stackoverflow.com/q/427102
has answer: http://stackoverflow.com/a/69257252
has answer: http://stackoverflow.com/a/49967865
answer count: 3
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86951062

http://stackoverflow.com/comment/86934907
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49956409
has text: This looks promising, but the result from printing `future.result()` is list of empty lists: `[[], [], [], [], [], [], [], [], [], []]`

http://stackoverflow.com/q/49998451
type: AnsweredQuestion
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/47730967
downvote count: 0
linked to: http://stackoverflow.com/q/41424918
linked to: http://stackoverflow.com/q/1307378
tagged with: mysql
has title: Simple "CREATE" or "DROP TABLE" fails with PyMySQL and parameter replacement
type: Question
has body: I'm basically using the following code to drop an existing table using Python 3.6 and PyMySQL, with a MySQL 5.7 database: connection = pymysql.connect( host=host, user=username, password=password, db=database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) table_name = "video_playback_statistics" sql = "DROP TABLE IF EXISTS %s" params = (table_name,) with connection.cursor() as cursor: cursor.execute(sql, params) I get the following error: pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''video_playback_statistics'' at line 1" I've successfully executed other, more complicated SQL statements with more parameters, but this simple one does not work. When I run the SQL command without parametrization, it works fine: cursor.execute('DROP TABLE IF EXISTS video_playback_statistics') I've looked at the following questions: 1064, "You have an error in your SQL syntax;..." Python MySQL pymysql return error SQL syntax But these kinds of queries seem to work fine. Also I've seen this: Python MYSQL update statement But here the table name is directly written into the string.
answer count: 1
tagged with: pymysql
tagged with: python
linked to: http://stackoverflow.com/q/39965697
favorite count: 0
has answer: http://stackoverflow.com/a/49998482
accepted answer: http://stackoverflow.com/a/49998482

http://stackoverflow.com/comment/86867682
score: 0
has text: Worked perfectly, and the invalid default to NaN will help a ton. I need to look into using map() more. Thanks for the answer!
type: Comment
comment on: http://stackoverflow.com/a/49925676
type: AnswerComment

http://stackoverflow.com/comment/86888623
type: Comment
type: QuestionComment
has text: Can you add some sample data for testing? But this [graph](http://pandas.pydata.org/pandas-docs/stable/indexing.html#performance-of-query) explain `query` should be faster in large data.
comment on: http://stackoverflow.com/q/49936557
score: 1

http://stackoverflow.com/a/50026435
accepted answer of: http://stackoverflow.com/q/49988464
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49988464
score: 0
has body: I figured out my problem. pip install . Inside the project directory is actually giving me the wanted output, but problem is that I didn't nest the name of my package inside project. Think, I have project foo, and I want to have imports such as: from foo import bar Well I had project named foo but I didn't have first package named foo rather I had straight away bar and all other packages, so that was the mistake.
type: Answer

http://stackoverflow.com/comment/87122867
has text: I remember that we used [antlr](http://www.antlr.org/index.html) in a Java project to parse XPaths. I believe it’s available for Python too.
score: 0
comment on: http://stackoverflow.com/q/50053021
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49924180
answers question: http://stackoverflow.com/q/49921053
type: Answer
has body: Add the following configuration parameters at the top of your code. Note that userpass must consist of both the db username and password. socket is the location of the mysql socket file in the XAMPP directory. app.config['SECRET_KEY'] = 'some secret string here' userpass = 'mysql+pymysql://root:@' basedir = '127.0.0.1' dbname = '/nameofdatabase' socket = '?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock' dbname = dbname + socket app.config['SQLALCHEMY_DATABASE_URI'] = userpass + basedir + dbname app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
score: 0

http://stackoverflow.com/a/49988864
answers question: http://stackoverflow.com/q/49988766
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: I guess you run into problems, as your file is called "/Users/jim/PycharmProject/untitled/matplotlib.py" and you have a naming conflict there. Try to rename it to sth else and rerun.

http://stackoverflow.com/a/50034599
score: 0
has comment: http://stackoverflow.com/comment/87092584
has body: You should use either DictReader from CSV Module or read_csv from pandas module I recommend pandas module as you also perform operations on your data using. import pandas as pd df = pd.read_csv("test_results.csv") df will contain your CSV table as is, no need to convert to floats or integers
answers question: http://stackoverflow.com/q/50034477
type: Answer

http://stackoverflow.com/comment/87109680
has text: There are dates in the desired `Date2` column which are not in the (given) first or second DataFrame. How are the `Value`s being determined here?
score: 1
comment on: http://stackoverflow.com/q/50045805
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87163671
comment on: http://stackoverflow.com/q/50073653
type: QuestionComment
score: 0
type: Comment
has text: You seem to be defining the `shotype` variable *after* the if statement that's supposed to check it.

http://stackoverflow.com/a/50024138
answers question: http://stackoverflow.com/q/50023744
has comment: http://stackoverflow.com/comment/87065318
score: 1
has comment: http://stackoverflow.com/comment/87064617
type: Answer
has body: I believe need change condition with chain condition for compare E and for second group by A use factorize, for second group use &gt;0: def eleven(g): cond = (g.B.dt.hour==11) &amp; (g.E.ge(20) &amp; pd.factorize(g.A)[0]) &gt; 0 if cond.any(): return g[cond].iloc[0] else: return g.iloc[0] r = df.groupby('C', as_index=False, sort=False).apply(eleven) print (r) A B C D E 0 2002-01-12 2018-04-25 10:00:00 John 19 19 1 2002-01-26 2018-04-25 11:00:00 George -8 22
accepted answer of: http://stackoverflow.com/q/50023744
has comment: http://stackoverflow.com/comment/87064633
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87065294
type: AcceptedAnswer

http://stackoverflow.com/comment/87080756
type: Comment
type: QuestionComment
has text: numba will fail to compile the code if it includes function calls to non-Python code, which usually happens if you call numpy functions. If you re-wrote cost_fn_delta to use Python code only (and avoid numpy), numba should be able to JIT it.
comment on: http://stackoverflow.com/q/50027782
score: 0

http://stackoverflow.com/comment/86879721
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49928582
has text: You can use reshape to do that aswell! aMatrix = numpy.reshape(aVector,2,3)
type: AnswerComment

http://stackoverflow.com/comment/87339417
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49941825
has text: Please share the code you are running and please also tell us on what platform (hardware, operating system, Python version, and so forth) you are running that code?

http://stackoverflow.com/a/50062917
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87142393
answers question: http://stackoverflow.com/q/50062474
downvote count: 0
has body: Although i agree with the comments that knowing the details of the file would be essential to providing an actual working answer, i had a similar issue and resolved it using pandas. The .read_csv method of pandas will use the csv reader to only partially read the csv files without loading the whole file into memory. Best is to do some trial and error and see how many rows at a time is your system able to support import pandas as pd num_rows = 6000 # or some value which depends on system memory NewDf1 =pd.DataFrame() NewDf2 = pd.DataFrame() for i in range(start,stop,num_rows): rawdata_df = pd.read_csv(filename,skiprows=range(1,i),nrows=num_rows) NewDf1.append(rawdata_df[rawdata_df.iloc[1]&gt;0],ignore_index=True) NewDf2.append(rawdata_df[rawdata_df.iloc[2]&gt;0],ignore_index=True) At the end depending on your actual system memory and structure of files (because the size of dataframe depends also on number of columns and structure of data) you can save the separate dataframes in separate csvs if len(NewDf1) &gt; toolarge: NewDf1.to_csv('newdf1Filename.csv')
has comment: http://stackoverflow.com/comment/87142807
upvote count: 1

http://stackoverflow.com/a/63182788
score: 20
answers question: http://stackoverflow.com/q/49943410
has body: The following solution worked for me : Go to run. Type %appdata% Go to the folder pip and edit the pip.ini file. If the folder doesn't exist create one and also create a pip.ini file and edit in a text editor. Add the following : [global] trusted-host = pypi.python.org pypi.org files.pythonhosted.org raw.githubusercontent.com github.com
downvote count: 0
upvote count: 20
type: Answer
has comment: http://stackoverflow.com/comment/137930970

http://stackoverflow.com/comment/86994853
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49988638
type: QuestionComment
has text: i simply want a different flag for each instance

http://stackoverflow.com/comment/87092134
type: QuestionComment
type: Comment
has text: what would you expect if you compare 'filename1' and '1696' ?
score: 3
comment on: http://stackoverflow.com/q/50037992

http://stackoverflow.com/q/49925374
has answer: http://stackoverflow.com/a/49925884
has answer: http://stackoverflow.com/a/49926589
tagged with: python
has body: I found a piece of code in Chapter 7,Section 1 of deep Deep Learning with Python as follow： from keras.models import Model from keras import layers from keras import Input text_vocabulary_size = 10000 question_vocabulary_size = 10000 answer_vocabulary_size = 500 # Our text input is a variable-length sequence of integers. # Note that we can optionally name our inputs! text_input = Input(shape=(None,), dtype='int32', name='text') # Which we embed into a sequence of vectors of size 64 embedded_text = layers.Embedding(64, text_vocabulary_size)(text_input) # Which we encoded in a single vector via a LSTM encoded_text = layers.LSTM(32)(embedded_text) # Same process (with different layer instances) for the question question_input = Input(shape=(None,), dtype='int32', name='question') embedded_question = layers.Embedding(32, question_vocabulary_size)(question_input) encoded_question = layers.LSTM(16)(embedded_question) # We then concatenate the encoded question and encoded text concatenated = layers.concatenate([encoded_text, encoded_question], axis=-1) # And we add a softmax classifier on top answer = layers.Dense(answer_vocabulary_size, activation='softmax')(concatenated) # At model instantiation, we specify the two inputs and the output: model = Model([text_input, question_input], answer) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc']) as you see this model's input don't have raw data's shape information, then after Embedding layer, the input of LSTM or the output of Embedding are some variable length sequence. So I want to know: in this model, how keras to determine the number of lstm_unit in LSTM layer how to deal with variable length sequence Additional information: in order to explain what lstm_unit is (I don't know how to call it,so just show it image):
score: 11
tagged with: lstm
has comment: http://stackoverflow.com/comment/86866750
upvote count: 11
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/86871363
tagged with: deep-learning
downvote count: 0
tagged with: machine-learning
has title: How LSTM deal with variable length sequence
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/49925884
possible better answer: http://stackoverflow.com/a/49926589
type: Question

http://stackoverflow.com/comment/87055247
type: Comment
comment on: http://stackoverflow.com/a/50019535
type: AnswerComment
has text: well i get the error - 'DatetimeProperties' object has no attribute 'stfrtime'
score: 0

http://stackoverflow.com/q/50007424
tagged with: keras
accepted answer: http://stackoverflow.com/a/50007615
has answer: http://stackoverflow.com/a/50007615
has comment: http://stackoverflow.com/comment/87031508
tagged with: conv-neural-network
possible better answer: http://stackoverflow.com/a/50007513
has comment: http://stackoverflow.com/comment/87031622
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87031387
has answer: http://stackoverflow.com/a/50007513
has title: How to train a CNN model on 2 classes of 100 samples each and then test it on 200 new samples?
has body: I've got 2 classes for my training set: Birds(100 samples) and no_birds(100) samples. And, the test set is unlabelled consisting of 200 test samples (mixed with birds and no_birds). For every sample in the test set I intend to classify it as bird or no_bird using CNN with Keras. import numpy as np import keras from keras import backend as K from keras.models import Sequential from keras.layers import Activation from keras.layers.core import Dense, Flatten from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.preprocessing.image import ImageDataGenerator from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import * from sklearn.metrics import confusion_matrix import itertools import matplotlib.pyplot as plt train_path = 'dataset/train_set' test_path = 'dataset/test_set' train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224,224), classes=['bird', 'no_bird'], batch_size=10) # bird directory consisting of 100 test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(224,224), classes=['unknown'], batch_size=10) model = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=(224,224,3)), Flatten(), Dense(2, activation='softmax'), ]) model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit_generator(train_batches, steps_per_epoch=20, validation_data=test_batches, validation_steps=20, epochs=10, verbose=2) Error I'm getting at the last step is this: ValueError: Error when checking target: expected dense_1 to have shape (2,) but got array with shape (1,) Now, I know it could be probably because of test_set having only 1 directory, since it's unlabelled. Correct me if I'm wrong. What should I do to make this work?
has comment: http://stackoverflow.com/comment/87031425
tagged with: tensorflow
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/q/50051919
score: 1
upvote count: 1
has body: I am trying to put all crud methods under one handler class in python Tornado framework. Post() and get() works, but for some reason carId cannot be defined. What is one way I can pass the id of the api endpoint to the method. endpoint for put and delete: api/cars/1 Error: TypeError: put() missing 1 required positional argument: 'carId' ERROR:tornado.access:500 PUT /api/cars/1 (::1) 0.50ms Methods: # Delete method that deletes data specified by HTTP client from database def delete(self, carId): try: data = json.loads(self.request.body) print(data) print("Deleting Car") id = data["id"] if not carId: return self.write({"success": False}) if not len(id): return self.write({"success": False}) c.execute( "DELETE FROM cars WHERE id=?",(carId)) self.write({"success": 200}) except: self.write({"success": False}) conn.commit() # Put route to edit an entity in DB. def put(self, carId): try: data = json.loads(self.request.body) print(data) print("Updating Cars table") id = data["id"] make = data["make"] model = data["model"] if not make or not model or not carId: return self.write({"success": False}) if not len(make) or not len(model): return self.write({"success": False}) c.execute( "UPDATE cars SET make=?, model=? WHERE id=?",(make, model, id)) self.write({"success": 200}) except: self.write({"success": False}) conn.commit() def verifyDatabase(): try: c.execute('SELECT * FROM cars') print('Table already exists') except: print('Creating table \'cars\'') c.execute('CREATE TABLE cars (\ id integer primary key,\ make text,\ model text)') print('Successfully created table \'cars\'') conn.commit() class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), (r"/api/cars/?", CarHandler), (r"/api/cars/[0-9]/?", CarHandler) ] tornado.web.Application.__init__(self, handlers) def main(): # Verify the database exists and has the correct layout verifyDatabase() app = Application() app.listen(80) IOLoop.instance().start() conn.close() if __name__ == '_…
tagged with: tornado
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87132536
has answer: http://stackoverflow.com/a/50082279
tagged with: api
has answer: http://stackoverflow.com/a/50096424
possible better answer: http://stackoverflow.com/a/50096424
tagged with: python
has title: How to get ID from url for Put route and Delete
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87132371
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50082279

http://stackoverflow.com/comment/87150431
type: Comment
type: AnswerComment
has text: Then I do not understand your question.
score: 1
comment on: http://stackoverflow.com/a/50066824

http://stackoverflow.com/comment/87051053
score: 0
has text: actually "n" is the tolerance. So it can be changed
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50016973

http://stackoverflow.com/a/50318363
type: Answer
answers question: http://stackoverflow.com/q/49984553
has body: I've investigated a little and found that there is a library for loading the files, called matrixconverters, you can load a PTV Visum matrix by using the following command: from matrixconverters.read_ptv import ReadPTVMatrix the_matrix = ReadPTVMatrix(filename="pathtoyourfile") That's a short answer, it works with some exports, not with others, depending on your format. The concrete MTX subformat is the text in the first line of your .mtx file, for example: $V;D3 format didn't work for me, but others did.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
accepted answer of: http://stackoverflow.com/q/49984553

syntactic-sugar
type: Tag
tags question: http://stackoverflow.com/q/49966596
tag name: syntactic-sugar
tags question: http://stackoverflow.com/q/49991840

http://stackoverflow.com/q/50009125
has comment: http://stackoverflow.com/comment/87035150
has comment: http://stackoverflow.com/comment/87035359
score: 0
has comment: http://stackoverflow.com/comment/87035236
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87035441
tagged with: python
type: Question
has title: SQLite Optimization (Python) : Finding duplicate entries, and then consolidating referenced values to a representative unique entry?
answer count: 0
has comment: http://stackoverflow.com/comment/87035070
type: UnansweredQuestion
has body: My problem is as follows: I have a list of entries in a file that is analogous to names and addresses in a phone book. This list is unordered, somewhere on the order of 1-10 billion entries long, and occupies 500gb on disk. I'd like to count how many times each name is represented in this file (i.e., how many duplicates there are for each name), and then concatenate all known addresses to that name. My first approach was to insert the entries with a try/except clause, and update if necessary (UPSERT?): c.execute('CREATE TABLE IF NOT EXISTS MYTable (Name TEXT PRIMARY KEY, Address TEXT) WITHOUT ROWID') try: c.execute(f'INSERT INTO MYTable (Name, Address) VALUES ("{thename}","{theaddress}"') except sqlite3.IntegrityError: c.execute(f'UPDATE MYTable SET Address = Address || "{theaddress}" WHERE Name = "{thename}"') And this performs the job at a rate of about 50,000 rows/s. However, I'm trying to make it go faster, as it will take about 50-60 hours to create the database with this approach. I've tried the following optimization attempts: PRAGMA journal_mode = WAL ; little effect PRAGMA synchrounous = off ; little effect beginning transactions/committing transactions manually ; little effect Removing the index, using executemany, adding the index back on, and then using the fast searches to find duplicates; ~2-4x faster to create the initial DB, but preserves the duplicates until they can be indexed and then collapsed into a single (name:address1,address2,address_n) representation. Also occupies a lot of space on disk. Is there something about either the approach I should change, or some optimization to solve this issue? Thanks for any help!
has comment: http://stackoverflow.com/comment/87035015
has comment: http://stackoverflow.com/comment/87035088
has comment: http://stackoverflow.com/comment/87034978
has comment: http://stackoverflow.com/comment/87035294
has comment: http://stackoverflow.com/comment/87035030

http://stackoverflow.com/q/49965818
has comment: http://stackoverflow.com/comment/91829639
tagged with: doc
type: Question
has comment: http://stackoverflow.com/comment/87010973
tagged with: http://stackoverflow.com/tag/docx
has comment: http://stackoverflow.com/comment/86949519
has answer: http://stackoverflow.com/a/63255120
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/63763402
has answer: http://stackoverflow.com/a/66108935
favorite count: 0
has body: I'm trying to find a way to convert a PDF file to a .docx file with Python. I have seen other posts related with this, but none of them seem to work correctly in my case. I'm using specifically import os import subprocess for top, dirs, files in os.walk('/my/pdf/folder'): for filename in files: if filename.endswith('.pdf'): abspath = os.path.join(top, filename) subprocess.call('lowriter --invisible --convert-to doc &quot;{}&quot;' .format(abspath), shell=True) This gives me Output[1], but then, I can't find any .docx document in my folder. I have LibreOffice 5.3 installed. Any clues about it? Thank you in advance!
has answer: http://stackoverflow.com/a/68719621
linked to: http://stackoverflow.com/q/49739245
has answer: http://stackoverflow.com/a/50218260
has comment: http://stackoverflow.com/comment/86992552
has comment: http://stackoverflow.com/comment/86948294
has title: Convert PDF to .docx with Python
upvote count: 9
has comment: http://stackoverflow.com/comment/89240846
has comment: http://stackoverflow.com/comment/86947755
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/77823866
tagged with: python
tagged with: libreoffice
answer count: 6
score: 7

http://stackoverflow.com/q/49984173
has body: I am trying to make a real-time searching algorithm in GUI with tkinter in Python 3. So I have this window and entry box for typing keywords in for searching: from tkinter import * root = Tk() root.geometry('800x400') root.resizable(False,False) root.title('Window') var = StringVar() root.SearchBox = ttk.Entry(root, textvariable=var, font='Fixedsys 28') root.SearchBox.place(relx=0.5, rely=0.5, height=50, width=400, anchor="center") search_input = var.get() What should I put here, without an enter button for the search box ...Some codes here... To get the following results? When the tkinter window is already open and some keywords typed into the search entry box &gt;&gt;&gt;print(search_input) Search Terms and as soon as the search entry box search_input =! '' how could I get a global variable to change, say is_entry_box_empty = False to is_entry_box_empty = True I found this to be impossible without threading, since the GUI window will block any codes after it. Many thanks
answer count: 1
type: Question
tagged with: python-3.x
tagged with: tkinter
has title: Automatically Update a Variable from Tkinter Entry Widget
tagged with: python
has answer: http://stackoverflow.com/a/49984980
accepted answer: http://stackoverflow.com/a/49984980
type: AnsweredQuestion
score: 0

unicode
tags question: http://stackoverflow.com/q/49987163
tags question: http://stackoverflow.com/q/50030944
tags question: http://stackoverflow.com/q/50004087
tags question: http://stackoverflow.com/q/49957069
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/50015521
tags question: http://stackoverflow.com/q/49938517
tags question: http://stackoverflow.com/q/49958062
tags question: http://stackoverflow.com/q/49955795
tags question: http://stackoverflow.com/q/50008296
tags question: http://stackoverflow.com/q/50001268
tags question: http://stackoverflow.com/q/49997503
tags question: http://stackoverflow.com/q/49958287
tags question: http://stackoverflow.com/q/49962659
tags question: http://stackoverflow.com/q/49930710
tags question: http://stackoverflow.com/q/50024626
tags question: http://stackoverflow.com/q/50060231
tags question: http://stackoverflow.com/q/50035082
tags question: http://stackoverflow.com/q/49968074
tags question: http://stackoverflow.com/q/50025219

http://stackoverflow.com/comment/87143212
type: AnswerComment
has text: TypeError: must be str, not int
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50063244

http://stackoverflow.com/q/50048105
has answer: http://stackoverflow.com/a/50048152
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/50048159
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87112470
has answer: http://stackoverflow.com/a/50048383
type: Question
has title: Python: check if last value of list occurs more than once
tagged with: python
has comment: http://stackoverflow.com/comment/87112721
has comment: http://stackoverflow.com/comment/87112360
has body: Problem: Write a program that will search through a list to see if the last value in the list occurs more than once. If the last value occurs more than once, return true. Otherwise, return false. If the list is empty, return false. My Code: def go(list1): for i in range(0,len(list1)): if list1[i] is list1[-1:]: return True else: return False print ( go( [-99,1,2,3,4,5,6,7,8,9,10,5] ) ) print ( go( [10,9,8,7,6,5,4,3,2,1,9] ) ) print ( go( [10,20,30,40,50,-11818,40,30,20,10] ) ) print ( go( [32767] ) ) print ( go( [7,7,7,7] ) ) print ( go( [9,10,-88,100,-555,1000] ) ) print ( go( [10,10,10,11,456,10,10] ) ) print ( go( [-111,1,2,3,9,11,20,30] ) ) print ( go( [9,8,7,6,5,4,3,2,0,-2,9,9] ) ) print ( go( [12,15,18,21,23,1000] ) ) print ( go( [250,19,17,15,13,11,10,9,6,3,2,1,250] ) ) print ( go( [] ) ) My Output: False False False False False False False False False False False False Desired Output: True True True False True False True False True False True False What am I doing wrong? Why am I getting False for all my outputs?
accepted answer: http://stackoverflow.com/a/50048152
tagged with: list
possible better answer: http://stackoverflow.com/a/50048159

http://stackoverflow.com/comment/87119149
type: AnswerComment
score: 0
type: Comment
has text: I see what you did. It might be slow if file gets bigger but It works for me so I will take it. Thank you
comment on: http://stackoverflow.com/a/50051361

http://stackoverflow.com/comment/87051629
has text: It is a positive lookahead. It does not consume chars, so there is no need making `W` optional. I added the information to [my answer](https://stackoverflow.com/a/50016565/3832970).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50016381
score: 0

http://stackoverflow.com/q/49980255
has comment: http://stackoverflow.com/comment/86977416
accepted answer: http://stackoverflow.com/a/49980664
has comment: http://stackoverflow.com/comment/86977581
answer count: 1
has answer: http://stackoverflow.com/a/49980664
has comment: http://stackoverflow.com/comment/86977190
type: Question
has body: I am splitting x variable (string) in based on * and then ; and return out all info. I tried so for below and it give only own1 info. so basically I want to split and iterating on all over instance and return two items which will then go into OS.Path.Join(path,own1,OwnAdd1) to make folder/subfolder x= 'own1;own1Add*own2;ownAdd2*own3:ownAdd' def cleanAndMakeSubfolder(x) : for x in x.split("*"): Owner= x.split(";") [0].replace(" ","_").strip() count = x.split(";")[1].count(" ")-1 OwnerADD = x.split(";")[1].replace(",","_") .replace(" ","_",count).replace('"',"").replace("(","").strip() return Owner,OwnerADD print cleanAndMakeSubfolder(x)
has title: Splitting and iterating on all over instance and return two items
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50009143
has comment: http://stackoverflow.com/comment/87034880
tagged with: python
has body: I am in need of some guidance and/or help! I have a dataframe that has a unique observation for each row. There is a variable that has THE APPEARANCE of nested lists as the observation but is actually a string. For example: Var1 [X, Y, [Z, A, B]] [A, [R,S,T]] [B] What I need is to append a variable/series that has the count of the number of items within that list. So for example: Var2: 5 4 1 The values are strings and I need a count not a sum. That the lists are nested is irrelevant, each item separated by a comma is considered 1 count. Thanks so much! I don't know if I'm searching the wrong terms, but any time I do a length statement (whether I use for loops or not), I get the length of characters, not the length of items. ETA: Realized that it's actually a string for the observations.
has title: Count items in list when each observation is a string that looks like a list
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50009267
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87035588
has comment: http://stackoverflow.com/comment/87035648
favorite count: 0
has comment: http://stackoverflow.com/comment/87035147
linked to: http://stackoverflow.com/q/27761463
tagged with: pandas

http://stackoverflow.com/comment/87100557
comment on: http://stackoverflow.com/q/50041938
type: QuestionComment
has text: looks like a character encoding issue that your browser and python don't think it's the same encoding.
score: 0
type: Comment

http://stackoverflow.com/comment/87137206
score: 0
type: Comment
has text: Hi @hpaulj, thanks for explaining this. Can you please clarify - When we are reshaping a 2d into 3d, in what sequence the elements of 2d array will be placed into different dimensions.
type: AnswerComment
comment on: http://stackoverflow.com/a/50055299

http://stackoverflow.com/comment/87056592
type: Comment
score: 0
has text: Your "`res2` of shape `(10000, 10)`" idea is the right way to do this. You say you tried and it is too slow. Show us your code for that. Also, what is the real maximum size of the data, and how much RAM do you have?
comment on: http://stackoverflow.com/q/50020336
type: QuestionComment

http://stackoverflow.com/q/49936222
has comment: http://stackoverflow.com/comment/86888776
has answer: http://stackoverflow.com/a/60962926
has answer: http://stackoverflow.com/a/64885693
has comment: http://stackoverflow.com/comment/86888906
has title: An Efficient Sieve of Eratosthenes in Python
tagged with: python
has comment: http://stackoverflow.com/comment/86889756
has comment: http://stackoverflow.com/comment/86889701
tagged with: sieve-of-eratosthenes
linked to: http://stackoverflow.com/q/20228805
upvote count: 12
linked to: http://stackoverflow.com/q/2068372
score: 12
has comment: http://stackoverflow.com/comment/86889052
has comment: http://stackoverflow.com/comment/86890027
downvote count: 0
has answer: http://stackoverflow.com/a/79105449
has comment: http://stackoverflow.com/comment/86888818
has answer: http://stackoverflow.com/a/79106534
answer count: 7
has comment: http://stackoverflow.com/comment/86888143
has comment: http://stackoverflow.com/comment/86888186
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86888191
tagged with: numpy
has comment: http://stackoverflow.com/comment/86888412
has answer: http://stackoverflow.com/a/49936915
has answer: http://stackoverflow.com/a/78566917
has answer: http://stackoverflow.com/a/64638229
has body: This very short and simple code in #Python tries to simulate the "Sieve of Eratosthenes" for the first N natural numbers with the constraints of (0) script shortness; (1) minimization of the 'if statements' and 'for/while loops'; (2) efficiency in terms of CPU time. import numpy as np N = 10**5 a = np.array(range(3,N,2)) for j in range(0, int(round(np.sqrt(N),0))): a[(a!=a[j]) &amp; (a%a[j] == 0)] = 0 a = a[a!=0] a = [2]+list(a) On an Intel Core I5, it returns the prime numbers among the first: N = 100,000 in 0.03 seconds; N = 1,000,000 in 0.63 seconds; N = 10,000,000 in 22.2 seconds. Would someone like to share more efficient codes in term of CPU time within the aforementioned constraints?
type: UnansweredQuestion

http://stackoverflow.com/a/49988153
has body: I guess you will like this when it works. There were just some minor issues with the loops and placement of the time function. In your case, you placed a second while loop to initiated the timer. Hence the code kept looping in there. That is why (as @api55 mentioned) the timer was NOT running in the background. Rather upon detection of a face it started a loop and kept counting seconds. Here is the code: import numpy as np import cv2 import time path = '/Desktop/Stack/face_detection/' face_cascade = cv2.CascadeClassifier(path + 'haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(path + 'haarcascade_eye.xml') cap = cv2.VideoCapture(0) Sec = 0 Min = 0 while 1: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) if len(faces) &gt; 0: Sec += 1 print(str(Min) + " Mins " + str(Sec) + " Sec ") cv2.putText(img, "Time: " + str(Min) + " Mins " + str(Sec) + " Sec ", (0,img.shape[0] -30), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,0,255), 1) cv2.putText(img, "Number of faces detected: " + str(faces.shape[0]), (0,img.shape[0] -10), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,0,255), 1) time.sleep(1) if Sec == 60: Sec = 0 Min += 1 print(str(Min) + " Minute") if len(faces) == 0: print('No face detected') cv2.putText(img, "No face detected ", (0,img.shape[0] -10), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,0,255), 1) Sec = 0 Min = 0 cv2.imshow('img',img) k = cv2.waitKey(30) &amp; 0xff if k == 27: break cap.release() cv2.destroyAllWindows() Hope this is what you expected !!
score: 1
answers question: http://stackoverflow.com/q/49986150
accepted answer of: http://stackoverflow.com/q/49986150
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/86931274
type: QuestionComment
has text: There's nothing that does this automatically. Most functions are not reversible like this, so there's not much value in it.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49957573

http://stackoverflow.com/q/50050739
linked to: http://stackoverflow.com/q/34735659
tagged with: macos
type: Question
tagged with: terminal
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/87138800
tagged with: python
has comment: http://stackoverflow.com/comment/87138515
has comment: http://stackoverflow.com/comment/87137266
has comment: http://stackoverflow.com/comment/87137223
has title: python manage.py migrate Segmentation fault: 11
score: 0
has body: Specs: OS: macOS High Sierra 10.13.2 Interpeter: Python 3.6.5 When i run the command sudo python manage.py migrate or sudo python manage.py runserver this is the output i get: Segmentation fault: 11 Django: 'python manage.py runserver' gives "Segmentation fault" error There is another post out there with similar questions and suggestions but its never resolved. And i tried suggestions from there but none of it worked out for me. This is part of my settings.py file regarding migration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoproject', 'USER': 'root', 'PASSWORD': 'test123', 'HOST': '/Applications/MAMP/tmp/mysql/mysql.sock', 'PORT': '3306' } } Any new suggestions? I am stuck. EDIT: error also occurs with pip3 or python3 When i run sudo python3 manage.py runserver
answer count: 0
has comment: http://stackoverflow.com/comment/87121747

http://stackoverflow.com/a/55131881
score: 7
answers question: http://stackoverflow.com/q/49926147
type: Answer
has comment: http://stackoverflow.com/comment/114237194
downvote count: 0
has body: Quoting seaborn's documentation for violinplot: linewidth : float, optional Width of the gray lines that frame the plot elements. So it looks pretty hardcoded. As a matter of fact, quoting seaborn's draw violins code: def draw_violins(self, ax): """Draw the violins onto `ax`.""" fill_func = ax.fill_betweenx if self.orient == "v" else ax.fill_between for i, group_data in enumerate(self.plot_data): kws = dict(edgecolor=self.gray, linewidth=self.linewidth) So I guess you can't do that easily with seaborn's API. Or if you're into hacking/monkey patching the seaborn's classes ... import seaborn.categorical seaborn.categorical._Old_Violin = seaborn.categorical._ViolinPlotter class _My_ViolinPlotter(seaborn.categorical._Old_Violin): def __init__(self, *args, **kwargs): super(_My_ViolinPlotter, self).__init__(*args, **kwargs) self.gray='red' seaborn.categorical._ViolinPlotter = _My_ViolinPlotter import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks", color_codes=True) tips = sns.load_dataset("tips") g = sns.FacetGrid(tips, col="time", row="smoker") g.map(sns.violinplot, "tip") plt.show() However, seaborn's FacetGrid is based on matplotlib's subplots. Maybe there is a trick to change the diagram once it is prepared for drawing.
upvote count: 7

http://stackoverflow.com/comment/87067604
type: QuestionComment
comment on: http://stackoverflow.com/q/50025331
type: Comment
has text: Might be worth checking: if you are using pip, try to run `pip install --upgrade pip` before running again and see if https://bhch.github.io/posts/2017/04/fix-the-pip-error-couldnt-find-a-version-that-satisfies-the-requirement/ applies to your case (it's hard for me to tell what would work without more details).
score: 0

themes
type: Tag
tag name: themes
tags question: http://stackoverflow.com/q/49943847

http://stackoverflow.com/comment/86859167
type: AnswerComment
comment on: http://stackoverflow.com/a/49920455
score: 1
type: Comment
has text: @KeyurPotdar: an argument of `enumerate` which I hadn't seen before – thanks!

http://stackoverflow.com/a/50048241
answers question: http://stackoverflow.com/q/50047929
score: 0
has comment: http://stackoverflow.com/comment/87124431
has comment: http://stackoverflow.com/comment/87121944
has body: You can create an instannce without keypair however you will not be able to ssh into it or you can start it with ssm agent installed and running and use ec2 ssm service to send shell commands.
has comment: http://stackoverflow.com/comment/87124404
has comment: http://stackoverflow.com/comment/87112629
type: Answer
has comment: http://stackoverflow.com/comment/87112806

http://stackoverflow.com/q/49981835
tagged with: python
has answer: http://stackoverflow.com/a/49983631
favorite count: 0
tagged with: optimization
score: 2
tagged with: performance
has title: Python / C++ Fast Gaussian Fit on 4 points
has comment: http://stackoverflow.com/comment/86979885
tagged with: curve-fitting
tagged with: c++
type: Question
upvote count: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I'm trying to do gaussion peak rekonstruktion. The special thing is I need to fit to only 4 points and I need to do that very fast. At the moment I'm using python with scipy curve_fit. It takes about 0.5ms/peak. Has someone a good idea how to speed that up? (beside parallelization) Are there faster things than curve_fit? Maybe some special things due to the fakt that I have only 4 Points to fit to? I'm not fixed to python. Could it be significant faster with c++? Tips for good C++ Libs for that job? I know that this is a very wide question, so thanks for every helpful Idea or hint were to look at. Thanks

http://stackoverflow.com/comment/87058365
type: QuestionComment
score: 0
has text: Does anyone have any idea? :S
type: Comment
comment on: http://stackoverflow.com/q/50020949

http://stackoverflow.com/q/49993361
tagged with: python
has title: Creating a new 2 column numpy array from filtering through the first coumn/array
accepted answer: http://stackoverflow.com/a/49994050
type: AnsweredQuestion
score: 2
has body: I am trying to create a new 2 dimensional or 2 column array, which will consist of (data value &lt;=20000) from the first column, and their associated ID values in the second column. Mathematically I am doing the following: I am reading data from a text file. I am finding distance to all the points from the last point. # ID M1 M2 M3 M4 R4 M5 R5 x y z 10217 11.467 11.502 13.428 13.599 432.17 13.266 281.06 34972.8 42985.9 14906 7991 11.529 11.559 13.438 13.520 435.23 13.224 272.23 8538.05 33219.8 43375.1 2100 11.526 11.573 13.478 13.490 448.97 13.356 301.27 9371.75 13734.1 43398.6 9467 11.557 11.621 13.481 13.537 449.99 13.367 303.67 33200.3 36008.9 12735.8 4002 11.454 11.530 13.502 13.583 457.34 13.327 294.53 44607.2 10410.9 9090 2971 11.475 11.563 13.506 13.558 458.77 13.391 309.43 29818.3 98.65 11718.6 1243 11.538 11.581 13.509 13.513 459.62 13.377 306.09 16238.4 11067.9 25048 9953 11.523 11.544 13.559 13.913 477.72 13.440 321.20 34589.6 42869 14878.6 7411 11.547 11.576 13.610 13.658 496.81 13.479 330.96 31436 42092.8 12307.8 1820 11.606 11.619 13.652 12.543 513.11 13.571 355.21 1758.75 15809.8 40473.6 2792 11.647 11.679 13.744 13.877 550.82 13.643 375.38 24393 6774.8 8346.35 510 11.687 11.717 13.771 13.810 562.27 13.642 375.14 22340.3 9316.4 13209.9 1721 11.602 11.646 13.821 14.139 584.37 13.770 413.84 2144.95 15769.1 40470.1 After I get the distances, I only want to take distances&lt;=20,000 from my calculations and also their associated ID column. So far I wrote this code to return calculated distances and IDs: # Find nearest neighbors import numpy as np import matplotlib.pyplot as plt halo = 'nntest.txt' ID, m,r,x,y,z= np.loadtxt(halo, usecols=(0,6,7,8,9,10), unpack =True) # selet the last point m_mass = m[-1:] ID_mass = ID[-1:] r_mass = r[-1:] x_mass = x[-1:] y_mass = y[-1:] z_mass = z[-1:] ####################################### #Find distance to all points from our targeted point nearest_neighbors = [] def neighbors(ID_mass, cx,cy,cz, ID, x, y, z): dist = np…
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49994050
tagged with: numpy
tagged with: arrays

http://stackoverflow.com/comment/86997698
type: AnswerComment
has text: @computer you can do whatever you like in the list comprehension. I don't know what `x` is in your sample code in the comment, but if `class` is the datetime, then `[ {..., "ClassAttended": class.strftime('%Y-%m-%d %H:%M:%S')} for ...]` should give you your result. Also note my adaptation of your code below the rule.
score: 0
comment on: http://stackoverflow.com/a/49990489
type: Comment

http://stackoverflow.com/comment/87530028
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50000042
type: QuestionComment
has text: you should be able to comment and edit your own question. If not post your comments as an answer and ask a moderator to convert it to to a comment.

http://stackoverflow.com/comment/87099419
type: Comment
comment on: http://stackoverflow.com/a/50041218
type: AnswerComment
has text: Thank you so much but my question is how to upload the file into my folder in s3 bucket
score: 0

http://stackoverflow.com/q/49943206
tagged with: python
has title: New column in csv based on list, python
score: 0
tagged with: linux
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/49943712
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49943411
has body: I have a csv file (VV_AL_3T3_P3.csv) and each of the rows of each csv file correspond to tiff images of plankton. It looks like this: Particle_ID Diameter Image_File Lenght ....etc 1 15.36 VV_AL_3T3_P3_R3_000001.tif 18.09 2 17.39 VV_AL_3T3_P3_R3_000001.tif 19.86 3 17.21 VV_AL_3T3_P3_R3_000001.tif 21.77 4 9.42 VV_AL_3T3_P3_R3_000001.tif 9.83 The images were located all together in a folder and then classified by shape in folders. The name of the tiff images is formed by the Image_file + Particle ID; for example for the first row: VV_AL_3T3_P3_R3_000001_1.tiff Now, I want to add a new column called 'Class' into the csv file that I already have (VV_AL_3T3_P3.csv) with the name of the folder where each .tiff file is located (the class) using python; like this: Particle_ID Diameter Image_File Lenght Class 1 15.36 VV_AL_3T3_P3_R3_000001.tif 18.09 Spherical 2 17.39 VV_AL_3T3_P3_R3_000001.tif 19.86 Elongated 3 17.21 VV_AL_3T3_P3_R3_000001.tif 21.77 Pennates 4 9.42 VV_AL_3T3_P3_R3_000001.tif 9.83 Others So far, I have a list with the names of the folders where every tiff file is located. This is the list that will be the new column. However, how can I do to fit every folder with its row? In other words, matching the 'Class' with 'Particle ID' and 'Image file'. For now: ## Load modules: import os import pandas as pd import numpy as np import cv2 ## Function to recursively list files in dir by extension def file_match(path,extension): cfiles = [] for root, dirs, files in os.walk('./'): for file in files: if file.endswith(extension): cfiles.append(os.path.join(root, file)) return cfiles ## Load all image file at all folders: image_files = file_match(path='./',extension='.tiff') ## List of directories where each image was found: img_dir = [os.path.dirname(one_img)[2:] for one_img in image_files] len(img_dir) ## List of images: # Image file column in csv files: img_file = [os.path.basename(one_img)[:22] for one_img in image_files] len(img_file) # Particle id column in csv files: …
type: Question
has answer: http://stackoverflow.com/a/49943601
linked to: http://stackoverflow.com/q/46789098
type: UnansweredQuestion

http://stackoverflow.com/q/49936612
has comment: http://stackoverflow.com/comment/86888728
answer count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86888788
has comment: http://stackoverflow.com/comment/86888830
has comment: http://stackoverflow.com/comment/86892164
has answer: http://stackoverflow.com/a/49936751
accepted answer: http://stackoverflow.com/a/49936751
tagged with: python
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/86889070
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/49936806
possible better answer: http://stackoverflow.com/a/49936806
upvote count: 1
has answer: http://stackoverflow.com/a/49936901
has title: Regular expression to match after last - (dash)
has body: Suggest a regular expression to match anything after last - (dash) Case 1 In [1]: a = 'abc - def - ghi' Out [2]: result = '- ghi' Case 2 In [1]: a = 'abc - def - ghi 2323' Out [2]: result = '- ghi 232' I have tried following regex -[\s|\w|\d]+)(?!.*\-) but failed to get desire output in below case: Aaab, xyz, abc - Offer No. 18155
has answer: http://stackoverflow.com/a/49936834

http://stackoverflow.com/q/49991912
has body: I have the problem, that a simple GET HTTP request does not execute on an AWS EC2 Windows Server Machine with Python 3.6.3 running: import requests requests.get('http://some_picture_url') The command never terminates on the windows machine. I can retrieve the image in Internet Explorer on the same machine. How can I debug this? Other urls just work fine.
type: UnansweredQuestion
has title: requests: Request never terminates on windows machine
has answer: http://stackoverflow.com/a/49994331
tagged with: python
tagged with: request
downvote count: 0
score: 1
upvote count: 1
tagged with: windows
answer count: 1
has comment: http://stackoverflow.com/comment/87005398
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87024825
score: 0
type: Comment
type: AnswerComment
has text: first correct your class code, then maybe flow of program will be more clear. Actually it is not. eg while True: block should be in a function.
comment on: http://stackoverflow.com/a/49992254

http://stackoverflow.com/comment/87105801
score: 0
type: Comment
type: AnswerComment
has text: Can you please be more clear on what you want to do? What do you mean by user offset input? Can you specify your goal with example input and output?
comment on: http://stackoverflow.com/a/50044541

http://stackoverflow.com/comment/86895052
type: Comment
has text: if it was FileNotFound, It would have made little bit explicit sense. Thank you
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49938861

http://stackoverflow.com/comment/87059482
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50020118
has text: Showing the rest of the `editrow` view won't help, unless the error is occurring when you access that view (e.g. `http://localhost:8000/editrow/10/`). I'll try one more way to explain - how do you expect `rowid=id` to work if you don't set `id` anywhere?

http://stackoverflow.com/comment/86942778
type: QuestionComment
has text: So lets say the file it loads is a text file containing the numbers 1 to 100. I want this split into 5 text files containing 10 numbers each, then 2 text files containing 25 numbers each.
score: 1
comment on: http://stackoverflow.com/q/49963044
type: Comment

http://stackoverflow.com/q/49983661
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49983754
favorite count: 0
type: AnsweredQuestion
has body: I am trying to read a text file I created, which looks like this: small.txt %%%%%%%%%%%%%%%%%%%%%%% %eeeeeee%eeeee%eeeee%G% %%%e%e%%%%%e%e%%%e%e%e% %e%e%eeeeeee%eee%e%eee% %e%e%e%e%%%e%%%e%e%%%e% %eeeee%eee%eeeeeeeee%e% %e%%%e%e%e%e%e%e%%%%%e% %e%e%eee%e%e%eeeeeee%e% %e%e%e%%%e%%%%%e%e%%%e% %Pee%eeeeeeeee%e%eeeee% %%%%%%%%%%%%%%%%%%%%%%% I want to create a a 2D array board[21][11] in the specific situation. I want each char to be in a cell, because I want to implement BFS and other algorithms to reach a specific path, it's a kind of Pacman game. Here is my code: f = open("small.txt", "r") output_list = [] for rec in f: chars = rec.split() print chars inner_list = [] for each in chars: inner_list.append(each) output_list.append(inner_list) print output_list As you see the output i get now is [[%%%%%%%%%%%%%%%%%%%%%%%]]
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/86983894
has answer: http://stackoverflow.com/a/49983792
possible better answer: http://stackoverflow.com/a/49983792
has title: How to convert txt file into 2d array of each char
has answer: http://stackoverflow.com/a/49983754
has comment: http://stackoverflow.com/comment/86983656
has answer: http://stackoverflow.com/a/49983941
type: Question
has comment: http://stackoverflow.com/comment/86983642
downvote count: 0

http://stackoverflow.com/comment/87184143
comment on: http://stackoverflow.com/a/50074720
score: 0
type: AnswerComment
has text: @ abarnert You are right. I have another question. Does multiprocessing.sharedctypes support independent processes? I think it only supports father child process or brotherly process communication.
type: Comment

http://stackoverflow.com/comment/86928690
type: QuestionComment
has text: Which version of Windows are your using? Please try running those commands with Administrator privilege.
score: 0
comment on: http://stackoverflow.com/q/49948638
type: Comment

http://stackoverflow.com/comment/86906357
type: QuestionComment
comment on: http://stackoverflow.com/q/49944803
score: 0
type: Comment
has text: error: IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

http://stackoverflow.com/q/49975482
favorite count: 0
type: Question
has body: I have a list of lists looking like this: ['user1', time, cpus, mem] ['user1', time, cpus, mem] ['user2', time, cpus, mem] ['user3', time, cpus, mem] and so on.. I need just one list per user with time, cpus and mem added together. I've tried a few things but i cant make it work.
has answer: http://stackoverflow.com/a/59912297
has title: How to group list of lists in Python?
score: 6
has answer: http://stackoverflow.com/a/49975954
tagged with: python
has answer: http://stackoverflow.com/a/49975674
answer count: 4
accepted answer: http://stackoverflow.com/a/49975674
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/86967174
has answer: http://stackoverflow.com/a/49975719
has comment: http://stackoverflow.com/comment/86967173
upvote count: 7
downvote count: 1
possible better answer: http://stackoverflow.com/a/49975954

http://stackoverflow.com/q/49988848
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/66926471
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have been trying to generate a 2x3 figure using matplotlib.pyplot.subplots wherein the first and second rows use plot and loglog commands, respectively. Accordingly, I try to configure subplots, so that plots within the same row share the same y-axis. However, the loglog y-axis (the latter row) appears in the plot y-axis (the former row). Could you please advise us a viable configuration, if possible? An MWE with a random data set may be shown as follows: plt.clf() data = np.arange(0.01, 20.0, 0.01) f, axarr = plt.subplots(2, 3, sharey=True) for i, ax in enumerate(axarr[0].flatten()): ax.plot(data, np.exp(-data / 5.0)) for i, ax in enumerate(axarr[1].flatten()): ax.loglog(data, np.exp(-data / 5.0)) plt.show() plt.close() results in:
type: UnansweredQuestion
tagged with: subplot
has title: How to apply different sharey for rows in a MxN Matplotlib figure?
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/86994256
has answer: http://stackoverflow.com/a/49989076

http://stackoverflow.com/q/49988185
tagged with: python
has body: I have asked about this Python script before, but now i have become faced with a new question: I want to have the texture slider of my script affect the bump depth of my model, but I am not sure how to do so. Is there anyone out there that can help me? I have a bump map texture applied in my model, I just need help getting the slider from the image below into Python format. import maya.cmds as mc if mc.window("Mat_Tex", exists=True): mc.deleteUI(ram) ram = mc.window("Mat_Tex", t="Material and Texture", w=300, h=300) mc.columnLayout(adj=True) imagePath = mc.internalVar(upd=True) + "icons/scriptlogo.jpg" mc.image(w=300, h=200, image=imagePath) # A dropdown menu deisnged to change material/color of octopus matOptionMenu = mc.optionMenu(label="Material") myBlinn = mc.menuItem(label="Red") myBlinn = mc.menuItem(label="Blue") myBlinn = mc.menuItem(label="Yellow") myBlinn = mc.menuItem(label="Green") myBlinn = mc.menuItem(label="Orange") myBlinn = mc.menuItem(label="Purple") # A slider designed to alter the intensity of the octopus' texture texBumpDepth = mc.floatSliderGrp(label="Texture", min=-5, max=5, field=True) def applySlider(*args): slidervalue = mc.floatSliderGrp(texBumpDepth, q = True, value = True) # here is where you want to do something with the value print "setting bump value to", slidervalue # it will probably look like mc.setAttr( "bump2d2" + ".bumpDepth", slidervalue) def set_shader_bump_depth(shader, amount): bump2ds = mc.listConnections(shader, type = 'bump2d') # that's always list, so we loop over it for eachbump2d in bump2ds: print "editing", eachbump2d mc.setAttr(eachbump2d + ".bumpDepth", amount) mc.floatSliderGrp(texBumpDepth, e=True, changeCommand = applySlider) def applyMaterial(*args): currentValue = mc.optionMenu(matOptionMenu, query=True, value=True) if currentValue == "Red": mc.hyperShade(assign='red') elif currentValue == "Blue": mc.hyperShade(assign='blue') elif currentValue == "Yellow": mc.hyperShade(assign='yellow') elif currentValue == "Gr…
has title: Bump Depth slider for Maya Python script
has answer: http://stackoverflow.com/a/49989602
score: 0
answer count: 1
tagged with: maya
tagged with: bump-mapping
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/86990099
type: Comment
has text: for check box use this code : check_box = driver.find_element_by_id('coverLetterCheckBox') check_box.click()
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49986145

http://stackoverflow.com/a/50019223
answers question: http://stackoverflow.com/q/50009296
has body: In Longer The other answer was more on the NLP side of things but here's a walkthrough on your code in the OP and see what's happening. Python Conventions Firstly, some conventions of Python code. Usually CamelCase variable names are not actual variables but class objects, so avoid using variables such as Passage. Also, using better variable names help, instead of PassageList, you can call them words. E.g. import random import sys from nltk.corpus import wordnet print('Enter your passage') passage = sys.stdin.readline() # The passage.split() is aka word tokenization # note you've skipped sentence tokenization, # so it doesn't fit the goal of getting first and last sentence # that you've described in the OP words = passage.split(' ') Collections is your friend Next, there are counter objects in native Python that you can make use of and that'll help you with some optimization and more readable code. E.g. from collections import Counter word_counter = Counter() Take a look at https://docs.python.org/3/library/collections.html Synsets are not Synonyms As explained in the other answer, WordNet is indexed by meanings (aka synsets) and they are not synonyms. To get the synonyms, you can use the Synset.lemma_names() function. But they are really limited and you would have to go through the process of WSD before knowing the lemma_names of which synset to choose from any ambiguous word. Also, explicit is better than implicit, using humanly-understandable variable names helps a lot in understanding and improving the code, so instead of syn = [], use synonyms = []. Otherwise, it's really unclear what syn is storing. Functions shouldn't be abused Disregarding the wrong indentation, it's unclear what function is trying to achieve here. You are simply adding 1 to each item in a list, which essentially is the length function, so you could simply use len(x). def maxInt(list): i = 0 for x in list: i += 1 return i x = [1,2,3,4,5] maxInt(x) == len(x) To access an item from a list sequ…
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87146504
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87134894

http://stackoverflow.com/comment/86849478
has text: Thanks a lot. This solved my problem. I would appreciate it if you could elaborate on why this worked and where my logic was flawed.
type: Comment
comment on: http://stackoverflow.com/a/49917007
score: 0
type: AnswerComment

http://stackoverflow.com/a/50054113
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50053408
type: Answer
upvote count: 2
has body: This is a great case for using decorators. import logging from os import mkdir from os.path import exists from sys import exc_info # for retrieving the exception from traceback import format_exception # for formatting the exception def id_logger_setup(level=logging.DEBUG): def setup_logger(func): if not exists(func.__name__): # makes the directory if it doesn't exist mkdir(func.__name__) logger = logging.getLogger("{}_id_logger".format(func.__name__)) logger.setLevel(level) def _setup_logger(id, *args, **kwargs): handler = logging.FileHandler("{}/{}.txt".format(func.__name__, id)) # a unique handler for each id handler.setFormatter(logging.Formatter("[%(asctime)s][%(levelname)s]%(message)s")) logger.addHandler(handler) try: rtn = func(id, logger=logger, *args, **kwargs) except Exception: # if the function breaks, catch the exception and log it logger.critical("".join(format_exception(*exc_info()))) rtn = None finally: logger.removeHandler(handler) # remove ties between the logger and the soon-to-be-closed handler handler.close() # closes the file handler return rtn return _setup_logger return setup_logger @id_logger_setup(level=logging.DEBUG) # set the level def f1(id, *, logger): logger.debug("In f1 with id {}".format(id)) @id_logger_setup(level=logging.DEBUG) def f2(id, *, logger): logger.debug("In f2 with id {}".format(id)) @id_logger_setup(level=logging.DEBUG) def f3(id, *, logger): logger.debug("In f3 with id {}".format(id)) logger.debug("Something's going wrong soon...") int('opps') # raises an error f1(1234) f2(5678) f1(4321) f2(8765) f3(345774) From the code sample, you get the following: f1 - | 1234.txt 4321.txt f2 - | 5678.txt 8765.txt f3 - | 345774.txt Where in the first four txt files you get something like this: [2018-04-26 18:49:29,209][DEBUG]In f1 with id 1234 and in f3/345774.txt, you get: [2018-04-26 18:49:29,213][DEBUG]In f3 with id 345774 [2018-04-26 18:49:29,213][DEBUG]Something's going wrong soon... [2018-04-26 18:49:29,216][CRITICAL]Traceback (…

http://stackoverflow.com/a/50042956
has comment: http://stackoverflow.com/comment/87135273
score: 0
has comment: http://stackoverflow.com/comment/87216494
type: Answer
has comment: http://stackoverflow.com/comment/87135655
has comment: http://stackoverflow.com/comment/87216940
has body: Your PyCharm on Linux is simply rounding of your large floating point number. Rounding it off to the nearest 6 or 7 can resolve your issue but DONT USE THESE AS FILE NAMES. Keeping your code constant in both cases then, their can be many explanations: 1) 32-bit Processors handles float differently than 64-Bit Processors. 2) PyCharm for both Linux and Windows behaves differently for floating points which we cannot determine exactly, may be PyCharm for Windows is better optimised. edit 1 Explanation for Point 1 on 32-Bit processors everything is really done in 80-bit precision internally. The precision really just determines how many of those bits are stored in memory. This is part of the reason why different optimisation settings can change results slightly: They change the amount of rounding from 80-bit to 32- or 64-bit. edit 2 You can use hashmapping for saving your data in files and then mapping them onto the co-ordinates. Example: # variable = {(long,lat):"&lt;random_file_name&gt;"} cordinates_and_file ={(-92.45453534,-87.2123123):"AxdwaWAsdAwdz"}
answers question: http://stackoverflow.com/q/50042704

http://stackoverflow.com/q/49944602
type: AnsweredQuestion
upvote count: 0
has title: Regular expression to extract numbers after a specific semicolon
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/38816794
favorite count: 0
has answer: http://stackoverflow.com/a/49944793
type: Question
has body: Can you help me to write an expression for the following string: Multi 3620 IDS; 17120846;9;12.04.2018 14:09:02;8,531;;pH;24,1;°C;Temp;AR;60%;;SenTix 940; C171412055; How to get just the number 8,531 using a regular expression? Is there any rule to extract the numbers after a specific number of semicolons? Thank you
has comment: http://stackoverflow.com/comment/86905594
score: -2
has comment: http://stackoverflow.com/comment/86905862
has comment: http://stackoverflow.com/comment/86905532
has comment: http://stackoverflow.com/comment/86905477
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/49944793
has comment: http://stackoverflow.com/comment/86906124

http://stackoverflow.com/q/50010843
tagged with: parsing
has comment: http://stackoverflow.com/comment/87043849
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50014545
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50014545
has body: I wanna Iterate through the Users Stackoverflow dump File. The problem is it is very Huge and it is XML. For me xml is a new Topic. I read several Documentation and Stackoverflow Post but for some reason it doesn't work. XML Format: &lt;users&gt; &lt;row Id="-1" Reputation="1" CreationDate="2008-07-31T00:00:00.000" DisplayName="Community" LastAccessDate="2008-08-26T00:16:53.810" WebsiteUrl="http://meta.stackexchange.com/" Location="on the server farm" AboutMe="&amp;lt;p&amp;gt;Hi, I'm not really a person.&amp;" Views="649" UpVotes="245983" DownVotes="924377" AccountId="-1" /&gt; &lt;/users&gt; The Code: from xml.etree.ElementTree import iterparse for evt, elem in iterparse('data/Users.xml', events=('start','end')): print(evt, elem) What I get: The For Loop outprint me a bunch of hexacode. And in the End I get an Memory Exception. Maybe its normal because I try it a second time and it iterate the xml very fast 0.13 seconds start &lt;Element 'row' at 0x04CC16F0&gt; end &lt;Element 'row' at 0x04CC16F0&gt; start &lt;Element 'row' at 0x04CC1810&gt; I hope you guys can help by the Question. How I get the Value of this Output? I wanna save it into SQL. All of the File is 199 GB (Badge,Comment,PostLinks,PostHistory,Users,Posts,Tags and Votes). The Users.xml specific for this Question is 2,49 GB. But I wanna put all of the Data From SO into the database. Yours faithfully HanahDevelope
tagged with: python
tagged with: data-processing
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87040336
score: 1
upvote count: 1
has title: Iterate through Huge XML File and get the Value?

http://stackoverflow.com/comment/87157608
comment on: http://stackoverflow.com/a/50070467
score: 0
type: Comment
type: AnswerComment
has text: @confused just to create some anticipation: all datatypes in python are objects so learning how to use methods and access variables will come handy.

http://stackoverflow.com/q/49965838
linked to: http://stackoverflow.com/q/10271484
has answer: http://stackoverflow.com/a/49965852
upvote count: 2
has answer: http://stackoverflow.com/a/49965896
downvote count: 3
duplicate of: http://stackoverflow.com/q/10271484
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/11344827
possible better answer: http://stackoverflow.com/a/49965874
has comment: http://stackoverflow.com/comment/86950195
has answer: http://stackoverflow.com/a/49965868
has comment: http://stackoverflow.com/comment/86947542
has answer: http://stackoverflow.com/a/49965874
has title: In python individual multiplication of list values with a loop?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86947439
has body: If I have a list data_x = [1,2,3,4], how do I multiply each element of data_x with each element of another list data_y = [2,3,4,5] and sum the values? The answer should be 1*2 +2*3 +3*4+ 4*5 = 40. I am looking for some kind of for loop.
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49965852

http://stackoverflow.com/q/49947188
has body: I need to extract the URL and error message from the images. The DPI of the image is 300 and size is W 1536 Pixels H 1068 Pixels. import glob list_f = glob.glob('/home/agnihotri/img/*.jpg') if len(list_f) != 0: res_final = [] for f in list_f: from PIL import Image import pytesseract import argparse import cv2 import os, glob from matplotlib import pyplot as plt import re if not os.path.exists('processed/images'): os.makedirs('processed/images') image = cv2.imread(f) if image.shape[0]&lt; 715 or image.shape[1]&lt;1020: print('Resolution too low') else: image = cv2.resize(image, None, fx = 10, fy = 10) config='-c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:.// -psm 3' text = pytesseract.image_to_string(image, config=config, nice=2) try: url = (''.join( re.findall('(http|ftp|https):(//|H)([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?', text)[0]).replace('H', '://').replace('::', ':').replace('I', '/').replace('BBBB', '8888')) except: url = 'No url found in image' print(url) err_message = [] for l in text.split(sep='\n'): if any(i in l.lower() for i in ['error', 'cannot', 'warning', 'problem', "can't", 'unable', 'could not', 'invalid']): err_message.append(l) if len(err_message) == 0: err_message=['No error message found'] err_message = '\n'.join(err_message) print (err_message) However, i do get the error message after executing above mentioned code: No url found in image Traceback (most recent call last): File "./oc_script.py", line 37, in &lt;module&gt; TypeError: split() takes no keyword arguments Link for the input image is https://drive.google.com/open?id=1drdqJjR06EIkt_YbBcVLDZW1s8FRj1J6 Does anyone know why this happens?
answer count: 1
type: Question
has title: Extracting URL and error message from images
score: 0
tagged with: python
tagged with: ocr
has answer: http://stackoverflow.com/a/49947215
type: UnansweredQuestion

http://stackoverflow.com/a/50010898
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50010703
upvote count: 4
answers question: http://stackoverflow.com/q/50010703
downvote count: 0
type: Answer
has body: def replace (list1, target, replaceWord): new = [] replacements_no = 0 for word in list1: if word == target: new.append(replaceWord) replacements_no += 1 else: new.append(word) return new, replacements_no def main(): print ("Welcome! Enter your words one at a time and hit enter after each value.\nWhen you are done entering values, type stop.") inp = input ("Enter first value: ") list1 = [] while inp !="stop": list1.append(inp) inp = input ("Enter first value: ") target = input("Enter targe word :") replaceWord = input("Enter replacement word: ") print() newlist, replacements = replace(list1,target,replaceWord) print("Number of replacements: {}".format(replacements)) print ("Original list: " + (str (list1))) print ("List with replacement: {}".format(', '.join(newlist))) main() something like this should work. you do not have to stick together words in replace function, you can build new list.
has comment: http://stackoverflow.com/comment/87039810
score: 4
has comment: http://stackoverflow.com/comment/87046715

http://stackoverflow.com/q/50024169
answer count: 1
accepted answer: http://stackoverflow.com/a/50024356
type: Question
type: AnsweredQuestion
tagged with: c#
has answer: http://stackoverflow.com/a/50024356
has body: I used pythons serial lib to write commands to a usb port: ser = serial.Serial() ser.port = 'com4' ser.baudrate = 115200 ser.parity = serial.PARITY_NONE ser.stopbits = serial.STOPBITS_ONE ser.bytesize = serial.EIGHTBITS ser.timeout = None ser.open() CMD_MOTOR_DRIVE=[1, 249, 3, 6, 42, 100] ser.write(CMD_MOTOR_DRIVE_1) Now I wants to do the same in c# with help of the SerialPort class: SerialPort port = new SerialPort(); port.PortName = ports[0]; //"com4" port.BaudRate = 115200; port.Parity = Parity.None; port.StopBits = StopBits.One; port.DataBits = 8; port.Open(); //System.Threading.Thread.Sleep(20); if(port.IsOpen == true) { log.Info("Port has been opened"); } while(true) { port.Write("1, 249, 3, 6, 11, 100"); } I am able to open the port, but the controller seems not to response to the command of the port.Write(string) function. I do not know what is the corresponding way in c# to convert the command into a byte array. I think I have to use the port.Write((Byte[], Int32, Int32)) function and not the port.Write(string) one?
tagged with: serial-port
tagged with: python
has title: Write to a serial port like with pythons serial lib
score: 0

http://stackoverflow.com/comment/86980292
type: AnswerComment
score: 0
type: Comment
has text: I am trying to avoid just that. Otherwise I wouldn't need the G.C. at all. I can make my own DB and my own Cal, but I don't want to. Are you quite sure the API doesn't return the URL/ID to the web view anywhere? Would somewhere be any hack or do I have to reverse engineer the G.C. app?
comment on: http://stackoverflow.com/a/49974861

http://stackoverflow.com/a/49941135
has body: Here's a simple script to do what you want. It uses plt.subplots to create the first three Axes with a shared xaxis, then ax.twinx to create the twin Axes. The offset spine on one of the shared axes is done using this example on the matplotlib gallery. import matplotlib.pyplot as plt def make_patch_spines_invisible(ax, offset): ''' This function inspired by this example, to offset a twin axis spine. link: https://matplotlib.org/gallery/ticks_and_spines/multiple_yaxis_with_spines.html ''' ax.spines["right"].set_position(("axes", offset)) ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) ax.spines["right"].set_visible(True) # First create your figure, with 3 subplots sharing the x axis. fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True) # make some room on the right for the twin axes fig.subplots_adjust(right=0.8) # The easy ones, create the first twin axes on ax1 and ax2 ax1t = ax1.twinx() ax2t = ax2.twinx() # Create the twin axis on ax2 with an offset spine ax2tb = ax2.twinx() make_patch_spines_invisible(ax2tb, offset=1.15) # Here I just set some axes limits to show the y axis scales are all independent ax3.set_xlim(0, 900) ax1.set_ylim(0, 2000) ax2.set_ylim(0, 1000) ax3.set_ylim(0, 50) ax1t.set_ylim(0, 12) ax2t.set_ylim(0, 12) ax2tb.set_ylim(0, 100) plt.show()
answers question: http://stackoverflow.com/q/49939738
has comment: http://stackoverflow.com/comment/86898553
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86906310
accepted answer of: http://stackoverflow.com/q/49939738
type: Answer

http://stackoverflow.com/comment/87114513
comment on: http://stackoverflow.com/a/50049188
type: Comment
score: 0
type: AnswerComment
has text: I suspect this is significantly more inefficient than just iterating through a regular Python list, which the OP is already reluctant to do.

http://stackoverflow.com/comment/86905371
type: QuestionComment
score: 0
has text: If all else fails you could try the second-top answer on the suggested duplicate: delegating the filtering step to a separate process via `multiprocessing`.
type: Comment
comment on: http://stackoverflow.com/q/49939860

http://stackoverflow.com/q/49996057
tagged with: python
has answer: http://stackoverflow.com/a/55005536
score: 0
tagged with: gpu
tagged with: plotly
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has body: I use Plotly with python and I struggle with the low performance of mesh3D plots as I draw thousands of points. I try to plot 1500 cubes, but it takes 3 minutes to load the plot's html page. Is there a way to speed up rendering? Activating gpu or something like that? Or is there another option of mesh3D like Scatter and Scattergl in Plotly? Here is my code: import plotly.offline as po import plotly.graph_objs as go def cubes(x=None, y=None, z=None, mode='', db=None): size = 0.05 data = [] for index in range(len(x)): cube = go.Mesh3d( x=[x[index] - (size), x[index] - (size), x[index] + (size), x[index] + (size), x[index] - (size), x[index] - (size), x[index] + (size), x[index] + (size)], y=[y[index] - (size), y[index] + (size), y[index] + (size), y[index] - (size), y[index] - (size), y[index] + (size), y[index] + (size), y[index] - (size)], z=[z[index] - (size), z[index] - (size), z[index] - (size), z[index] - (size), z[index] + (size), z[index] + (size), z[index] + (size), z[index] + (size)], i=[7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2], j=[3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3], k=[0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6], showscale=True ) data.append(cube) layout = go.Layout( xaxis=go.XAxis( title='x' ), yaxis=go.YAxis( title='y' ) ) fig = go.Figure( data=data, layout=layout ) po.plot( fig, filename='cubes.html', auto_open=True ) Thanks for answers! EDIT: I guess the main problem is not the rendering itself, because after loading process is finished the plot interactes perfectly. I tried to analyze the created plotly html page and there is one huuuuuuuuge script tag that takes so much time that where all data points are included... weird... Still have no idea how to handle that. EDIT 2: The problem with the long loading time is the multiple generation of cubes for each Mesh3d. Can I create multiple cubes in a Mesh3d diagram so that only one Mesh3d is created?
type: Question
has comment: http://stackoverflow.com/comment/87025046
has title: Python Plotly slow loading of Mesh3D plot
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87054014

http://stackoverflow.com/a/49944026
has comment: http://stackoverflow.com/comment/86905996
has body: This'll work: from itertools import chain import numpy as np a = np.arange(1, 100) def chunk(xs, nlow, nhigh, shuffle=True): xs = np.asarray(xs) if shuffle: # shuffle, if you want xs = xs.copy() np.random.shuffle(xs) # get at least enough random chunk sizes in the specified range, ie nlow &lt;= n &lt;= nhigh ns = np.random.randint(nlow, nhigh+1, size=xs.size//nlow) # add up the chunk sizes to get the indices at which we'll slice up the input array ixs = np.add.accumulate(ns) # truncate ixs so that its contents are all valid indices with respect to xs ixs = ixs[:np.searchsorted(ixs, xs.size)] # yield slices from the input array for start,end in zip(chain([None], ixs), chain(ixs, [None])): yield xs[start:end] list(chunk(a, 5, 10)) Output: [array([67, 79, 17, 62, 12, 37, 70, 24]), array([98, 48, 88, 59, 47]), array([52, 60, 89, 23, 43, 44]), array([ 7, 27, 33, 74, 49, 2]), array([ 6, 51, 40, 13, 56, 45]), array([31, 3, 55, 10, 11, 46, 9, 42, 34]), array([53, 22, 95, 41, 19, 32, 4, 69, 86]), array([93, 68, 57, 65, 92, 76, 28, 63, 64, 58]), array([91, 66, 18, 99, 21]), array([36, 83, 15, 78, 1, 81, 97, 84]), array([61, 71, 25, 94, 87, 20, 85, 38]), array([ 8, 96, 75, 30, 77, 14, 72, 29]), array([35, 90, 82, 73, 39, 5, 26, 50, 16]), array([80, 54])] edit My original answer doesn't put a lower bound on the size of the final chunk, so sometimes it will be smaller than specified (though never larger). As far as I know there's no direct way of dealing with this. However, in general you can remove an unwanted region from a random distribution by just rejecting any samples that comes from that region. In other words, you can ensure that the last chunk is large enough by just throwing out any proposed chunks in which it is not: def getIxs(xsize, nlow, nhigh): # get at least enough random chunk sizes in the specified range, ie nlow &lt;= n &lt;= nhigh ns = np.random.randint(nlow, nhigh+1, size=xsize//nlow) # add up the chunk sizes to get the indices at which we'll slice up the in…
score: 2
has comment: http://stackoverflow.com/comment/86906133
upvote count: 2
has comment: http://stackoverflow.com/comment/87044048
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86979150
answers question: http://stackoverflow.com/q/49943442
accepted answer of: http://stackoverflow.com/q/49943442
type: Answer

http://stackoverflow.com/comment/86859049
type: Comment
has text: @PaulKremershof: ack – I tested on one of my own XML files, which had different elements & id designations, so I had to re-write the working code to use yours. The *array* is `items` (and can be anything), the *element* is `sentence` (and must match your XML). [Changed variables for clarity.]
comment on: http://stackoverflow.com/a/49920455
score: 0
type: AnswerComment

http://stackoverflow.com/q/49972462
type: UnansweredQuestion
downvote count: 2
tagged with: datetime
tagged with: python
has body: I am using fatsecret REST api and the api specifies that I need to get the number of days in dateint format. I have tried all the posts on stack overflow I could find but all the solutions provided turn the datetime in seconds to an int. Which gives me this error datetime.datetome.now() returns the date like this: 2018-04-23 01:59:45.451741 If I try to strformat the date I get this error: TypeError: unsupported operand type(s) for -: 'float' and 'datetime.datetime' I just need the number of days from january 1, 1970 in a datetime.datetime format. Thanks
has comment: http://stackoverflow.com/comment/86962634
has comment: http://stackoverflow.com/comment/86987118
has answer: http://stackoverflow.com/a/49972562
answer count: 1
upvote count: 1
favorite count: 0
score: -1
type: Question
has comment: http://stackoverflow.com/comment/86987463
has title: How to get days from Epoch january 1 1970 in datetime.datetime format

http://stackoverflow.com/q/49981145
has comment: http://stackoverflow.com/comment/86982301
has comment: http://stackoverflow.com/comment/86984102
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86983133
score: 0
has title: Can't get Celery task result in Django 1.11
answer count: 1
accepted answer: http://stackoverflow.com/a/49983890
has answer: http://stackoverflow.com/a/49983890
tagged with: celery
has comment: http://stackoverflow.com/comment/86982030
type: Question
tagged with: ajax
has comment: http://stackoverflow.com/comment/86979615
has body: I want to get some Celery task result in django with AJAX. I have view like this: def ajax_brand_count(request, task_id): extra_data = brand_count.AsyncResult(task_id) print("1", extra_data.state) print("2", extra_data.get()) if extra_data.ready(): print("3", extra_data) return HttpResponse('') On print 1 I get SUCCESS On print 2 I get None On print 3 I get a string which = task_id I have Redis instance running. I have Celery instance running with SETTINGS: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' In Terminal I see that task finishes successfully. What am I doing wrong? UPDATE: I am using Celery 3.1.25. My task, it returnes a QuerySet, which I want to render later in HTML: @task(bind = True) def brand_count(self, brand_ids): queryset = Brand.objects.filter(brand_id__in=brand_ids) queryset.annotate(amount_of_products=Count('products'))
tagged with: django
tagged with: python

http://stackoverflow.com/q/49964017
score: 3
has title: Bootstrapping java and python compilers
has body: The wikipedia page on compiler bootstrapping lists python and java among the languages whose compilers are bootstrapped. Aren't javac and cpython implemented in c? Why are these languages listed on that page?
tagged with: java
tagged with: bootstrapping
has comment: http://stackoverflow.com/comment/86944212
has answer: http://stackoverflow.com/a/49964354
tagged with: python
tagged with: compiler-construction
answer count: 2
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49964331
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/86944186
type: Question

http://stackoverflow.com/comment/86972637
comment on: http://stackoverflow.com/q/49977257
has text: The docs have examples that should be enough, I'll post an answer later if you're still stuck
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87053331
comment on: http://stackoverflow.com/q/50017003
has text: Just a dinausaur remark: it is no use loading the file in memory. It doesn't speed up anything and just wastes memory.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49978432
type: Question
answer count: 1
tagged with: python
has body: I want the output of the query to be consumed by charts js. They require json/array format for values and labels. I am new to python and pandas. My code - import pandasql as pdsql str="""select DISTINCT File_type,count(File_type) as files from final_df where Search_String='amy' group by File_type """ result=pdsql.sqldf(str,locals()) result to be converted into json format. Any help would be appreciated.
type: AnsweredQuestion
score: 0
has title: covert sql query output to json in python
tagged with: http://stackoverflow.com/tag/json
tagged with: pandasql
has answer: http://stackoverflow.com/a/49994514
accepted answer: http://stackoverflow.com/a/49994514

http://stackoverflow.com/a/50057092
score: 8
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50056605
accepted answer of: http://stackoverflow.com/q/50056605
type: Answer
has body: In some databases, string columns are case-insensitive by default (MySQL, SQL Server), so you wouldn't need to do anything extra. In others, you can create a functional index that enforces the case-insensitive unique constraint: Index('myIndex', func.lower(mytable.c.myColumn), unique=True) You can also specify a case-insensitive collation for the column if the database supports it. For instance SQLite has a 'NOCASE' collation: myColumn = Column(String(255), collation='NOCASE', nullable=False) See http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight=collation#sqlalchemy.types.String.params.collation You may also specify a user-defined type for your column if your database provides a suitable one. PostgreSQL has a citext data type which is case-insensitive. See https://github.com/mahmoudimus/sqlalchemy-citext Finally you can customize the DDL to create the constraint for your specific database.
upvote count: 8

http://stackoverflow.com/q/49968706
downvote count: 0
tagged with: radio-button
answer count: 1
tagged with: user-interface
favorite count: 0
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/49968789
tagged with: python
accepted answer: http://stackoverflow.com/a/49968789
has title: Tkinter Widget won't disappear even if I use destroy/pack_forget
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I'm learning GUI, and as a test I'm trying to develop a frame with two radio buttons, one for random simulation and one for file input simulation. When I want a file input simulation the file name is needed, so I meant my second radio button to pack new Label/Entry throught the switch_entry command. The method called also should delete the Label and the entry if the first radio button is selected. I tried pack_forget and destroy, but the result is I achieve to create de Label/Entry by selecting the second radio button, but can't destroy them by selecting the first. As I select first and second radio buttons alternatively, the GUI keeps adding label/entry sets. Code and image follow: import tkinter as tk class InterRiver(tk.Frame): def __init__(self, master = None): self.mode = tk.StringVar(value="Random") tk.Frame.__init__(self, master) self.lblChooseMode = tk.Label(self, text="Opções do Simulador").pack(side="top") self.rdModeRndm = tk.Radiobutton(self, text = "Rio Aleatório", value = "Random", variable = self.mode, command = self.switch_entry).pack(anchor="w", side="top") self.rdModeFile = tk.Radiobutton(self, text = "Rio a partir de arquivo", value= "File", variable = self.mode, command = self.switch_entry).pack(anchor ="w", side="top") self.btnStart= tk.Button(self, text = "Simular", command = simular).pack(side = "bottom") self.lblCycles = tk.Label(self, text = "Número de Ciclos").pack(side="top") self.ntyCycles = tk.Entry(self).pack(side="top") def switch_entry(self): lblFile = tk.Label(self, text="Insira o nome do arquivo") ntyFile = tk.Entry(self) if self.mode.get() == "File": lblFile.pack(side="top") ntyFile.pack(side="top") else: lblFile.destroy() ntyFile.destroy() if __name__ == "__main__": w = tk.Tk() InterRiver(w).pack() w.title("Bears and Fishes") w.mainloop()

knitr
type: Tag
tags question: http://stackoverflow.com/q/50029466
tag name: knitr

http://stackoverflow.com/a/50031917
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50026147
has body: worked out by meself from geopy.geocoders import Nominatim geolocator = Nominatim() geolocator=Nominatim(timeout=1000) import io import sys # import urllib.request sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码 import pandas as pd df = pd.read_csv("1.csv", encoding="cp1252") #改变标准输乳的默认编码 # print(df) df["Conca_1"]=df["City"] df["Conca_2"]=df["country2"]+" " " "+df["City"] # print(df["Conca2"]) df["Coordinates_1"]=df["Conca_1"].apply(geolocator.geocode) df["Coordinates_2"]=df["Conca_2"].apply(geolocator.geocode) # df["zip"] = df['Coordinates_1'].apply(lambda x: x[0].split(',')[-2] if x != None else None) # df["zip"] = df"Coordinates_1","Coordinates_2".apply(lambda x: x["Coordinates_1"][0].split(',')[-2] if x["Coordinates_1"] != None else x["Coordinates_2"][0].split(',')[-2] if x["Coordinates_2"] != None axis = 1) df["zip"] = df"Coordinates_1","Coordinates_2".apply(lambda x: x["Coordinates_1"][0].split(',')[-2] if x["Coordinates_1"] != None else x["Coordinates_2"][0].split(',')[-2] if x["Coordinates_2"] != None else None, axis = 1) print(df["zip"]) writer = pd.ExcelWriter('coordinates_result.xlsx', engine='xlsxwriter') # Convert the dataframe to an XlsxWriter Excel object. df.to_excel(writer, sheet_name='Sheet1') writer.save()

http://stackoverflow.com/q/50045518
downvote count: 0
has body: I have dataframe as below : User_Id MARKED_CONTENT_AS_FAVOURITE RATE_CONTENT SEARCH VIEWED_CELEBRITY VIEWED_MOVIE VIEWED_TVSHOW 1 6916484f-b7bd-431a-818d-d1a63ff7c717 0 0 1 0 4 0 2 9fbb7702-5209-46c8-b7c8-2c3d03550b56 2 2 1 1 20 3 3 cb1fc554-8566-4c9f-a3ca-f64be302d65e 0 0 1 1 0 0 Now I have a series with just one value. I want to perform a sort of vectorized operation where I have series with only one value. USER_CHECKED_IN_CONTENT 3 0 I want to append this column to the dataframe, as follows. User_Id MARKED_CONTENT_AS_FAVOURITE RATE_CONTENT SEARCH VIEWED_CELEBRITY VIEWED_MOVIE VIEWED_TVSHOW USER_CHECKED_IN_CONTENT 1 6916484f-b7bd-431a-818d-d1a63ff7c717 0 0 1 0 4 0 0 2 9fbb7702-5209-46c8-b7c8-2c3d03550b56 2 2 1 1 20 3 0 3 cb1fc554-8566-4c9f-a3ca-f64be302d65e 0 0 1 1 0 0 0 But when I use pivot_activity.append(subsetx for x in list(subset) if x not in list(pivot_activity)) It gives the output as belows : MARKED_CONTENT_AS_FAVOURITE RATE_CONTENT SEARCH USER_CHECKED_IN_CONTENT User_Id VIEWED_CELEBRITY VIEWED_MOVIE 0 0.0 0.0 1.0 NaN 6916484f-b7bd-431a-818d-d1a63ff7c717 0.0 4.0 1 2.0 2.0 1.0 NaN 9fbb7702-5209-46c8-b7c8-2c3d03550b56 1.0 20.0 2 0.0 0.0 1.0 NaN cb1fc554-8566-4c9f-a3ca-f64be302d65e 1.0 0.0 2 NaN NaN NaN 0.0 NaN NaN NaN
has answer: http://stackoverflow.com/a/50046211
upvote count: 1
has answer: http://stackoverflow.com/a/50046361
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33088010
has answer: http://stackoverflow.com/a/50045792
has comment: http://stackoverflow.com/comment/87107492
score: 1
tagged with: dataframe
tagged with: python
tagged with: merge
has title: Merging a single column dataframe to another dataframe without having any common key
tagged with: pandas
has comment: http://stackoverflow.com/comment/87108654
has comment: http://stackoverflow.com/comment/87108346
answer count: 3
has comment: http://stackoverflow.com/comment/87108260
type: UnansweredQuestion

http://stackoverflow.com/comment/87150291
score: 2
has text: [I downvoted because being unresponsive to comments is not helpful](http://idownvotedbecau.se/beingunresponsive).
comment on: http://stackoverflow.com/q/50063964
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87151173
type: Comment
score: 0
has text: Not a dupe, but my sentiment and an approach is presented [here](https://stackoverflow.com/q/49038635/4799172)
type: QuestionComment
comment on: http://stackoverflow.com/q/50067205

http://stackoverflow.com/comment/86953056
type: Comment
type: QuestionComment
score: 1
has text: What output are you currently getting?
comment on: http://stackoverflow.com/q/49968623

http://stackoverflow.com/comment/87002963
type: AnswerComment
has text: That did not work either. I did get a GET /signUp HTTP/1.1 400 but not returning to home.
type: Comment
comment on: http://stackoverflow.com/a/49993276
score: 0

http://stackoverflow.com/q/49960270
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49960711
has body: I have this code that should run a virtual game called mastermind and I'm having problems trying to code in a way to keep track of how many attempts the player takes. I've added in attempts as a variable but it has no value except for 0 and I would like a way to increment the value each time the function display feedback is run. Is there a better way to achieve this? Here is my code: import random def getGuessFromUser(guess): player_guess.clear() for g in guess: player_guess.append(g) return player_guess #the players code does not match up to the color code def displayFeedback(): while attempts &lt; 10 and player_guess != color_code: for i in range(4): if player_guess[i] == color_code[i] and player_guess != color_code: feedback[i] = color_code[i] if player_guess[i] != color_code[i] and player_guess[i] in color_code and player_guess[i] not in feedback: feedback[i] = 'W' if player_guess[i] != color_code[i] and player_guess[i] in colors and player_guess[i] not in color_code: feedback[i] = '_' print(printNicely(feedback)) #getGuessFromUser(input('Guess: ' + '\n')) guessD() else: finalScoreCodebreaker() #while the players guess is not valid def errorMessage(): if len(player_guess) != len(color_code): getGuessFromUser((input('Error ' + '\n'))) if printNicely(player_guess) != printNicely(player_guess).upper(): getGuessFromUser((input('Error ' + '\n'))) for x in range(4): if player_guess[x] not in colors: getGuessFromUser((input('Error ' + '\n'))) else: displayFeedback() #attempts(attempts) #if player guesses on first try or if they run out of attempts def finalScoreCodebreaker(): if attempts &gt;= 10: print("Color code was: " + str(printNicely(color_code))) print('Score: -' + str(10 - attempts)) if player_guess == color_code: print("Score: -" + str(10 - attempts)) #returns as string def printNicely(self): return ''.join(self) def guessD(): guess = getGuessFromUser(input('guess: ')) colors = ["R", "G", "Y", "P", "B", "O"] attempts = 0 color_code = random.sample(colors, 4) f…
type: UnansweredQuestion
has title: keeping track of how many attempts player takes in mastermind?
tagged with: python
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86937378
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49929088
has body: If you know beforehand how big the partitions are you can read them in chunk by chunk. (chunk size 8 in your example data.) I also assume you are reading in a csv file. chunksize = 8 for chunk in pd.read_csv('file_name1.csv', chunksize=chunksize): print(chunk) or create a new dataframe with sector labels: df = pd.DataFrame() chunksize = 8 for counter, chunk in enumerate(pd.read_csv('file_name1.csv', chunksize=chunksize)): chunk['sector'] = counter df = df.append(chunk)
score: 0
answers question: http://stackoverflow.com/q/49927610
type: Answer
has comment: http://stackoverflow.com/comment/86875509

http://stackoverflow.com/q/50037702
has comment: http://stackoverflow.com/comment/87091609
accepted answer: http://stackoverflow.com/a/50037791
answer count: 5
has answer: http://stackoverflow.com/a/50037881
has answer: http://stackoverflow.com/a/50037791
tagged with: python
possible better answer: http://stackoverflow.com/a/50037799
has answer: http://stackoverflow.com/a/50037943
has answer: http://stackoverflow.com/a/50037799
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87091747
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/87092779
has title: Regex to catch the main name of a file
tagged with: expression
has body: I got stuck on regex to catch the main name of a file in the elements of a list. Suppose I have a list of filepath: path_list = ['/Users/buggylines/histogram/offline-deployer-list_b7bacc7fdb-0e0e08077c_GERONIMO-2886_635_histogrambuglines_635.diff', '/Users/buggylines/histogram/normal.jsp_aa0c2c26dd-90188cc2a4_GERONIMO-4597_1293_histogrambuglines_1293.diff', '/Users/buggylines/histogram/hbase-env.sh_aa0c2c26dd-90188cc2a4_GERONIMO-4597_1293_histogrambuglines_1293.diff', '/Users/buggylines/histogram/LICENSE-tesh_cd1ec17e43-4ebc5e8021_GERONIMO-5702_1573_histogrambuglines_785.diff', '/Users/buggylines/histogram/geronimo_dcce59ae71-8f5c1aa7a1_GERONIMO-5661_1554_histogrambuglines_54.diff', '/Users/buggylines/histogram/catalina-6.0.18-G678601.jar.sha1_cd1ec17e43-4ebc5e8021_GERONIMO-5702_1573_histogrambuglines_785.diff', '/Users/buggylines/histogram/geronimo-naming-1.0.xsd_544dee5179-40a2ae1d41_GERONIMO-1027_131_histogrambuglines_131.diff', '/Users/buggylines/histogram/6.0.18-G678601.README.TXT_cd1ec17e43-4ebc5e8021_GERONIMO-5702_1573_histogrambuglines_785.diff' ] I want to capture only the name of a file using regex. I need the following output: expected_output = ['offline-deployer-list', 'normal.jsp', 'hbase-env.sh', 'LICENSE-tesh', 'geronimo', 'catalina-6.0.18-G678601.jar.sha1', 'geronimo-naming-1.0.xsd', '6.0.18-G678601.README.TXT' ] This is the code I have written: filename = [] for z, path in enumerate(path_list): pattern = re.search("((?:\w+[-]\w+[-]\w+|\w+[-]\w+|\w+)[.]\w+[_])|(?&lt;=histogram/)(?:\w+[-]\w+[-]\D+[_]|\D+[-]\w+[_])|(?&lt;=histogram\/)(\w+[_])(?&lt;=[_])", path) pattern = pattern.groups() filename.append(pattern[0]) However, the output isn't what I expected. This is the output of the code: filename = [None, 'normal.jsp_', 'hbase-env.sh_', None, None, 'jar.sha1_', '0.xsd_', 'README.TXT_'] I need help to fix the regex. Thank you so much.
tagged with: regex
has answer: http://stackoverflow.com/a/50037774
type: Question
has comment: http://stackoverflow.com/comment/87091716

http://stackoverflow.com/comment/86932153
has text: Not sure if that's your actual use case, but if you want to create a temporary file and delete it at the end of the program's execution, there's a [modue](https://docs.python.org/3/library/tempfile.html) for that.
type: QuestionComment
comment on: http://stackoverflow.com/q/49957826
type: Comment
score: 0

azure
tags question: http://stackoverflow.com/q/50067205
tags question: http://stackoverflow.com/q/49992431
tags question: http://stackoverflow.com/q/50054412
tags question: http://stackoverflow.com/q/50072018
type: Tag
tags question: http://stackoverflow.com/q/50035661
tags question: http://stackoverflow.com/q/50062764
tags question: http://stackoverflow.com/q/50071264
tag name: azure
tags question: http://stackoverflow.com/q/50014827

http://stackoverflow.com/comment/87120245
type: Comment
type: QuestionComment
score: 0
has text: What about dict.update() or a ChainMap ?
comment on: http://stackoverflow.com/q/50051890

http://stackoverflow.com/comment/87098246
score: 1
comment on: http://stackoverflow.com/q/50041035
type: Comment
type: QuestionComment
has text: @AshishAcharya If you got it working, post an answer, not an edit.

http://stackoverflow.com/q/50047815
tagged with: python-3.x
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/50051751
has body: I have this query that joins multiple tables together: select p.player_id , d.player_data_1 , l.year , l.league , s.stat_1 , l.stat_1_league_average from stats s inner join players p on p.player_id = s.player_id left join player_data d on d.other_player_id = p.other_player_id left join league_averages as l on l.year = s.year and l.league = s.year where p.player_id = 123 My models look like this: class Stats(models.Model): player_id = models.ForeignKey(Player) stat_1 = models.IntegerField() year = models.IntegerField() league = models.IntegerField() class Player(models.Model): player_id = models.IntegerField(primary_key=True) other_player_id = models.ForeignKey(PlayerData) class PlayerData(models.Model): other_player_id = models.IntegerField(primary_key=True) player_data_1 = models.TextField() class LeagueAverages(models.Model): year = models.IntegerField() league = models.IntegerField() stat_1_league_average = models.DecimalField() I can do something like this: Stats.objects.filter(player_id=123).select_related('player') to do the first join. For the second join, I tried: Stats.objects.filter(player_id=123).select_related('player').select_related('player_data') but I got this error: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'player_data'. Choices are: player How would I do the third join considering that year and league aren't foreign keys in any of the tables? Thanks!
tagged with: django
tagged with: django-models
tagged with: python
tagged with: django-queryset
linked to: http://stackoverflow.com/q/16669422
score: 1
has title: How would I do these multiple joins as a Django queryset?
has answer: http://stackoverflow.com/a/50051751
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/25820170
favorite count: 0

http://stackoverflow.com/q/50038729
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87108806
linked to: http://stackoverflow.com/q/13440956
tagged with: execution
has body: When I execute my python script in pydev/eclipse in debug mode everything works as expected I see this in the console: The script creates some excel files with openpyxl and populates them with created .png files from matplotlib.pyplot but if I execute the script with the normal run: Neither the excel files are created nor the .png files? In the normal run I do not see the above picture in the console pydev version: 6.2.0.... openpyxl version: 2.5.2 matplotlib version: 2.2.2 i also checked the Run->Debug Configurations and Run->Run Configurations but the settings are the same i start execution from my main script : import script2 as sc2 def main(): sc2.start("test_1") if __name__ == '__main__': main() from here if i execute/run with debug mode everything works but if i use the normal run mode it doesnt work. in this script2 the excel files are generated and populated with the .png files generated from matplotlib Edit: excel_file = str(file_path) try: wb = load_workbook(excel_file,read_only=False) except OSError as e: wb = openpyxl.Workbook() wb.save(excel_file) wb = load_workbook(excel_file,read_only=False) wb.create_sheet(sheet_name) sheet = wb[sheet_name] sheet.column_dimensions['B'].width = 50 sheet.column_dimensions['C'].width = 80 sheet['A1'] = "Testing Res" sheet['A1'].font = Font(color = '00FF00') sheet['A1'].font = Font(name='Arial', size=12,bold=True) sheet['A1'].alignment = Alignment(wrap_text=False) for idx,values in enumerate(testing_list,1): sheet["F"] = idx sheet["G"] = elemnts[idx-1] sheet["H"] = values['key1'] sheet["H32"] = "Description :" sheet["I32"] = "balblablabl" wb.save(excel_file) and later some pictures with matplotlib: wb= load_workbook(excel_file,read_only=False) wb.create_sheet(result_graph) sheet = wb[result_graph] data_to_plot_1=[] data_to_plot_2=[] data_to_plot_3=[] for s in sheet_names: df = pd.read_excel(excel_file, s) values = df._series['test_1'] data_to_plot_1.append(values ) for s in sheet_names: df = pd.read_excel(excel_file, s) …
tagged with: matplotlib
has title: pydev executing a script in normal vs debug mode
has comment: http://stackoverflow.com/comment/87120755
has comment: http://stackoverflow.com/comment/87102095
score: 1
has comment: http://stackoverflow.com/comment/87120645
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87111043
answer count: 0
tagged with: pydev
type: UnansweredQuestion
tagged with: openpyxl
downvote count: 0

http://stackoverflow.com/q/50007308
tagged with: python
has title: How can I install a kernel to my Jupyter Notebook to run Python 2.7 (having installed Python 3.6 via Anaconda3)
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50007589
score: 0
answer count: 1
tagged with: jupyter-notebook
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I run Windows 10 and have installed Python 3.6 via Anaconda3. I would like to run Python 2.7 as well for the well known reasons. I presume that one way to do so would be to install a separate kernel in my Jupyter Notebook that would run Python 2.7 (another way would be to be able to switch within the same Jupyter Notebook instance between Python 3.6 and Python 2.7 -- which I do not know if it is feasible and if yes what I should do). I have installed Python 2.7 in my PC in a separate directory (C:\Python27). How can I achieve my objectives?

http://stackoverflow.com/comment/87117952
type: QuestionComment
comment on: http://stackoverflow.com/q/50050796
has text: Rather than pseudocode, can you make this into a self-contained example? It's not clear to me how you'd see the value of `x` from `A`. But, `main` in `A` doesn't `return` anything so it's not clear what you're trying to do
score: 0
type: Comment

http://stackoverflow.com/a/49919621
has body: Use join by 2 columns created by xs for select close level and unstack for reshape: s = df1.xs('close', axis=1, level=1).unstack().rename('close') df2 = (df2.drop('close', 1) .reset_index() .join(s, on=['contract', 'index']) .set_index('index') .rename_axis(None)) print (df2) contract close 2018-03-20 ZN1805 124 2018-03-21 ZN1805 112 2018-03-22 ZN1807 118 2018-03-23 ZN1807 136 2018-03-24 ZN1805 103 2018-03-25 ZN1805 135 2018-03-26 ZN1805 138 2018-03-27 ZN1805 109 2018-03-28 ZN1805 129 2018-03-29 ZN1805 104
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49919252
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49919252
has comment: http://stackoverflow.com/comment/86855607
type: Answer

http://stackoverflow.com/comment/86957325
has text: From what I have observed, I don't think closed form solution does give the optimal weight. Instead of randomly initializing the weights I initialize it with analytical solution and then optimize it using gradient descent. If you read what I have said in the last line when I subtract the gradient from the old weight the loss starts increasing while it decreases when I add it. Why is this behavior
comment on: http://stackoverflow.com/q/49970642
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49992790
score: 0
has answer: http://stackoverflow.com/a/49992818
upvote count: 1
answer count: 1
downvote count: 1
has title: Split digit and text by regexp
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49992818
has body: I want to split digit and number into parts in a string by python with regexp. For example : string = "this1is2a3string4" output = my_func(string) The output will be ['this','1','is','2','my','3','string','4'] I found some similar question but not what i want. Thanks for helping
tagged with: python
tagged with: regex
type: AnsweredQuestion

http://stackoverflow.com/a/49961206
has body: I believe you should be able to stay in NumPy here by using return_inverse within np.unique(): If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([[2,2,3,3], ... [2,3,3,3], ... [3,3,4,4]]) &gt;&gt;&gt; _, inv, cts = np.unique(a, return_inverse=True, return_counts=True) &gt;&gt;&gt; cts[inv].reshape(a.shape) array([[3, 3, 7, 7], [3, 7, 7, 7], [7, 7, 2, 2]]) This will also work for the case where the flattened array is not sorted, such as b = np.array([[1, 2, 4], [4, 4, 1]]).
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49961043
downvote count: 0
score: 4

command
tags question: http://stackoverflow.com/q/50064445
tag name: command
tags question: http://stackoverflow.com/q/50057820
type: Tag

http://stackoverflow.com/comment/86915861
type: Comment
has text: Good catch, thank you! OK, that means back to the editor and hacking up my own wrapper.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49942877

http://stackoverflow.com/comment/87031018
comment on: http://stackoverflow.com/q/50007292
has text: `row['PIC_1]'` is already a string. You just need to do `row['PIC_1'].find`
score: 2
type: Comment
type: QuestionComment

callback
tags question: http://stackoverflow.com/q/50067934
tag name: callback
tags question: http://stackoverflow.com/q/49980998
tags question: http://stackoverflow.com/q/50065411
tags question: http://stackoverflow.com/q/49926263
tags question: http://stackoverflow.com/q/50033276
tags question: http://stackoverflow.com/q/49932140
type: Tag
tags question: http://stackoverflow.com/q/50066468

telegram
tags question: http://stackoverflow.com/q/50012489
tags question: http://stackoverflow.com/q/49977974
tags question: http://stackoverflow.com/q/49952083
tags question: http://stackoverflow.com/q/49964957
tag name: telegram
tags question: http://stackoverflow.com/q/49971659
type: Tag
tags question: http://stackoverflow.com/q/50049680
tags question: http://stackoverflow.com/q/49965738

http://stackoverflow.com/comment/86993209
score: 0
comment on: http://stackoverflow.com/a/49988218
type: Comment
type: AnswerComment
has text: The problem is that I would like to use `assert_frame_equal` to deal with the whole floating point madness. `np.array_equal` returns `False` because of some precision issues but I don't really care about those in my unit test.

http://stackoverflow.com/a/50015940
score: 1
answers question: http://stackoverflow.com/q/50015719
type: Answer
has comment: http://stackoverflow.com/comment/87048319
has comment: http://stackoverflow.com/comment/87048241
downvote count: 0
has comment: http://stackoverflow.com/comment/87048159
upvote count: 1
has body: You can do this, as long as overriding it is your only choice to get the functionality you need. For example, django-rest-framework overrides the dispatch method to provide functionality like authentication, permission, throttling. See here. def dispatch(self, request, *args, **kwargs): """ `.dispatch()` is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. """ self.args = args self.kwargs = kwargs request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response

http://stackoverflow.com/q/50067249
type: AnsweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/50067279
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: css class=fb_pagZ and all the li a under this class. So in css that would be: fb_pagZ li a, but I'm having trouble seeing how to represent it in beautifulsoup. I currently have beautifulsoup code that finds all the classes on the page with fb_pagZ name, but i cannot seem to filter further down into the list items, specifically the li a, with only the href value being parsed. next_page_base=soup.find_all(class_='fb_pagZ') Example html output: &lt;div class="fb_pagZ"&gt; &lt;li&gt;&lt;a href="site.com/img=2" /&gt;&lt;/li&gt; &lt;/div&gt; Can someone please help?
has answer: http://stackoverflow.com/a/50067279
has comment: http://stackoverflow.com/comment/87150953
has title: Beautifulsoup find items in page with these attributes
tagged with: python
score: 1

http://stackoverflow.com/a/50057041
has body: You may use (?&lt;=[0-9]) and (?=[A-Za-z]) lookarounds instead of consuming patterns: import re dummy_string= "I Dont_Know The-Meaning_2018-You Know_Meaning_2017+You Know_Meaning_2017" string_list = re.split("(?&lt;=[0-9])[+/*-](?=[A-Za-z])", dummy_string) print(string_list) # =&gt; ['I Dont_Know The-Meaning_2018', 'You Know_Meaning_2017', 'You Know_Meaning_2017'] See the Python demo When you use [0-9][+/*\-][A-Za-z] to split a string, the digit before a non-word delimiter and a letter after it are consumed, i.e. added to the match value, and re.split removes this text from the resulting output. When using lookarounds, the matched texts remain "unconsumed", they are not added to the match value and thus remain in the re.split output. Note that you do not have to escape - when it is at the end of the character class, [+/*-] = [+/*\-]. If you plan to add more chars into the class, you may keep - escaped to avoid further issues.
accepted answer of: http://stackoverflow.com/q/50056999
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50056999
score: 1

http://stackoverflow.com/comment/86861644
has text: Don't modify your dicts when looping over. Copy (from copy import deepcopy) or use other ones.
type: Comment
comment on: http://stackoverflow.com/q/49922911
score: 0
type: QuestionComment

http://stackoverflow.com/q/49999993
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/87015952
upvote count: 3
has answer: http://stackoverflow.com/a/50000174
tagged with: python
has title: append to list the result of a thread
has comment: http://stackoverflow.com/comment/87016126
favorite count: 0
has comment: http://stackoverflow.com/comment/87016599
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87021660
has body: this is my code: import threading def worker(num): """thread worker function""" print '{Worker: %s}' % num return threads = [] for i in range(5): t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() print(threads) and this is the result from above code: {Worker: 0} {Worker: 1} {Worker: 2} {Worker: 3} {Worker: 4} [&lt;Thread(Thread-1, stopped 17204)&gt;, &lt;Thread(Thread-2, stopped 852)&gt;, &lt;Thread(Thread-3, stopped 17092)&gt;, &lt;Thread(Thread-4, stopped 10632)&gt;, &lt;Thread(Thread-5, stopped 2396)&gt;] how can i append those results to list and create a list something like this: [[{Worker: 0}],[{Worker: 1}],[{Worker: 2}],[{Worker: 3}],[{Worker: 4}]] edited: in reality my def contain a request REST method and it consume some seconds and after some trying i found thread not wait to get result and not fill array list, then i reform my code into a string variable to simulate for you, in this situation i put a time.sleep(1) in first line of def and then run thread, it's have a empty list.... i less sleep time to 0.001 till get result and thread work and array have populated. import threading def worker(txt): """thread worker function""" if txt != '[{}]': time.sleep(0.01) # this time has empty result till replace with 0.001 or lesser lst.append(['{Worker: %s}' % txt]) # time.sleep(5) return xx = ['abc','def','ghi','jkl','mno','pqr','stw','xyz'] threads, lst = [], [] for i in xx: t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() # t.join() print(lst) #[['{Worker: abc}'], ['{Worker: jkl}'], ['{Worker: ghi}'], ['{Worker: def}']] for 0.001 sleep time # print(threads)
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/50000174

http://stackoverflow.com/a/50112822
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50066163
has body: It was the problem in database. It was a new project so I could also just delete and start a new database.
accepted answer of: http://stackoverflow.com/q/50066163
type: AcceptedAnswer

http://stackoverflow.com/q/49924132
score: 2
has comment: http://stackoverflow.com/comment/86864776
answer count: 2
has title: map lambda creating dictionary
upvote count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49924471
type: Question
has body: I have this [('h', ['ab', 'aus']), ('c', ['ab', 'escu']), ('n', ['lia', 'lmos'])] I want this [{'ab': 1, 'aus': 1}, {'ab': 1, 'escu': 1}, {'lia': 1, 'lmos': 1}] I tried map(lambda row: [{b: 1 } for b in row[1]]) results [[{‘ab': 1}, {'aus': 1}], [{'ab': 1}, {'escu': 1}], [{'lia': 1}, {'lmos': 1}]] Can you help me to correct my map function?
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49924163

http://stackoverflow.com/comment/87067753
has text: Did the tutorial use a `namedtuple`?
type: Comment
comment on: http://stackoverflow.com/q/50025742
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87071896
type: QuestionComment
type: Comment
score: 0
has text: @roganjosh it could be Vincent might need more than one transformation. So maybe a flexible solution is best
comment on: http://stackoverflow.com/q/50027783

http://stackoverflow.com/comment/87058283
has text: Be kind and accept my answer if you think it was of help. :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49954614
type: Comment

http://stackoverflow.com/a/49917131
answers question: http://stackoverflow.com/q/49916887
type: Answer
has comment: http://stackoverflow.com/comment/86849588
score: 0
has body: You can do it using a for loop and a single else: for password in list_of_password: ... "credentials = username:" + password + "\n" ... if '1 devices were successfully added/updated' in p1: ... break else: print "Unsuccessfull"
has comment: http://stackoverflow.com/comment/86849555
has comment: http://stackoverflow.com/comment/86849629

http://stackoverflow.com/q/49959667
tagged with: flask-restful
has body: I'm using flask-restful and wanted to use bcrypt from passlib to hash users passwords stored in database, when I run the solution by python3 app.py, everything works perfectly and I can hash the passwords and validate them , but when I run the solution through uwsgi uwsgi uwsgi.ini I get internal server error when I try to authenticate. When I review the log file from passlib.hash import bcrypt ImportError: No module named 'passlib' , although I can import it successfully from command line as well. I tried to do one solution suggested in : No module named 'passlib' and to add "#@UnresolvedImport" to import but still didn't work.
type: Question
has comment: http://stackoverflow.com/comment/86936158
has answer: http://stackoverflow.com/a/50050453
answer count: 1
linked to: http://stackoverflow.com/q/33915448
accepted answer: http://stackoverflow.com/a/50050453
type: AnsweredQuestion
score: 0
tagged with: hash
has title: passlib cannot be imported when using uwsgi
tagged with: database
tagged with: passlib
tagged with: python

http://stackoverflow.com/comment/87013083
comment on: http://stackoverflow.com/q/49998198
has text: A deleted question may be reopened, or linked to for +10K rep people; that might have been less confusing. Using the right tag (i.e., improving the original question) also helps.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86864975
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49923798
type: Comment
has text: Oh wow thanks alot! I cant believe I missed a line. This code was really making me go crazy. Appreciate your help.

http://stackoverflow.com/comment/86891778
type: QuestionComment
has text: @hikaru '2.1.5' don;t know to solve this error quite frustrating
score: 0
comment on: http://stackoverflow.com/q/49934926
type: Comment

http://stackoverflow.com/comment/94992281
type: Comment
type: AnswerComment
has text: the `~` in `~/.bash_profile` represents your home path. so `cd ~` would navigate you to your home directory.
score: 3
comment on: http://stackoverflow.com/a/49998052

bayesian
tags question: http://stackoverflow.com/q/50035005
tags question: http://stackoverflow.com/q/50014914
tag name: bayesian
tags question: http://stackoverflow.com/q/49969960
type: Tag

http://stackoverflow.com/q/49971980
type: Question
accepted answer: http://stackoverflow.com/a/49980604
tagged with: opencv
tagged with: k-means
tagged with: python
has title: K-Means for color classification with filter for mask: ValueError: cannot reshape array of size 13498 into shape (3)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49980604
score: 1
answer count: 1
has body: I am trying to classify the color of an object in an image using KMeans. First, I have used a mask in order to subtract the background of the image in order to separate the object from the background. Hence, I am working with an image that has a pure black background i.e. rgb(0,0,0) with the object sitting isolated within that black space. Now I would like to perform KMeans on the colors of the object in the image without feeding the background to the algorithm, as I don't want the background to be included within the clusters. I am trying to filter out the black pixels and then reshape the array in order to feed it to the classifier. # reshape the image to be a list of pixels image = image[image != 0] image = np.reshape(image, (-1,3)) # cluster the pixel intensities clt = KMeans(n_clusters = 3, n_jobs=1,random_state=42) clt.fit(image) While this works for some images well, I get an error message for some of my other images, like so: ValueError: cannot reshape array of size 13498 into shape (3) Is there any way to dynamically adjust the size of the array after filtering in order for it to fit into shape 3? I am using Python v3 and the images are loaded using OpenCV2
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50015532
has title: Execute several commands on Cisco switch via Paramiko - improve performance
type: AnsweredQuestion
score: 0
has body: I'm trying to login into a cisco switch and do some stuff there (configure a port for example). I can't use exec_command(cmd1 \n cmd2 \n) on cisco devices apparently... So I'm using a channel to send my commands on like so: channel = ssh.invoke_shell() channel.send("show arp\n") while not channel.recv_ready(): time.sleep(0.5) out = channel.recv(9999) I don't like the time.sleep(0.5) and want something to dynamicaly wait for the command to be executed because sometimes commands take even longer than 0.5sec and that would slow down everything a lot. With exec_command(cmd) I had exit_status = channel.recv_exit_status()for example. Is there a way around this? Could I somehow listen to the channel and wait for the output to be like CISCOSWITCH# so that I know that I'm ready to send more commands or exit? I cannot use exec_command, because that closes the channel and when my intent is to configure a port I have to send multiple commands in the same session. (I think that's how it works)
accepted answer: http://stackoverflow.com/a/50016184
tagged with: cisco
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50016184
tagged with: ssh
tagged with: python
tagged with: paramiko

firefox
type: Tag
tags question: http://stackoverflow.com/q/50055401
tags question: http://stackoverflow.com/q/49929374
tags question: http://stackoverflow.com/q/49965956
tags question: http://stackoverflow.com/q/49985726
tag name: firefox
tags question: http://stackoverflow.com/q/49995704

http://stackoverflow.com/q/49945414
has body: I successfully added a cutoff option to get_close_matches in Pandas. For some reason when I add cutoff=0.7, when it outputs to my CSV, it reads as ['Name']. When it did not have the cutoff argument, it just outputted the match with no ['']. Below is my code. Any help would be appreciated! https://pastebin.com/nRt3rVPr import sys import difflib import csv import pandas as pd df = pd.read_csv(sys.argv[1]) List = df.list #.astype(str).values.tolist() MappedID = df.Party.astype(str) df['Name_r'] = MappedID.map(lambda x: (difflib.get_close_matches(x, List, cutoff=0.7)[:1] or [None][0])) header = [ "List", "Party", "Name_r"] df.to_csv(sys.argv[2], columns = header) print(df.to_string())
type: Question
has title: pandas csv output has [''] when adding cutoff argument
has comment: http://stackoverflow.com/comment/86908144
tagged with: http://stackoverflow.com/tag/csv
tagged with: difflib
has answer: http://stackoverflow.com/a/49945827
tagged with: python
linked to: http://stackoverflow.com/q/20109391
score: 0
tagged with: pandas
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/50063358
has body: I have a Python list (mixed with string and values) like below: mylist = [('Needie', 83, 55, 78, None), ('Blue', 80, 60, None, 66), ('Bloodnok', None, 54, 57, 59), (None,)] The desired output should be: newlist = [('Needie', 83, 55, 78, None), ('Blue', 80, 60, None, 66), ('Bloodnok', None, 54, 57, 59)] What should I do to remove the last tuple (None,) in the list? Keep other tuples as before, includes names (string), None value and floats del list[:-1] Output: [(None,)]
has title: In Python, how do I remove the last tuple (None,) in a list? The list mixes with string and floats
linked to: http://stackoverflow.com/q/627435
downvote count: 0
answer count: 0
upvote count: 1
favorite count: 0
tagged with: list
duplicate of: http://stackoverflow.com/q/627435
type: Question
has comment: http://stackoverflow.com/comment/87143294
tagged with: python
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87143704

http://stackoverflow.com/comment/86987057
score: 0
comment on: http://stackoverflow.com/q/49983951
type: Comment
type: QuestionComment
has text: @ Tom Dalton, I have made a lot of troubleshooting already, but it took me nowhere until now, however, I will check the link to see if I missing something. Thanks a lot for your reply.

http://stackoverflow.com/comment/87092235
comment on: http://stackoverflow.com/q/50030447
type: Comment
has text: @Newbiedev, I suppose that you do not use any additional library, but if you are interested, I can expand my answer and show how to avoid such problem using `SQLAlchemy`.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86947034
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49965552
has text: Try using filename='css/main.css' as per my answer
type: Comment

http://stackoverflow.com/comment/87039501
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50011417
score: 0
has text: Are you sure your warnings are coming from the compilation part (and are you sure you've cleaned your build/temp folders from the previous build without the applied `extra_compile_args` warning suppression)? `extra_compile_args` should most definitely be passed to `gcc` and the specified warnings should be suppressed. However, if the warnings are coming from linking, use `extra_link_args` instead. For a full option list check the [`distutils.core.Extension`](https://docs.python.org/3/distutils/apiref.html#distutils.core.Extension) documentation.

http://stackoverflow.com/comment/87512861
type: AnswerComment
has text: Thank you for your help!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50222508

http://stackoverflow.com/comment/86982836
score: 2
has text: Make `set`s with 2nd elements. Then get the `intersection`. Then run through the lists and keep only those which's 2nd element is in the intersection.
type: QuestionComment
comment on: http://stackoverflow.com/q/49983239
type: Comment

http://stackoverflow.com/q/49929025
tagged with: python
has answer: http://stackoverflow.com/a/49929342
has body: Sorry, beginner here. Trying to make this program that scans for a certain letter combination, and if it does not find any, it returns the "else" statement. However, I can't figure out how to have the "else" statement apply ONLY if ALL of the "if" statements return False. Here's my code: class color: BOLD = '\033[1m' END = '\033[0m' GREEN = '\033[92m' print("Welcome to the Sequence Scanner") print(" ") ## just putting a space between the welcome message and the input box seq = input("Provide your nucleotide sequence here: ") def scan(): if 'aataaa' in scan(): print('The trouble sequence, Canonical Poly-A Signal, is present') if 'aatgga' in scan(): print('The trouble sequence, Pea Poly-A Signal, is present') ### the same format for the previous if statements is repeated for different sequences else: print(color.GREEN + 'No trouble sequences are present' + color.END) scan(seq) Right now, it prints the "else" statement any time the last "if" statement is false. So I'm assuming I need to make it so it's not just applying to the last "if" statement, but I've tried different indentations and it just doesn't work for me. I know this is probably a really stupid question, so I'm sorry in advance. Also, if there are any other things I should do/know about to make this code more efficient, it would be awesome if you could point me towards resources for that! Thanks for any help, I really appreciate it. Other questions if you're really bored and want to help me out at all: is there any way to make the function print the input sequence with the "trouble sequences" highlighted (like in red or something)? That would be awesome, but it seems like it might be too hard for me to pull off with my current level of coding experience.
tagged with: python-3.6
has title: Python 3: How to have the "else" statement apply only if none of the "if" statements are true?
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/49929089
has comment: http://stackoverflow.com/comment/86874419
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/86874053
has answer: http://stackoverflow.com/a/49929076
favorite count: 0
type: Question
tagged with: if-statement
tagged with: function
has comment: http://stackoverflow.com/comment/86874404
type: UnansweredQuestion

http://stackoverflow.com/q/50033317
has title: Python regex ignore punctuation when using re.sub
has comment: http://stackoverflow.com/comment/87083622
downvote count: 1
has comment: http://stackoverflow.com/comment/87086358
favorite count: 0
has comment: http://stackoverflow.com/comment/87082935
score: 0
has comment: http://stackoverflow.com/comment/87082938
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87084529
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87083461
has comment: http://stackoverflow.com/comment/87083070
answer count: 0
has comment: http://stackoverflow.com/comment/87082951
has body: Let's say I want to convert the word center to centre, theater to theatre, etc. In order to do so, I have written a regex like the one below: s = "center ce..nnnnnnnnteeeerrrr mmmmeeeeet.eeerrr liiiiIIiter l1t3r" regex = re.compile(r'(?:((?:(?:[l1]+\W*[i!1]+|m+\W*[e3]+|c+\W*[e3]+\W*n+)\W*t+|t+\W*h+\W*[e3]+\W*a+\W*t+|m+\W*a+\W*n+\W*[e3]+\W*u+\W*v+)\W*)([e3]+)(\W*)(r+))', re.I) print(regex.sub(r'\1\4\3\2',s) #prints "centre ce..nnnnnnnntrrrreeee mmmmeeeeet.rrreee liiiiIIitre l1tr3" In order to account for loopholes like c.e.nn.ttteee,/rr (basically repeated characters and added punctuation), I have been forced to add \W* between each character. However, people are still able to use strings like c.c.e.e.n.n.t.t.e.e.r.r, which don't match as there is punctuation between each letter, not just different letters. I was wondering whether there is a smarter method of doing this, where I can use re.sub without removing whitespace/punctuation but nonetheless have it match.
has comment: http://stackoverflow.com/comment/87083526
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87083019
upvote count: 1
has comment: http://stackoverflow.com/comment/87083124

http://stackoverflow.com/q/49945963
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49948009
possible better answer: http://stackoverflow.com/a/49948009
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/49963806
accepted answer: http://stackoverflow.com/a/49963806
has title: How to get value from a span class with a countdown timer?
has comment: http://stackoverflow.com/comment/86914772
has body: So I have been playing around with webscraping and basically what I am trying to is to scrape down a timer that is right now that is shown etc in picture below: What I want to scrape is the 00 : 14 : 40 : 38 and what it does is that every second it counts down but basically what I wish is that whenever I do a webscrape, Just grab the value that is currently right now. However I coded this and it gave ma a value of None: bs4 = soup(requests.get(url).text, "html.parser") test = bs4.find("span",{'class':'countdown-row countdown-amount'}) print(test) could that be an issue because of the countdown or? Because whenever I do print(bs4) it will not be shown in the print the span class but on the website there is...
tagged with: web-scraping

http://stackoverflow.com/comment/86902063
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49942773
type: Comment
has text: @ John Coleman, At First I tried installing "finadatpy" using pip install git+https://github.com/cuemacro/findatapy.git But then, I found out "statsmodels" was not insatlled. So I tried to install it along with other dependencies..But "blosc" was not successful, because it required "statsmodels"

http://stackoverflow.com/q/50004087
type: Question
has comment: http://stackoverflow.com/comment/87024711
has comment: http://stackoverflow.com/comment/87025344
has answer: http://stackoverflow.com/a/50005712
has body: Firstly, I am aware that there are tons of questions regarding en/de-coding of strings in Python 2.x, but I can't seem to find a solution to this problem. I have a unicode string, that contains letter č which is represented as \u00c4\u008d If in Python console I write >>> a = u"\u00c4\u008d" >>> print a I get two strange characters printed out instead of č, probably because the actual encoding of that string is supposed to be UTF-8. Therefore I try to use .decode("utf-8") but for this I get the standard UnicodeEncodeError. Do you know how I can make Python print that string as č in the console?
has comment: http://stackoverflow.com/comment/87024921
has comment: http://stackoverflow.com/comment/87025035
tagged with: python
tagged with: utf-8
has title: Converting unicode string to utf-8
has comment: http://stackoverflow.com/comment/87025124
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87025286
has comment: http://stackoverflow.com/comment/87024978
answer count: 2
downvote count: 0
tagged with: encoding
has answer: http://stackoverflow.com/a/50006695
possible better answer: http://stackoverflow.com/a/50006695
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87025246
accepted answer: http://stackoverflow.com/a/50005712
tagged with: unicode
favorite count: 0

http://stackoverflow.com/comment/87050068
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50016800
has text: Why your `compare` url name is `home` ?. Change that name to `compare` for correctly redirecting to `compare` url

http://stackoverflow.com/comment/87232857
has text: The yarn resource manager has its own dashboard that will give you its view on things, or you can get the same information via the yarn_api module in `knit` (any dask_yarn or knit instance also has a yarn_api instance within it, if you look around).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50077472
type: Comment

http://stackoverflow.com/a/52508908
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49983339
has body: Since you're using grayscale images, you need to specify this by adding the 0 parameter as follows: frame0 = cv2.imread("frame0.jpg", 0) Check OpenCV documentation for more detail: https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html

http://stackoverflow.com/comment/86930799
has text: sorry and thanks for all the help. I'll try and clarify it :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49956952
type: AnswerComment

http://stackoverflow.com/comment/87145970
has text: @mafrasi2 ok, perhaps I wasn't clear. I updated the question there and hope it's clearer now?
score: 0
comment on: http://stackoverflow.com/q/50064445
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50033847
score: 0
type: Answer
has body: The project is definitely in a usable state, and is used to test a couple of professional projects today. Using the pip install method that python-pact-testing-example outlines in the README should be enough to properly install pact-python. During that install process it will download a separate package to do the actual contract work. There is a chance that something happened with the download of that package that caused the mock service to not get installed on your machine, but looking at the code today I think it should have blown up during install. We could certainly look at making this situation more friendly, by telling you which file is missing and that it could be an install issue. If that is the issue, this may resolve the issue: pip uninstall pact-python pip install pact-python If you are looking for an example, you might check out the end to end tests of pact-python. These illustrate a lot of the major features of the project and run during the build process.
answers question: http://stackoverflow.com/q/49983126

http://stackoverflow.com/comment/87001481
type: QuestionComment
has text: Is this python? If so, please tag it as such.
score: 0
comment on: http://stackoverflow.com/q/49992442
type: Comment

http://stackoverflow.com/comment/86879138
comment on: http://stackoverflow.com/q/49931623
type: QuestionComment
type: Comment
has text: confirming that it didn't make any difference, thanks for the recommendation though
score: 1

http://stackoverflow.com/comment/86863472
has text: The third line of your output doesn't satisfy your requirements...
comment on: http://stackoverflow.com/q/49923212
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86868903
type: QuestionComment
has text: @Uueerdo Without those quotes, it gives me an SQL-Syntax-Error, so they are needed I suppose :/
type: Comment
comment on: http://stackoverflow.com/q/49925982
score: 0

http://stackoverflow.com/comment/87056530
type: AnswerComment
has text: @SiongThyeGoh Cannot plot the coordinates still. where should I rewrite to solve them ?
type: Comment
comment on: http://stackoverflow.com/a/50018793
score: 0

http://stackoverflow.com/q/49966166
has body: I have installed python 3.6.5 followed by pip using following command: python get-pip.py Added path till Scripts folder to "User PATH variable" as I dont have admin rights. But When I am trying to access pip (pip --version), it throws me errors which mainly relate to not finding the module. Description is given below. File "....\Python\python-3.6.5-embed-amd64\Scripts\pip.exe\__main__.py", line 5, in &lt;module&gt; ModuleNotFoundError: No module named 'pip'
type: Question
has title: Python3.6: pip is installed but not working in windows
has comment: http://stackoverflow.com/comment/86948782
tagged with: python
type: UnansweredQuestion
score: 0
answer count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/86962541

automation
tags question: http://stackoverflow.com/q/50043295
tags question: http://stackoverflow.com/q/50065083
tag name: automation
tags question: http://stackoverflow.com/q/49968037
tags question: http://stackoverflow.com/q/49996084
type: Tag
tags question: http://stackoverflow.com/q/50000321
tags question: http://stackoverflow.com/q/50044926

http://stackoverflow.com/comment/86878799
type: QuestionComment
has text: part of the problem is that you copied and pasted c/c++ code into a .py file (alright it might be php or something ... but my guess is c/c++)
comment on: http://stackoverflow.com/q/49931376
score: 1
type: Comment

http://stackoverflow.com/comment/87174947
type: AnswerComment
comment on: http://stackoverflow.com/a/50044983
has text: Hi Haggi, oh yes, sorry i accidentally remove the 'global myDic'... hope it works now :)
type: Comment
score: 0

http://stackoverflow.com/q/49926504
tagged with: pyspark
has comment: http://stackoverflow.com/comment/86869830
tagged with: python
tagged with: delimiter
has comment: http://stackoverflow.com/comment/106685294
type: Question
has comment: http://stackoverflow.com/comment/86870325
has comment: http://stackoverflow.com/comment/113218275
score: 5
has comment: http://stackoverflow.com/comment/107798198
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/107734195
type: UnansweredQuestion
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/36007686
has answer: http://stackoverflow.com/a/72997244
has comment: http://stackoverflow.com/comment/86879297
has comment: http://stackoverflow.com/comment/86870992
favorite count: 0
has body: I'm trying to read csv files with ^A(\001) delimiter in pyspark. I have gone through the below link and as mentioned in link I tried the same approach and it's working as expected i.e. I was able to read the csv files and process them further. Link: How to parse a csv that uses ^A (i.e. \001) as the delimiter with spark-csv? Working spark.read.option("wholeFile", "true"). \ option("inferSchema", "false"). \ option("header", "true"). \ option("quote", "\""). \ option("multiLine", "true"). \ option("delimiter", "\u0001"). \ csv("path/to/csv/file.csv") Instead of hard coding the delimiter, I want to read it from database and below is the approach I tried. update table set field_delimiter= 'field_delimiter=\\u0001' (Key value pair. Using the key, I'm accessing the value) delimiter = config.FIELD_DELIMITER (This will fetch the delimiter from the database) &gt;&gt;print(delimiter) \u0001 Not Working spark.read.option("wholeFile", "true"). \ option("inferSchema", "false"). \ option("header", "true"). \ option("quote", "\""). \ option("multiLine", "true"). \ option("delimiter", delimiter). \ csv("path/to/csv/file.csv") Error: : java.lang.IllegalArgumentException: Unsupported special character for delimiter: \u0001 at org.apache.spark.sql.execution.datasources.csv.CSVUtils$.toChar(CSVUtils.scala:106) at org.apache.spark.sql.execution.datasources.csv.CSVOptions.&lt;init&gt;(CSVOptions.scala:83) at org.apache.spark.sql.execution.datasources.csv.CSVOptions.&lt;init&gt;(CSVOptions.scala:39) at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.inferSchema(CSVFileFormat.scala:55) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$7.apply(DataSource.scala:178) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$7.apply(DataSource.scala:178) at scala.Option.orElse(Option.scala:289) at org.apache.spark.sql.execution.datasources.DataSource.getOrInferFileFormatSchema(DataSource.scala:177) at org.apache.spark.sql.execution.datasources.DataSource.r…
tagged with: http://stackoverflow.com/tag/csv
upvote count: 5
has title: Spark csv read ^A(\001)

http://stackoverflow.com/comment/87521745
score: 0
has text: I don't even have any "yaml" command installed on my system, don't think it'll contribute to installing ROS?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50060718

http://stackoverflow.com/a/49923723
type: Answer
has comment: http://stackoverflow.com/comment/86864138
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86863357
has comment: http://stackoverflow.com/comment/86863597
downvote count: 0
has comment: http://stackoverflow.com/comment/86864195
has comment: http://stackoverflow.com/comment/86865385
accepted answer of: http://stackoverflow.com/q/49923631
has body: It would seem that your python installation doesn't have community installed. You can install it by running: pip install python-louvain Cheers!
has comment: http://stackoverflow.com/comment/86863467
answers question: http://stackoverflow.com/q/49923631
has comment: http://stackoverflow.com/comment/86863425
has comment: http://stackoverflow.com/comment/86864918
type: AcceptedAnswer

http://stackoverflow.com/a/50009438
type: Answer
has comment: http://stackoverflow.com/comment/87257867
has comment: http://stackoverflow.com/comment/87145849
has comment: http://stackoverflow.com/comment/87115119
downvote count: 0
upvote count: 1
score: 1
has body: To find area of red rectangle in the image you can do as: extract red channel of the image threshold red channel count number of nonzero pixels Example code: import cv2 import numpy as np img = cv2.imread('vju0v.png') img = np.array(img) # convert to numpy array red = img[:,:,2] # extract red channel rect = np.float32(red &gt; 200) # find red pixels area = np.sum(rect) # count nonzero pixels print('Area = ' + str(area)) cv2.imshow('Red Channel',rect) cv2.waitKey(0)
answers question: http://stackoverflow.com/q/50008022
has comment: http://stackoverflow.com/comment/87119005
has comment: http://stackoverflow.com/comment/87114985

http://stackoverflow.com/q/49955674
answer count: 1
has title: Python: access values of a panda series
favorite count: 0
tagged with: series
type: Question
type: AnsweredQuestion
score: 0
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49955693
tagged with: python
has answer: http://stackoverflow.com/a/49955693
has body: I grouped a dataframe by two columns and calculated a quantile of each group. So the series looks like this now: Group vehicle 1 car 5.6 bike 34.0 2 car 7.0 bike 40.0 in a next step I need to check if values are below the quantile and if so, do something. For that, I need to access the specific value (column 3 of the series) for group and vehicle. Summed up, how do I get for example the value 34.0 by group and vehicle?
upvote count: 2
downvote count: 2

http://stackoverflow.com/a/49950739
has comment: http://stackoverflow.com/comment/86918356
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49950699
has body: This is fine, to be more pythonic you can chain calls like: grades = [int(x) for x in grades.split(',')] without having to use a temporary assignment of .split() You can do the same with the round() call: return round(sum(grades) / len(grades), 2)

http://stackoverflow.com/comment/87124035
type: Comment
has text: The problem with PHP is that it loads modules for just about everything even if you aren't using them.
type: QuestionComment
comment on: http://stackoverflow.com/q/50013067
score: 0

http://stackoverflow.com/q/50044759
score: 10
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50045177
downvote count: 0
tagged with: amazon-ec2
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/87118066
has comment: http://stackoverflow.com/comment/87106176
has title: Boto3 - Print AWS Instance Average CPU Utilization
possible better answer: http://stackoverflow.com/a/50045177
type: AnsweredQuestion
answer count: 3
has body: I am trying to print out just the averaged CPU utilization of an AWS instance. This code will print out the 'response' but the for loop at the end isn't printing the averaged utilization. Could someone assist? Thank you in advance! import boto3 import sys from datetime import datetime, timedelta client = boto3.client('cloudwatch') response = client.get_metric_statistics( Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[ { 'Name': 'InstanceId', 'Value': 'i-1234abcd' }, ], StartTime=datetime(2018, 4, 23) - timedelta(seconds=600), EndTime=datetime(2018, 4, 24), Period=86400, Statistics=[ 'Average', ], Unit='Percent' ) for cpu in response: if cpu['Key'] == 'Average': k = cpu['Value'] print(k) This is the error message I am getting: Traceback (most recent call last): File "C:\bin\TestCW-CPU.py", line 25, in &lt;module&gt; if cpu['Key'] == 'Average': TypeError: string indices must be integers
accepted answer: http://stackoverflow.com/a/50049078
has answer: http://stackoverflow.com/a/74772611
has answer: http://stackoverflow.com/a/50049078
upvote count: 10

http://stackoverflow.com/comment/86849684
has text: Thanks a lot for the valuable advice. I'll keep this in mind. I was aware of the creating another list and filtering the values approach but I wanted to know the specific mistake in my snippet of code. Thanks anyways.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49917080
score: 1

http://stackoverflow.com/comment/86987181
type: QuestionComment
comment on: http://stackoverflow.com/q/49985017
has text: Thank you for your comment, probably I was not 100% clear: from this example it seems to me that they all work fine, however maybe there are some issues that may arise, or tricks I am not aware of
type: Comment
score: 0

http://stackoverflow.com/comment/87072287
type: QuestionComment
has text: Why are you using slicing to get the table name?
comment on: http://stackoverflow.com/q/50028067
score: 1
type: Comment

http://stackoverflow.com/a/50062949
has comment: http://stackoverflow.com/comment/87288320
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50062855
answers question: http://stackoverflow.com/q/50062855
has body: Use a while loop to check if the next line have any content. Ex: with open(filename2, "r") as in_file: for line in in_file: abc="Escape character is '^]'." if line.strip()==abc: while True: result= next(in_file) if result.strip(): break print(result)
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86884923
type: Comment
has text: Binary image can work, if you change the threshold accordingly, can you upload some sample images to give us an idea as to what it actually looks like? Sample images would help in formulating a better solution.
type: QuestionComment
comment on: http://stackoverflow.com/q/49932344
score: 0

http://stackoverflow.com/q/49938509
type: Question
has comment: http://stackoverflow.com/comment/86931396
type: UnansweredQuestion
tagged with: python
tagged with: amazon-web-services
tagged with: flask
has comment: http://stackoverflow.com/comment/86893583
tagged with: zappa
has comment: http://stackoverflow.com/comment/86911681
answer count: 0
score: 1
has body: I created my flask application to connect with mongodb and retrieve information from a collection based on the api methods. here is my code: from flask import Flask, jsonify, request from flask_pymongo import PyMongo import re app = Flask(__name__) app.config['MONGO_DBNAME'] = 'mydb' app.config['MONGO_URI'] = 'mongodb://user:pwd@ds157711.mlab.com:57711/mydb' mongo = PyMongo(app) @app.route('/framework', methods=['GET']) def get_all_frameworks(): framework = mongo.db.mydb output = [] for q in framework.find(): output.append({"_id": q["_id"], "username":q["username"], return jsonify({'result':output}) @app.route('/product/&lt;name&gt;', methods=['GET']) def get_one_framework(name): framework = mongo.db.offers result=[] for q in framework.find({"product": {'$regex':name,'$options':'i'}}): # print(type(q)) # print(q) result.append(q) if len(result)!=0: return jsonify({"result":result}) else: return "no matching results" @app.route('/seller/&lt;name&gt;',methods=["GET"]) def seller_record(name): framework=mongo.db.offers q=framework.find_one({'seller':name}) if q: return jsonify(q) else: return "No seller found for {}".format(name) I ran zappa init and zappa deploy dev and got the url. but, when I ran the url,https://abcd.execute-api.us-east-2.amazonaws.com/dev/framework I am getting the below error: "{'message': 'An uncaught exception happened while servicing this request. You can investigate this with the `zappa tail` command.', 'traceback': ['Traceback (most recent call last):\\n', ' File \"/var/task/handler.py\", line 452, in handler\\n response = Response.from_app(self.wsgi_app, environ)\\n', ' File \"/var/task/werkzeug/wrappers.py\", line 903, in from_app\\n return cls(*_run_wsgi_app(app, environ, buffered))\\n', ' File \"/var/task/werkzeug/test.py\", line 884, in run_wsgi_app\\n app_rv = app(environ, start_response)\\n', \"TypeError: 'NoneType' object is not callable\\n\"]}" here is my zappa.json file: { "dev": { "app_function": "mongo.app", "aws_region": "us-east…
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86932323
has title: Error after deploying my flask script in Amazon lambda using zappa
favorite count: 0
tagged with: aws-lambda

http://stackoverflow.com/q/50007292
type: Question
accepted answer: http://stackoverflow.com/a/50007335
tagged with: pandas
has title: String capture function giving unknown error
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50007335
tagged with: dataframe
favorite count: 0
has body: df71 equals: PIC_1 p_lgth Wgt 420294189300189843900787520557 30 112 420951119300189843900787520618 30 64 **PARTIAL-DECODE***P / 42011721930018984390078... 53 112 420112289300189843900782713107 30 144 420212369300189843900787520397 30 70 Below is the function I'm applying to each row of df71 using apply() def pic_mod(row): if row['p_lgth'] !=30: n = row['PIC_1'].str.find('42') PIC_2 = row['PIC_1'].str[int(n):int(n+28)] elif row['p_lgth']==30: PIC_2=row['PIC_1'] return PIC_2 df71['PIC_1_master'] = df71.apply(pic_mod, axis=1) When I run the above code, I get: File "&lt;ipython-input-192-9d112a2f0924&gt;", line 3, in pic_mod n = row['PIC_1'].str.find('42') AttributeError: ("'str' object has no attribute 'str'", 'occurred at index 2') Why!!!???? Below are the data types in case you're wondering. df71.dtypes PIC_1 object p_lgth int64 Wgt object Thanks in advance.
upvote count: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/87031018
tagged with: python
tagged with: string
score: -2
has comment: http://stackoverflow.com/comment/87481944
possible better answer: http://stackoverflow.com/a/50007353
has answer: http://stackoverflow.com/a/50007353

scikit-learn
tags question: http://stackoverflow.com/q/49948628
tags question: http://stackoverflow.com/q/49979171
tags question: http://stackoverflow.com/q/50064632
tags question: http://stackoverflow.com/q/50019036
tags question: http://stackoverflow.com/q/50008391
tags question: http://stackoverflow.com/q/49918876
tags question: http://stackoverflow.com/q/50070398
tags question: http://stackoverflow.com/q/49969960
tags question: http://stackoverflow.com/q/49989889
tag name: scikit-learn
tags question: http://stackoverflow.com/q/50011348
tags question: http://stackoverflow.com/q/49955592
tags question: http://stackoverflow.com/q/49943935
tags question: http://stackoverflow.com/q/49942700
tags question: http://stackoverflow.com/q/50009682
tags question: http://stackoverflow.com/q/49973586
tags question: http://stackoverflow.com/q/50008120
tags question: http://stackoverflow.com/q/50068227
tags question: http://stackoverflow.com/q/49930996
tags question: http://stackoverflow.com/q/50034958
tags question: http://stackoverflow.com/q/49997685
type: Tag
tags question: http://stackoverflow.com/q/49922120
tags question: http://stackoverflow.com/q/49956654
tags question: http://stackoverflow.com/q/49946462
tags question: http://stackoverflow.com/q/50050708
tags question: http://stackoverflow.com/q/50010065
tags question: http://stackoverflow.com/q/50006318
tags question: http://stackoverflow.com/q/50044974
tags question: http://stackoverflow.com/q/50030751
tags question: http://stackoverflow.com/q/49950092
tags question: http://stackoverflow.com/q/50051040
tags question: http://stackoverflow.com/q/49989128
tags question: http://stackoverflow.com/q/49969788
tags question: http://stackoverflow.com/q/49968432
tags question: http://stackoverflow.com/q/50002315
tags question: http://stackoverflow.com/q/49927354
tags question: http://stackoverflow.com/q/50069166
tags question: http://stackoverflow.com/q/49961668
tags question: http://stackoverflow.com/q/49942452
tags question: http://stackoverflow.com/q/50013828
tags question: http://stackoverflow.com/q/49940816
tags question: http://stackoverflow.com/q/49974120
tags question: http://stackoverflow.com/q/49931965
tags question: http://stackoverflow.com/q/49956354
tags question: http://stackoverflow.com/q/49987686
tags question: http://stackoverflow.com/q/50047844
tags question: http://stackoverflow.com/q/49924824
tags question: http://stackoverflow.com/q/49991677
tags question: http://stackoverflow.com/q/49949224
tags question: http://stackoverflow.com/q/50072501
tags question: http://stackoverflow.com/q/50041551
tags question: http://stackoverflow.com/q/49969087
tags question: http://stackoverflow.com/q/49987532
tags question: http://stackoverflow.com/q/50027959
tags question: http://stackoverflow.com/q/49966639
tags question: http://stackoverflow.com/q/50002654
tags question: http://stackoverflow.com/q/49957598
tags question: http://stackoverflow.com/q/49929912
tags question: http://stackoverflow.com/q/49962238
tags question: http://stackoverflow.com/q/49974030
tags question: http://stackoverflow.com/q/50012584
tags question: http://stackoverflow.com/q/49970178
tags question: http://stackoverflow.com/q/50023771
tags question: http://stackoverflow.com/q/49997883
tags question: http://stackoverflow.com/q/49936379
tags question: http://stackoverflow.com/q/49978509
tags question: http://stackoverflow.com/q/50045558
tags question: http://stackoverflow.com/q/49974855
tags question: http://stackoverflow.com/q/49923800

pca
tag name: pca
tags question: http://stackoverflow.com/q/49957601
tags question: http://stackoverflow.com/q/50008391
type: Tag

http://stackoverflow.com/a/49997313
accepted answer of: http://stackoverflow.com/q/49996592
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87011205
upvote count: 1
downvote count: 0
type: Answer
has body: It is not a memory problem. Problem is in p_i import numpy as np cm = np.array([[65, 4, 22, 24], [6, 81, 5, 8], [0, 11, 85, 19], [4, 7, 3, 90]]) proportions = [0.3, 0.4, 0.1, 0.2] n = np.sum(cm) nisum = np.sum(cm, axis=1) nsumj = np.sum(cm, axis=0) p_i = np.zeros([cm.shape[0], 1]) p_ii = np.zeros([cm.shape[0], cm.shape[1]]) prod_ac = np.zeros([cm.shape[0], 1]) user_ac = np.zeros([cm.shape[0], 1]) overall_ac = 0 for i in range(cm.shape[1]): for j in range(cm.shape[0]): p_ii[i, j] = proportions[i] * cm[i, j] / nisum[i] if i == 0: p_i = np.sum(p_ii, axis=0) print(p_i) prod_ac[i] = ((proportions[i] / p_i[i]) * (cm[i, i] / nisum[i])) user_ac[i] = cm[i, i] / nisum[i] overall_ac += proportions[i] * cm[i, i] / nisum[i] for i in range(cm.shape[1]): for j in range(cm.shape[0]): p_ii[i, j] = proportions[i] * cm[i, j] / nisum[i] if i == cm.shape[1]-1: p_i = np.sum(p_ii, axis=0) print(p_i) prod_ac[i] = ((proportions[i] / p_i[i]) * (cm[i, i] / nisum[i])) user_ac[i] = cm[i, i] / nisum[i] overall_ac += proportions[i] * cm[i, i] / nisum[i] would give [0.16956522 0.01043478 0.0573913 0.0626087 ] [0.20125753 0.35746154 0.15707358 0.28420736] so that is causing the difference. And the reason is you are summing across the ith axis before the ith axis is completed. So it makes sense that it works the second time because this time the entire array was already ready so it can use values that would have been generated in the following iterations. How to solve this is up to you. One working example is below: for i in range(cm.shape[1]): for j in range(cm.shape[0]): p_ii[i, j] = proportions[i] * cm[i, j] / nisum[i] p_i = np.sum(p_ii, axis=0) for i in range(cm.shape[1]): prod_ac[i] = ((proportions[i] / p_i[i]) * (cm[i, i] / nisum[i])) user_ac[i] = cm[i, i] / nisum[i] overall_ac += proportions[i] * cm[i, i] / nisum[i]
answers question: http://stackoverflow.com/q/49996592

http://stackoverflow.com/comment/87051770
score: 1
type: QuestionComment
has text: Welcome to StackOverflow! Your code snippet is not complete since you do not define `basicoperationslist`. Please show a complete, self-contained snippet that shows your error as well as the traceback of the error for that snippet. Please read and follow [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).
type: Comment
comment on: http://stackoverflow.com/q/50017784

http://stackoverflow.com/a/49989909
downvote count: 0
answers question: http://stackoverflow.com/q/49981497
has comment: http://stackoverflow.com/comment/87049647
has comment: http://stackoverflow.com/comment/87317332
has comment: http://stackoverflow.com/comment/87048051
has comment: http://stackoverflow.com/comment/87016429
has comment: http://stackoverflow.com/comment/87009461
has comment: http://stackoverflow.com/comment/87012708
has comment: http://stackoverflow.com/comment/86996809
has comment: http://stackoverflow.com/comment/87316988
accepted answer of: http://stackoverflow.com/q/49981497
has comment: http://stackoverflow.com/comment/87050279
has comment: http://stackoverflow.com/comment/87318089
type: Answer
has comment: http://stackoverflow.com/comment/87316024
has comment: http://stackoverflow.com/comment/87019386
has comment: http://stackoverflow.com/comment/87317155
has comment: http://stackoverflow.com/comment/87049488
has comment: http://stackoverflow.com/comment/87017154
score: 3
has comment: http://stackoverflow.com/comment/87049541
has comment: http://stackoverflow.com/comment/87008414
has body: Firstly I assume that there are no Pairings in 'blast' with sequences from two different Clusters. In other words: in this solution the cluster-ID of a pairing will be evaluated by only one of the two sequence IDs. Including cluster information and pairing information into one dataframe: data = cluster.merge(blast, left_on='seq_names', right_on='qseqid') Then the data should only contain pairings of different sequences: data = data[data['qseqid']!=data['sseqid']] To ignore pairings which have the same substrings in their seqid, the most readable way would be to add data columns with these data: data['qspec'] = [seqid.split('_')[1] for seqid in data['qseqid'].values] data['sspec'] = [seqid.split('_')[1] for seqid in data['sseqid'].values] Now equal spec-values can be filtered the same way like it was done with equal seqids above: data = data[data['qspec']!=data['sspec']] In the end the data should be grouped by cluster-ID and within each group, the maximum of pident is of interest: data_grpd = data.groupby('cluster_name') result = data.loc[data_grpd['pident'].idxmax()] The only drawback here - except the above mentioned assumption - is, that if there are several exactly equal max-values, only one of them would be taken into account. Note: if you don't want the spec-columns to be of type string, you could easiliy turn them into integers on the fly by: import numpy as np data['qspec'] = [np.int(seqid.split('_')[1]) for seqid in data['qseqid'].values]
has comment: http://stackoverflow.com/comment/87317319
upvote count: 3
has comment: http://stackoverflow.com/comment/87038091
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87048912

http://stackoverflow.com/a/50023090
score: -1
has comment: http://stackoverflow.com/comment/87065782
answers question: http://stackoverflow.com/q/50022814
has comment: http://stackoverflow.com/comment/87065684
upvote count: 0
has comment: http://stackoverflow.com/comment/87071945
downvote count: 1
has body: Try using pickle to serialize and write to .JSON https://docs.python.org/3/library/pickle.html Here's an example of how I save my data for a game I'm working on using pickle def save(): file_player = "Save/%s/player.JSON" % functions.player.name file_world = "Save/%s/world.JSON" % functions.player.name file_counter = "Save/%s/counter.JSON" % functions.player.name a = functions.player b = world.world_map c = functions.counter save_player = open(file_player, 'wb') save_world = open(file_world, 'wb') save_counter = open(file_counter, 'wb') pickle.dump(a, save_player, -1) pickle.dump(b, save_world, -1) pickle.dump(c, save_counter, -1) save_player.close() save_world.close() save_counter.close() This is saving 3 different classes from 3 different files, and dumping them into 1 save folder.
type: Answer

http://stackoverflow.com/q/49981649
has answer: http://stackoverflow.com/a/49982081
downvote count: 1
favorite count: 0
has title: transform touple with (key and list) to (key and list item)
type: Question
has answer: http://stackoverflow.com/a/49982083
tagged with: pyspark
linked to: http://stackoverflow.com/q/22350722
tagged with: python
score: -1
tagged with: rdd
has body: I have an RDD with (key, list[word1, word2, word3]) and i want to transform this to (key, word1), (key, word2)... (key, word-n), can anyone point me in the right direction on how to solve this?
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/86979852
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86979655

http://stackoverflow.com/comment/134719146
comment on: http://stackoverflow.com/a/75477420
score: 0
type: Comment
has text: and might need to restart terminal afterwards.
type: AnswerComment

http://stackoverflow.com/comment/86913459
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49945938
has text: If `GROUP_ID=185` had another row with begin date of 2012-01-01 and `GAP=1` would it's `GAP_THREE` value be 36?
score: 1

http://stackoverflow.com/q/49959621
has body: I have a project with the following hierarchy and I am trying to use a class defined in the file Student.py in the file webcam_classifier.py. I do so like this: from .Student import Student However, I get the following error: ModuleNotFoundError: No module named '__main__.Student'; '__main__' is not a package I'm not sure what I'm doing wrong. Any help is appreciated!!!
has comment: http://stackoverflow.com/comment/86935584
linked to: http://stackoverflow.com/q/72852
score: 1
has comment: http://stackoverflow.com/comment/86935652
tagged with: python
has comment: http://stackoverflow.com/comment/86935851
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86938633
has comment: http://stackoverflow.com/comment/86935739
has title: Errors using class defined in another module in python project
upvote count: 1
has comment: http://stackoverflow.com/comment/86935695
has comment: http://stackoverflow.com/comment/86935822
favorite count: 0

http://stackoverflow.com/comment/87194541
type: AnswerComment
comment on: http://stackoverflow.com/a/50067344
score: 0
type: Comment
has text: Gives me the following error: `UnicodeEncodeError: 'charmap' codec can't encode character '\u2075' in position 0: character maps to <undefined>`

http://stackoverflow.com/comment/86998239
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49987325
score: 0
has text: @martineau I added a simplified version of my .txt file

http://stackoverflow.com/q/49971708
downvote count: 0
tagged with: floating-point
has comment: http://stackoverflow.com/comment/86959328
linked to: http://stackoverflow.com/q/18557337
possible better answer: http://stackoverflow.com/a/49971811
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49971742
has title: Python / Numpy AttributeError: 'float' object has no attribute 'sin'
has answer: http://stackoverflow.com/a/49971811
score: 5
has answer: http://stackoverflow.com/a/49971742
upvote count: 5
has body: I'm going to post this here because it's quite a chestnut and caused me some head-scratching. It's arguably a duplicate of this question posted four years ago but I'll post it again in case someone has the specific pandas-numpy incompatibility that I have encountered here. Or maybe someone will come up with a better answer. Code snippet: #import pdb; pdb.set_trace() # TODO: This raises AttributeError: 'float' object has no attribute 'sin' xr = xw + L*np.sin(θr) Output: Traceback (most recent call last): File "MIP_MPC_demo.py", line 561, in &lt;module&gt; main() File "MIP_MPC_demo.py", line 557, in main animation = create_animation(model, data_recorder) File "MIP_MPC_demo.py", line 358, in create_animation xr = xw + L*np.sin(θr) AttributeError: 'float' object has no attribute 'sin' What I've tried so far: (Pdb) type(np) &lt;class 'module'&gt; (Pdb) np.sin &lt;ufunc 'sin'&gt; (Pdb) type(θr) &lt;class 'pandas.core.series.Series'&gt; (Pdb) np.sin(θr.values) *** AttributeError: 'float' object has no attribute 'sin' (Pdb) θr.dtype dtype('O') (Pdb) np.sin(θr) *** AttributeError: 'float' object has no attribute 'sin' (Pdb) θr.sin() *** AttributeError: 'Series' object has no attribute 'sin' (Pdb) θr.values.sin() *** AttributeError: 'numpy.ndarray' object has no attribute 'sin' (Pdb) θr.values.max() nan (Pdb) np.max(θr) 0.02343020407511865 (Pdb) np.sin(θr) *** AttributeError: 'float' object has no attribute 'sin' (Pdb) np.sin(θr[0]) 0.0 On a side-note, the exception is misleading to say the least. It's been four years since the other person posted the issue. Does anyone else agree that this should be modified and any suggestions on how? What is the explanation for the exception? Is numpy doing some kind of map operation and trying to call the sin method of each element of θr? I will post the answer shortly...
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: attributeerror
tagged with: pandas

http://stackoverflow.com/a/50015399
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87050173
score: 4
answers question: http://stackoverflow.com/q/50015104
upvote count: 4
has body: if your template is stored in directory called template_dir, then you can modify your code as 'DIRS':[os.path.join(BASE_DIR,'template_dir')]. In your code you have joined project directory path with templates. Which(directory) probably does not exist. the get_template function returns a Template object, which does not fit the function template for render, it(render) takes the template nametemplate.html directly.
has comment: http://stackoverflow.com/comment/87051467

http://stackoverflow.com/comment/86987437
type: QuestionComment
has text: The name of the artist in this case is György Kepes, my guess is that my file is not reading the special characters so that's why I'm getting the GyÌ¦rgy Kepes. I have other examples like that across my dataset like: LÌÁszlÌ_ Moholy-Nagy instead of László Moholy-Nagy. I am not worried about the correct spelling since I am going to transform the names to categorical values. So yes, the suggestion you gave me works perfectly!
score: 0
comment on: http://stackoverflow.com/q/49985363
type: Comment

http://stackoverflow.com/q/49990493
downvote count: 1
favorite count: 0
type: Question
tagged with: graph
has title: How to properly use semilogy?
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49990585
has body: For class, we are supposed to calculate the absolute error, realistic error for an e series. In the end, we have to graph both the relative error and the absolute error using a "semilogy" graph. The code itself works fine and produces a numerical calculation as expected. But in terms of the graph, it doesn't get near the actual result. Any idea of why this isn't working? An image of the graph has been attached at the end. import numpy as np import math as m import matplotlib.pyplot as plt Exp_List = [] Relative_Error = [] Absolute_Error = [] def ExpCalc(x,N,t): exp = 0.0 for i in range(N-1): fac = m.factorial(i) next_term = x**i/fac Exp_List.append(next_term) exp += next_term Relative = abs((sum(Exp_List)-t)/sum(Exp_List)) Relative_Error.append(Relative) Absolute = abs(sum(Exp_List)-t) Absolute_Error.append(Absolute) i += 1 return (Absolute_Error, Relative_Error) A = m.exp(1) B = m.exp(20) C = m.exp(100) print(ExpCalc(1,20,A)) plt.figure() plt.semilogy(ExpCalc(1,20,A)) plt.show() The image shows the numerical calculations as well as the graph obtained from the code
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86997659
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/49978682
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/49979235
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49979235
has title: How to get a list of strings for a pandas dataframe?
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49978732
answer count: 2
tagged with: pandas
score: 1
has body: I have a dataframe which I obtain after doing certain operations. This is how my dataframe looks like date metric stat val device 0 2018-03-21 cpu mean 76.724406 10.41.100.1 3 2018-03-21 cpu std 124.285789 10.41.100.1 Now I want to convert it to a list of strings stored inside a list, something like below lis = [["2018-03-21", "cpu", "mean", "76.724406", "10.41.100.1"], ["2018-03-21", "cpu", "mean", "124.285789", "10.41.100.1"]] I did something like this for i in df: print(df[i].tolist()) But I get something like this [Timestamp('2018-03-21 00:00:00'), Timestamp('2018-03-21 00:00:00')] ['cpu', 'cpu'] ['mean', 'std'] [76.72440613174048, 124.28578926665278] ['10.41.100.1', '10.41.100.1'] But I want the format to be like mentioned above. How can I do this?
has answer: http://stackoverflow.com/a/49978732

http://stackoverflow.com/a/49922315
answers question: http://stackoverflow.com/q/49922120
type: Answer
score: 0
has body: Try this import numpy as np import pandas as pd from scipy import sparse obs = np.random.randint(0, 2, 50) pred = np.random.randint(0, 2, 50) vals = np.ones(50).astype('int') con = sparse.coo_matrix((vals, (pred, obs))) print (con.todense())

http://stackoverflow.com/a/50015977
has comment: http://stackoverflow.com/comment/87237230
has body: You can use 1 as the batch dimension for the constant tensor in your Lambda: import keras.backend as K [...] def my_lambda(x): q_array = np.zeros((1, SEQ_LEN)) q_array = ... # your value q = K.constant(q_array.T) return Dot()([q, x]) result = Lambda(my_lambda)(word_embs)
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50013640
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50013640

http://stackoverflow.com/q/50034347
has answer: http://stackoverflow.com/a/50042416
tagged with: dynamic-programming
accepted answer: http://stackoverflow.com/a/50042416
has comment: http://stackoverflow.com/comment/87086467
has comment: http://stackoverflow.com/comment/87084830
tagged with: python
has title: Convert the input number to alphabet representation
linked to: http://stackoverflow.com/q/159590
has comment: http://stackoverflow.com/comment/87092997
has comment: http://stackoverflow.com/comment/87093620
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87101554
downvote count: 0
has comment: http://stackoverflow.com/comment/87104041
has comment: http://stackoverflow.com/comment/87088762
answer count: 1
has comment: http://stackoverflow.com/comment/87093545
has comment: http://stackoverflow.com/comment/87084814
favorite count: 0
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87086988
has comment: http://stackoverflow.com/comment/87093285
has body: I was asked below program to code and have coded to a good extent. But not able to simulate 0 case consideration, Where am I missing? Below is the question and code: Let 0 represent ‘A’, 1 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit sequence. Input: digits[] = "121" Output: 3 ( The possible decodings are "BCB", "BV", "MB" ) Similarly "200" can be interpreted as "caa" or "ua" and "007" has one. My code: def countValidSequences(input_num): n = len(input_num) number = list(input_num) occurance = [0] * (n+1) occurance[0] = 1 occurance[1] = 1 for i in range(2, n+1): occurance[i] = 0 if (number[i-1] &gt; '0'): occurance[i] += occurance[i-1] if (number[i-2] &lt; '2' or (number[i-2] &lt;= '2' and number[i-1] &lt; '6') ): occurance[i] += occurance[i-2] return occurance[n] print("Count ",countValidSequences("200")) print("Count ",countValidSequences("2563")) print("Count ",countValidSequences("123")) print("Count ",countValidSequences("99")) print("Count ",countValidSequences("100200300")) O/P: Count 1 Count 2 Count 3 Count 1 Count 3 It works fine for the input not having 0, any idea where am I missing?

amazon-athena
type: Tag
tag name: amazon-athena
tags question: http://stackoverflow.com/q/49948563

http://stackoverflow.com/q/49922120
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/86859887
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49922315
has comment: http://stackoverflow.com/comment/86860051
type: Question
has title: How can I get sparce confusion matrix?
type: UnansweredQuestion
has body: I'm trying to "rolling Random forest classification" for timeseries data. The model classifies two classes. It changes the data samples and fits several times, which I mean "rolling". I get confusion matrixes for each sample sets and sum up as final step. but in several sample sets, only one class exit. In this case, matrix shows up like below: [[22]] I want to make this case like below; [[22, 0] [0, 0]] Do you have any idea to make this happen?

http://stackoverflow.com/comment/86877632
has text: If you want to use it you can download the codec from http://www.fourcc.org/downloads/h264-unknown-10/
comment on: http://stackoverflow.com/q/49929581
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87107983
type: QuestionComment
comment on: http://stackoverflow.com/q/50045648
has text: Not clear, but I suppose you should use some gems, for example `require "csv"` and `require "sqlite3"`
score: 0
type: Comment

http://stackoverflow.com/q/50025532
tagged with: set-theory
linked to: http://stackoverflow.com/q/12390698
has comment: http://stackoverflow.com/comment/87067593
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87070272
upvote count: 3
duplicate of: http://stackoverflow.com/q/12390698
has body: I need to find out if there is any intersection between two arrays with start and end value (wiki on this https://en.wikipedia.org/wiki/Intersection_(set_theory)). For example (just a few cases): a = (10, float("inf")) b = (8, float("inf")) or a = (10, 20) b = (4, 25) So, b contains a. How can I do this in python ? Are there any tools for this ? Thanks
downvote count: 2
has comment: http://stackoverflow.com/comment/87067715
score: 1
accepted answer: http://stackoverflow.com/a/50025629
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50025629
type: Question
tagged with: math
tagged with: intersection
has title: Checking intersection of two sets by two values in each
has comment: http://stackoverflow.com/comment/87067253
has comment: http://stackoverflow.com/comment/87067553
tagged with: python

http://stackoverflow.com/a/58173389
has body: This has now been implemented. Use torch.set_printoptions(sci_mode=False) https://pytorch.org/docs/stable/torch.html#torch.set_printoptions
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/50043438
upvote count: 5
type: Answer

http://stackoverflow.com/comment/86899365
has text: Unicode is not an encoding. The encoding of source file (which has the strings) is usually the same for the two files. The first is encoded internally as `unsigned char`. The second as `UCS2` in Python2 (so a unicode code can be represented by one or two python `u` characters. On Python3, it can be one of ASCII, UTF16 or UTF32 (selected dynamically), so just ignore how Python encode internally characters.
comment on: http://stackoverflow.com/q/49941052
type: Comment
type: QuestionComment
score: 2

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/49956275
type: Tag

caching
tags question: http://stackoverflow.com/q/49957335
tags question: http://stackoverflow.com/q/49999474
type: Tag
tag name: caching
tags question: http://stackoverflow.com/q/49929615

http://stackoverflow.com/comment/87099521
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169851/discussion-between-simon-and-philippos).
score: 1
comment on: http://stackoverflow.com/q/50038651
type: Comment

http://stackoverflow.com/a/50039886
score: 0
has body: The error is coming from Haystack, so it looks as if your version of Haystack does not support Django 1.11. Try upgrading Haystack. Version 2.8.1, the latest release at the time of writing, supports Django 1.11. I can't find anything explicit in the docs, but this commit suggests that support for Django 1.11 was added in version 2.7.
answers question: http://stackoverflow.com/q/50039758
type: Answer

http://stackoverflow.com/comment/87002302
has text: If you're running the Python script as part of some request in node.js, then you should just pass the value to the Python script when you start it. If it's not a dynamic value that changes a lot, you can just put the value in a JSON file and have each script just read it from disk when needed. For a single value, I wouldn't introduce a database just for that. For data that doesn't need to persist, you can also use redis.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49992649

http://stackoverflow.com/a/49967591
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: Using pandas import pandas as pd df = pd.read_csv(filename, sep="\t")
answers question: http://stackoverflow.com/q/49967297

http://stackoverflow.com/q/49973107
answer count: 1
upvote count: 1
has body: I have the following dataset: d1 = {'Indiv1':['Subject1','Subject2','Subject1','Subject1','Subject2','Subject1','Subject1','Subject2'], 'Indiv2': ['Subject4','Subject3','Subject2','Subject4','Subject4','Subject2','Subject3','Subject3'], 'Event':['1','1','2','2','2','3','3','3'], 'Category':['1','2','1','1','1','2','2','2'], 'Variable1':['1','2','3','4','5','6','7','8'], 'Variable2':['12','11','10','9','8','7','6','5'], 'Variable3': ['-4','-3','-2','-1','0','1','2','3']} d1 = pd.DataFrame(d1) d1=d1'Indiv1','Indiv2','Event','Category','Variable1','Variable2','Variable3' d1 Which gives the following (In my dataset this particular file has over 2 million rows): d1= I have a second smaller dataset (about 1500 rows) in the following format: d2 = {'Indiv1': ['Subject1','Subject3','Subject1','Subject4','Subject2','Subject1','Subject1','Subject2'], 'Indiv2': ['Subject4','Subject2','Subject6','Subject1','Subject1','Subject8','Subject9','Subject113'], 'Event':['1','1','2','2','2','3','3','3'], 'Category':['1','2','1','1','1','2','2','2']} d2 = pd.DataFrame(d2) d2=d2'Indiv1','Indiv2','Event','Category' d2 which looks like the following: d2= what I need to do is to look up the pairs of subjects in each event in each category from the second file (d2). If the pair exixts in both d1 and d2 for the given event id and category, then assign 1 to the row in df1. Otherwise assign 0. Note that in row 2 of df2, the order of the two individuals are flipped. Instead of Subject 2 and Subject 3 as in d1, in d2 we have Subject 3 and Subject 2. However, in my case I want to treat both as the same. In this case, I want to assign a value of 1 to these cases. Finally there are pairs in d1 which are not in d2 (for each event, for each category). For example, for event 3, there is no pair with Subject1 and Subject 2 in df2 (although this exists in df1). In such a case, assign a value =0 under the column present. The final output will look like this: I am especially very perplexed with how t…
score: 1
favorite count: 0
type: Question
tagged with: data-manipulation
downvote count: 0
accepted answer: http://stackoverflow.com/a/49973148
has title: Python find pairs when from subset (pair numbers are changing)
tagged with: python
has answer: http://stackoverflow.com/a/49973148
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas

http://stackoverflow.com/comment/86942265
comment on: http://stackoverflow.com/a/49935109
type: Comment
has text: @AdhiR. You're correct. I also should have written "non-tree DAG" instead of "DAG" in the above (a tree is a DAG). In general, I think your problem is pretty simple Pandas-wise, but has graph theory questions. Again, I suggest asking a new question with your above comment: I am modeling an online forum, here is the dataframe, I'd like to find the levels, what is the best way? If you ping me here, I'll be happy to look at it.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87049153
has text: @ptb Unfortunately, the memory keeps exploding.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49997220
type: QuestionComment

http://stackoverflow.com/comment/126128148
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49973522
has text: @climatestudent Yes, now xarray has `interp` and `interp_like`, which I have implemented ;) Use these methods instead.
score: 2

http://stackoverflow.com/q/50048484
tagged with: list
tagged with: join
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87113149
has body: I am trying to join a lists of appended sentences into a large a string text object so that I can use it as an input for the Gensim summarize module. However, when I try to do this, it says the input sentences are less than 2. But when I run a split on the text, I see multiple sentences but it counts each sentence once instead of the total of sentences together. And the variable r is a string type object. I would like to concatenate the sentences together into one large string so it can be read through the Gensim summarize module. Sample Code: import re ruling_corpora = re.findall("\.?([^\.].\*?I find[^\.]*\. |[^\.]*$In sum[^\.]*\. |[^\.]*$agree[^\.]*\.)", tokenized, re.I |re.DOTALL |re.M)[1:-1] for r in ruling_corpora: print(type(r)) rc= ''.join(r) print(summarize(rc)) SAMPLE OUTPUT: raise ValueError("input must have more than one sentence") ValueError: input must have more than one sentence Here is an example of my input I want to summarize with the Gensim summarizer. The numbers underneath each string represent the count of sentences ending in periods: ####Beginning of File### LUMB65.BL23607963.xml Background Content: ANDERSON INITIAL DECISIONOn January 13, 2015, the appellant filed this appeal arguing that the agency's decision not to renew his term limited appointment which expired on January 28, 2015, is in error. For the reasons discussed below, this appeal is DISMISSED for lack of jurisdiction without a hearing. 1 There is nothing in the agreement that curtails the agency's ability not to extend the term appointment. IdIn reviewing the appellant's arguments, the appellant fails to establish that the Board has jurisdiction to review the agency's decision not to renew his time-limited appointment at issue in this appeal. Following a review of the record evidence, I find that the appellant has failed to non-frivolously allege Board jurisdiction over this appeal on any basis. Accordingly, this appeal must be dismissed for lack of jurisdiction. 1 ####End of File#…
has title: joining sentences from a list in python3
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50048953
tagged with: python
score: -1
tagged with: gensim
tagged with: regex
accepted answer: http://stackoverflow.com/a/50048953
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/49924237
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: guppy
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86865075
answer count: 0
linked to: http://stackoverflow.com/q/38859593
has body: I'm currently facing a weird issue that I cannot successfully install guppy package into my project using the command: pip install guppy The console ends up with: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c src/sets/sets.c -o build/temp.macosx-10.12-x86_64-3.6/src/sets/sets.o src/sets/sets.c:77:1: error: expected function body after function declarator INITFUNC (void) ^ src/sets/sets.c:39:18: note: expanded from macro 'INITFUNC' #define INITFUNC initsetsc ^ 1 error generated. error: command 'clang' failed with exit status 1 Command "/Users/unifiedloaner/.virtualenvs/communique/bin/python3.6 -u -c "import setuptools, tokenize;file='/private/var/folders/kb/ynmw5jys2_ddb7_1qy8x6l7r0000gr/T/pip-install-r90baffb/guppy/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/kb/ynmw5jys2_ddb7_1qy8x6l7r0000gr/T/pip-record-mbb2utye/install-record.txt --single-version-externally-managed --compile --install-headers /Users/unifiedloaner/.virtualenvs/communique/bin/../include/site/python3.6/guppy" failed with error code 1 in /private/var/folders/kb/ynmw5jys2_ddb7_1qy8x6l7r0000gr/T/pip-install-r90baffb/guppy/ I'm using pip 10.0.0 and Python 3.6 in my virtualenv communique
downvote count: 0
has comment: http://stackoverflow.com/comment/86864749
has comment: http://stackoverflow.com/comment/88342427
duplicate of: http://stackoverflow.com/q/38859593
has title: Cannot install Guppy into my project
favorite count: 0
has comment: http://stackoverflow.com/comment/86864461
type: Question

http://stackoverflow.com/comment/87095785
type: Comment
has text: There's a chat system. Let me just create one :)
type: AnswerComment
comment on: http://stackoverflow.com/a/50039184
score: 0

http://stackoverflow.com/a/50000911
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/50000399
has comment: http://stackoverflow.com/comment/87027469
has comment: http://stackoverflow.com/comment/87025725
has comment: http://stackoverflow.com/comment/87025414
type: Answer
has comment: http://stackoverflow.com/comment/87024554
has comment: http://stackoverflow.com/comment/87024317
has comment: http://stackoverflow.com/comment/87024875
has body: Using the module os you can check the existence of the file within python by running import os os.path.isfile(fname) If it returns False, that means that your file doesn't exist in the specified fname. If it returns True, it should be read by np.loadtxt(). Extra: good practice working with files and paths When working with files it is advisable to use the amazing functionality built in the Base Library, specifically the module os. Where os.path.join() will take care of the joins no matter the operating system you are using. fname = os.path.join(BASE_FOLDER, BASE_NAME) In addition it is advisable to use raw strings by adding an r to the beginning of the string. This will be less tedious when writing paths, as it allows you to copy-paste from the navigation bar. It will be something like BASE_FOLDER = r'C:\path'. Note that you don't need to add the latest '\' as os.path.join takes care of it.
has comment: http://stackoverflow.com/comment/87024089
downvote count: 0
has comment: http://stackoverflow.com/comment/87024984
has comment: http://stackoverflow.com/comment/87020091

http://stackoverflow.com/a/49942602
upvote count: 5
type: Answer
has body: Existing answers cover the "how?" of the question, but not the "why". Which is to say, why doesn't lambda: print(3); print(5) work? The answer is in the language specification. From https://docs.python.org/3/reference/expressions.html#lambda: Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression lambda arguments: expression yields a function object. [...] Note that functions created with lambda expressions cannot contain statements or annotations. From https://docs.python.org/3/reference/simple_stmts.html?highlight=semicolon#simple-statements: A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. print(3); print(5) contains a semicolon, so it is a collection of simple statements. But a lambda can't contain statements. So a lambda can't contain print(3); print(5). So why does (lambda key: (print(3), print(5))) work? It's because (print(3), print(5)) is not a statement. It's an expression: in particular, it is a tuple literal (formally, a parenthesized form whose expression list contains at least one comma), whose first element is a call to print with argument 3, and whose second element is a call to print with argument 5. All of this is a single expression, so lambda accepts it without trouble.
answers question: http://stackoverflow.com/q/49942050
type: AcceptedAnswer
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49942050

http://stackoverflow.com/comment/86953570
type: Comment
comment on: http://stackoverflow.com/q/49941881
type: QuestionComment
has text: @tburrows13 I install my modules through pycharm, I think it updates automatically.
score: 0

http://stackoverflow.com/comment/86973036
comment on: http://stackoverflow.com/q/49978415
score: 0
has text: Be careful with the file paths under Windows.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50037803
has body: In Excel you use the single quote to stop Excel converting a numerical string into a number. In openpyxl you don't need to this, just assign the cell the value as a string, eg. ws['A1'] = "4". openpyxl does not support the quotePrefix attribute.
answers question: http://stackoverflow.com/q/50027429
score: -3
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/126936320
downvote count: 3

http://stackoverflow.com/comment/87144923
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50061458
has text: So as I am on Python2.7 the version outputted was: `OpenSSL 0.9.8l 5 Nov 2009`
score: 0

http://stackoverflow.com/q/50050692
has comment: http://stackoverflow.com/comment/92915490
tagged with: telegram-bot
has comment: http://stackoverflow.com/comment/87122000
answer count: 0
has comment: http://stackoverflow.com/comment/87117682
tagged with: cherrypy
favorite count: 0
type: Question
score: 5
has comment: http://stackoverflow.com/comment/87175667
type: UnansweredQuestion
has body: I am using python and cherrypy with my telegram bot. Also, I am using webhooks instead of long polling. But the bot doesn't work. Get_webhook_info returns this message: { "ok": true, "result": { "url": "https://IP/571605115:token/", "has_custom_certificate":true, "pending_update_count":3, "last_error_date":1524150207, "last_error_message":"Connection timed out", "max_connections":40 } } Could somebody please help with this?
has title: Connection time-out on telegram-bot
tagged with: webhooks
upvote count: 5
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87118084

http://stackoverflow.com/comment/112631166
has text: Why I have black screen?) Kivy program starts, but it does nothing, only black screen)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50029481

http://stackoverflow.com/a/49963285
type: Answer
accepted answer of: http://stackoverflow.com/q/49963241
answers question: http://stackoverflow.com/q/49963241
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86942577
has body: This line if (player != 'Rock') or (player != 'Paper') or (player != 'Scissor'): will always be True if there is no tie. Change it to if player not in options: Some suggestions to improve your code You can remove the ()s in all your ifs. This if (player == npc): is the same as if player == npc: You should also use if/elif/else instead of only if. This will make the use of continue unncessary. Edit: Improved version: import random options = ['Rock','Paper', 'Scissor'] npc = random.choice(options) print('Hello') print('We are about to play Rock,Paper,Scissors.') while True: npc = random.choice(options) player = str(input('Please declare your weapon: ')).capitalize() if player == npc: print('Your choice: ', player) print('npc choice: ', npc) print('Oopsie looks like we have a tie!') print('Lets Try again!') elif player not in options: print('Poo Poo, that is not a valid option! Please try again!') elif (player == 'Rock' and npc == 'Scissor') or (player == 'Scissor' and npc == 'Paper') or (player == 'Paper' and npc == 'Rock'): print('Your choice: ', player) print('npc choice: ', npc) print('You win!') break else: print('Your choice: ', player) print('npc choice: ', npc) print('You lose!') break
downvote count: 1
score: 1

http://stackoverflow.com/comment/87033221
comment on: http://stackoverflow.com/q/50008237
score: 0
type: Comment
type: QuestionComment
has text: If you want this to be at all useful, you probably want the abstract method to take the extra parameter (maybe with a default value, and maybe even with classes that don’t want that parameter asserting that they got the default value). Otherwise, knowing that an object meets the Agent ABC doesn’t actually tell you how to use it, so why even have an ABC?

http://stackoverflow.com/comment/86893457
type: Comment
has text: oh boi, that's it, thanks a lot dude ! (and yes i'm writting a test client ;) )
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49924807

http://stackoverflow.com/q/50037208
answer count: 0
has body: I want to have a custom python function which: Takes a mathematical expression f(x) , bounds of the integral x1,x2 and desired tolerance tol Uses sympy.integrate(y, x) to check if it has analytical/symbolic solution, if it does then returns the result using sympy.integrate(y, (x,x1,x2).evalf()) If it doesn't have an analytical solution out of the sympy then it uses scipy.integrate.quad or other numerical functions to calculate the integral. The reason is that with this method it will be probably faster and more accurate as a majority of mathematical expressions I'm working with, have analytical integrals. But I have some issues first of all scipy.integrate.quad and sympy.integrate two very different forms of functions. scipy takes python def y(x): return f(x) or lambda y=lambda x: f(x) functions. But sympy takes mathematica expressions y=f(x) where x has been symbolized by sympy.Symbol('x'). I need to find a way to convert a sympy symbolic mathematical expression to python/lambda function or vise versa. my second issue is that sympy does not give any error when the expression doesn't have an analytical integral. it just prints the integral! (for this issue I posted a different question here) And last one I don't know how control the tolerance in sympy's evalf(). I think for scipy.integrate.quad one can control the tolerance with epsabs input? I would appreciate if you could let me know if it is possible and how to do it.
tagged with: sympy
upvote count: 2
type: UnansweredQuestion
tagged with: symbolic-math
downvote count: 0
has comment: http://stackoverflow.com/comment/87095223
linked to: http://stackoverflow.com/q/50039222
tagged with: numerical-integration
has comment: http://stackoverflow.com/comment/87093124
has comment: http://stackoverflow.com/comment/87094443
tagged with: python
tagged with: scipy
has comment: http://stackoverflow.com/comment/87093642
favorite count: 0
has comment: http://stackoverflow.com/comment/87093080
type: Question
has title: Python integration using both scipy and sympy
score: 2
has comment: http://stackoverflow.com/comment/87094957
linked to: http://stackoverflow.com/q/50033275

http://stackoverflow.com/comment/107076712
type: Comment
has text: @Suhas not sure I understand your comment: the OP's example was about rows, so excluding the last row is the intended behavior. Am I missing something?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49962706

http://stackoverflow.com/a/62812817
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49990243
type: Answer
has body: Can you try config.cache E.g. - request.config.cache.set('run_id', run_id) refer documention

http://stackoverflow.com/q/50038842
has comment: http://stackoverflow.com/comment/87094811
score: 0
answer count: 1
has body: I have troubles designing a working udf for my task on PySpark (python=2.7, pyspark=1.6) I have a data DataFrame which looks like this : +-----------------+ | sequence| +-----------------+ | idea can| | fuel turn| | found today| | a cell| |administration in| +-----------------+ And for each row in data I'd like to lookup info in an other DataFrame called ggrams (based on the attribute sequence), compute aggregates and return that as a new column in data. My feeling is that I should do it that way : from pyspark.sql.types import IntegerType from pyspark.sql.functions import udf def compute_aggregates(x): res = ggrams.filter((ggrams.ngram.startswith(x)) \ ).groupby("ngram").sum("match_count") return res.collect()[0]['sum(match_count)'] aggregate = udf(compute_aggregates, IntegerType()) result = data.withColumn('aggregate', compute_aggregates('sequence')) But that returns a PicklingError. PicklingError: Could not serialize object: Py4JError: An error occurred while calling o1759.__getstate__. Trace: py4j.Py4JException: Method __getstate__([]) does not exist
has comment: http://stackoverflow.com/comment/87095226
tagged with: user-defined-functions
type: Question
has comment: http://stackoverflow.com/comment/87094963
tagged with: pyspark
has title: Method for all rows of a PySpark DataFrame
accepted answer: http://stackoverflow.com/a/50039701
tagged with: python
has answer: http://stackoverflow.com/a/50039701
has comment: http://stackoverflow.com/comment/87095066
has comment: http://stackoverflow.com/comment/87094049
has comment: http://stackoverflow.com/comment/87095123
has comment: http://stackoverflow.com/comment/87093973
type: AnsweredQuestion

http://stackoverflow.com/a/50048887
score: 3
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50048681
has body: There are several different ways to do this, you could parse the dictionary inside your __init__ function for example. I tend to handle this by having a separate @classmethod that is responsible for parsing dictionaries to create instances of my class. Something like this: class Coinbuilder: def __init__(self, cur, curlong): self.currency = cur self.currency_long = curlong @classmethod def build_from_dict(coin_b, d): attributes = {'Currency', 'CurrencyLong'} try: class_dct = {a: d[a] for a in attributes} except: raise ValueError('Input did not contain necessary attributes') return coin_b(class_dct['Currency'], class_dct['CurrencyLong']) This way I am not forced to pass Coinbuilder a dictionary to create a class instance, but I have a simple method I can use to parse a dictionary to create an instance of my class. For this simple example, I can do the following: x = Coinbuilder.build_from_dict({'Currency': 'BTC', 'CurrencyLong': 'Bitcoin'}) Or I could use: y = Coinbuilder('BTC', 'Bitcoin') And get two equal class instances: print(x.currency, x.currency_long) print(y.currency, y.currency_long) Output: BTC Bitcoin BTC Bitcoin Using your sample input as a guide, once you write your @classmethod to parse your dictionary, you could then simply use: my_coins = [] for result in coins['result']: my_coins.append(Coinbuilder.build_from_dict(result)) Or: my_coins = [Coinbuilder.build_from_dict(result) for result in coins['result']]

http://stackoverflow.com/comment/87622029
has text: @ws_e_c421, I posted an example on gist, please check it.
comment on: http://stackoverflow.com/a/49972446
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50044114
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pandas
has title: Append results of DataFrame apply lamda to DateFrame or new Series
has body: I am using the apply method with a lamda to compute on each row of a Dataframe to return a Series. statsSeries = matchData.apply(lambda row: mytest(row), axis=1) where mytest(row) is a function that returns timestamp, float, float. def mytest(row): timestamp = row['timestamp'] wicketsPerOver = row['wickets']/row['overs'] runsPerWicket = row['runs']/row['wickets'] return timestamp, wicketsPerOver, runsPerWicket As I have written it, the statsSeries contains two columns, one an index and the other a tuple of the (timestamp, wicketsPerOver, runsPerWicket). How can I return a Series with three columns [timestamp, wicketsPerOver, runsPerWicket]?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: series
has comment: http://stackoverflow.com/comment/87104486
tagged with: python
accepted answer: http://stackoverflow.com/a/50044325
tagged with: lambda
tagged with: apply
has answer: http://stackoverflow.com/a/50044325

http://stackoverflow.com/q/50018843
tagged with: psycopg2
score: 0
answer count: 1
has body: I am trying to a simple make a http request to a server inside my company, from a dev server. I figured out that depending on the origin / destination server, I might, or not, to be forced to use qualified name of the destination server, like srvdestination.com.company.world instead of just srvdestination. I am ok with this, but I don't understand how come my DB connection works? Let's say I have srvorigin. Now, to make http request, I must use qualified name srvdestination.com.company.world. However, for database connection, the connection string with un-qualified name is enough psycopg.connect(host='srvdestination', ...) I understand that protocols are different, but how psycopg2 does to resolve the real name?
has title: Name resolving in http requests
type: Question
has answer: http://stackoverflow.com/a/50476805
type: UnansweredQuestion
tagged with: dns
tagged with: python

http://stackoverflow.com/comment/86870244
type: Comment
type: AnswerComment
has text: this returns a list not the desired output
score: 0
comment on: http://stackoverflow.com/a/49927085

http://stackoverflow.com/comment/87037923
type: Comment
comment on: http://stackoverflow.com/a/50009888
has text: Perfect. No new lines of code needed and does exactly what I need.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50022851
type: Question
has comment: http://stackoverflow.com/comment/87063082
has title: Python SQlite. LIMIT variable does not change value in a loop
tagged with: for-loop
upvote count: 2
has comment: http://stackoverflow.com/comment/87063151
has comment: http://stackoverflow.com/comment/87063912
accepted answer: http://stackoverflow.com/a/50029953
has comment: http://stackoverflow.com/comment/87062523
answer count: 1
has comment: http://stackoverflow.com/comment/87063441
has comment: http://stackoverflow.com/comment/87062724
tagged with: python
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87062833
has comment: http://stackoverflow.com/comment/87063250
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87063017
has body: I am trying to find the difference in the number SEN students in each row. (code, output and database table is at the bottom) What I have done: Finding the number of rows in a table. Initializing the LIMIT number to 0 BEFORE the loop starts. I then add one to LIMIT and output it as a string. I then select the number of SEN students at LIMIT currLimitStr I then add one to LIMIT and output it as a string. I then select the number of SEN students at LIMIT currLimitStr I then fetch this data and print it out. The loop starts again. Incrementing currLimit 2 every loop works BUT for some reason the same values of senRow1 and senRow2 are being used after every loop. Why is this the case countNumRows = cur.execute("SELECT count(*) FROM SEN_Table") countNumFetch = countNumRows.fetchone() countNumRowsTable = countNumFetch[0] print("Number of rows in the table: " + str(countNumRowsTable)) currLimit = 0 for x in range(0, countNumRowsTable): currLimit = currLimit + 1 currLimit1Str = str(currLimit) senRow1 = cur.execute("SELECT SenNumber FROM SEN_Table ORDER BY SenNumber DESC limit " + currLimit1Str) currLimit = currLimit + 1 currLimit2Str = str(currLimit) senRow2 = cur.execute("SELECT SenNumber FROM SEN_Table ORDER BY SenNumber DESC limit " + currLimit2Str) senRow1Num = senRow1.fetchone()[0] senRow2Num = senRow2.fetchone()[0] print(senRow1Num) print(senRow2Num) print("") senDiff = print(senRow1Num - senRow2Num) print("") The output: The database table:
has comment: http://stackoverflow.com/comment/87062976
has comment: http://stackoverflow.com/comment/87063317
has comment: http://stackoverflow.com/comment/87063129
has comment: http://stackoverflow.com/comment/87062480
has comment: http://stackoverflow.com/comment/87063684
score: 1
tagged with: select
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87062675
has comment: http://stackoverflow.com/comment/87063479
tagged with: loops
has answer: http://stackoverflow.com/a/50029953
has comment: http://stackoverflow.com/comment/87062758
has comment: http://stackoverflow.com/comment/87067529
has comment: http://stackoverflow.com/comment/87063453
has comment: http://stackoverflow.com/comment/87062882

http://stackoverflow.com/comment/87039056
type: QuestionComment
comment on: http://stackoverflow.com/q/50011251
score: 0
has text: What's wrong with using CGI?
type: Comment

http://stackoverflow.com/comment/86964316
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49973682
has text: 1st and 2nd column makes my entry unique.eg. a-b ,d-e and a-c are the unique keys
score: 0

http://stackoverflow.com/a/50006315
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/50006255
downvote count: 0
type: Answer
has body: You should iterate over the array itself: array = [1, 2, 3, 4, 5] for item in array: if item &gt;= 3: print("yes") else: print("no")

http://stackoverflow.com/q/50062414
has answer: http://stackoverflow.com/a/50062448
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/87141604
has answer: http://stackoverflow.com/a/50062557
downvote count: 0
duplicate of: http://stackoverflow.com/q/29246455
upvote count: 1
has body: Edit: I saw the two similar questions but I didn't get my answer. I want to square some numbers with 4 numbers after the decimal point: import math lis=math.sqrt(19) print("%.4f" % lis) sqrt(19)=4.35889894 so the output will be: 4.3589 and I want it to be: 4.3588 without rounding up. What do I do?
has comment: http://stackoverflow.com/comment/87141901
linked to: http://stackoverflow.com/q/49592945
possible better answer: http://stackoverflow.com/a/50062557
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87141748
duplicate of: http://stackoverflow.com/q/49592945
has title: How can I print a number without rounding?(Python)
tagged with: python
has comment: http://stackoverflow.com/comment/87141800
linked to: http://stackoverflow.com/q/29246455
has comment: http://stackoverflow.com/comment/87141652
accepted answer: http://stackoverflow.com/a/50062448
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87141792
has comment: http://stackoverflow.com/comment/87141873

http://stackoverflow.com/comment/86881136
has text: thanks! I already have dataframes read in to python from excel files but the logic of your code helped me alot!
type: Comment
comment on: http://stackoverflow.com/a/49932453
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87099501
type: Comment
comment on: http://stackoverflow.com/q/50035827
type: QuestionComment
score: 0
has text: Is there a specific reason you don't want to use `pandas`? I wrote an answer with `pandas` but deleted it once I saw your `P.S.` :)

http://stackoverflow.com/q/49971915
tagged with: python
tagged with: plot
has title: Python: How to make (3d) plots of functions without needing linspace/meshgrid?
type: AnsweredQuestion
has body: Question: In WolframAlpha, I can get a plot for "z = x^2 - y^2" directly from that string. How would one make plots like the above from a string in python? A few things I already know about: You can do linspace or meshgrid, compute the function at each point, and then pass those values to either matplotlib or plotly. Plotly makes beautiful plots in this case, and this is what I'm using right now, but it's definitely still a hassle. It's possible to do plotting in Sympy, but that library is a little heavy-handed in its own way, and the documentation is a little sparse. What would make a great answer: A library I haven't heard of or been able to find which provides easy, elegant plotting of functions without needing to do the linspace myself. A thorough explanation of why the available tools I listed above are the best you can do, and perhaps some tutorials you like for getting a better grasp of these techniques. Updates: This seems relevant: https://wiki.python.org/moin/NumericAndScientific/Plotting
tagged with: plotly
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/49973005
favorite count: 0
has comment: http://stackoverflow.com/comment/86979733
type: Question
has answer: http://stackoverflow.com/a/49973005
tagged with: sympy
has comment: http://stackoverflow.com/comment/86960061
upvote count: 0
score: -2
downvote count: 2

http://stackoverflow.com/comment/87236025
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50072756
has text: What if I dont need to use argv=None as an argument to the function? I just need to take a pathname from the command line, go to that directory, and analyze the files inside. How would I go about that without using sys.argv[1]?
score: 0

http://stackoverflow.com/comment/86952889
type: QuestionComment
score: 0
has text: data=(X_train[col].append(X_test[col])).astype(str)
comment on: http://stackoverflow.com/q/49968432
type: Comment

http://stackoverflow.com/comment/87008868
comment on: http://stackoverflow.com/q/49996248
has text: How this is related to python 2.7 and python 3.x both?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49941466
tagged with: python
has body: I'm trying to get a custom PyPI server running using pypiserver. I tried to modify the example nginx.conf file in the README in order to use /mylocation instead of / and ended up with the following: server { server_name mypi.com; listen 443 ssl; ssl_certificate /cert/path; ssl_certificate_key /key/path; include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location /mylocation { auth_basic "Howdy!"; auth_basic_user_file /path/to/pwd; proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_pass 127.0.0.1:8080/; } } If I connect directly (via browser) to http://mypi.com:8080, the default welcome page of pypiserver pops up. If I try instead to connecto to https://mypi.com/mylocation it redirects me to https://mypi.com/simple/ and throws a 404 error. I thought that the combination of location + proxy_pass was basically a way of saying "Connecting to mypi.com/mylocation is the same as mypi.com:8080/". Did I get this wrong? Or is the problem related to pypiserver itself? If it helps, I'm on a Raspberry Pi with the following programs' versions: nginx: 1.12.2 pypiserver: 1.2.1 python: 3.6.5
has answer: http://stackoverflow.com/a/49954926
tagged with: nginx-location
type: AnsweredQuestion
tagged with: pypiserver
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: nginx-reverse-proxy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49954926
has title: Nginx reverse proxy fails if location is not `/` with pypiserver
tagged with: nginx

http://stackoverflow.com/comment/87115904
has text: I don't understand what you're asking. Does `df[df.a == 'two']` give you what you want? Where does the slice come in here? Or maybe you are looking for `df[df.a == 'two'].reset_index(drop=True)`?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50049823

http://stackoverflow.com/comment/87108203
has text: My confusion came from the fact that DataFrame is column first, and not row first as one would expect from general multi-dimension data structures. So I could as well get my value using d['a'][d.index[0]]
score: 0
comment on: http://stackoverflow.com/a/50045255
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50029940
has comment: http://stackoverflow.com/comment/87076276
has comment: http://stackoverflow.com/comment/87076164
has body: If you can break the sequence into a list, e.g. of 5-letter sequences, you could then use this function to find repeated sequences. from itertools import groupby import numpy as np def find_repeats(input_list, n_repeats): flagged_items = [] for item in input_list: # Create itertools.groupby object groups = groupby(str(item)) # Create list of tuples: (digit, number of repeats) result = [(label, sum(1 for _ in group)) for label, group in groups] # Extract just number of repeats char_lens = np.array([x[1] for x in result]) # Append to flagged items if any(char_lens &gt;= n_repeats): flagged_items.append(item) # Return flagged items return flagged_items #-------------------------------------- test_list = ['aatcg', 'ctagg', 'catcg'] find_repeats(test_list, n_repeats=2) # Returns ['aatcg', 'ctagg']
has comment: http://stackoverflow.com/comment/87076187
upvote count: 0
answers question: http://stackoverflow.com/q/50029759
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/comment/87227152
type: QuestionComment
has text: There is no error. I just don’t see the output that I should with the require() running
comment on: http://stackoverflow.com/q/50074188
score: 0
type: Comment

http://stackoverflow.com/q/50041346
has body: I'm quite a newbie and I'm converting all my excel vba to python at this moment. I have these lists. s1a = [1, 2, 3] s1b = [2, 3, 4] s2a = [3, 4, 5] s2b = [4, 5, 6] s3a = [5, 6, 7] s3b = [6, 7, 8] and I've got another list, result = ['s2as1a', 's1bs2a', 's1as3b', 's2as3a'] from the lists above, I'd like to make the following lists. A = [3, 4, 5, 1, 2, 3] # s2a + s1a B = [2, 3, 4, 3, 4, 5] # s1b + s2a C = [1, 2, 3, 6, 7, 8] # s1a + s3b D = [3, 4, 5, 5, 6, 7] # s2a + s3a I tried to make this but I can only come up with some messy "if/elif" things. How to make this in a nice and simple way? thanks all!
answer count: 1
accepted answer: http://stackoverflow.com/a/50041434
has answer: http://stackoverflow.com/a/50041434
duplicate of: http://stackoverflow.com/q/1373164
tagged with: list
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
has title: Python combine variable number of lists via identifiers
tagged with: for-loop
type: Question
linked to: http://stackoverflow.com/q/1373164
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/96931785
score: 4
type: AnswerComment
has text: Thanks for pointing out this subtle but important detail. One question that immediately came to my mind when I read your description was: What are good ways to correct for two losses of significantly different magnitudes? My ideas were: input normalization or taking the log of loss terms.
comment on: http://stackoverflow.com/a/52228323
type: Comment

http://stackoverflow.com/comment/87014304
has text: I mean, do you want the function evaluated on a specific grid? Do you just want a callable you can use, is any dense grid OK?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49998879

http://stackoverflow.com/q/49950175
has comment: http://stackoverflow.com/comment/87114369
tagged with: python
has comment: http://stackoverflow.com/comment/87302462
has body: I am writing a script intended to be used by members of a project team. As part of the script, I am launching a 3rd party proprietary application run through Citrix. I am going to use the script mostly to send keys to this application, but the first step once it launches is for the user to log in. Because I would like the user to log in while the script is running, rather than asking for user/pass from some kind of GUI input earlier, and because the time it takes Citrix to launch varies, I would like to include some kind of logic that detects when the user has logged in and then resume the script from there, rather than including an obnoxiously long implicit wait or risking the script timing out. Is there a way to detect user keystrokes using win32com.client (or to detect a change in state of the application itself)? See below for the relevant code to launch the app: import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.Run('C:\Citrix\[rest of path]) EDIT: Per Vasily's suggestion in the comments below, I attempted to adapt the "hook and listen" code to my scenario, but was unsuccessful. When I launch my file, I don't even get an exception message in my terminal, I get a Windows pop-up that says Python encountered a problem and needs to quit. This is how I adapted it: #[omitting import lines for brevity] def on_timer(): """Callback by timer out""" win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0); def on_event(args): """Callback for keyboard and mouse events""" if isinstance(args, KeyboardEvent): for i in range(1,100): time.sleep(1) if args.pressed_key == 'Lcontrol': break def init(): hk = Hook() hk.handler = on_event main_thread_id = win32api.GetCurrentThreadId() t = Timer(55.0, on_timer) # Quit after 55 seconds t.start() hk.hook(keyboard=True, mouse=True) At the point when the 3rd party Citrix app begins to launch in my main script, I call hookandlisten.init(). As a reminder, my goal is to wait until the user sends a certai…
has comment: http://stackoverflow.com/comment/87106623
has comment: http://stackoverflow.com/comment/87155321
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/50284747
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87087483
tagged with: pywinauto
answer count: 1
has answer: http://stackoverflow.com/a/50284747
favorite count: 0
has title: Waiting for user input when controlling 3rd party application via python script
type: Question
tagged with: windows
tagged with: pywin32

http://stackoverflow.com/comment/87142616
type: QuestionComment
has text: @SeanFrancisN.Ballais updated again.
score: 0
comment on: http://stackoverflow.com/q/50062663
type: Comment

http://stackoverflow.com/q/50049487
tagged with: oop
tagged with: mysql-python
answer count: 0
downvote count: 0
has body: I have a class (which works [or appears to]) to run an sql query. Code is below. If I inherit from object and do not use super, it works fine. I am learning about inserting methods from super classes and so I thought that I would make my class header look like this class database_connector(Connection) and incorporate a super call in init like this super().__init__() However, I get TypeError: function() argument 1 must be code, not str I tried super(database_connector, self).__init__() after reading some other stuff in StackOverFlow but I now still get TypeError: function() argument 1 must be code, not str I am anticipating that this work will allow me to call more methods from pymysql.Connection. Here is my class from pymysql import Connection # set up default values for database connector class database_connector(Connection): def __init__(self, host=None, db=None, user=None, passwd=None): super(database_connector, self).__init__() if host is None: self.host = "mysql_host_ip" else: self.host = host if db is None: self.db = "fred_db" else: self.db = db if user is None: self.user = "fred" else: self.user = user if passwd is None: self.passwd = "fredspasswd" else: self.passwd = passwd self.this_database = (Connection(host=self.host, user=self.user, passwd=self.passwd, db=self.db)) self.cur = self.this_database.cursor() def my_sql_run_this_sql(self, sql_to_run=None): if sql_to_run is None: data = self.cur.execute("SELECT * FROM person") else: data = self.cur.execute(sql_to_run) data = [] for row in self.cur.fetchall(): data.append(row) self.this_database.close() return data
score: 1
has comment: http://stackoverflow.com/comment/87115737
has comment: http://stackoverflow.com/comment/87119797
favorite count: 0
has comment: http://stackoverflow.com/comment/87121029
tagged with: python-3.x
has title: Inherited Methods How do I make super methods available?
type: Question
has comment: http://stackoverflow.com/comment/87131337
tagged with: pymysql
has comment: http://stackoverflow.com/comment/87115229
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87115142
has comment: http://stackoverflow.com/comment/87116657

http://stackoverflow.com/comment/86925681
score: 0
comment on: http://stackoverflow.com/q/49954533
type: Comment
type: QuestionComment
has text: Sure, But for my case, it would just add one more layer of difficulty. The code required a lot of data processing, which I wish to leave to the local machine of each user.

http://stackoverflow.com/comment/87021259
type: QuestionComment
comment on: http://stackoverflow.com/q/50002386
has text: @benwad I'm not sure I am clear on that, could you provide an explanation? I am new to Python/Flask.
score: 0
type: Comment

http://stackoverflow.com/comment/87055866
has text: @eyllanesc that's right. but the popup closes automatically even if I click just arrow
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50019909

http://stackoverflow.com/comment/87117710
comment on: http://stackoverflow.com/q/50050631
has text: Use numpy instead of raw Python?
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87163442
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50054868
score: 1
has text: Can you access EC2 instance manually via ssh command? Did you try to set `~/.ssh/config`? Are username, path to private key or authorized_key on remote server set correctly?

http://stackoverflow.com/q/50004166
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Highlight all date values in word doc using python docx
tagged with: python-docx
has body: I'm looking for python code to highlight all date values with format "MM-DD-YYYY" in a word document. I'm using word docx to do so. below is my code but it is highlighting complete line instead of the only date. for p in doc.paragraphs: date1 = re.findall(r"[0-9]{2}-[0-9]{2}-(?!0000)[0-9]{4}", p.text) for run in p.runs: if date1: run.font.highlight_color = WD_COLOR_INDEX.YELLOW
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50009858
score: 0
has comment: http://stackoverflow.com/comment/87036412
answer count: 1

http://stackoverflow.com/comment/87064625
has text: yes you are correct in that regard @zwer . maybe would be easier to save as txt file and bring it in that way.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50024085

http://stackoverflow.com/comment/86888893
comment on: http://stackoverflow.com/a/49936631
type: Comment
type: AnswerComment
score: 1
has text: works, great. I was meddling with pd.to_datetime, but was unware of the kwargs 'unit='s''!

http://stackoverflow.com/q/50044021
tagged with: for-loop
answer count: 0
has comment: http://stackoverflow.com/comment/87104535
type: UnansweredQuestion
score: 1
tagged with: python-3.5
has title: Update value of specific key in a dictionary, contained in a list for one dictionary in the list raher than for all dictionaries in the list
has comment: http://stackoverflow.com/comment/87104566
downvote count: 0
has comment: http://stackoverflow.com/comment/87105501
upvote count: 1
has comment: http://stackoverflow.com/comment/87104539
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87104396
has comment: http://stackoverflow.com/comment/87104716
has comment: http://stackoverflow.com/comment/87104264
linked to: http://stackoverflow.com/q/2465921
tagged with: python
tagged with: dictionary
has body: I have the following variables: A list called word_frequencies that has the same dictionary with all values 0, at each position of the list. A list called all_preprocessed_articles that has a vector that contains all the words from a particular article, at each position of the list. (Thus, len(word_frequencies) = len(all_preprocessed_articles)) The dictionary is a set of all the words in all the articles. I have Initialised the list item, with all the dictionary items as follows: word_frequencies = [] for word in vocab: temp_frequency_dict.update({word:0}) for i in range(0, num_articles): word_frequencies.append(temp_frequency_dict) With the following code, I am aiming to iterate through each vector i in all_preprocessed_articles and changing the dictionary i in the word_frequencies list for that word, by adding 1 to the value of that particular word (key). for i in range(0, num_articles): current_article = all_preprocessed_articles[i] for word in current_article: word_frequencies[i][word] += 1 What I expect as output is that each dictionary in word_frequencies shows the frequencies for each word in that specific article. However, what it outputs is the same dictionary at each position in word_frequencies. What can I do to so that the output is a list with i dictionaries in which each dictionary shows the occurrences per word in the corresponding article?
has comment: http://stackoverflow.com/comment/87105089

http://stackoverflow.com/q/49956664
tagged with: python
has comment: http://stackoverflow.com/comment/86979963
type: AnsweredQuestion
has title: keras : Implementing a custom metric with logical operators
answer count: 1
downvote count: 0
score: 1
upvote count: 1
tagged with: keras
accepted answer: http://stackoverflow.com/a/49981112
has body: I'm trying to create a custom metric to evaluate a keras model. The evaluation consist in returning 1 if y_true and y_pred are both higher or lower than a certain value (in my case 5), 0 otherwise. The following lambda expression is a demo stating what I want to achieve lambda y_pred, y_true : 1 if y_true &gt; 5 and y_pred &gt; 5 or y_true &lt; 5 and y_pred &lt; 5 else 0 I've tried to implement it on a custom keras model doing the following: def SAGR(y_true, y_pred): maj = K.greater([y_true, y_pred], 5) men = K.less([y_true, y_pred], 5) aremaj= K.all(maj) aremen = K.all(men) res = K.any([aremaj, aremen]) return K.mean(K.cast(res,'float32')) But the function always return 0. The output of the last layer is linear with shape [None, 2]. Can anyone please explain me a way to implement the custom metric? Thanks
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49981112

http://stackoverflow.com/a/49994595
answers question: http://stackoverflow.com/q/49978662
has body: You're sub-classing Django's UserCreationForm that is meant to create a user, and operates on the User model. Inside this form, you will not get access to the UserProfile model instance. As you can see from the Django source code, the UserCreationForm is restricted to the User model and exposes the fields that are present in the User model only class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField(label=_("Password"), strip=False, widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification.")) class Meta: model = User fields = ("username",) The clean method thus correctly returns username, first_name e.t.c here
score: 0
type: Answer

http://stackoverflow.com/comment/86957159
comment on: http://stackoverflow.com/a/49970566
score: 0
type: Comment
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Yeah, you're right (thanks). I read the part about the unnamed columns and stuff, and didn't continue on to the csv part.

http://stackoverflow.com/q/49951620
upvote count: 1
type: UnansweredQuestion
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86919802
favorite count: 0
score: 0
has body: How would I go about taking the following regular expression: re.compile(r'(\'?(("(\"|[^"])*")|^#.*\n|;.*\n|\(|\)|-?[0-9]+(\.[0-9]+)?|[a-zA-Z-#][a-zA-Z0-9.+-/\!]*))|\'.*') and writing it across multiple lines? For whatever reason my attempts at using re.VERBOSE seem to change the value of the expression.
has title: Using re.VERBOSE on a regular expression
linked to: http://stackoverflow.com/q/13761723
tagged with: regex
has answer: http://stackoverflow.com/a/49951723
has answer: http://stackoverflow.com/a/49955966
type: Question
duplicate of: http://stackoverflow.com/q/13761723
answer count: 2

http://stackoverflow.com/a/53292073
has body: I don't understand why you're concerned about the dict that is supplied? That is an input for your use to aid in your handler code and doesn't need to be utilized at all if you don't want it. It isn't {}, as you indicated, if you use encode without unpicklable=False. If you don't include that, then you actually get this: {'py/object': '__main__.Bar'} All that is providing is the type of the variable and you wrote the handler, so you naturally know the type. If you want a nice JSON output of your enum, just tell Python that obj of the flatten function is a Bar type (optional, but nice for the IDE and for later maintenance), like this: def flatten(self, obj: Bar, data): Then, just return obj.name. Doing this, the output is: {"py/object": "__main__.Foo", "bar": ["A", "B"], "hello": "hello"} Of course, we can make it cleaner by telling the encoder not to worry about decoding later with: unpicklable=False The final output is then: {"bar": ["A", "B"], "hello": "hello"} The whole example code: import jsonpickle from enum import Enum class Bar(Enum): A = 1 B = 2 class Foo: def __init__(self): self.hello = 'hello' self.bar = [Bar.A, Bar.B] class Handler(jsonpickle.handlers.BaseHandler): def flatten(self, obj: Bar, data): print(obj) return obj.name jsonpickle.handlers.registry.register(Bar, Handler) def main(): fizbuz = Foo() encoded = jsonpickle.encode(fizbuz, unpicklable=False) print(encoded) if __name__ == '__main__': main() Generic Approach You can also generically handle all enums by using a class like this: from enum import Enum import jsonpickle class JsonEnumHandler(jsonpickle.handlers.BaseHandler): def restore(self, obj): pass def flatten(self, obj: Enum, data): return obj.name Then, register every enum in your JSON like this: jsonpickle.handlers.registry.register(LimitType, JsonEnumHandler) jsonpickle.handlers.registry.register(DeviceType, JsonEnumHandler)
type: Answer
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/49963305

http://stackoverflow.com/a/62176555
answers question: http://stackoverflow.com/q/50016862
has comment: http://stackoverflow.com/comment/117579485
has comment: http://stackoverflow.com/comment/117567935
score: 146
has body: This answer presents two compelling use-cases for a TestClass in pytest: Joint parametrization of multiple test methods belonging to a given class. Reuse of test data and test logic via subclass inheritance Joint parametrization of multiple test methods belonging to a given class. The pytest parametrization decorator, @pytest.mark.parametrize, can be used to make inputs available to multiple methods within a class. In the code below, the inputs param1 and param2 are available to each of the methods TestGroup.test_one and TestGroup.test_two. # in file `test_class_parametrization.py` import pytest @pytest.mark.parametrize( ("param1", "param2"), [ ("a", "b"), ("c", "d"), ], ) class TestGroup: """A class with common parameters, `param1` and `param2`.""" @pytest.fixture def fixt(self) -> int: """This fixture will only be available within the scope of TestGroup""" return 123 def test_one(self, param1: str, param2: str, fixt: int) -> None: print("\ntest_one", param1, param2, fixt) def test_two(self, param1: str, param2: str) -> None: print("\ntest_two", param1, param2) $ pytest -s test_class_parametrization.py ================================================================== test session starts ================================================================== platform linux -- Python 3.8.6, pytest-6.2.1, py-1.10.0, pluggy-0.13.1 rootdir: /home/jbss plugins: pylint-0.18.0 collected 4 items test_class_parametrization.py test_one a b 123 . test_one c d 123 . test_two a b . test_two c d . =================================================================== 4 passed in 0.01s =================================================================== Reuse of test data and test logic via subclass inheritance I'll use a modified version of code taken from another answer to demonstrate the usefulness of inheriting class attributes/methods from TestClass to TestSubclass: # in file `test_inheritance.py` class TestClass: VAR: int = 3 DATA: int = 5 def test_var_positive(self) -> None: assert…
upvote count: 146
downvote count: 0
has comment: http://stackoverflow.com/comment/139362757
has comment: http://stackoverflow.com/comment/134918924
type: Answer

http://stackoverflow.com/comment/86947782
score: 2
has text: `'__file__'` should be `__file__`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49965992

http://stackoverflow.com/a/50041860
downvote count: 1
score: 3
answers question: http://stackoverflow.com/q/50040470
has comment: http://stackoverflow.com/comment/109327283
type: Answer
accepted answer of: http://stackoverflow.com/q/50040470
has comment: http://stackoverflow.com/comment/99213293
upvote count: 4
has comment: http://stackoverflow.com/comment/99217842
has body: I see a small (~25%) performance improvement from bypassing pandas.concat. Otherwise, rewriting / optimizing json_normalize doesn't seem straightforward. def original(df): parsed_df = pd.concat([json_normalize(json.loads(js)) for js in df['data']]) parsed_df['bank_account'] = df['bank_account'].values parsed_df.index = parsed_df['uid'] return parsed_df def jp(df): cols = ['account_data.currency.current', 'account_data.currency.minimum', 'account_data.fees.monthly', 'account_type', 'uid', 'user_name'] parsed_df = pd.DataFrame([json_normalize(json.loads(js)).values[0] for js in df['data']], columns=cols) parsed_df['bank_account'] = df['bank_account'].values parsed_df.index = parsed_df['uid'] return parsed_df df = pd.concat([df]*100, ignore_index=True) %timeit original(df) # 675 ms per loop %timeit jp(df) # 526 ms per loop
type: AcceptedAnswer

http://stackoverflow.com/a/50001962
accepted answer of: http://stackoverflow.com/q/50001840
has body: Your output file name is constant, so it gets overwritten with each iteration of the for loop. Try the following instead of your final line, which opens the file in "append" mode instead: #write everything in one document with open("/Users/Documents/Analyse/Eye movements/final_data.csv", "a") as f: final_frame.to_csv(f, header=False)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50001840
type: AcceptedAnswer

http://stackoverflow.com/comment/87079363
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50031506
has text: The way I told you in my very first comment. `['egrep', 'sbin|lib']`
score: 0

http://stackoverflow.com/comment/86906606
has text: https://codeshare.io/2pgzBx see this code. The while loop inside loading_screen() cannot be interrupted because can produce freezes in animation. Is there a solution for this?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49943548
type: Comment

http://stackoverflow.com/a/74319405
has body: One way to do it is use pandas and python-docx libraries. Pandas to read the excel and then docx to write iteratively to docx file import docx import pandas as pd df = pd.read_excel("test.xlsx") doc = docx.Document() t = doc.add_table(df.shape[0]+1, df.shape[1]) # convert the RHS to str for j in range(df.shape[-1]): t.cell(0,j).text = str(df.columns[j]) # add the rest of the data frame for i in range(df.shape[0]): for j in range(df.shape[-1]): t.cell(i+1,j).text = str(df.values[i,j]) # save the doc doc.save('./test.docx')
score: 0
answers question: http://stackoverflow.com/q/49926444
type: Answer

http://stackoverflow.com/q/49981190
tagged with: pandas
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49981316
favorite count: 0
has body: I made a groupby operation in a dataframe to group by the categorical value of an specific column. Something like: grouped = df.groupby(df["categories"]) If I do list(grouped) what I get is a list of dataframes, one for each category. So far, so good. But I want to select an specific column in each dataframe in the list. Imagine the column I want to access is named vals. I want something like: my_array = [grouped[i]["vals"] for i in grouped] But the previous command doesn't work, neither other combinations I have tried. Do you have any suggestions? Thanks.
answer count: 2
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49981253
has title: Accessing to columns in a grouped list in pandas
type: Question
has answer: http://stackoverflow.com/a/49981253
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49981316
tagged with: pandas-groupby

http://stackoverflow.com/q/50021381
has comment: http://stackoverflow.com/comment/87058466
answer count: 1
has comment: http://stackoverflow.com/comment/87058527
has answer: http://stackoverflow.com/a/50021509
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87060802
accepted answer: http://stackoverflow.com/a/50021509
tagged with: python
has title: Do both lines return a string?
has body: I am currently following through the beginner Codebat track. Both pieces of code work however is there anything fundamentally wrong/different between the two ways of writing the below code? thanks, def mine(myStr, x): myResult = myStr * x return myResult def codebat(thierStr, i): codeResult = '' for i in range(i): codeResult += thierStr return codeResult
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87058521
has comment: http://stackoverflow.com/comment/87058917
score: 0

http://stackoverflow.com/a/50055502
has comment: http://stackoverflow.com/comment/87139850
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/136810030
has comment: http://stackoverflow.com/comment/87139815
has body: you may consider changing your model: import numpy as np, pandas as pd, matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import LSTM, Dense, TimeDistributed, Bidirectional from sklearn.metrics import mean_squared_error, accuracy_score from scipy.stats import linregress from sklearn.utils import shuffle fi = 'pollution.csv' raw = pd.read_csv(fi, delimiter=',') raw = raw.drop('Dates', axis=1) print (raw.shape) scaler = MinMaxScaler(feature_range=(-1, 1)) raw = scaler.fit_transform(raw) time_steps = 7 def create_ds(data, t_steps): data = pd.DataFrame(data) data_s = data.copy() for i in range(time_steps): data = pd.concat([data, data_s.shift(-(i+1))], axis = 1) data.dropna(axis=0, inplace=True) return data.values ds = create_ds(raw, time_steps) print (ds.shape) n_feats = raw.shape[1] n_obs = time_steps * n_feats n_rows = ds.shape[0] train_size = int(n_rows * 0.8) train_data = ds[:train_size, :] train_data = shuffle(train_data) test_data = ds[train_size:, :] x_train = train_data[:, :n_obs] y_train = train_data[:, n_obs:] x_test = test_data[:, :n_obs] y_test = test_data[:, n_obs:] print (x_train.shape) print (x_test.shape) print (y_train.shape) print (y_test.shape) x_train = x_train.reshape(x_train.shape[0], time_steps, n_feats) x_test = x_test.reshape(x_test.shape[0], time_steps, n_feats) print (x_train.shape) print (x_test.shape) print (y_train.shape) print (y_test.shape) model = Sequential() model.add(LSTM(64, input_shape=(time_steps, n_feats), return_sequences=True)) model.add(LSTM(32, return_sequences=False)) model.add(Dense(n_feats)) model.compile(loss='mse', optimizer='rmsprop') model.fit(x_train, y_train, epochs=10, batch_size=1, verbose=1, shuffle=False) y_predict = model.predict(x_test) print (y_predict.shape) y_predict = scaler.inverse_transform(y_predict) y_test = scaler.inverse_transform(y_test) y_test = y_test[:,0] y_predict = y_predict[:,0] print (y_test.shape) print (y_predict.sha…
has comment: http://stackoverflow.com/comment/87139932
answers question: http://stackoverflow.com/q/50054419
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/87127462

http://stackoverflow.com/comment/87116046
has text: It isn't a memory leak but rather a space leak. That is where the amount of memory used continues to grow as the program runs. A unbounded cache is a space leak.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50049769
type: Comment

http://stackoverflow.com/a/50027554
accepted answer of: http://stackoverflow.com/q/50027490
has comment: http://stackoverflow.com/comment/87074040
has comment: http://stackoverflow.com/comment/92363500
has body: We can use np.where after extending the mask to 3D that let's it do the choosing in a broadcasted manner - np.where(mask[...,None]==0, originalImage,[0,0,255]) Or staying closer to the original code, make a copy and then assign in one go with the mask - result = originalImage.copy() result[mask!=0] = (0,0,255)
answers question: http://stackoverflow.com/q/50027490
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87074082
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/91891401
type: Answer
has comment: http://stackoverflow.com/comment/87074172

http://stackoverflow.com/comment/86929923
type: Comment
type: QuestionComment
has text: Your are totally right, but I am working on an open source project and I am trying to write a child class that inherits the parent class as I have described in my example. For better or worse, this is how the parent class is written. I'm finding that things are getting convoluted because of this.
comment on: http://stackoverflow.com/q/49953268
score: 0

http://stackoverflow.com/comment/86891754
type: Comment
type: QuestionComment
has text: yes, that is correct
score: 0
comment on: http://stackoverflow.com/q/49937891

http://stackoverflow.com/a/61107642
score: 0
answers question: http://stackoverflow.com/q/49936845
type: Answer
has body: I had the same problem. Let's say you have this in a test.py file: def print_hello(): with open('log.txt') as f: sys.stdout = f print('hello') If you run this in the command line python test.py you wont have any problem. But if you run this in a Jupyter notebook, you have to add stdout_obj like so: stdout_obj = sys.stdout # store original stdout print_hello() sys.stdout = stdout_obj # restore print commands to to interactive prompt

http://stackoverflow.com/comment/87110727
comment on: http://stackoverflow.com/q/50047174
has text: I'd be curious to see what the values of the 3 or so indices on each side of the index is (and the value at the index).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49961281
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49965771
has body: Beginning Python and BeautifulSoup user here. I'm trying to scrape some sports score from ESPN website but the returns are empty. Sample Target: ESPN Website > NBA > Scores I want to get some info such as Team Name, Score, Record, and Quarter/Final but since I'm having trouble I'll just start with Score. I would like to get the total score of the teams. from bs4 import BeautifulSoup as bs from urllib.request import urlopen as uReq html_url = 'http://www.espn.co.uk/nba/scoreboard' uClient = uReq(html_url) page_html = uClient.read() uClient.close() page_soup = bs(page_html, 'html.parser') containers = page_soup.findAll('td',{"class":"total"}) print (len(containers)) print (type(containers)) Output 0 &lt;class 'bs4.element.ResultSet'&gt; I spent the whole day trying to figure out why all my results keep coming back NoneType and empty I can't seem to figure it out. I tried just looking for 'td' and this is the result containers = page_soup.findAll('td') print (len(containers)) print (type(containers)) Output 0 &lt;class 'bs4.element.ResultSet'&gt; Not sure why I'm unable to pull the data. Is there something going on behind the scenes that ESPN is purposely not allowing us to scrape or something? I have tried looking through different tags, attributes, etc but can't figure it out. Thank you
tagged with: espn
has title: BeautifulSoup ESPN: Scraping Sports Score but .findAll gives an empty ResultSet. How to pull proper info?
has answer: http://stackoverflow.com/a/49961801
accepted answer: http://stackoverflow.com/a/49961801
type: Question
possible better answer: http://stackoverflow.com/a/49965771
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/40208051
answer count: 2
linked to: http://stackoverflow.com/q/17597424
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/a/49951069
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86918793
type: Answer
has body: It's not so matter of a replacement, as a string cut. From what I understand, you want cut first character or two? grade = "D 85" grade[2:] &gt; "85" String is an array, and you can ask for some part of it. [2:] means since third (we count from 0) character to end. EDIT: To process all grades and remove first character and store result in new list (gradesClean): grades = ["D85", "D100", "M20", "D70"] gradesClean = [] for g in grades: gradesClean.append(g[1:]) gradesClean &gt; ['85', '100', '20', '70']
answers question: http://stackoverflow.com/q/49951041
downvote count: 0

http://stackoverflow.com/q/49990580
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86997817
has comment: http://stackoverflow.com/comment/87069184
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87002409
tagged with: python
has comment: http://stackoverflow.com/comment/86997746
has comment: http://stackoverflow.com/comment/86997868
tagged with: centos
tagged with: docker
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has body: I have an container based on CentOS, running gunicorn, and serving a flask app. I would like a startup script to run when it's first started, although I would like my entrypoint to remain my gunicorn call. Dockerfile snippet COPY startup.py / ENTRYPOINT ["gunicorn", "-b", "0.0.0.0:8000", "app:app"] CMD /usr/bin/python3 /startup.py I cannot get this to work with the shell style CMD instruction. The logs show CMD complaining that "Error: '/usr/bin/python3 /startup.py' doesn't exist", although both python3 and the startup.py file exist. The reason I want this script to be run on startup is that I would like it to work against a volume that is being configured on run. I've tried many other configurations, but can't find the magic combo.
has title: docker: run python CMD startup script alongside ENTRYPOINT
has comment: http://stackoverflow.com/comment/86998379

http://stackoverflow.com/q/50009141
linked to: http://stackoverflow.com/q/18697532
upvote count: 2
tagged with: healpy
accepted answer: http://stackoverflow.com/a/50115552
has answer: http://stackoverflow.com/a/50115552
tagged with: python
possible better answer: http://stackoverflow.com/a/50073967
has answer: http://stackoverflow.com/a/50073967
type: AnsweredQuestion
score: 1
has body: I'd like to smooth a map that doesn't cover the full sky. This map is not Gaussian nor has it mean zero, so the default behavior of healpy in which it fills missing values with 0 leads to a bias towards lower values at the edges of this mask: import healpy as hp nside = 128 npix = hp.nside2npix(nside) arr = np.ones(npix) mask = np.zeros(npix, dtype=bool) mask[:mask.size//2] = True arr[~mask] = hp.UNSEEN arr_sm = hp.smoothing(arr, fwhm=np.radians(5.)) hp.mollview(arr, title='Input array') hp.mollview(arr_sm, title='Smoothed array') I would like to preserve the sharp edge by setting the weight of the masked values to zero, instead of setting the values to zero. This appears to be difficult because healpy performs the smoothing in harmonic space. To be more specific, I'd like to mimic the mode keyword in scipy.gaussian_filter(). healpy.smoothing() implicitly uses mode=constant with cval=0, but I'd require something like mode=reflect. Is there any reasonable way to overcome this issue?
has title: Smoothing without filling missing values with zeros
downvote count: 1
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/50024828
tagged with: python
possible better answer: http://stackoverflow.com/a/50025187
accepted answer: http://stackoverflow.com/a/50025039
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/50025039
type: AnsweredQuestion
answer count: 2
upvote count: 3
downvote count: 0
has title: with open() error 22 (windows path)
has answer: http://stackoverflow.com/a/50025187
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has body: I have trouble getting the following code to work: path = "C:\\Users\\jiversen\\Documents\\Jsons\\"+jsonName+'.json' with open(path,'w') as outfile: json.dump(df,outfile) I get the following error: OSError Traceback (most recent call last) &lt;ipython-input-162-ad4856eeb7ee&gt; in &lt;module&gt;() 7 #path = r "C:\Users\jiversen\Documents\CosmosDB Simulator\Jsons\"+jsonName+'.json' 8 ----&gt; 9 with open(abs_file_path,'w') as outfile: 10 json.dump(df,outfile) OSError: [Errno 22] Invalid argument: 'C:\\Users\\jiversen\\Documents\\Jsons\\2018.04.06 12:00:00.000.json' I have tried the following ways to create the path: 1 path = "C:\Users\jiversen\Documents\Jsons\"+jsonName+'.json' this produces the following error: File "&lt;ipython-input-166-405d2aae6e9c&gt;", line 7 path = "C:\Users\jiversen\Documents\Jsons\"+jsonName+'.json' ^ SyntaxError: EOL while scanning string literal 2 path = R"C:\Users\jiversen\Documents\Jsons\"+jsonName+'.json' this produces the folling error: File "&lt;ipython-input-167-ff5d5da61135&gt;", line 7 path = R"C:\Users\jiversen\Documents\Jsons\"+jsonName+'.json' ^ SyntaxError: EOL while scanning string literal 3 import os script_dir = os.path.abspath('C:\\Users\\jiversen\\Documents\\jsons\\') # i.e. /path/to/dir/foobar.py rel_path = 'Jsons\\'+jsonName+'.json' abs_file_path = os.path.join(script_dir, rel_path) this produces the folling error: OSError Traceback (most recent call last) &lt;ipython-input-168-d286c1f58b6a&gt; in &lt;module&gt;() 7 #path = R"C:\Users\jiversen\Documents\Jsons\"+jsonName+'.json' 8 ----&gt; 9 with open(path,'w') as outfile: 10 json.dump(df,outfile) OSError: [Errno 22] Invalid argument: 'C:\\Users\\jiversen\\Documents\\Jsons\\2018.04.06 12:00:00.000.json' 4 no subdir and no spaces with open(jsonName+'.json','w') as outfile: json.dump(df,outfile) this produces the following error: OSError Traceback (most recent call last) &lt;ipython-input-173-818eaaa66077&gt; in &lt;module&gt;() 6 path = 'C:\\Users\\jiversen\\Documents\\Jso…

http://stackoverflow.com/comment/86990951
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49987267
has text: Glad to hear it! I think this will be way simpler than trying to write anything yourself.
type: AnswerComment

http://stackoverflow.com/comment/86906133
type: AnswerComment
has text: @Garini yeah, I wasn't sure if `shuffle` was something you intended or if was just cruft carried over in the copied code. So I made it optional
type: Comment
comment on: http://stackoverflow.com/a/49944026
score: 0

http://stackoverflow.com/comment/87141161
type: QuestionComment
score: 0
type: Comment
has text: @What dont know what you meant
comment on: http://stackoverflow.com/q/50062029

http://stackoverflow.com/q/50016967
linked to: http://stackoverflow.com/q/613183
score: -3
has comment: http://stackoverflow.com/comment/87050543
has body: labels = app.config["LABELS"] then print(labels) [{'name': '', 'image': '34-4.png', 'xMax': '2287', 'xMin': '2102', 'yMin': '53', 'id': '1', 'yMax': '110'}, {'name': '', 'image': '34-4.png', 'xMax': '2414', 'xMin': '2299', 'yMin': '80', 'id': '2', 'yMax': '118'}, {'name': '', 'image': '34-4.png', 'xMax': '2193', 'xMin': '2138', 'yMin': '128', 'id': '3', 'yMax': '140'}] The actual list is way bigger , how can i order these values so the dictionary starts with image instead of name, and for some reason they always start with name, i did check previous answers on here like Key Order in Python Dictionaries ,orderedDict but i'm not inserting them that way, i already have them and want to change they are(their order)
tagged with: python
has comment: http://stackoverflow.com/comment/87050813
tagged with: dictionary
tagged with: flask
has comment: http://stackoverflow.com/comment/87051048
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87050305
has comment: http://stackoverflow.com/comment/87050295
has comment: http://stackoverflow.com/comment/87050684
has comment: http://stackoverflow.com/comment/87050291
upvote count: 0
answer count: 1
downvote count: 3
has title: How can i make 'image' key the first?
accepted answer: http://stackoverflow.com/a/50017055
has answer: http://stackoverflow.com/a/50017055
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/5629023
has comment: http://stackoverflow.com/comment/87050253

http://stackoverflow.com/q/50066428
has body: I have successfully subscribed to a websocket and am receiving data. I am waiting to save my data so I can use it in a data frame for further analysis. My code so far is only returning empty lists and dataframes. Code: RETURNS EMPTY LIST wsClient = GDAX.WebsocketClient(url="wss://ws-feed.gdax.com", products="LTC-USD") df1 = [] for i in wsClient.start(): df1 = df1.append(wsClient.start()) Code: RETURNS EMPTY LIST AND DATAFRAME wsClient = GDAX.WebsocketClient(url="wss://ws-feed.gdax.com", products="LTC-USD") dfs = [] for i in wsClient.start(): dfs.append(wsClient.start()) df1 = pd.concat(dfs)
accepted answer: http://stackoverflow.com/a/50066777
has comment: http://stackoverflow.com/comment/87149401
has answer: http://stackoverflow.com/a/50066777
tagged with: pandas
has title: How do I save data from websocket?
type: AnsweredQuestion
tagged with: websocket
upvote count: 1
score: 1
favorite count: 0
type: Question
downvote count: 0
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/87149437

http://stackoverflow.com/comment/86948062
score: 0
type: AnswerComment
has text: Actually this is what it says `27.0.0.1 - - [22/Apr/2018 15:59:58] "GET /test/alex/1 HTTP/1.1" 200 - 127.0.0.1 - - [22/Apr/2018 15:59:58] "GET /static/css/main.css%3Fq%3D1280549780 HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 15:59:58] "GET /test/static/images/logo2.png HTTP/1.1" 404 - 127.0.0.1 - - [22/Apr/2018 15:59:58] "GET /favicon.ico HTTP/1.1" 404 -`
comment on: http://stackoverflow.com/a/49965569
type: Comment

http://stackoverflow.com/q/50004602
has body: Problem: Finding the bigrams, trigrams and bigram_score of a domain_name.I have a dataset and I want to differentiate them whether they are dga domains or not using some simple classification.So i wanted to use bigrams, trigrams and entropy to start with. What I tried: from nltk import ngrams sentence = 'some big sentence' n = 2 sixgrams = ngrams(sentence.split(), n) for grams in sixgrams: print grams here i got bigrams of a sentence.But my intenstion is not this. i want to convert Example domain: google.co.in bigrams [‘$g’, ‘go’, ‘oo’, ‘og’, ‘gl’, ‘le’, ‘e$’, ‘$c’, ‘co’, ‘o$’, ‘$i’, ‘in’, ‘n$’] trigrams [‘$go’, ‘goo’, ‘oog’, ‘ogl’, ‘gle’, ‘le$’, ‘$co’, ‘co$’, ‘$in’, ‘in$’] and then calculate the bigrams_score.From which i can use it to prediction module and analyze. Can anyone help me in getting an idea of how to solve the problem?
has comment: http://stackoverflow.com/comment/87026007
has answer: http://stackoverflow.com/a/50012407
upvote count: 2
tagged with: classification
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: machine-learning
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87026198
has title: How to find character bigrams and trigrams?
has comment: http://stackoverflow.com/comment/87025706
tagged with: nltk
tagged with: python
has comment: http://stackoverflow.com/comment/87025624
score: 2
tagged with: python-3.x