http://stackoverflow.com/comment/86285848
score: 0
type: Comment
type: QuestionComment
has text: @martineau Oh okay, thank you for the info. Ill have a play around with it and try figure out how to implement it into my program :)
comment on: http://stackoverflow.com/q/49638148

http://stackoverflow.com/a/49604566
has body: If you want the code to work in the way you have it organized, you will have to make MetaType a subclass of MetaWord. When Python tries to instantiate your Type class it looks at the MRO and sees that Type has metaclass MetaType and base class Word, but class Word has metaclass MetaWord. This raises a conflict because there is no way for Python to resolve the fact that Type seems to have two metaclasses, MetaWord and MetaType, which are unrelated to each other. The following code is a minimal reproduction of what I think your problem is: class Meta1(type): pass class Class1(metaclass=Meta1): pass class Meta2(type): pass class Class2(Class1, metaclass=Meta2): pass This code will give the same sort of error as yours. Changing the definition of Meta2 to: class Meta2(Meta1): pass resolves the issue.
has comment: http://stackoverflow.com/comment/86233110
score: 2
answers question: http://stackoverflow.com/q/49604330
type: AcceptedAnswer
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49604330
type: Answer

http://stackoverflow.com/comment/86502608
type: AnswerComment
has text: What is `base64_bytes`? I'm getting an undefined error
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49705259

http://stackoverflow.com/a/49642255
downvote count: 1
answers question: http://stackoverflow.com/q/49642101
has comment: http://stackoverflow.com/comment/86292477
has comment: http://stackoverflow.com/comment/86292436
has body: By using lambda functions and the thresholds in your if-else statements, you could do: TAX_DICT = { 0: lambda income: income * 0.1, 9325: lambda income: 932.5 + .15 * (income - 9325), 37950: lambda income: 5226.25 + .25 * (income - 37950), 91900: lambda income: 18713.75 + .28 * (income - 91900), 191650: lambda income: 46643.75 + .33 * (income - 191650), 416700: lambda income: 120910.25 + .35 * (income - 416700), 418400: lambda income: 121505.25 + .396 * (income - 418400) } def taxes(income): for threshold in sorted(TAX_DICT)[::-1]: if income &gt;= threshold: return TAX_DICT[threshold](income) You could also create a regular function for each threshold instead of a lambda function.
type: Answer
has comment: http://stackoverflow.com/comment/86292391
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/86292633
accepted answer of: http://stackoverflow.com/q/49642101
type: AcceptedAnswer

http://stackoverflow.com/comment/86213367
score: 0
comment on: http://stackoverflow.com/q/49601677
has text: @TarunLalwani How can I fix that? It sometimes happens in headed mode too. I tried user agent but it didn't work. Headless chrome should be indistinguishable from chrome. I even hex edited out $cdc_ from chromedriver.exe.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49644992
has comment: http://stackoverflow.com/comment/86299383
type: Question
has comment: http://stackoverflow.com/comment/86298012
upvote count: 0
has comment: http://stackoverflow.com/comment/86299253
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: python
has body: I've got a PDF file that I'm trying to obtain specific data from. I've been able to parse the PDF via PyPDF2 into one long string but searching for specific data is difficult because of - I assume - formatting in the original PDF. What I am looking to do is to retrieve specific known fields and the data that immediately follows (as formatted in the PDF) and then store these in seperate variables. The PDFs are bills and hence are all presented in the exact same way, with defined fields and images. So what I am looking to do is to extract these fields. What would be the best way to achieve this?
favorite count: 0
has comment: http://stackoverflow.com/comment/86299050
has answer: http://stackoverflow.com/a/49645110
has comment: http://stackoverflow.com/comment/86299128
has comment: http://stackoverflow.com/comment/86298037
has comment: http://stackoverflow.com/comment/86299322
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/86299368
has comment: http://stackoverflow.com/comment/86299293
has title: Searching for data in a PDF
score: -1
has comment: http://stackoverflow.com/comment/86298973

http://stackoverflow.com/q/49633831
type: Question
linked to: http://stackoverflow.com/q/17140886
tagged with: python
has body: I am trying to perform some replacements in a file: '\t' --&gt; '◊' '⁞' --&gt; '\t' This question recommends the following procedure: import fileinput with fileinput.FileInput(filename, inplace=True, backup='.bak') as file: for line in file: line = line.replace('\t','◊') print(line.replace('⁞','\t'), end='') I am not allowed to comment there, but when I run this piece of code I get an error saying: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 10: character maps to &lt;undefined&gt; This kind of error I have remedied previously by adding encoding='utf-8'. The problem is that fileinput.FileInput() does not allow for an encoding argument. Question: How to get rid of this error? The above solution, if it would work and provided that the speed is comparable to the following method, would please me most. It seems to be doing inplace replacements as it should be done. I have tried also: replacements = {'\t':'◊', '⁞':'\t'} with open(filename, encoding='utf-8') as inFile: contents = inFile.read() with open(filename, mode='w', encoding='utf-8') as outFile: for i in replacements.keys(): contents = contents.replace(i, replacements[i]) outFile.write(contents) which is relatively fast, but very greedy when it comes to memory. For UNIX users, I need something which does the following thing: sed -i 's/\t/◊/g' 'file.csv' sed -i 's/⁞/\t/g' 'file.csv' This turns out to be rather slow.
linked to: http://stackoverflow.com/q/908331
has answer: http://stackoverflow.com/a/49635013
type: AnsweredQuestion
score: 3
has title: Inplace (multiple) replacements in a file
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49635013

http://stackoverflow.com/q/49690515
has answer: http://stackoverflow.com/a/49690745
tagged with: multithreading
has title: Replacing foreach with threading
type: Question
has comment: http://stackoverflow.com/comment/86393299
tagged with: python
has comment: http://stackoverflow.com/comment/86394828
has answer: http://stackoverflow.com/a/49693882
has comment: http://stackoverflow.com/comment/86402116
answer count: 2
has comment: http://stackoverflow.com/comment/86392850
has comment: http://stackoverflow.com/comment/86393040
type: UnansweredQuestion
score: 0
has body: My program basically has to get around 6000 items from the DB and calls an external API for each item. This almost takes 30 min to complete. I just thought of using threads here where i could create multi threads and split the process and reduce the time. So i came up with some thing like this. But I have two questions here. How do i store the response from the API that is processed by the function. api = externalAPI() for x in instruments: response = api.getProcessedItems(x.symbol, days, return_perc); if(response &gt; float(return_perc)): return_response.append([x.trading_symbol, x.name, response]) So in the above example the for loop runs for 6000 times(len(instruments) == 6000) Now lets take i have splited the 6000 items to 2 * 3000 items and do something like this class externalApi: def handleThread(self, symbol, days, perc): //I call the external API and process the items // how do i store the processed data def getProcessedItems(self,symbol, days, perc): _thread.start_new_thread(self.handleThread, (symbol, days, perc)) _thread.start_new_thread(self.handleThread, (symbol, days, perc)) return self.thread_response I am just starting out with thread. would be helpful if i know this is the right thing to do to reduce the time here. P.S : Time is important here. I want to reduce it to 1 min from 30 min.

http://stackoverflow.com/comment/86440539
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49713507
has text: data is same just large, however, I had this issue before with list object not callable. In my code its give error - If I take out of my code on the same server and create a new script it works fine. very strange ...

http://stackoverflow.com/q/49699168
has body: from Tkinter import Tk, PhotoImage, Label def start_up(): app = Tk() app.title("Tower") app.geometry('600x900') photo = PhotoImage("Python.png") label = Label(app, image = photo) label.pack() app.mainloop() start_up() I'm currently struggling with tkinter 2.7. I cannot display the image I want, therefore please take a look at my code and help me fix it. Thanks.
type: Question
has comment: http://stackoverflow.com/comment/86411863
linked to: http://stackoverflow.com/q/27430648
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86411737
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49699373
tagged with: python-2.7
tagged with: tkinter
linked to: http://stackoverflow.com/q/50499
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/27430648
has comment: http://stackoverflow.com/comment/86411653
has title: Tkinter 2.7- image won't show up in the window with Tk.mainloop()
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86312640
has text: Well, that is not in your original question, or in your sample data. But in that case: a record will **not** be inserted. In another case (also not in your example) `A->C->D->A->C->D`, **two** `B` records would be inserted.
score: 1
comment on: http://stackoverflow.com/a/49651217
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49708190
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49712589
tagged with: raspberry-pi
tagged with: pwm
type: UnansweredQuestion
answer count: 1
has body: I need to generate a 1Mhz short unipolar pulse every 20 seconds to generate an ultrasonic pulse on my ultrasonic transducers. What do you think is the best way to do this? My plan was to connect the transducers to the PWM pins and use pigpio to generate the square wave. I was thinking about doing something along these lines... would this work? import time import pigpio pi = pigpio.pi() # Connect to local Pi. while true pi.hardware_clock(18, 1000000) # 1 MHz square wave on gpio#18 (PWM) time.sleep(0.5) #wait for 0.5 seconds to shut the signal off pi.hardware_clock(18, 0) # turn signal off time.sleep(20) #wait 20 seconds before turning signal back on pi.stop() # Disconnect from local Pi.
tagged with: gpio
tagged with: raspberry-pi3
score: 0
has title: Raspberry Pi PWM with Ultrasound Transducers

http://stackoverflow.com/comment/86439238
type: Comment
score: 0
type: QuestionComment
has text: That'll do. Thanks.
comment on: http://stackoverflow.com/q/49712849

http://stackoverflow.com/q/49618485
has comment: http://stackoverflow.com/comment/86244250
score: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49618713
has comment: http://stackoverflow.com/comment/86244906
answer count: 1
tagged with: rpython
has comment: http://stackoverflow.com/comment/86273793
downvote count: 1
has comment: http://stackoverflow.com/comment/86244784
has comment: http://stackoverflow.com/comment/86245988
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/86244348
has comment: http://stackoverflow.com/comment/86284427
tagged with: python
has comment: http://stackoverflow.com/comment/86244837
upvote count: 6
has comment: http://stackoverflow.com/comment/86329908
has title: How to run python script in Rstudio
favorite count: 0
type: Question
has body: I have a problem on how to run a python script from Rstudio? My initial idea is to grab the python script from a GitHub repository then run it in R, I grabbed python code by using script &lt;- getURL(URL, ssl.verifypeer = FALSE), from RCurl package, I was stuck on how to run Python code without storing the script as a file in the working directory, that is, running the R variable script above directory in Rstudio. I did know python.load() in _rPython_ package in R could help to run Python script, but it requires the .py file as the first argument. I would like to find a way without storing the Python script as a file. Thank you in advance if you have any idea of this problem.

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

http://stackoverflow.com/q/49659417
tagged with: normalization
has comment: http://stackoverflow.com/comment/86329052
has comment: http://stackoverflow.com/comment/86328612
has body: Can anyone explain the math behind the scenes? why Python and R return me the different result? which one should I use for real-world business scenario? original data id cost sales item 1 300 50 pen 2 3 88 wf 3 1 70 gher 4 5 80 dger 5 2 999 ww Python code: import pandas as pd from sklearn.preprocessing import StandardScaler df = pd.read_csv('Scale.csv') df'cost', 'sales' = StandardScaler().fit_transform(df'cost', 'sales') df Python normalized result id cost sales item 0 1 1.999876 -0.559003 pen 1 2 -0.497867 -0.456582 wf 2 3 -0.514686 -0.505097 gher 3 4 -0.481047 -0.478144 dger 4 5 -0.506276 1.998826 ww and R code library(readr) library(dplyr) df &lt;- read_csv("C:/Users/Ho/Desktop/Scale.csv") df &lt;- df %&gt;% mutate_each_(funs(scale(.) %&gt;% as.vector), vars=c("cost","sales")) R normalized result id cost sales item 1 1 1.7887437 -0.4999873 pen 2 2 -0.4453054 -0.4083792 wf 3 3 -0.4603495 -0.4517725 gher 4 4 -0.4302613 -0.4276651 dger 5 5 -0.4528275 1.7878041 ww thanks @Wen
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/86329295
accepted answer: http://stackoverflow.com/a/49659643
has comment: http://stackoverflow.com/comment/86329011
tagged with: python
has comment: http://stackoverflow.com/comment/86328484
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has title: Why two different normalized results from Python vs R
has comment: http://stackoverflow.com/comment/86328634
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86328752
has answer: http://stackoverflow.com/a/49659643
tagged with: standardized
favorite count: 0
type: Question

http://stackoverflow.com/q/49743647
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Can't we use a single variable in three different module by making it global in python
score: 2
has body: I am pretty new at programming. I have three files, first one is "main.python", second one is "driver.python", third one is "global_var.python" which is only used to intialise global variables. main.python import global_var import driver global_var.init() driver.fun() print(shinchan) driver.python import global_var def fun(): shinchan ="hello python" global_var.python def init(): global shinchan upon running this I am getting error File "main.py", line 13, in &lt;module&gt; print(shinchan) NameError: name 'shinchan' is not defined I understand that in driver.python, python is creating altogether a new variable "shinchan" which has nothing to do with the global variable "shinchan" defined in "global_var.python", which I am trying to implement. can't we use same variable in these three different files. please help me out here.
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86502255
tagged with: global-variables
favorite count: 0
has answer: http://stackoverflow.com/a/49743717
type: Question

http://stackoverflow.com/q/49661380
accepted answer: http://stackoverflow.com/a/49661466
upvote count: 1
possible better answer: http://stackoverflow.com/a/49661430
has answer: http://stackoverflow.com/a/49661466
has answer: http://stackoverflow.com/a/49661430
type: AnsweredQuestion
has title: Store file output in dictionaries
answer count: 3
tagged with: python
tagged with: dictionary
score: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49661555
type: Question
has comment: http://stackoverflow.com/comment/86332677
has body: I have a file with two column as shown below -34G trendmar +41G trendmar 1.4G ttpsenet 3.6G tyibahco -13M uberhelp +19M uberhelp -8.9G umljgate +9.2G umljgate I want to store it in dictionaries to do some mathematical operations but using the first column as value and second as key. How could I do that?
downvote count: 0

http://stackoverflow.com/q/49616500
has title: Is it possible to delete a repetitive things of an element in a list?
has body: I have a list that I queried from MySQL server that contains something similar to example below but way more elements in it. For some reasons it has extra commas and brackets. [(datetime.datetime(2013, 1, 1, 0, 1, 14),), (datetime.datetime(2013, 1, 1, 1, 33, 50),)] Is there a way to eliminate specific brackets and comas that will produce [datetime.datetime(2013, 1, 1, 0, 1, 14), datetime.datetime(2013, 1, 1, 1, 33, 50)] When I print the first element in the list it shows (datetime.datetime(2013, 1, 1, 0, 1, 14),) Where I want it to be datetime.datetime(2013, 1, 1, 0, 1, 14) I can't seem to know where to look for this solution or how to even search for this problem. Any advice?
downvote count: 1
has answer: http://stackoverflow.com/a/49616620
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86240082
answer count: 3
accepted answer: http://stackoverflow.com/a/49616647
linked to: http://stackoverflow.com/q/45849120
tagged with: python
has comment: http://stackoverflow.com/comment/86240012
has comment: http://stackoverflow.com/comment/86240112
has answer: http://stackoverflow.com/a/49616647
favorite count: 0
type: Question
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/49616648
upvote count: 1
possible better answer: http://stackoverflow.com/a/49616620

http://stackoverflow.com/q/49691983
has answer: http://stackoverflow.com/a/49692395
downvote count: 0
favorite count: 0
has body: Say if I have a .csv file that looks like this: 0,0 1,1 2,2 3,3 4,4 5,5,5,5 6,6,6,6 7,7,7,7 How could I create a dataframe from row 5, without it depending on the row number? Obviously I know you can make the header=5 but I would like it to do something more like header=#when it reaches 4 columns#, whatever that row may be. I realise that this question was not quite as specific as I needed so I have reiterated it here: Creating a dataframe from different rows
type: Question
duplicate of: http://stackoverflow.com/q/15242746
tagged with: row
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
has title: Creating a dataframe from an unknown row
score: 2
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49694778
upvote count: 2
linked to: http://stackoverflow.com/q/15242746

http://stackoverflow.com/a/49737850
accepted answer of: http://stackoverflow.com/q/49737760
type: Answer
has comment: http://stackoverflow.com/comment/86500343
has body: To iterate with a delay, you can use df.iterrows() and time.sleep(): from time import sleep for row in df.iterrows(): # run your code sleep(1) # how many seconds to wait Or you can just put time.sleep() within the apply function itself (as @RafaelC suggests in the comments): def f(x, delay=1): # run your code sleep(delay) df.apply(f)
has comment: http://stackoverflow.com/comment/86489959
score: 9
answers question: http://stackoverflow.com/q/49737760
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86491386
has comment: http://stackoverflow.com/comment/86503766
upvote count: 9

udp
tags question: http://stackoverflow.com/q/49716147
tags question: http://stackoverflow.com/q/49618055
tag name: udp
type: Tag
tags question: http://stackoverflow.com/q/49688273
tags question: http://stackoverflow.com/q/49691805
tags question: http://stackoverflow.com/q/49726643

http://stackoverflow.com/comment/128974602
comment on: http://stackoverflow.com/a/49800671
score: 0
type: Comment
has text: Still getting this error even with 4gb ram..
type: AnswerComment

http://stackoverflow.com/q/49615328
has comment: http://stackoverflow.com/comment/86237733
has answer: http://stackoverflow.com/a/49615425
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49615422
has comment: http://stackoverflow.com/comment/86237258
tagged with: for-loop
answer count: 3
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/86237351
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86237271
type: Question
tagged with: tuples
has comment: http://stackoverflow.com/comment/86237255
has body: I am currently trying to change all values in a large dictionary (to the negative). I would like the statement to be in one line. I have the following dictionary sample: dict = {(0,0): 1, (2, 4): 2} What I want is newdict = {(0,0): -1, (2, 4): -2} I first tried several variations newdict = {x: -x for x in dict} However, I get always got the following error TypeError: bad operand type for unary -: 'tuple' I need something that is able to loop through the tuple keys to change all the values.
has answer: http://stackoverflow.com/a/49615422
tagged with: python
accepted answer: http://stackoverflow.com/a/49615425
has title: Change all values of dictionary with tuple keys in python
has answer: http://stackoverflow.com/a/49615455

http://stackoverflow.com/q/49636215
has comment: http://stackoverflow.com/comment/86280744
has comment: http://stackoverflow.com/comment/86280372
linked to: http://stackoverflow.com/q/14672753
answer count: 0
tagged with: flask
tagged with: video-streaming
tagged with: opencv
has comment: http://stackoverflow.com/comment/86281563
duplicate of: http://stackoverflow.com/q/14672753
type: Question
has title: Live video stream issue in Flask
has body: Hye. I am new to Python and Flask. I am getting live video streaming from camera and displaying it on web interface (FLASK). The server stays locked to the client until the client disconnects (mean camera is turned off). During video streaming I remain unable to do any other action(mean unable to perform any other action). Any solution to get rid from that issue? PS. I am using OPENCV to capture video.
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86281281
score: 0

http://stackoverflow.com/comment/86494078
has text: Yes, this approach actually worked. I used scipy griddata function because the velocity fields had nan values. Thanks for the idea
type: QuestionComment
comment on: http://stackoverflow.com/q/49657956
type: Comment
score: 0

http://stackoverflow.com/a/49704206
has comment: http://stackoverflow.com/comment/86445510
has comment: http://stackoverflow.com/comment/86433185
answers question: http://stackoverflow.com/q/49620507
has comment: http://stackoverflow.com/comment/86445526
score: 0
has comment: http://stackoverflow.com/comment/86432419
has comment: http://stackoverflow.com/comment/86421687
has comment: http://stackoverflow.com/comment/86434196
has body: You can use the below code from scapy.all import IP, UDP, L3RawSocket, conf from scapy.all import send as scapy_send def send(dest_ip, port, src_ip, payload, count=1): if dest_ip in ("127.0.0.1", "localhost"): conf.L3socket = L3RawSocket ip = IP(dst=dest_ip, src=src_ip) udp = UDP(dport=port) scapy_send(ip/udp/str(payload), count=count) send("192.168.1.100", 9090, "192.168.33.100", "Tarun here", 2)
has comment: http://stackoverflow.com/comment/86435679
has comment: http://stackoverflow.com/comment/86434363
type: Answer

http://stackoverflow.com/a/49680274
upvote count: 1
has comment: http://stackoverflow.com/comment/86374694
answers question: http://stackoverflow.com/q/49680054
type: Answer
has body: As stated by Mad Physicist and Anton vBR, the set of square brackets, [], is the issue. When you put these brackets around something in python, it will create a list upon execution. So, by putting a list object, first_row_values, within square brackets, you are nesting a list within a new list, as its only element.
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49680054
downvote count: 0

http://stackoverflow.com/q/49661720
tagged with: qt
score: 0
tagged with: pyqt
tagged with: selectionmodel
has comment: http://stackoverflow.com/comment/86369092
has comment: http://stackoverflow.com/comment/86334796
has body: The code below creates a single QTableView with a QPushButton: from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * app = QApplication([]) class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setLayout(QVBoxLayout()) self.view = QTableView(self) self.view.setSelectionBehavior(QTableWidget.SelectRows) self.view.setSortingEnabled(True) self.view.sortByColumn(0, Qt.DescendingOrder) self.view.setModel(QStandardItemModel(4, 4)) for each in [(row, col, QStandardItem('item %s_%s' % (row, col))) for row in range(4) for col in range(4)]: self.view.model().setItem(*each) self.layout().addWidget(self.view) btn1 = QPushButton('Invert selection') btn1.clicked.connect(self.invertSelection) self.layout().addWidget(btn1) self.resize(500, 250) self.show() def invertSelection(self): model = self.view.model() for i in range(model.rowCount()): for j in range(model.columnCount()): ix = model.index(i, j) self.view.selectionModel().select(ix, QItemSelectionModel.Toggle) dialog = Dialog() app.exec_() .... Step 1: Select the last row by clicking on any of its cells. The clicked row is highlighted blue to indicate it is now selected: Step 2: Click "Invert selection" button. The selection is properly inverted: Step 3: Now click on column header #4 to sort by last column. At this point the selection is broken (there is only one cell is selected and it is shifted wild): Question: How to fix the issue?
type: Question
answer count: 0
type: UnansweredQuestion
has title: How to invert QTableView selection with Sorting Enabled
tagged with: python
tagged with: qtableview

http://stackoverflow.com/comment/86320574
comment on: http://stackoverflow.com/q/49655712
score: 0
type: QuestionComment
has text: related to [this](https://stackoverflow.com/questions/49339739/simple-text-cleaning-python-3-6-script-not-giving-correct-output-on-executing-th)
type: Comment

http://stackoverflow.com/comment/86279666
has text: @jpp oh sorry, no thats variable
comment on: http://stackoverflow.com/q/49636021
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86474196
type: Comment
has text: Relevant answers: https://stackoverflow.com/q/44254458/6220679
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49723410

http://stackoverflow.com/q/49622338
type: Question
has answer: http://stackoverflow.com/a/49622732
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/613183
has comment: http://stackoverflow.com/comment/86252516
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86251596
has title: Sort dictionary items using a key while looping
upvote count: 4
score: 4
answer count: 2
has body: I have a dictionary: sequence = { 'group4': {'shutdown_grace': 300, 'startup_order': 4, 'warmup_time': 300, 'shutdown_order': 6, 'servers': ['group4_1', 'group4_2']}, 'group1': {'shutdown_grace': 300, 'startup_order': 1, 'warmup_time': 900, 'shutdown_order': 10, 'servers': ['group1_1', 'group1_2', 'group1_3']}, 'group3': {'shutdown_grace': 300, 'startup_order': 3, 'warmup_time': 900, 'shutdown_order': 7, 'servers': ['group3_1', 'group3_2']}, 'group2': {'shutdown_grace': 300, 'startup_order': 2, 'warmup_time': 900, 'shutdown_order': 8, 'servers': ['group2_1', 'group2_2']} } I wanted to create a loop that will go through this list using a value in the sequence dictionary (e.g. sequence['group4']['startup_order']). How do I do this using sorted()? I tried using this: for k, v in sorted(sequence.items(), key=sequence[k]['startup_order']): print(k, v) but it's throwing an error: UnboundLocalError: local variable 'k' referenced before assignment
downvote count: 0
has answer: http://stackoverflow.com/a/49622372
favorite count: 0

epoch
tags question: http://stackoverflow.com/q/49643737
type: Tag
tag name: epoch

http://stackoverflow.com/q/49614340
type: Question
has comment: http://stackoverflow.com/comment/86282434
has comment: http://stackoverflow.com/comment/86277156
has comment: http://stackoverflow.com/comment/86282570
has comment: http://stackoverflow.com/comment/86281963
tagged with: mnist
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/86300458
has comment: http://stackoverflow.com/comment/86251135
has comment: http://stackoverflow.com/comment/86260250
has comment: http://stackoverflow.com/comment/86282791
has comment: http://stackoverflow.com/comment/86277230
answer count: 0
has comment: http://stackoverflow.com/comment/86281742
has title: why does my Neural network not work with MNIST dataset?
downvote count: 0
has comment: http://stackoverflow.com/comment/86281560
upvote count: 1
has comment: http://stackoverflow.com/comment/86235939
type: UnansweredQuestion
score: 1
has body: i have written the attached neural net twice reading each line carefully i have taken reference from tariq rashid's book how to train your neural network in the book hi claims to have an accuracy of upto 95%. But my code does not converge, accuracy revolves around 10% which means it is guessing randomly. please help import numpy as np import scipy.special from random import * class NeuralNetwork: def __init__(self,inp_layer,hid_layer,out_layer): self.inp_layer = inp_layer self.hid_layer = hid_layer self.out_layer = out_layer self.learning_rate = 0.1 self.weights_ih = np.random.normal(0.0, pow(self.hid_layer, 0.5),(self.hid_layer, self.inp_layer)) self.weights_ho = np.random.normal(0.0, pow(self.out_layer, 0.5),(self.out_layer, self.hid_layer)) self.bias_h = np.random.rand(self.hid_layer,1) self.bias_o = np.random.rand(self.out_layer,1) #self.activation = lambda x: scipy.special.expit(x) #self.d_activation = lambda x: x*(1-x) self.activation = lambda x: np.tanh(x) self.d_activation = lambda x: 1-(x*x) def train(self,inps,targs): inputs = np.array(inps,ndmin=2).T targets = np.array(targs,ndmin=2).T hidden_inputs = np.dot(self.weights_ih, inputs) hidden_inputs += self.bias_h hidden_outputs = self.activation(hidden_inputs) output_inputs = np.dot(self.weights_ho, hidden_outputs) output_inputs += self.bias_o outputs = self.activation(output_inputs) output_errors = targets - outputs hidden_errors = np.dot(self.weights_ho.transpose(),output_errors) delta_weights_ho = self.learning_rate*np.dot((output_errors*self.d_activation(outputs)),hidden_outputs.transpose()) delta_weights_ih = self.learning_rate*np.dot((hidden_errors*self.d_activation(hidden_outputs)),inputs.transpose()) delta_bias_o = self.learning_rate*(output_errors*self.d_activation(outputs)) delta_bias_h = self.learning_rate*(hidden_errors*self.d_activation(hidden_outputs)) self.weights_ho += delta_weights_ho self.weights_ih += delta_weights_ih self.bias_o += delta_bias_o self.bias_h += delta_bias_h def predict(sel…
has comment: http://stackoverflow.com/comment/86281800
favorite count: 0

http://stackoverflow.com/comment/86222929
type: Comment
type: QuestionComment
has text: So with four numbers in the wrong place you win? (Dues to your code.)
comment on: http://stackoverflow.com/q/49608130
score: 0

http://stackoverflow.com/comment/86259015
score: 0
type: AnswerComment
has text: `input()` will also work the same, for more details check the docs.
comment on: http://stackoverflow.com/a/49625247
type: Comment

http://stackoverflow.com/comment/86407165
score: 0
type: Comment
type: QuestionComment
has text: @pault I am trying to avoid making a list of the unique items in 'Particulars' as its a 1000 row df and then setting up empty dataframes in the list(making a dictionary) and then looping through. :( I was hoping there was a way to split the dataframe based 'Particulars' column
comment on: http://stackoverflow.com/q/49697056

http://stackoverflow.com/comment/86332606
score: 0
comment on: http://stackoverflow.com/a/49651183
has text: Thank you for your answer. I am using the scikit learn package, and I have 29 parameters. I have a 'predictions' array, but I don't see any array throughout the process that would contain the parameters.
type: Comment
type: AnswerComment

opencv
tags question: http://stackoverflow.com/q/49643616
tags question: http://stackoverflow.com/q/49701525
tags question: http://stackoverflow.com/q/49706503
tags question: http://stackoverflow.com/q/49636215
tags question: http://stackoverflow.com/q/49654051
tags question: http://stackoverflow.com/q/49663401
type: Tag
tags question: http://stackoverflow.com/q/49717822
tags question: http://stackoverflow.com/q/49656522
tags question: http://stackoverflow.com/q/49683473
tags question: http://stackoverflow.com/q/49620855
tags question: http://stackoverflow.com/q/49659236
tags question: http://stackoverflow.com/q/49675692
tags question: http://stackoverflow.com/q/49680152
tags question: http://stackoverflow.com/q/49732130
tags question: http://stackoverflow.com/q/49725744
tags question: http://stackoverflow.com/q/49734130
tags question: http://stackoverflow.com/q/49610140
tags question: http://stackoverflow.com/q/49755892
tags question: http://stackoverflow.com/q/49724767
tags question: http://stackoverflow.com/q/49684815
tags question: http://stackoverflow.com/q/49749294
tags question: http://stackoverflow.com/q/49656671
tags question: http://stackoverflow.com/q/49733841
tags question: http://stackoverflow.com/q/49748702
tags question: http://stackoverflow.com/q/49646334
tags question: http://stackoverflow.com/q/49741781
tags question: http://stackoverflow.com/q/49748917
tags question: http://stackoverflow.com/q/49636870
tags question: http://stackoverflow.com/q/49633399
tags question: http://stackoverflow.com/q/49707922
tags question: http://stackoverflow.com/q/49747708
tags question: http://stackoverflow.com/q/49711650
tags question: http://stackoverflow.com/q/49667248
tags question: http://stackoverflow.com/q/49740758
tags question: http://stackoverflow.com/q/49687284
tags question: http://stackoverflow.com/q/49698001
tags question: http://stackoverflow.com/q/49606509
tags question: http://stackoverflow.com/q/49706803
tags question: http://stackoverflow.com/q/49629221
tags question: http://stackoverflow.com/q/49666349
tags question: http://stackoverflow.com/q/49619132
tags question: http://stackoverflow.com/q/49634567
tags question: http://stackoverflow.com/q/49655556
tags question: http://stackoverflow.com/q/49662022
tags question: http://stackoverflow.com/q/49611403
tags question: http://stackoverflow.com/q/49688722
tags question: http://stackoverflow.com/q/49613059
tags question: http://stackoverflow.com/q/49675419
tags question: http://stackoverflow.com/q/49631518
tags question: http://stackoverflow.com/q/49621780
tags question: http://stackoverflow.com/q/49714258
tags question: http://stackoverflow.com/q/49603106
tags question: http://stackoverflow.com/q/49693264
tags question: http://stackoverflow.com/q/49609062
tags question: http://stackoverflow.com/q/49638305
tags question: http://stackoverflow.com/q/49737541
tags question: http://stackoverflow.com/q/49744376
tags question: http://stackoverflow.com/q/49650772
tags question: http://stackoverflow.com/q/49718057
tags question: http://stackoverflow.com/q/49610409
tags question: http://stackoverflow.com/q/49737231
tags question: http://stackoverflow.com/q/49631816
tags question: http://stackoverflow.com/q/49711408
tags question: http://stackoverflow.com/q/49691601
tags question: http://stackoverflow.com/q/49755568
tags question: http://stackoverflow.com/q/49746500
tags question: http://stackoverflow.com/q/49668053
tags question: http://stackoverflow.com/q/49640744
tags question: http://stackoverflow.com/q/49750691
tags question: http://stackoverflow.com/q/49638123
tags question: http://stackoverflow.com/q/49602465
tags question: http://stackoverflow.com/q/49688880
tags question: http://stackoverflow.com/q/49681166
tags question: http://stackoverflow.com/q/49754666
tags question: http://stackoverflow.com/q/49660153
tags question: http://stackoverflow.com/q/49663474
tags question: http://stackoverflow.com/q/49663284
tags question: http://stackoverflow.com/q/49618269
tags question: http://stackoverflow.com/q/49723460

http://stackoverflow.com/comment/86337183
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49663657
has text: ok. `soup.find_all(class_='stoksPrice')` prints `[ , 191.1 ]`
type: Comment

http://stackoverflow.com/a/49613606
type: Answer
answers question: http://stackoverflow.com/q/49613360
upvote count: 2
has comment: http://stackoverflow.com/comment/86234119
has body: Very simple solution using sum and enumerate initialList = [1, 2, 3, 5] targetList = sum((times*[index] for index, times in enumerate(initialList)), [])
downvote count: 1
score: 1

http://stackoverflow.com/q/49711868
has answer: http://stackoverflow.com/a/49711977
has comment: http://stackoverflow.com/comment/86437655
has body: Trying to figure out class inheritance of class attributes that are themselves classes. Here's what I'm trying to do: class foo: hello = None world = None def __init__(self, **kwargs): for k,v in kwargs.items(): if hasattr(self, k): setattr(self, k, v) else: raise AttributeError(f'class foo has no attribute {k}') class foo2: hi = None earth = None def __init__(self, **kwargs): for k,v in kwargs.items(): if hasattr(self, k): setattr(self, k, v) else: raise AttributeError(f'class foo has no attribute {k}') class bar: foo_attr = foo(hello=1, world=2) foo2_attr = foo2(hi=3, earth=4) class bar2(bar): def __init__(self): super().__init__() So I have 2 base classes (foo and foo2) with 2 attributes each (hello &amp; world, hi &amp; earth, respectively). I have another base class (bar) that has class attributes inside with default values for foo and foo2. Update (to include question): Lastly, I have bar2 which is a subclass of bar. How can I change the values of an attribute of a subclass that are themselves, classes? (say hello attribute of the foo_attr in bar2) I'm trying to set a default value for bar but i want to be able to set different attributes for each of the class attributes inside bar when I subclass it. This way, I can create a bunch of subclasses of bar like so: a bar2 with default attributes except foo2.earth which i set to 20. So that means bar2 has: foo.hello = 1 foo.world = 2 foo2.hi = 3 foo2.earth = 20 and then still be able to create a bar3, with say default attributes for foo() and foo2() except for foo.hello, which maybe I want to set to 30 and then add a new attribute of say "jeez". How do I go about doing this?
has comment: http://stackoverflow.com/comment/86438119
has comment: http://stackoverflow.com/comment/86437559
answer count: 2
has comment: http://stackoverflow.com/comment/86437271
has comment: http://stackoverflow.com/comment/86437715
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86437679
has answer: http://stackoverflow.com/a/49712302
has comment: http://stackoverflow.com/comment/86437737
has comment: http://stackoverflow.com/comment/86437510
has comment: http://stackoverflow.com/comment/86437459
type: Question
has title: Understanding Python class instantiation
score: 0
has comment: http://stackoverflow.com/comment/86437880
tagged with: subclass
has comment: http://stackoverflow.com/comment/86437764
tagged with: python

utf
tag name: utf
type: Tag
tags question: http://stackoverflow.com/q/49604819

http://stackoverflow.com/q/49617178
has answer: http://stackoverflow.com/a/49618248
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86241482
has comment: http://stackoverflow.com/comment/86241624
has answer: http://stackoverflow.com/a/49617921
has comment: http://stackoverflow.com/comment/86241720
answer count: 3
has title: Word file to json in python
score: 1
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
has body: I have a few word files (doc and docx) containing data of following form and I need to convert them to JSON: 1.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890 2.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890 3.Name: ABC, Place: Maryland, Country: US, PHONE NO.:1234567890 What's the easiest way to do this in python?
has answer: http://stackoverflow.com/a/49617695
favorite count: 0
type: Question

http://stackoverflow.com/comment/86446876
comment on: http://stackoverflow.com/q/49716841
has text: @mehrdad-pedramfar Ultimately, I'd like see the total sum of values in C, that apply the condition mentioned for B. Next step would be to add another condition, e.g. 1980<x<1989 and see the total sum for this.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86315552
type: Comment
comment on: http://stackoverflow.com/a/49653430
has text: @BryanOakley Oh wait. Sorry about that I just realized my mistake here. Thanks for pointing that out.
score: 0
type: AnswerComment

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/49688972
tags question: http://stackoverflow.com/q/49745485
tags question: http://stackoverflow.com/q/49756389
tags question: http://stackoverflow.com/q/49640460
tags question: http://stackoverflow.com/q/49752424
tags question: http://stackoverflow.com/q/49650531
tags question: http://stackoverflow.com/q/49630130
tags question: http://stackoverflow.com/q/49681168
tags question: http://stackoverflow.com/q/49756600
tags question: http://stackoverflow.com/q/49661985
tags question: http://stackoverflow.com/q/49739795
tags question: http://stackoverflow.com/q/49716568
tags question: http://stackoverflow.com/q/49652758
tags question: http://stackoverflow.com/q/49644252
tags question: http://stackoverflow.com/q/49709201
tags question: http://stackoverflow.com/q/49617116
tags question: http://stackoverflow.com/q/49692402
tags question: http://stackoverflow.com/q/49683241
tags question: http://stackoverflow.com/q/49735252
tags question: http://stackoverflow.com/q/49600772
tags question: http://stackoverflow.com/q/49609196
tags question: http://stackoverflow.com/q/49705454
tags question: http://stackoverflow.com/q/49605789
tags question: http://stackoverflow.com/q/49624954
tags question: http://stackoverflow.com/q/49703454
tags question: http://stackoverflow.com/q/49642982
tags question: http://stackoverflow.com/q/49644779
tags question: http://stackoverflow.com/q/49651890
tags question: http://stackoverflow.com/q/49684795
type: Tag
tags question: http://stackoverflow.com/q/49674071
tags question: http://stackoverflow.com/q/49719537

http://stackoverflow.com/comment/86391736
type: Comment
has text: update script output and desired ouput
type: QuestionComment
comment on: http://stackoverflow.com/q/49689115
score: 0

http://stackoverflow.com/comment/86521425
type: Comment
type: AnswerComment
has text: thanks for your help. I understand about indexing in python. The bit i am struggling with is why the first 4 rows of AllData are being rewritten when i have not rewritten them?
score: 0
comment on: http://stackoverflow.com/a/49746592

http://stackoverflow.com/comment/86499082
has text: You may edit your question further. It is not clear if you know how to do it in Python (or not), or why exactly you are asking for advice.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49742047

http://stackoverflow.com/a/49658558
score: 0
has body: You should change: def g(t,y,B): return math.exp(np.dot(y,B)) to: def g(t,y,B): return np.exp(np.dot(y,B))
answers question: http://stackoverflow.com/q/49658375
has comment: http://stackoverflow.com/comment/86339748
type: Answer

http://stackoverflow.com/a/49718556
score: 0
type: AcceptedAnswer
has body: It shouldn't be hard to find considering socket.accept returns it with every accepted connection. So does socket.recvfrom. A typical IPv4 socket address looks like: &gt;&gt;&gt; socket.getaddrinfo('www.google.com','www') [(2, 1, 6, '', ('64.233.163.99', 80)), (2, 1, 6, '', ('64.233.163.104', 80)), (2, 1, 6, '', ('64.233.163.147', 80)), (2, 1, 6, '', ('64.233.163.105', 80)), (2, 1, 6, '', ('64.233.163.103', 80)), (2, 1, 6, '', ('64.233.163.106', 80)), (10, 1, 6, '', ('2a00:1450:4010:c06::6a', 80, 0, 0))] &gt;&gt;&gt; _[0][4] ('64.233.163.99', 80) That 80 is the port number.
accepted answer of: http://stackoverflow.com/q/49718402
answers question: http://stackoverflow.com/q/49718402
type: Answer

http://stackoverflow.com/q/49720616
has body: I have this Dataframe: import pandas as pd df = pd.DataFrame({'Hugo' : {'age' : 21, 'weight' : 75}, 'Bertram': {'age' : 45, 'weight' : 65}, 'Donald' : {'age' : 75, 'weight' : 85}}).T df.index.names = ['name'] age weight name Bertram 45 65 Donald 75 85 Hugo 21 75 I want to change the index to the column 'age': df.set_index('age', inplace=True) weight age 45 65 75 85 21 75 The old index-column name gets lost. Is there a way to change the index without losing the original index-column and getting the old column as 'normal' column again, so that it looks like this? name weight age 45 Bertram 65 75 Donald 85 21 Hugo 75
accepted answer: http://stackoverflow.com/a/49720630
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49720630
upvote count: 31
has answer: http://stackoverflow.com/a/53716446
downvote count: 0
has title: python - Pandas - Dataframe.set_index - how to keep the old index column
possible better answer: http://stackoverflow.com/a/49720658
favorite count: 0
has answer: http://stackoverflow.com/a/49720658
score: 31
type: AnsweredQuestion
tagged with: pandas
answer count: 5
has answer: http://stackoverflow.com/a/65094607
has answer: http://stackoverflow.com/a/54676591
tagged with: python

http://stackoverflow.com/comment/86511560
score: 0
has text: @SlipFist Evidently that did not remove the problematic content.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49748278

http://stackoverflow.com/comment/86240334
has text: In my opinion `df['col1'] == df['col2']` is better/faster here, better avoid `apply`, because `loops under the hood`.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49616682

pip
tags question: http://stackoverflow.com/q/49688517
tags question: http://stackoverflow.com/q/49718754
tags question: http://stackoverflow.com/q/49685775
tags question: http://stackoverflow.com/q/49748063
tags question: http://stackoverflow.com/q/49633385
tags question: http://stackoverflow.com/q/49652084
tags question: http://stackoverflow.com/q/49631240
tags question: http://stackoverflow.com/q/49613734
tags question: http://stackoverflow.com/q/49685085
tags question: http://stackoverflow.com/q/49628139
tags question: http://stackoverflow.com/q/49743961
tags question: http://stackoverflow.com/q/49728265
tags question: http://stackoverflow.com/q/49616658
tags question: http://stackoverflow.com/q/49740628
tags question: http://stackoverflow.com/q/49749808
tags question: http://stackoverflow.com/q/49692192
tags question: http://stackoverflow.com/q/49662177
tags question: http://stackoverflow.com/q/49614096
tags question: http://stackoverflow.com/q/49600203
tags question: http://stackoverflow.com/q/49648719
tags question: http://stackoverflow.com/q/49689880
tags question: http://stackoverflow.com/q/49634506
tags question: http://stackoverflow.com/q/49707372
tags question: http://stackoverflow.com/q/49737799
tags question: http://stackoverflow.com/q/49653161
type: Tag
tags question: http://stackoverflow.com/q/49750356
tags question: http://stackoverflow.com/q/49712543
tags question: http://stackoverflow.com/q/49709504
tags question: http://stackoverflow.com/q/49745995
tags question: http://stackoverflow.com/q/49635600
tags question: http://stackoverflow.com/q/49627807
tags question: http://stackoverflow.com/q/49655444
tags question: http://stackoverflow.com/q/49608953
tags question: http://stackoverflow.com/q/49640513
tags question: http://stackoverflow.com/q/49615357
tags question: http://stackoverflow.com/q/49734434
tags question: http://stackoverflow.com/q/49617861
tags question: http://stackoverflow.com/q/49707239
tags question: http://stackoverflow.com/q/49619099
tags question: http://stackoverflow.com/q/49728277
tags question: http://stackoverflow.com/q/49651523
tags question: http://stackoverflow.com/q/49618548
tags question: http://stackoverflow.com/q/49674684
tags question: http://stackoverflow.com/q/49744793
tags question: http://stackoverflow.com/q/49728797
tags question: http://stackoverflow.com/q/49718346
tags question: http://stackoverflow.com/q/49715923
tags question: http://stackoverflow.com/q/49757409
tag name: pip
tags question: http://stackoverflow.com/q/49663327
tags question: http://stackoverflow.com/q/49731747
tags question: http://stackoverflow.com/q/49748870
tags question: http://stackoverflow.com/q/49643044
tags question: http://stackoverflow.com/q/49645581
tags question: http://stackoverflow.com/q/49748389
tags question: http://stackoverflow.com/q/49640389
tags question: http://stackoverflow.com/q/49624730
tags question: http://stackoverflow.com/q/49756084
tags question: http://stackoverflow.com/q/49713337
tags question: http://stackoverflow.com/q/49636986
tags question: http://stackoverflow.com/q/49616399
tags question: http://stackoverflow.com/q/49609473
tags question: http://stackoverflow.com/q/49745105
tags question: http://stackoverflow.com/q/49610858
tags question: http://stackoverflow.com/q/49672621
tags question: http://stackoverflow.com/q/49661119
tags question: http://stackoverflow.com/q/49650990
tags question: http://stackoverflow.com/q/49634510
tags question: http://stackoverflow.com/q/49618052
tags question: http://stackoverflow.com/q/49731828

http://stackoverflow.com/q/49677653
score: 2
has comment: http://stackoverflow.com/comment/86367861
has title: How to avoid memory blow up when using vstack on multiple astropy tables
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86367314
has comment: http://stackoverflow.com/comment/86376396
answer count: 1
downvote count: 0
tagged with: python
tagged with: astropy
has answer: http://stackoverflow.com/a/49688878
has comment: http://stackoverflow.com/comment/86367272
has body: I need to build a large astropy table by merging many smaller tables. I am using vstack repeatedly as bigTable = vstack([bigTable, smallTable]) but the memory is blowing up very fast. Each individual table is typically 9 columns times ~1000 lines and after 5 or 6 iterations the memory is >100 GB
favorite count: 0
type: Question

http://stackoverflow.com/a/49663700
accepted answer of: http://stackoverflow.com/q/49663551
upvote count: 1
type: AcceptedAnswer
has body: Here is one way to do it using findAll. Because all the previous stoksPrice are empty the only one that remains is the one with the price.. You can put in a check using try/except clause to check if it is a floating point number. If it is not it will continue iterating and if it is it will return it. res = soup.findAll("td", {"class": "stoksPrice"}) for r in res: try: t = float(r.text) print(t) except: pass 191.1
answers question: http://stackoverflow.com/q/49663551
score: 0
downvote count: 1
type: Answer

http://stackoverflow.com/q/49650990
has comment: http://stackoverflow.com/comment/86310394
has comment: http://stackoverflow.com/comment/86350663
tagged with: macos
has title: Python 3 can't use installed packages
has body: After installing the ics package with pip3 in my terminal on Mac OS High Sierra. I can't use this package in Python 3.6. I installed it by using: pip3 install --user ics When doing this again, I get the following message: Requirement already satisfied: ics in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requirement already satisfied: six&gt;1.5 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from ics) Requirement already satisfied: arrow==0.4.2 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from ics) Requirement already satisfied: python-dateutil in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from ics) But when I try to run a script using: python3 test.py I get the following error: from ics import Calendar, Event ImportError: cannot import name 'Calendar' The test.py file just contains an import of the package: from ics import Calendar, Event c = Calendar() It is not the first time that I can't use an installed package with Python 3 on my Mac. I looked at a couple of solutions, like updating the .bash_profile file, but that already pointed at the correct Python version I was using. # Setting PATH for Python 3.6 # The original version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}" export PATH This issue is frustrating me for days right now and I can't seem to find any solution..
has comment: http://stackoverflow.com/comment/86310268
type: Question
has comment: http://stackoverflow.com/comment/86310186
answer count: 0
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86310472
has comment: http://stackoverflow.com/comment/86310574
score: 0

http://stackoverflow.com/comment/86403835
comment on: http://stackoverflow.com/q/49632451
type: QuestionComment
type: Comment
score: 0
has text: The 2nd cell in your notebook has missing variables? Can you please provide a notebook which works. Also try adding `df.columns = df.columns.astype(str)` after loading the dataframe in the first cell and see if it fixes the issue

http://stackoverflow.com/q/49657742
score: 0
has comment: http://stackoverflow.com/comment/86324977
has answer: http://stackoverflow.com/a/49658803
has comment: http://stackoverflow.com/comment/86324655
has body: I'm trying to build a decision tree classifier, and I have the following code: def dtree(data, attrs, target): data = data[:] vals = [] for entry in data: entry_index = attrs.index(target) vals.append(entry[entry_index]) major = majority(data, attrs, target) if not data or (len(attrs) - 1) &lt;= 0: return major elif vals.count(vals[0]) == len(vals): return vals[0] else: pick = choose(data, attrs, target) tree = {pick:{}} for each in get_vals(data, attrs, pick): new_d = get_data(data, attrs, pick, each) newAttr = attrs[:] newAttr.remove(pick) subtree = dtree(new_d, newAttr, target) tree[pick][each] = subtree return tree Where: data is a pandas dataframe of my training data (33582 x 21), attrs is a list of the dataframe headers, target is the string name of the target attribute. vals is a list When I call this method, I get the following error: File "dtree_classifier.py", line 176, in dtree vals.append(entry[entry_index]) IndexError: string index out of range I'm not sure what about that line is throwing the error and I don't know what I'm supposed to do to diagnose it. Here's a data example:
answer count: 1
has comment: http://stackoverflow.com/comment/86325804
accepted answer: http://stackoverflow.com/a/49658803
tagged with: anaconda
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86325105
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/86324839
has title: Fixing an Index Error for a dataframe
type: Question

http://stackoverflow.com/q/49619541
score: 0
tagged with: list
tagged with: python
has body: Let say I have a hidden list of numbers, for example: [3397, 3343, 3297, 3251, 3215, 3159, 3107, 3061, 3029, 2979, 2939, 2879, 2829, 2781, 2733, 2673, 2615, 2579, 2633, 2669, 2713] I cannot see the list; I can only probe for individual values. How do I find the smallest value with the least number of probes? What I know of the list is that it has center of gravity, i.e. they are sorted towards this position from both sides. In the above case, the list is sorted outward from position 17 (value 2579) in both directions. Based on Prune recommendation : def mini(lst, low, high): zrange = (high-low) if zrange &lt;= 3 : return min(lst[low:high]) i25 = int(low + zrange*0.25); i50 = int(low + zrange*0.5); i75 = int(low + zrange*0.75) q25 = lst[i25]; q50 = lst[i50]; q75 = lst[i75] if q25 &lt;= q50 &lt;= q75 : high = i50 elif q25 &gt;= q50 &gt;= q75 : low = i50 elif q25 &gt; q50 &lt; q75 : low = i25; high = i75 return mini(lst, low, high) def minis(lst): low = 0; high = len(lst) return mini(lst, low, high) Any other takers on different algorithm. To lower the probes, I have to make it iteration, rather than recursion. This way I can reuse probes.
has comment: http://stackoverflow.com/comment/86246171
has title: Center-of-gravity list search?
tagged with: search
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49619947
answer count: 1
type: Question

http://stackoverflow.com/q/49660124
has answer: http://stackoverflow.com/a/49660477
possible better answer: http://stackoverflow.com/a/49660477
has answer: http://stackoverflow.com/a/49660180
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86330036
tagged with: python
has title: Reverse Values Based on Successive Count
accepted answer: http://stackoverflow.com/a/49660180
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/86329895
answer count: 2
has body: I have a series containing only 1's and 0's used as a flag. I'm trying to figure out a good way to count the number of successive repeat values, and if it doesn't meet a threshold, I'd like to reverse them. For instance, if I have less than 5 repeated values in succession, reverse them from 0's to 1's or vice versa. For example: Flag 1 1 1 1 1 0 0 0 0 1 1 ... Would become: Flag 1 1 1 1 1 1 1 1 1 1 1 ...
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/86329976
downvote count: 0

pyqt
type: Tag
tags question: http://stackoverflow.com/q/49663980
tags question: http://stackoverflow.com/q/49734666
tags question: http://stackoverflow.com/q/49682271
tags question: http://stackoverflow.com/q/49633281
tags question: http://stackoverflow.com/q/49630745
tags question: http://stackoverflow.com/q/49615844
tags question: http://stackoverflow.com/q/49621152
tags question: http://stackoverflow.com/q/49621849
tags question: http://stackoverflow.com/q/49602337
tags question: http://stackoverflow.com/q/49645898
tags question: http://stackoverflow.com/q/49679827
tags question: http://stackoverflow.com/q/49685065
tags question: http://stackoverflow.com/q/49617149
tags question: http://stackoverflow.com/q/49752388
tags question: http://stackoverflow.com/q/49664603
tags question: http://stackoverflow.com/q/49728012
tags question: http://stackoverflow.com/q/49722276
tags question: http://stackoverflow.com/q/49620929
tags question: http://stackoverflow.com/q/49631464
tags question: http://stackoverflow.com/q/49615013
tags question: http://stackoverflow.com/q/49698060
tags question: http://stackoverflow.com/q/49609259
tags question: http://stackoverflow.com/q/49638110
tags question: http://stackoverflow.com/q/49741391
tags question: http://stackoverflow.com/q/49639518
tags question: http://stackoverflow.com/q/49639135
tags question: http://stackoverflow.com/q/49715458
tags question: http://stackoverflow.com/q/49644530
tags question: http://stackoverflow.com/q/49728462
tags question: http://stackoverflow.com/q/49744581
tags question: http://stackoverflow.com/q/49665870
tags question: http://stackoverflow.com/q/49615650
tags question: http://stackoverflow.com/q/49647205
tags question: http://stackoverflow.com/q/49664780
tags question: http://stackoverflow.com/q/49688681
tag name: pyqt
tags question: http://stackoverflow.com/q/49744088
tags question: http://stackoverflow.com/q/49661720
tags question: http://stackoverflow.com/q/49667299
tags question: http://stackoverflow.com/q/49741129
tags question: http://stackoverflow.com/q/49686907
tags question: http://stackoverflow.com/q/49670460
tags question: http://stackoverflow.com/q/49710186
tags question: http://stackoverflow.com/q/49747858
tags question: http://stackoverflow.com/q/49718552
tags question: http://stackoverflow.com/q/49677073
tags question: http://stackoverflow.com/q/49734880
tags question: http://stackoverflow.com/q/49619631
tags question: http://stackoverflow.com/q/49640489

apache-spark
tags question: http://stackoverflow.com/q/49646184
tags question: http://stackoverflow.com/q/49663835
tags question: http://stackoverflow.com/q/49606742
tags question: http://stackoverflow.com/q/49751909
tags question: http://stackoverflow.com/q/49624744
tags question: http://stackoverflow.com/q/49661434
tags question: http://stackoverflow.com/q/49711665
tags question: http://stackoverflow.com/q/49725614
tags question: http://stackoverflow.com/q/49697086
tags question: http://stackoverflow.com/q/49681837
tags question: http://stackoverflow.com/q/49666927
tags question: http://stackoverflow.com/q/49703022
tags question: http://stackoverflow.com/q/49710133
tags question: http://stackoverflow.com/q/49714328
tags question: http://stackoverflow.com/q/49729510
tags question: http://stackoverflow.com/q/49683897
tags question: http://stackoverflow.com/q/49699936
tags question: http://stackoverflow.com/q/49686275
tags question: http://stackoverflow.com/q/49742065
tags question: http://stackoverflow.com/q/49676701
tags question: http://stackoverflow.com/q/49652312
tags question: http://stackoverflow.com/q/49755034
tags question: http://stackoverflow.com/q/49685206
tags question: http://stackoverflow.com/q/49667461
tags question: http://stackoverflow.com/q/49623620
tags question: http://stackoverflow.com/q/49754476
tags question: http://stackoverflow.com/q/49721738
tags question: http://stackoverflow.com/q/49645139
tags question: http://stackoverflow.com/q/49634651
tags question: http://stackoverflow.com/q/49720956
tags question: http://stackoverflow.com/q/49675860
tags question: http://stackoverflow.com/q/49614856
tags question: http://stackoverflow.com/q/49669226
type: Tag
tags question: http://stackoverflow.com/q/49641137
tags question: http://stackoverflow.com/q/49716307
tags question: http://stackoverflow.com/q/49729648
tag name: apache-spark
tags question: http://stackoverflow.com/q/49703810
tags question: http://stackoverflow.com/q/49754318
tags question: http://stackoverflow.com/q/49632616
tags question: http://stackoverflow.com/q/49707239
tags question: http://stackoverflow.com/q/49698111
tags question: http://stackoverflow.com/q/49734374
tags question: http://stackoverflow.com/q/49646757

http://stackoverflow.com/comment/86354630
score: 0
type: AnswerComment
has text: I don't want to sort the list. I want to output the list element in exact same manner, either ['hello', 'bye', 'start'] or ['bye', 'start', 'hello'].
comment on: http://stackoverflow.com/a/49671874
type: Comment

http://stackoverflow.com/a/49731085
score: 1
type: Answer
has body: With numpy arrays, you can use np.array_equal. This tests for same shape and same elements. But if your logic is as simple as the code you have, use @Divakar's vectorized solution. points = np.unique(np.array(som.bmus), axis = 0) for idx, bmu in enumerate(som.bmus): for point_idx, point in enumerate(points): if np.array_equal(bmu, point): print(idx, point_idx) break
downvote count: 0
answers question: http://stackoverflow.com/q/49730895
upvote count: 1

http://stackoverflow.com/comment/86491523
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49738452
has text: Okay, so what is your problem/question?

http://stackoverflow.com/comment/110670968
type: Comment
has text: Thanks for the tip :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49604694
score: 1

http://stackoverflow.com/a/49640787
type: AcceptedAnswer
has body: You need to add STATIC_ROOT as a parameter to your settings.py. Here is how it works with those static files: In STATICFILES_DIRS you tell django where to go and look for static files. This not primarily to serve them, but to collect them! The point is that on a productive server, django is not supposed to server static files, this task should be handled by the web server. Check the docs for details. The idea is that you run the command python manage.py collectstatic and django will go through all the paths in STATICFILES_DIRS, collect the static files and put them... - exactly! - into the STATIC_ROOT folder. At this point 2 things should become clear: 1. You need to provide STATIC_ROOT in your settings.py. 2. The path provided in STATIC_ROOT cannot be part of STATICFILES_DIRS, as this would mean django would need to put the folder into itself. Again, this is in the case of a productive server. During development django can handle static files without help of a web server, here is more from the docs on that. Nevertheless, the STATIC_ROOT parameter is always required. Hope that helped to clarify things. Happy coding! :)
type: Answer
accepted answer of: http://stackoverflow.com/q/49640644
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49640644
downvote count: 0

http://stackoverflow.com/comment/86479277
type: Comment
has text: Not sure if that's the best solution, it did the job: `e = dict((i['index'],i['new']) for i in exceptions) if i in e: destlist.append({'id': i, 'dest': e[1]}) else: destlist.append({'id': i, 'dest': orig_destlist[i]})`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49731099

http://stackoverflow.com/comment/86529764
score: 0
type: Comment
type: QuestionComment
has text: @ma3oun What would my condition be for `tf.cond`? How would I specify that I want one expression in the forward pass and the other for differentiation?
comment on: http://stackoverflow.com/q/49757285

http://stackoverflow.com/comment/86501660
type: AnswerComment
has text: That last bit about algebra substitution is particularly cool.
comment on: http://stackoverflow.com/a/49743114
score: 1
type: Comment

http://stackoverflow.com/comment/86342093
has text: @AmiHollander https://pastebin.com/nmaGyrUs
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49665963
score: 0

http://stackoverflow.com/a/49733382
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49733101
type: Answer
has body: This is simple when you think about it so here goes: list_1 = ['12_a1_pp.csv', '32_a3_pp.csv', '45_a17_pp.csv', '81_a123_pp.csv'] list_2 = ['12_a1.json', '32_a3.json', '61_a54.json'] starters = [eachfile.partition(".")[0] for eachfile in list2] for eachelement in starters: for eachfile in list_1: if eachfile.startswith(eachelement): list_1b.append(eachfile) list_2b.append(eachelement+".json") Furthermore if you want specific to this case: collective_set_1 = { each.replace("_pp.csv","") for each in list_1} collective_set_2 = { each.replace(".json","") for each in list_2} intersection = collective_set_1.intersection(collective_set2) list_1b = [ each+"_pp.csv" for each in intersection ] list_2b = [ each+".json" for each in intersection ]
score: 1

http://stackoverflow.com/comment/86211225
type: AnswerComment
has text: @abarnert, Fair point. But I am wary of the fact not all the elements in the OP's dataset may be tuples. Some may be `set`, `list`, etc. Need some more information about how the data got into that state in the first place.
comment on: http://stackoverflow.com/a/49601948
score: 0
type: Comment

http://stackoverflow.com/q/49712308
has answer: http://stackoverflow.com/a/49713215
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86438285
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/993984
tagged with: python
has answer: http://stackoverflow.com/a/49712339
linked to: http://stackoverflow.com/q/35713093
answer count: 4
has answer: http://stackoverflow.com/a/49715263
has title: Comparing two lists on Python
has answer: http://stackoverflow.com/a/49712373
score: 2
tagged with: list
has body: I need help comparing two lists and returning the indices that they don't match. a = [0, 1, 1, 0, 0, 0, 1, 0, 1] b = [0, 1, 1, 0, 1, 0, 1, 0, 0] indices 4 and 8 don't match and i need to return that as a list [4,8] I've tried a few methods but they haven't worked for me.
upvote count: 3
has comment: http://stackoverflow.com/comment/86438324

http://stackoverflow.com/q/49722275
has title: Kivy Creating screens as variables
tagged with: python
tagged with: kivy
has body: I have a question about kivy. Is it possible to create screens as variables? Lets say I want to create a new screen with a button inside the kivy application. Is it possible to do that? If so how could you do it??
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49722504
accepted answer: http://stackoverflow.com/a/49722504

http://stackoverflow.com/a/49641953
has comment: http://stackoverflow.com/comment/86291677
answers question: http://stackoverflow.com/q/49641930
has comment: http://stackoverflow.com/comment/86291734
has comment: http://stackoverflow.com/comment/86291597
has comment: http://stackoverflow.com/comment/86292129
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/86291507
has body: Strings are infinitely iterable. Even a one-character string is iterable. Therefore, you will always get a stack overflow unless you add special handling for strings: def flatten(x): try: it = iter(x) except TypeError: yield x return if isinstance(x, (str, bytes)): yield x return for elem in it: yield from flatten(elem) Note: using hasattr(i, '__iter__') is not sufficient to check if i is iterable, because there are other ways to satisfy the iterator protocol. The only reliable way to determine whether an object is iterable is to call iter(obj).
has comment: http://stackoverflow.com/comment/86292102
score: 7
accepted answer of: http://stackoverflow.com/q/49641930
has comment: http://stackoverflow.com/comment/86291809
type: Answer
has comment: http://stackoverflow.com/comment/86291694

http://stackoverflow.com/comment/86318588
comment on: http://stackoverflow.com/q/49654597
has text: Updated the quesition.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86493657
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49739594
has text: I think that should be `[2:-1]`.
type: Comment

http://stackoverflow.com/a/49695752
has comment: http://stackoverflow.com/comment/86404708
downvote count: 0
has comment: http://stackoverflow.com/comment/86404338
has comment: http://stackoverflow.com/comment/86404917
score: 3
has comment: http://stackoverflow.com/comment/86404302
answers question: http://stackoverflow.com/q/49695687
type: Answer
has body: Apparently you want DataFrame.head. It's a convenience method; basically head(self, n) returns self.iloc[:n]. Please note that this is not cutting the original frame. It returns a view (subset) of the original frame, as much as I can tell. Some kinds of slicing return copies; it depends on context and is not very easy to predict.
upvote count: 3
has comment: http://stackoverflow.com/comment/86404848

http://stackoverflow.com/comment/86525989
comment on: http://stackoverflow.com/q/49726326
score: 0
type: Comment
type: QuestionComment
has text: Hi Will, I tried your suggestion. It will simply create the one without an integer ID (the one in the bottom, please see the attached images in the original post). So it seems that the create_user_profile function not working properly. I googled around, it seems that it is kind of standard way to create a object. Any more suggestions, please?

http://stackoverflow.com/q/49627823
downvote count: 0
tagged with: machine-learning
upvote count: 1
favorite count: 0
type: Question
tagged with: cosine-similarity
has body: I have n and m binary vectors(of length 1500) from set A and B respectively. I need a metric that can say how similar (kind of distance metric) all those n vectors and m vectors are. The output should be total_distance_of_n_vectors and total_distance_of_m_vectors. And if total_distance_of_n_vectors > total_distance_of_m_vectors, it means Set B have more similar vectors than Set A. Which metric should I use? I thought of Jaccard similarity. But I am not able to put it in this context. Should I find the distance of each vector with each other to find the total distance or something else ?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49630619
tagged with: similarity
has title: Distance metric for n binary vectors
tagged with: python
has comment: http://stackoverflow.com/comment/86264246
has comment: http://stackoverflow.com/comment/86263999
score: 1
answer count: 1

http://stackoverflow.com/q/49657952
has comment: http://stackoverflow.com/comment/86325263
score: 0
has comment: http://stackoverflow.com/comment/86325445
answer count: 1
has comment: http://stackoverflow.com/comment/86325508
has body: I am using python 2.7 with sqlite3 I've created an empty table to and a function that checks if the table is empty it gets the mac address of the current pc and stores it at the table, it works every time the program work, then if the table is not empty it calls another function that gets the current mac and compares it to the one stored in the table , then closes the program if its not the same ,, Here is the code : def active(): from uuid import getnode as get_mac mac = get_mac() name = 666 conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("SELECT COUNT(*) FROM mac") count = c.fetchall()[0] conn.close() if count == 0: conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("INSERT INTO mac (name, macAddress) VALUES (?, ?)", (name, mac, )) conn.commit() conn.close() else: checking() def checking(): from uuid import getnode as get_mac mac = get_mac() conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("SELECT macAddress FROM mac WHERE name = 666") table_mac = c.fetchall()[0] if mac == table_mac: critical_title1 = 'أهلاً بك ' critical_title = critical_title1.decode('utf-8') critical_msg1 = "تم تأكيد صلاحية النسخة للإستخدام " critical_msg = critical_msg1.decode('utf-8') QtGui.QMessageBox.information(mainWindow, critical_title, critical_msg) else: critical_title1 = 'خطأ' critical_title = critical_title1.decode('utf-8') critical_msg1 = "لا يمكنك إستخدام البرنامج من دون شراء نسختك الخاصة" critical_msg = critical_msg1.decode('utf-8') QtGui.QMessageBox.critical(mainWindow, critical_title, critical_msg) sys.exit() everything goes fine and the program already catches the mac address then add it to the table, but then, in all cases, it shows the error that closes the program after it .. ignoring the if-else statement that should stop the error from being showed i think the problem is here …
has answer: http://stackoverflow.com/a/49658265
type: Question
type: AnsweredQuestion
tagged with: sqlite
tagged with: python
accepted answer: http://stackoverflow.com/a/49658265
has title: Getting mac address from pc and compare it fails

http://stackoverflow.com/a/49752533
accepted answer of: http://stackoverflow.com/q/49752378
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86545860
answers question: http://stackoverflow.com/q/49752378
type: Answer
has body: In your main.py file, add following on the top. import sys path = r'{path_to_python_scripts}' if path not in sys.path: sys.path.append(path) # Now import import lib or import sys, os path = os.path.abspath('../..') if path not in sys.path: sys.path.append(path) # Now import import lib or How to import a module given the full path?
score: 4
upvote count: 4

http://stackoverflow.com/q/49600203
type: Question
has body: Is there an idiot's guide to installing gevent on Windows from scratch? I'm trying to install on to Windows 10 with Python 3.4. If I do a pip install then the installation blows out saying that it can't find Visual C++ compiler. (I definitely have 2017 VS Community edition installed, but obviously that's not acceptable to the installer for some reason.)
has title: Idiot's guide to installing gevent on Windows
tagged with: python
tagged with: visual-c++
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49618914
tagged with: pip
tagged with: gevent
has answer: http://stackoverflow.com/a/49618914

os.path
tags question: http://stackoverflow.com/q/49700561
tags question: http://stackoverflow.com/q/49687860
tag name: os.path
tags question: http://stackoverflow.com/q/49663348
tags question: http://stackoverflow.com/q/49631976
type: Tag
tags question: http://stackoverflow.com/q/49620855

http://stackoverflow.com/q/49743718
tagged with: python
upvote count: 0
has title: delete values from dictionary
accepted answer: http://stackoverflow.com/a/49743833
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/49743833
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
score: -3
has body: Doing a web scraping project, and tangled myself into a problem. I have this "data" dictionary with duplicates. In the data dictionary: I have unique keys, I would like to remove all values of a particular key wherein the value "the first part of the string" before "," is same and keep the last value. For example: data={ 'Peter Rabbit (2018)': 'AMC Norwalk 20,95 min,Animation|Adventure|Comedy|Family|Fantasy,User Rating: 6.5,Metascore:52,Showtimes:12:40 pm', 'Tomb Raider (2018)': 'Studio Movie Grill - Downey,118 min,Action|Adventure|Drama|Fantasy|Thriller,User Rating: 6.8,Metascore:48,Showtimes:11:10 am|1:55 pm|4:40|7:35|10:20\n AMC Norwalk 20,118 min,Action|Adventure|Drama|Fantasy|Thriller,User Rating: 6.8,Metascore:48,Showtimes:11:10 am|1:55 pm|4:40|7:35|10:20\n AMC Norwalk 20,118 min,Action|Adventure|Drama|Fantasy|Thriller,User Rating: 6.8,Metascore:48,Showtimes:4:45 pm|10:25'} As 'Peter Rabbit (2018)' key has one values we will skip it. Now, Tomb Raider (2018) has 3 values, I need to split based on "," for the first value of each value, I will get Studio Movie Grill - Downey AMC Norwalk 20 AMC Norwalk 20 I would like to remove 1 to n instance of duplicate entries and keep Nth value The final output will be data={ 'Peter Rabbit (2018)': 'AMC Norwalk 20,95 min,Animation|Adventure|Comedy|Family|Fantasy,User Rating: 6.5,Metascore:52,Showtimes:12:40 pm', 'Tomb Raider (2018)': 'Studio Movie Grill - Downey,118 min,Action|Adventure|Drama|Fantasy|Thriller,User Rating: 6.8,Metascore:48,Showtimes:11:10 am|1:55 pm|4:40|7:35|10:20\n AMC Norwalk 20,118 min,Action|Adventure|Drama|Fantasy|Thriller,User Rating: 6.8,Metascore:48,Showtimes:4:45 pm|10:25'} My questions are: What is the best-known method to achieve this output? Should I split the values based on "," or "\n "? Does python dictionary has any functions I can utilize? Any assistance will be apreciated.

http://stackoverflow.com/a/49617812
has body: Running graphical applications requires the DISPLAY environment variable to be set, which would be set when run it from the CLI, but not when run from systemd (unless you explicitly set it). This issue is covered more in Writing a systemd service that depends on XOrg. I agree with the general advise that systemd may not be the best tool for the job. You may be better off using an "auto start" feature of your desktop environment to run your app, which would set the correct things in the environment that you need.
has comment: http://stackoverflow.com/comment/86296546
type: Answer
answers question: http://stackoverflow.com/q/49608573
has comment: http://stackoverflow.com/comment/86257024
has comment: http://stackoverflow.com/comment/86313840
score: 0
has comment: http://stackoverflow.com/comment/86272417

http://stackoverflow.com/q/49638063
upvote count: 3
has body: I have the figure X.graph which is a matplotlib.figure.Figure being passed to an html template using render_template('page', graph= X.graph) from Flask. Is it possible to have my html page display this figure without saving it as an image and accessing it that way?
linked to: http://stackoverflow.com/q/20107414
downvote count: 0
tagged with: flask
has title: Display python matplotlib pyplot using html without saving figure
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/31492525
tagged with: http://stackoverflow.com/tag/html
tagged with: python
duplicate of: http://stackoverflow.com/q/20107414
score: 3
answer count: 0

http://stackoverflow.com/q/49608574
has body: I have a list of tuples that I want to plot. The tuples contain the number of times a word appears in a text collection and the number of words that appear this number of times. freq = [(k, len(list(v))) for k,v in itertools.groupby(sorted(coll.values()))] plt.bar(range(len(freq)), [val[1] for val in freq]) plt.xticks(range(len(freq)), [val[0] for val in freq]) plt.xticks(rotation=70) plt.xlabel('Times a word appears in the collection',labelpad=1) plt.ylabel('Number of words appearing x times') plt.show() I could provide the whole script but I think it's not needed. The plot I'm getting is this: Most of the words appear only one time, with frequency meaning less words. The 182 is the word "the" for example. Obviously this is an ugly and awkward plot. My question is how I can get the x-axis to appear more informative. Scaling the data with sklearn.preprocessing.scale() is futile as most observations turn negative. Should I group with np.arange() ?
has title: Formatting x-axis of discrete data in pyplot
score: 0
answer count: 1
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49608655
type: UnansweredQuestion
tagged with: python
tagged with: plot

http://stackoverflow.com/comment/86363595
type: AnswerComment
has text: Because `argpartition` doesn't sort, it just splits into two parts such that no item in the first part is larger than any item in the second. Even if you need the result sorted it's probably cheaper first to partition and then to sort only the `100` most similar
type: Comment
comment on: http://stackoverflow.com/a/49669295
score: 0

http://stackoverflow.com/q/49683437
accepted answer: http://stackoverflow.com/a/49683765
answer count: 1
has answer: http://stackoverflow.com/a/49683765
tagged with: scikit-learn
type: AnsweredQuestion
has body: I would like to use use gridsearchCV to tune hyperparameters from user defined estimators that perform on pandas dataframes. For example, impute the median, choose to include pass a column or not to the estimators and so on. Below, I exemplify just with a column selector, but the idea is to be able to tune the parameters in a more complex way. I keep getting some cryptic messages that I cannot yet decipher. For example, 'list' object has no attribute 'flags': from sklearn.datasets import california_housing from sklearn.linear_model import Ridge from sklearn.base import BaseEstimator from sklearn.model_selection import GridSearchCV import pandas as pd import numpy as np cal_house = california_housing.fetch_california_housing() data = cal_house['data'] names = cal_house['feature_names'] df = pd.DataFrame(data, columns=names) df['houseval'] = cal_house['target'] class ColumnSelector(BaseEstimator): def __init__(self, columns_for_x = ['MedInc','HouseAge']): self.columns = columns_for_x #self.lags = lags #self.grouper_col = grouper_col def fit(self, X, y): return self def transform(self, X, y): X = X.loc[:,self.columns].values return X, y pipe = Pipeline([('colselect', ColumnSelector()), ('Ridge', Ridge())]) gridsearch = GridSearchCV(cv=5, scoring='r2', param_grid= {'colselect__columns_for_x':[['MedInc','HouseAge'], ['MedInc','Population','Latitude'], ['MedInc','AveRooms','AveOccup']], 'Ridge__alpha':[0.001,0.01,0.1,1,10]}, estimator=pipe) X = df.drop('houseval', axis = 1).values y = df.loc[:,'houseval'].values # gridsearch.fit(X=X,y=y)
tagged with: python
has title: use gridsearchCV to tune hyperparameters that change a pandas df
type: Question
score: 0
tagged with: pandas

http://stackoverflow.com/comment/86206900
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49599886
has text: As in the operation of retrieving these tuples takes O(1) time (yours takes linear time)

http://stackoverflow.com/comment/86211116
has text: I think your problem is io bound, so your cpu can work just with 80%. You should use a faster storage like a ssd
comment on: http://stackoverflow.com/q/49601934
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49694321
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/102200838
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49695403
has body: Environment: Django 2, Python 3.6, PostgreSQL (optional) I am writing an application with multiple models, some of them might be stored in different databases. Example: models.py (might be in different apps) # this used to allow field 'database' to be processed in 'Meta' models.options.DEFAULT_NAMES = models.options.DEFAULT_NAMES + ('database', ) class MyModel01(models.Model): ... # this goes to default database class MyModel02(models.Model): ... class Meta: database = 'mydb02' class MyModel03(models.Model): ... class Meta: database = 'mydb03' routers.py: class MyRouter(object): def db_for_read(self, model, **hints): return getattr(model._meta, 'database', None) def db_for_write(self, model, **hints): return getattr(model._meta, 'database', None) def allow_migrate(self, db, app_label, model_name=None, **hints): model = hints.get('model') if not model: return None if db != 'default': modelname = model_name or model._meta.model_name usedb = getattr(model._meta, 'database', None) if not usedb: return False if modelname and usedb: return usedb == db return False else: usedb = getattr(model._meta, 'database', 'default') return usedb == db return None settings: DATABASES: { 'default': { # some db settings }, 'mydb02': { # db settings }, 'mydb03': { # the SAME db settings as for mydb02 } } The issue is that in settings there might be the same database set for all database aliases. When I run migrate the migration get applied to just one of the databases, but not always to required one. For example it gets applied to 'default', but not 'mydb03'. I suppose the mistake is in my router, but cannot find out correct implementation.
has comment: http://stackoverflow.com/comment/102197092
has comment: http://stackoverflow.com/comment/104939095
score: 2
has title: Django migrate multiple databases
has comment: http://stackoverflow.com/comment/102147288
tagged with: migration
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/102204874
has comment: http://stackoverflow.com/comment/86748270
favorite count: 0

http://stackoverflow.com/comment/90268880
type: Comment
comment on: http://stackoverflow.com/q/49699244
type: QuestionComment
has text: I got the same `.env` idea as you did. But then the value of my path is literally `${PYTHONPATH}:${PWD}`. Why did it work for you?
score: 2

http://stackoverflow.com/q/49711626
upvote count: 1
downvote count: 1
tagged with: julia
tagged with: import
favorite count: 0
has title: Fail to import matplotlib in Julia with @pyimport matplotlib.pyplot as plt
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49713664
tagged with: matplotlib
tagged with: python
has body: Hello I'm trying to use matplotlib in Julia with command Pkg.build("PyCall") using PyCall @pyimport matplotlib.pyplot as plt but I keep getting the following error message: PyError (ccall(@pysym(:PyImport_ImportModule), PyPtr, (Cstring,), name)) &lt;type 'exceptions.RuntimeError'&gt; RuntimeError("Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.",) File "/Users/mymac/Library/Python/2.7/lib/python/site-packages/matplotlib/pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/Users/mymac/Library/Python/2.7/lib/python/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/Users/mymac/Library/Python/2.7/lib/python/site-packages/matplotlib/backends/backend_macosx.py", line 19, in &lt;module&gt; from matplotlib.backends import _macosx Here are the following steps that I already tried In a Julia kernel tried to run @pyimport math ==> this works In a Python kernel, I tried to run import matplotlib as plt ==> it works I uninstall all the python versions on my MacOS 10.13.2 and reinstall Python version 3.6.5. I still get the same error message. In Terminal i tried to run: $ curl -O https://bootstrap.pypa.io/get-pip.py and then python3 get-pip.py but still getting the error message in Julia After removing Python from /Users/mymac/Library/, It seems that Julia recreates the path /Users/mymac/Library/Python/2.7/ Thank you very much in advance
accepted answer: http://stackoverflow.com/a/49713664
type: Question
score: 0
has comment: http://stackoverflow.com/comment/93716674
answer count: 1

http://stackoverflow.com/q/49718857
type: UnansweredQuestion
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49808404
favorite count: 0
tagged with: urllib
has body: I'm crawling some data from the web, and since the data that I should get is huge, I have got more than 500 simultaneous requests (made through urllib.request.urlopen(url) by pooling via multiprocessing). The problem here is that the following error is thrown: urllib.error.URLError: urlopen error Temporary failure in name resolution After some research, I have found that this problem was caused by the fact that the connections cannot be closed when there is too much requests. But haven't yet found any way to solve this. Should I limit the simultaneous connections at some safe range, or change urllib request configuration? Development environment: Ubuntu 16.04 Python 3.6
score: 3
tagged with: python
tagged with: web-crawler
type: Question
has title: Python WebCrawling urllib.error.URLError: <urlopen error Temporary failure in name resolution>
upvote count: 3

http://stackoverflow.com/q/49753136
score: -5
has body: I get a small code in the form of a string. "IF 'Physics' then 'Passed in physics' else IF 'Chemistry' then 'Passed in Chemistry' ENDIF ENDIF". I need to break this string into multiple values based on the IF and ENDIF. My output should be 1) IF 'Physics' then 'Passed in Physics' 2) IF 'Chemistry' then 'Passed in Chemistry'. The string which I get will have nested IF, so need to identify and break it into multiple values. Thank you Venkat
upvote count: 0
has comment: http://stackoverflow.com/comment/86521992
has comment: http://stackoverflow.com/comment/86526190
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50056469
has comment: http://stackoverflow.com/comment/86598502
has comment: http://stackoverflow.com/comment/86523209
type: UnansweredQuestion
downvote count: 5
tagged with: python
has title: Identify ENDIF for correspoding IF in a string
has comment: http://stackoverflow.com/comment/86520772
has comment: http://stackoverflow.com/comment/86520762

hidden-markov-models
tags question: http://stackoverflow.com/q/49663704
tag name: hidden-markov-models
type: Tag

http://stackoverflow.com/a/49683563
type: Answer
has body: In windows cmd execute: chcp 65001 and CodePage changes to UTF-8. Source: https://github.com/pypa/pip/issues/4998#issuecomment-361014560
accepted answer of: http://stackoverflow.com/q/49681811
score: 0
answers question: http://stackoverflow.com/q/49681811
type: AcceptedAnswer

http://stackoverflow.com/a/49721803
has comment: http://stackoverflow.com/comment/86457398
has comment: http://stackoverflow.com/comment/86457025
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86457113
has comment: http://stackoverflow.com/comment/86456880
accepted answer of: http://stackoverflow.com/q/49721159
has body: A oneliner could be as follows: indexes = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] my_filtered_lists = [sorted([d for d in my_list if d['item_index'] == i], key=lambda x: x["date"]) for i in indexes ] result = [l[-1]['item_value'] if len(l)&gt;0 else 0 for l in my_filtered_lists] For each index you filter the list, and sort each filtered list as desired and get the item_value of the last element. If the data set is big enough, this could be a little memory demanding, since you are creating one extra list for each item_idex. Tested with: my_list = [ {'item_value': 0.1, 'date': datetime.datetime(2017, 05, 01), 'item_index': 1.0}, {'item_value': 0.22, 'date': datetime.datetime(2016,05,01), 'item_index': 0.1}, {'item_value': 0.21, 'date': datetime.datetime(2017, 05, 01), 'item_index': 0.1}, {'item_value': 1.03, 'date': datetime.datetime(2016,05,01), 'item_index': 1.0}] It returns: [0, 0.21, 0, 0, 0, 0, 0, 0, 0, 0, 0.1] wich I understand is the expected output.
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49721159
has comment: http://stackoverflow.com/comment/86456858
has comment: http://stackoverflow.com/comment/86457409
has comment: http://stackoverflow.com/comment/86457133
type: Answer
has comment: http://stackoverflow.com/comment/86457272
has comment: http://stackoverflow.com/comment/86457386

http://stackoverflow.com/q/49658019
has comment: http://stackoverflow.com/comment/86325335
tagged with: python
has body: So, I have asked a similar question before, but I was still unable to solve my problem. I need to make a checkerboard with 6 game pieces evenly on each side. This code was helpful, but it randomly distributes the game pieces, I've played around with it in multiple lines and attempted to understand but it's not clicking for me. How can I get six pieces to be on top half and six to be on lower half with space in the middle? Like a regular checkerboard set up? from turtle import Turtle, Screen from random import randrange CURSOR_SIZE = 20 SQUARE_SIZE = 40 SQUARES_PER_SIDE = 8 def drawRect(color): turtle.color(color) turtle.pendown() turtle.begin_fill() for iterations in range(4): turtle.forward(SQUARE_SIZE) turtle.left(90) turtle.end_fill() turtle.penup() def pushTurtleForward(): turtle.forward(SQUARE_SIZE) def drawHorizontal(inverted=False): if inverted: for horizontal in range(SQUARES_PER_SIDE): if horizontal &gt; 0: if horizontal % 2 == 1: pushTurtleForward() drawRect("white") else: pushTurtleForward() drawRect("black") else: drawRect("black") else: for horizontal in range(SQUARES_PER_SIDE): if horizontal &gt; 0: if horizontal % 2 == 1: pushTurtleForward() drawRect("black") else: pushTurtleForward() drawRect("white") else: drawRect("white") screen = Screen() screen.bgcolor("Grey") turtle = Turtle(visible=False) turtle.speed('fastest') for drawVertical in range(SQUARES_PER_SIDE): turtle.setposition(0, SQUARE_SIZE * drawVertical) if drawVertical % 2 == 0: drawHorizontal(inverted=True) else: drawHorizontal() # Checker graphics demonstration. Distribute 12 red checkers around # black squares on board without any two landing on the same spot. red_checkers = [] for _ in range(12): checker = Turtle('circle') checker.color('black', 'red') checker.shapesize(SQUARE_SIZE / CURSOR_SIZE) checker.penup() red_checkers.append(checker) position = checker.position() # a position guaranteed to fail while any(map(lambda checker, p=position: checker.distance(p) &lt; SQUARE_SIZE/2, red_c…
accepted answer: http://stackoverflow.com/a/49658270
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49658270
score: 0
answer count: 1
has title: How do I control where game pieces go for checkerboard in Python?
has comment: http://stackoverflow.com/comment/86326282
type: Question
has comment: http://stackoverflow.com/comment/86325578

http://stackoverflow.com/comment/86477499
type: QuestionComment
comment on: http://stackoverflow.com/q/49731765
has text: I was hoping matplotlib (or some other library) would have a function to convert a list Z to the X, Y form where X is the unique elements in Z, and Y is the frequencies. The closest I can think of is Counter, but the dictionary returned by Counter wouldn't return X as sorted. Basically, this is an operation I've done hundreds of times in the past. I wonder if there's a function for it.
score: 0
type: Comment

http://stackoverflow.com/comment/86247743
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49620241
has text: @SoumilDeshpande `import re` for the regex module.

http://stackoverflow.com/comment/86510128
has text: Can you also add an additional part to your code which prints out every char as an ASCII code, each encased in brackets?
comment on: http://stackoverflow.com/a/49745821
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86348562
comment on: http://stackoverflow.com/a/49669130
type: Comment
has text: Thanks for your answer. So, each batch will contain a sequence related to the same video, so, if my batch_size is 30, the 30 frames are related to the same video. I did not catch in your explanation what window_size represents. If I have a batch which is made of 30 frames maybe after the last layer of my CNN (ouput: [batch_size, features_num]) to have a classification every 30 frames and so every 1 second, do I have to reshape it to [1, 30, features_num]? Thanks, for your help
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86332667
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49661411
has text: Where is that in the sample input? I told you you need to be very precise about what the pattern is.

http://stackoverflow.com/comment/86282252
comment on: http://stackoverflow.com/a/49635794
score: 0
type: AnswerComment
has text: I get an error that with open(filenae,'rb') as csvFile, tempfile: AttributeError:-____enter____
type: Comment

http://stackoverflow.com/q/49719052
tagged with: pickle
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49719505
has title: Is it faster to load a pickle dictionary or a file?
score: 0
answer count: 1
tagged with: python
tagged with: dictionary
favorite count: 0
has body: I have a .txt file with keys and values like this: k1 v11 k1 v12 k1 v13 k2 v21 k2 v22 k3 v31 k3 v32 Each time I run my script I need to check if the given values are on that list. I am considering preprocessing the .txt file to create a dict and save in a pickle file like this: d = { k1: [v11, v12, v13], k2: [v21, v22], k3: [v31, v32], } Should it be faster to load such a dict or to read the original file? I'd run the creation of the dict only once and than load it from the pickle.
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49719505
downvote count: 2
has comment: http://stackoverflow.com/comment/86451072

http://stackoverflow.com/q/49708348
has title: Pyopencl memory access/non repetitive results
tagged with: pyopencl
score: 0
tagged with: opencl
tagged with: python
has answer: http://stackoverflow.com/a/49756077
has body: PROBLEM: I see that the output varies depending on the execution. It suggests a memory access problem that I did not manage to find. ATTEMPT: I am trying to make linear operations in a 8x8 matrix with pyopencl. The example that I am showing operates the rows of the matrix, using the first row so the first column becomes 0 (except first row). The last loop executes this function "repetitions" times and compares it to the first execution, and counts the similar values. I never get as many similar value counts as repetitions where made, and the mismatch is located always in certain area of the matrix. You can see in the cl code that I got desperate already trying to fix the problem with memory barriers. There must be something out of my understanding going on. Python code: from __future__ import print_function from __future__ import absolute_import import pyopencl as cl import numpy as np import os from numpy.random import RandomState os.environ['PYOPENCL_COMPILER_OUTPUT'] = '1' for platform in cl.get_platforms(): print("Platform name:", platform.name) platform = cl.get_platforms() platform = [x for x in platform if "AMD" in x.name][0] device = platform.get_devices() # ctx = cl.create_some_context() ctx = cl.Context(device) queue = cl.CommandQueue(ctx) mf = cl.mem_flags n = 2**3 block_size = 2**2 bs = block_size prng = RandomState(666666) a=prng.uniform(0,100000,(n,n)) + 2 b = -a + 1 a = a.astype(np.float32) b = b.astype(np.float32) kernelpath = "./Stack_Overflow_pyopencl_question1.cl" with open(kernelpath, "r") as f: kernel_txt = "".join(f.readlines()) def col1_0(a, b, device): a_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a) b_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b) dest_buf = cl.Buffer(ctx, mf.READ_WRITE, a.nbytes ) prg = cl.Program(ctx, kernel_txt.replace("FLAG_gsize", str(n)).replace("FLAG_lsize", str(bs))).build() prg.col1_0(queue, a.shape, (bs,bs),np.int32(len(a)), a_buf, b_buf, dest_buf) final = np.empty_like(a) cl.enq…
type: Question
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/49631178
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49631701
linked to: http://stackoverflow.com/q/34794634
has comment: http://stackoverflow.com/comment/86269366
upvote count: 9
answer count: 5
tagged with: python
score: 8
has title: Using for loop to define multiple functions - Python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49631260
tagged with: functional-programming
has answer: http://stackoverflow.com/a/49631260
possible better answer: http://stackoverflow.com/a/49631500
has comment: http://stackoverflow.com/comment/86270064
has answer: http://stackoverflow.com/a/49631702
has comment: http://stackoverflow.com/comment/127068446
has answer: http://stackoverflow.com/a/49631500
has body: Suppose I need to create 10 functions called add1, add2, ..., add10. For each i, addi takes in an integer x and outputs x+i. Python gave me a NameError when I tried the following and evaluated add2(10). for i in range(10): def addi(x): return x + (i+1) I know the above code is wrong, since the addi functions I've defined aren't mutable; I'm pretty sure all I've done is redefine addi 10 times. How can these 10 functions be quickly defined?
has answer: http://stackoverflow.com/a/49631574
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86278845
comment on: http://stackoverflow.com/a/49621274
score: 1
has text: Sure, but you'll need a 3 channel color image to draw over. I read in the image as grayscale in the first lines of code above, so you'd want to read in a color image instead so you can use `drawContours()` with a `color=(b, g, r)` tuple for what color you'd like to draw.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86350405
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49669627
has text: Coding is the way of chaining inbuild things - did you even read the questions I linked you too and viewed the answers on them? They solve your problem ... thats kindof the definition of duplicate...
score: 0

http://stackoverflow.com/comment/86498476
type: Comment
has text: @ivan_pozdeev the real answer is to make imports quick and light enough that even in windows where they truly are completely re-imported, the speed / memory usage of just importing is minimal.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49741657

http://stackoverflow.com/comment/86300118
type: Comment
type: QuestionComment
has text: Have you tried setting the `locale` as used here: https://stackoverflow.com/a/5513747/4636715
comment on: http://stackoverflow.com/q/49645929
score: 0

http://stackoverflow.com/q/49753980
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49754181
has title: Repeat different elements of an array different amounts of times
linked to: http://stackoverflow.com/q/240178
has body: Say I have an array with longitudes, lonPorts lonPort =np.loadtxt('LongPorts.txt',delimiter=',') for example: lonPort=[0,1,2,3,...] And I want to repeat each element a different amount of times. How do I do this? This is what I tried: Repeat =[5, 3, 2, 3,...] lonPort1=[] for i in range (0,len(lenDates)): lonPort1[sum(Repeat[0:i])]=np.tile(lonPort[i],Repeat[i]) So the result would be: lonPort1=[0,0,0,0,0,1,1,1,2,2,3,3,3,...] The error I get is: list assignment index out of range How do I get rid of the error and make my array? Thank you!
tagged with: repeat
tagged with: python
has answer: http://stackoverflow.com/a/49754049
accepted answer: http://stackoverflow.com/a/49754049
has answer: http://stackoverflow.com/a/49754138
possible better answer: http://stackoverflow.com/a/49754138
type: Question
tagged with: numpy
answer count: 3
downvote count: 0
upvote count: 1
score: 1
tagged with: arrays

http://stackoverflow.com/q/49618352
has body: I'm trying generate a list of all possible combinations of characters over a several lengths using Python 2.7. For the sake of example, I'm using a much smaller subset to proof the concept. Below I generate all combinations of the letters from A-C, of lengths 1 and 2. I then try to generate one list using a second for loop in the same generator comprehension (wrong term?). I can get all of the strings of a single length into a list, but I get the error an integer is required when trying How do I concatenate all these responses from each of the levels of repeat in the product generator function? &gt;&gt;&gt; l ['A', 'B', 'C'] &gt;&gt;&gt; p1 = (''.join(p) for p in product(l, repeat=1)) &gt;&gt;&gt; p2 = (''.join(p) for p in product(l, repeat=2)) &gt;&gt;&gt; [str(i) for i in p1] ['A', 'B', 'C'] &gt;&gt;&gt; [str(i) for i in p2] ['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC'] &gt;&gt;&gt; pn = (''.join(p) for p in product(l, repeat=i) for i in range(1,3)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: an integer is required Yes, I could do this with nested for loops. I'm trying to do it with one-liners, since I saw a similar example with what looked like a generator comprehension. I've used list comprehensions before - but when I feed it nested list comprehensions, I get lists of long strings of the entire lists of combinations smashed together. It could also be that I don't understand iterator functions correctly, because I struggled to get those debug list comprehensions correct on lines 5 and 7 in my code example.
has answer: http://stackoverflow.com/a/49618400
upvote count: 1
answer count: 1
duplicate of: http://stackoverflow.com/q/1077015
has comment: http://stackoverflow.com/comment/86243815
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86243921
linked to: http://stackoverflow.com/q/25578774
tagged with: python-itertools
accepted answer: http://stackoverflow.com/a/49618400
tagged with: python
tagged with: list-comprehension
linked to: http://stackoverflow.com/q/19484705
has title: How can I concatenate all of the responses from (Python's) iter_tools.product()?
tagged with: generator
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/86380532
type: QuestionComment
comment on: http://stackoverflow.com/q/49684422
type: Comment
score: 3
has text: What program are you using to inspect the CSV file? It seems like Excel doesn't (or didn't) import UTF-8 CSV files very well. https://stackoverflow.com/questions/6002256/is-it-possible-to-force-excel-recognize-utf-8-csv-files-automatically

http://stackoverflow.com/comment/87041115
type: Comment
type: QuestionComment
has text: I don't have enough reputation to comment, but I just googled it and found a similar question: https://stackoverflow.com/questions/8087381/approximately-converting-unicode-string-to-ascii-string-in-python
score: 0
comment on: http://stackoverflow.com/q/49652528

http://stackoverflow.com/comment/86255355
score: 0
has text: Please don't repeat questions, that's considered noise. Your previous attempt at least had the indentation right.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49624055

http://stackoverflow.com/a/64477857
downvote count: 0
score: 7
upvote count: 7
has body: There is a way to avoid those errors from happening, by not using the decoration syntax. This might be what @Azsgy referred to as 'weird' :-) @click.option( "--direction", default="upgrade", type=click.Choice(["upgrade", "downgrade"]), help="Direction of migration upgrade/downgrade", ) @click.argument("revision", default="heads") def _main(direction, revision): """Runs migrations on each of the databases.""" pass main = click.command()(_main) if __name__ == "__main__": main() Whether it's nice or not is debatable :-)
answers question: http://stackoverflow.com/q/49680191
type: Answer

http://stackoverflow.com/a/49711717
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49711661
answers question: http://stackoverflow.com/q/49711661
has body: I believe need lookup by splited column to DataFrame and cast boolean mask to int for select first column by 0 and second column by 1: df[2] = df[1].str.split(',', expand=True).lookup(df.index, (df[0] % 2 == 0).astype(int)) print (df) 0 1 2 0 0 10,30 30 1 1 10,40 10 2 2 20,50 50 print (df[0] % 2 == 0) 0 True 1 False 2 True Name: 0, dtype: bool #select second, first, second column print ((df[0] % 2 == 0).astype(int)) 0 1 1 0 2 1 Name: 0, dtype: int32 Similar solution with changed condition: df[2] = df[1].str.split(',', expand=True).lookup(df.index, (df[0] % 2 != 0).astype(int)) print (df) 0 1 2 0 0 10,30 10 1 1 10,40 40 2 2 20,50 20 print (df[0] % 2 != 0) 0 False 1 True 2 False Name: 0, dtype: bool #select first, second, first column print ((df[0] % 2 != 0).astype(int)) 0 0 1 1 2 0 Name: 0, dtype: int32 print (df[1].str.split(',', expand=True)) 0 1 0 10 30 &lt;-first 10 1 10 40 &lt;-second 40 2 20 50 &lt;-first 20
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86445026
type: Comment
score: 0
type: AnswerComment
has text: Thank you Scott! Just what I was looking for!!
comment on: http://stackoverflow.com/a/49712953

http://stackoverflow.com/a/49714801
has body: LMDB is a general purpose DB that can be used for many applications in many ways. However, if you want to use it with caffe you are restricted to the interface written in caffe's "Data" layer. This interface is expecting a "Datum" elements in the LMDB. Other stored elements in the LMDB will simply results with a read error by caffe failing to interpret the stored elements. Therefore, if you are going to use LMDB as an input for a caffe "Data" layer, you must store elements as "Datum" in the LMDB. However, if you are going to use LMDB for other purposes, you may store any type of objects you wish, as long as you know how to read them correctly.
type: Answer
answers question: http://stackoverflow.com/q/49714629
has comment: http://stackoverflow.com/comment/90181159
score: 0

http://stackoverflow.com/q/49719353
accepted answer: http://stackoverflow.com/a/49719398
has title: Matching and reconstructing a pair of strings in Python based on a conditional
tagged with: pattern-matching
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/19717142
has answer: http://stackoverflow.com/a/49719398
tagged with: python
tagged with: string
type: AnsweredQuestion
score: 0
has body: I have the following pair of short strings in Python3.x, whose lengths must be equal: string_a = 'he_lo_world' string_b = 'hi_low_oldd' I would like to quickly as possible create a "summary string" based on how the characters in the pair match, given the following rules: (1) If the characters are the same, the new letter is S (same). Unless the matching characters are _, then it is U (underscore). (2) Otherwise, the characters don't match. If there's no match, the letter is N (no match). If string_a has _ and string_b does not, it is A. If string_b has _ and string_a does not, it is B. For the pair above, the string would be: SNUSSABSNNS To construct this string, I think multiple if/for statements will be too inefficient. Using the list comprehension and itertools example here, Trying to find a match in two strings - Python import itertools string_a = 'he_lo_world' string_b = 'hi_low_oldd' same = [ i for i,x in enumerate(itertools.izip(string_a,string_b)) if all(y==x[0] for y in x)] print(same) ## [0, 2, 3, 4, 7, 10] I can get the indices of the matches. (The _==_ exception would require a conditional in the list comprehension, so index 2 shouldn't exist above.) I'm confused how (A) to re-construct a string based on this list of indices and (B) how do I efficiently deal with non-matching characters?
tagged with: list
answer count: 1

http://stackoverflow.com/comment/86462829
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49724412
type: Comment
has text: Along with what @smac89 said, see how the string looks like. Are the elements seperated by `, ` or ` ,` or just `,` (notice the spaces) and then use split accordingly.

http://stackoverflow.com/comment/86485261
score: 0
has text: So which attribute(s) are `unicode` objects? Unless there is an actual problem, this isn't really anything other than a quirk of the implementation.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49735426

http://stackoverflow.com/q/49705246
has answer: http://stackoverflow.com/a/49705278
has title: what can I do to make long to wide format in python
possible better answer: http://stackoverflow.com/a/49705429
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/86423830
score: 0
has body: I have this long data. I like to sort this by 30 each and save separately. Data print like this, A292340 A291630 A278240 A267770 A267490 A261250 A261110 A253150 A252400 A253250 A243890 A243880 A236350 A233740 A233160 A225800 A225060 A225050 A225040 A225130 A219900 A204450 A204480 A204420 A196030 A196220 A167860 A152500 A123320 A122630 . This is fairly simple question, but I need your help.. Thank you. (And how can I make a list out of one results printed? list addtion?
has comment: http://stackoverflow.com/comment/86423929
upvote count: 1
has answer: http://stackoverflow.com/a/49705429
accepted answer: http://stackoverflow.com/a/49705278
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86529848
type: Comment
type: QuestionComment
has text: I believe `status_code` that you are passing is an int, which is not a string or buffer that is required, maybe try `r.text`
score: 0
comment on: http://stackoverflow.com/q/49757289

http://stackoverflow.com/comment/87061036
has text: Yes it is a package of compression and shuffle filters. For comparison you can try the following example with gzip and compare the performance. https://stackoverflow.com/questions/48672130/saving-to-hdf5-is-very-slow-python-freezing/48997927#48997927 (In this example I used pytables to register the blosc filters, but this should also work with globally installed blosc filters, mentioned in the comment above)
score: 1
comment on: http://stackoverflow.com/a/49991172
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49657590
tagged with: urlparse
type: Question
accepted answer: http://stackoverflow.com/a/49674457
tagged with: python
tagged with: bottle
has answer: http://stackoverflow.com/a/49674457
type: AnsweredQuestion
has title: Instagram Client Side Authentication using Python
score: 0
answer count: 1
has body: I am currently working on a bottle project and will be using Instagram api. I was hoping to use the client side authentication however I am having problems with the access token as it does not returns as a parameter. I am making the request here: https://api.instagram.com/oauth/authorize/?client_id=client_id&amp;redirect_uri=redirect_uri&amp;response_type=token&amp;scope=basic+follower_list The app is redirected to token page correctly and I can even see the token in the url. But when I try to parse it, it comes out empty. @route('/oauth_callback') def success_message(): token = request.GET.get("access_token") print token.values() return "success" The token.values() returns an empty list. ps: Keep in mind that when I try to do the same operation with server side authentication, I can successfully get the code and exchange it for a token.

http://stackoverflow.com/comment/86484899
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49735296
has text: A `.csv` is intentionally a *machine-readable* format. And it consists of rows and columns. There are no document sections of the sort you get in a human-readable document, no headers (other than, optionally, the names of the columns), no record types. If you have metadata like date and name associated with the file, either you cram it into the filename, or create columns for it in your `.csv` file, and tack those columns onto the first row (or every row, it doesn't matter much.)
type: Comment

http://stackoverflow.com/comment/86347275
comment on: http://stackoverflow.com/q/49668648
score: 1
type: QuestionComment
has text: `for index, item in enumerate(list):...`
type: Comment

http://stackoverflow.com/comment/86415961
has text: What is `self.api_url` value?
score: 0
comment on: http://stackoverflow.com/q/49701183
type: Comment
type: QuestionComment

relational-database
type: Tag
tag name: relational-database
tags question: http://stackoverflow.com/q/49661985

http://stackoverflow.com/q/49674212
tagged with: gradient-descent
has comment: http://stackoverflow.com/comment/86373008
has comment: http://stackoverflow.com/comment/86384069
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86384116
has body: For the past few days, I have been trying to code this application of Gradient Descent for my final-year project in Mechanical Engineering. https://drive.google.com/open?id=1tIGqZ2Lb0sN4GEpgYEZLFvtmhigXnot0 The HTML file is attached above. Just download the file, and if you see the results. There are only 3 values in theta, whereas x has 3 independent variables. So it should have 4 values in theta. The code is as follows. For the result, it is theta [-0.03312393 0.94409351 0.99853041] import numpy as np import random import pandas as pd def gradientDescent(x, y, theta, alpha, m, numIterations): xTrans = x.transpose() for i in range(0, numIterations): hypothesis = np.dot(x, theta) loss = hypothesis - y # avg cost per example (the 2 in 2*m doesn't really matter here. # But to be consistent with the gradient, I include it) cost = np.sum(loss ** 2) / (2 * m) print("Iteration %d | Cost: %f" % (i, cost)) # avg gradient per example gradient = np.dot(xTrans, loss) / m # update theta = theta - alpha * gradient return theta df = pd.read_csv(r'C:\Users\WELCOME\Desktop\FinalYearPaper\ConferencePaper\NewTrain.csv', 'rU', delimiter=",",header=None) x = df.loc[:,'0':'2'] y = df[3] print (x) m, n = np.shape(x) numIterations= 200 alpha = 0.000001 theta = np.ones(n) theta = gradientDescent(x, y, theta, alpha, m, numIterations) print(theta)
has comment: http://stackoverflow.com/comment/86360394
has comment: http://stackoverflow.com/comment/86363340
has comment: http://stackoverflow.com/comment/86363939
score: 0
has comment: http://stackoverflow.com/comment/86414958
answer count: 0
tagged with: pandas
has title: Multi-Variable Gradient Descent using Numpy - Error in no. of coefficients
has comment: http://stackoverflow.com/comment/86359564
has comment: http://stackoverflow.com/comment/86371933
has comment: http://stackoverflow.com/comment/86364383
has comment: http://stackoverflow.com/comment/86372379
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86371486
has comment: http://stackoverflow.com/comment/86361293
type: Question
tagged with: numpy

http://stackoverflow.com/comment/86402910
has text: This does what I wanted. Thank you. I actually ended up doing: chainedListProxy(x,x,x) and I use the middle third, which allows overflow wrap-arounds in both directions without concern for end conditions. I tried to tweak the code so that q[0] indexed the first value in the middle third, but couldn't quite sort it out.
comment on: http://stackoverflow.com/a/49680778
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49748736
accepted answer: http://stackoverflow.com/a/49750517
has answer: http://stackoverflow.com/a/51842609
upvote count: 6
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/86517600
tagged with: python
has answer: http://stackoverflow.com/a/68737909
has title: Selenium returns empty string instead of the actual data
tagged with: selenium-chromedriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67058660
tagged with: selenium
possible better answer: http://stackoverflow.com/a/67058660
tagged with: web-scraping
has body: I am using Selenium via Python in attempts to web scrape. I'm almost where I want to be but I ran into what I am now realizing is not so small of a problem. So the element I am working with is this: 10 My ultimate goal is to get the 10 that's between the a tags. This is my code so far: option = selenium.webdriver.ChromeOptions() option.add_argument(" - incognito") browser = webdriver.Chrome(executable_path=r"chromedriver.exe") browser.get(myUrl) calendar = browser.find_element_by_xpath( '/html/body/main/section/div[2]/div[1]/div[2]/div[3]/div/div[1]/div/div[1]/div[2]') viewCal = browser.find_element_by_name('choice_set[begin_at]') viewCal.click() row = calendar.find_elements_by_tag_name('tr') column = calendar.find_elements_by_tag_name('td') numb = column[0].find_element_by_tag_name('a') numb.text numb.text returns '' instead of 10. What am I doing wrong here?
has answer: http://stackoverflow.com/a/49749965
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/43429788
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49750517
answer count: 5

http://stackoverflow.com/q/49734434
has title: Unable to install Python libraries
has comment: http://stackoverflow.com/comment/86483883
has comment: http://stackoverflow.com/comment/86518168
tagged with: python
has answer: http://stackoverflow.com/a/49738721
has answer: http://stackoverflow.com/a/49811082
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/86483760
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86485322
has answer: http://stackoverflow.com/a/49749715
has comment: http://stackoverflow.com/comment/86512089
has answer: http://stackoverflow.com/a/49739399
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86484086
accepted answer: http://stackoverflow.com/a/49753227
has answer: http://stackoverflow.com/a/49735005
downvote count: 0
tagged with: pip
has answer: http://stackoverflow.com/a/49753227
has body: I am not able to install any Python libraries. I am using pip 9.0.1 and python 2.7. I am getting the following error: EN-NishantS:~ 8417$ pip install presto-python-client Collecting presto-python-client Could not find a version that satisfies the requirement presto-python-client (from versions: ) No matching distribution found for presto-python-client On running with pip install -vvv I am getting the following: Collecting presto-python-client 1 location(s) to search for versions of presto-python-client: * https://pypi.python.org/simple/presto-python-client/ Getting page https://pypi.python.org/simple/presto-python-client/ Looking up "https://pypi.python.org/simple/presto-python-client/" in the cache No cache entry available Starting new HTTPS connection (1): pypi.python.org "GET /simple/presto-python-client/ HTTP/1.1" 403 170 Status code 403 not in [200, 203, 300, 301] Could not fetch URL https://pypi.python.org/simple/presto-python-client/: 403 Client Error: TLSv1.2+ is required for url: https://pypi.python.org/simple/presto-python-client/ - skipping Could not find a version that satisfies the requirement presto-python-client (from versions: ) Cleaning up... No matching distribution found for presto-python-client Exception information: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 324, in run requirement_set.prepare_files(finder) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 554, in _prepare_file require_hashes File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upg…
answer count: 7
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
possible better answer: http://stackoverflow.com/a/49739399
has answer: http://stackoverflow.com/a/49765614
has comment: http://stackoverflow.com/comment/86483232
type: Question

http://stackoverflow.com/comment/86290313
has text: What does it mean that it does not start at (0, 0)? in kivy the coordinate (0, 0) is the bottom left position, perhaps it means that the buttons must be at the top?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49641307
type: Comment

http://stackoverflow.com/q/49628200
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86274157
has body: I am testing hyperoptim for parameter tuning of XGboost. I am kind of replicating the code from here- https://www.kaggle.com/eikedehling/tune-and-compare-xgb-lightgbm-rf-with-hyperopt I am using Python 3 and getting the following error for the code snippet given below. any idea how to resolve this? def objective(params): params = { 'max_depth': int(params['max_depth']), 'gamma': "{:.3f}".format(params['gamma']), 'colsample_bytree': '{:.3f}'.format(params['colsample_bytree']), } clf = xgb.XGBClassifier( n_estimators=50, learning_rate=0.1, n_jobs=4, **params ) score = cross_val_score(clf, train_X, train_Y, scoring=gini_scorer, cv=StratifiedKFold()).mean() print("Gini {:.3f} params {}".format(score, params)) return score space = { 'max_depth': hp.quniform('max_depth', 2, 8, 1), 'colsample_bytree': hp.uniform('colsample_bytree', 0.3, 1.0), 'gamma': hp.uniform('gamma', 0.0, 0.5), } best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=10) Traceback (most recent call last): File "", line 4, in File "/anaconda3/envs/py27/lib/python2.7/site-packages/hyperopt/fmin.py", line 314, in fmin pass_expr_memo_ctrl=pass_expr_memo_ctrl) File "/anaconda3/envs/py27/lib/python2.7/site-packages/hyperopt/base.py", line 786, in init pyll.toposort(self.expr) File "/anaconda3/envs/py27/lib/python2.7/site-packages/hyperopt/pyll/base.py", line 715, in toposort assert order[-1] == expr TypeError: 'generator' object has no attribute 'getitem'
tagged with: python
accepted answer: http://stackoverflow.com/a/49642178
has title: Issue with XGboost tuning with Hyperopt- TypeError: 'generator' object has no attribute '__getitem__'
tagged with: optimization
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/86270420
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49642178
tagged with: xgboost

http://stackoverflow.com/comment/86415246
score: 1
has text: Flags should be bitwise OR'd with `|`, not added, even though addition works in this case. Consider the result with something like `existing_flags + flag`; it's wrong in general.
comment on: http://stackoverflow.com/a/49692439
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86292705
score: 0
type: Comment
type: QuestionComment
has text: But note that [cross-posting is not allowed](https://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu).
comment on: http://stackoverflow.com/q/49642542

http://stackoverflow.com/q/49753316
has comment: http://stackoverflow.com/comment/86523785
has comment: http://stackoverflow.com/comment/86521389
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86521388
upvote count: 8
has body: I want to default an empty string to a 0 or null during deserialization. JSON { 'injuries': '6', 'children': '2', 'civilians': '', } However, I keep getting this error: "A valid integer is required." models.py from django.db import models class Strike(models.Model): location = models.ForeignKey('Location', on_delete=models.CASCADE) civilians = models.PositiveIntegerField(blank=True, null=True) injuries = models.PositiveIntegerField(blank=True, null=True) children = models.PositiveIntegerField(blank=True, null=True) serializers.py from rest_framework import serializers from .models import Strike class StrikeSerializer(serializers.ModelSerializer): civilians = serializers.IntegerField(default=0, required=False) class Meta: model = Strike fields = '__all__' def create(self, validated_data): return Strike.objects.create(**validated_data) main serializer = StrikeSerializer(data=strike) I tried manipulating data in create method, but the error gets raised before that. Where in the DRF structure can I override this, specifically convert '' to 0 or None?
has comment: http://stackoverflow.com/comment/86521511
has comment: http://stackoverflow.com/comment/86521194
has answer: http://stackoverflow.com/a/59841626
score: 8
has comment: http://stackoverflow.com/comment/86521341
has title: Django Rest Framework "A valid integer is required."?
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49753451
tagged with: django
tagged with: python
tagged with: django-rest-framework
possible better answer: http://stackoverflow.com/a/59841626
has answer: http://stackoverflow.com/a/49753451

http://stackoverflow.com/a/49604300
has body: In the page you're referring to there is a section under "Build the pip package" saying: NOTE on gcc 5 or later: the binary pip packages available on the TensorFlow website are built with gcc 4, which uses the older ABI. To make your build compatible with the older ABI, you need to add --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=0" to your bazel build command. ABI compatibility allows custom ops built against the TensorFlow pip package to continue to work against your built package. It is unclear from your question if you built the package yourself, but if yes, have you tried this option?
score: 0
answers question: http://stackoverflow.com/q/49604073
type: Answer

http://stackoverflow.com/a/59971943
downvote count: 0
has body: Per most recent update from Dash website, the below should now be sufficient: pip install dash==1.8.0 Note: starting with dash 0.37.0, dash automatically installs dash-renderer, dash-core-components, dash-html-components, and dash-table, using known-compatible versions of each. You need not and should not install these separately any longer, only dash itself. Per Lucas's comment above, with Anaconda distribution use : conda install -c conda-forge dash
answers question: http://stackoverflow.com/q/49613878
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/86330359
comment on: http://stackoverflow.com/a/49660220
score: 0
has text: Also, cases where a line ends with a quote and whitespace in the middle of a triple-quoted string will silently discard the whitespace, and a line with just `"""` will always be counted as opening a triple-quoted string, even if it's actually closing one.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49647769
type: Answer
has body: It seems that you have not understood the logic of my previous solution, I will detail the procedure: [1] self.thread = QtCore.QThread() [2] self.worker = SeleniumWorker() [3] self.worker.moveToThread(self.thread) [4] self.worker.progressChanged.connect(progressBar.setValue, QtCore.Qt.QueuedConnection) [5] self.thread.started.connect(self.worker.doWork) QThread is a thread handler, so an object of that class allows us to execute a task on a thread other than the main thread called the GUI thread. You are creating a SeleniumWorker object that has the doWork method, which is a blocking task that should not be executed in the GUI thread, and that will be achieved with the previous QThread. Since the function must be executed in another thread, the object that has that method must move to that other thread. The signal of the object that is in the other thread is connected to the QProgressBar that is in the GUI thread, this connection must be made with the flag QtCore.Qt.QueuedConnection. When the thread is started it will call the doWork function and since the self.worker object is in another thread then the function will also be executed in that other thread. In your case in the code that is shown in the next part you are calling the doWork function when the thread has not yet started so it will be executed in the main thread. def btn2(self): ... # main thread self.worker.doWork(self.lst2) One way to pass the urls is through a setter method, and then start the thread. When the thread starts, it will call doWork, and when the doWork is executed, the progressChanged signal will be emited. With all the above we obtain the following: import sys from PyQt5 import QtCore, QtGui, QtWidgets from selenium import webdriver class SeleniumWorker(QtCore.QObject): progressChanged = QtCore.pyqtSignal(int) started = QtCore.pyqtSignal() finished = QtCore.pyqtSignal() def setUrls(self, urls=['http://www.somesite.com/', 'http://www.somesite.com/page2', 'http://www.somesite.com/page3']): …
has comment: http://stackoverflow.com/comment/86305999
has comment: http://stackoverflow.com/comment/86308186
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86305830
answers question: http://stackoverflow.com/q/49647205
has comment: http://stackoverflow.com/comment/86306097
has comment: http://stackoverflow.com/comment/86307458
has comment: http://stackoverflow.com/comment/86304975
has comment: http://stackoverflow.com/comment/86304540
score: 3
accepted answer of: http://stackoverflow.com/q/49647205

http://stackoverflow.com/comment/86243420
comment on: http://stackoverflow.com/q/49617213
score: 1
type: Comment
type: QuestionComment
has text: @tomordonez Apostrophes are somewhat common in corporate email systems that use address formats like `FIRSTNAME-LASTNAME@example.com`, especially in conjunction with Irish patronymics like `O'Reilly` or `O'Sullivan`.

http://stackoverflow.com/comment/86342354
has text: You want to assign them values after they are in the list?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49666200

http://stackoverflow.com/comment/86461280
score: 1
comment on: http://stackoverflow.com/a/49723744
has text: Thanks! I will try to amend your answer as function to apply for groupby so that I can set created NaN for all groups.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49648845
has comment: http://stackoverflow.com/comment/86308374
has comment: http://stackoverflow.com/comment/86309354
has comment: http://stackoverflow.com/comment/86307714
has comment: http://stackoverflow.com/comment/86305981
has comment: http://stackoverflow.com/comment/86306948
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86309288
has comment: http://stackoverflow.com/comment/86308109
has comment: http://stackoverflow.com/comment/86309017
answers question: http://stackoverflow.com/q/49648581
has comment: http://stackoverflow.com/comment/86306699
has comment: http://stackoverflow.com/comment/86306181
has comment: http://stackoverflow.com/comment/86307863
has comment: http://stackoverflow.com/comment/86307790
accepted answer of: http://stackoverflow.com/q/49648581
score: 0
has comment: http://stackoverflow.com/comment/86308415
has comment: http://stackoverflow.com/comment/86306394
has comment: http://stackoverflow.com/comment/86306630
type: Answer
has comment: http://stackoverflow.com/comment/86305794
has comment: http://stackoverflow.com/comment/86308066
has body: If you map your RDD to the second tuple element, you should be able to reduce by key: rdd = sc.parallelize([(69120, (296, \ [296, 356, 2858, 608, 588, 1580, 597, 153, 4306, 587]))]) rdd = rdd.map(lambda tup: (tup[0], (tup[1][0], 1 if tup[1][0] in tup[1][1] else 0))) This keeps the same tuple structure, but replaces the movie list with the number of occurences of movie ID in it: dd.collect() That code outputs: [(69120, (296, 1))] That is (userID, (movieID, 1 if found else 0)) If you need to compute the total number of views per movie (for all users): rdd.map(lambda l: l[1])\ .reduceByKey(lambda a,b: a+b)\ .collect() With this collection, the result will be similar for the single movie: [(296, 1)]

http://stackoverflow.com/comment/86337587
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49663720
has text: well, validating would require code on the server to check - you haven't specified your server language, so, all I can say is that you need to make sure the 13th? character is 4, and and the 17th character is `8->f` (I think)
score: 1

http://stackoverflow.com/a/49656146
has body: pygame.display.set_mode only sets the resolution and returns a surface, therefore calling it two times will just return a new surface and change the window resolution, There is no way to have two displays at once in pygame but however you can call an alternate script to open up another process (therefore another display) from the existing one.
type: Answer
answers question: http://stackoverflow.com/q/49649288
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49649288

http://stackoverflow.com/comment/86243740
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49618055
has text: You're using a TCP socket here. Which is better as UDP is unreliable without defining your own checks.
type: Comment

xvfb
type: Tag
tags question: http://stackoverflow.com/q/49620853
tag name: xvfb
tags question: http://stackoverflow.com/q/49750037

http://stackoverflow.com/comment/86357147
type: Comment
has text: I have edited and added the command I run which contains the 2 inputs. I have tried it in the format that you recommended too but I got the same error message.
comment on: http://stackoverflow.com/a/49649129
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86342278
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49666050
has text: @RehanAzher How is `getattr` going to help here? There's no object with an attribute named `'one'` anywhere in his code.

http://stackoverflow.com/comment/86406835
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49685111
has text: Worked!! thanks for the help. Also wanted to know how to put output back to .csv file??

http://stackoverflow.com/q/49701131
answer count: 4
has answer: http://stackoverflow.com/a/59332816
has answer: http://stackoverflow.com/a/59066228
downvote count: 0
has comment: http://stackoverflow.com/comment/86419411
has title: django project polls stuck at using your own package step
has answer: http://stackoverflow.com/a/50032168
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49703648
has comment: http://stackoverflow.com/comment/86436461
linked to: http://stackoverflow.com/q/37424997
has comment: http://stackoverflow.com/comment/114844317
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86416511
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm new to Python and Django so forgive me if this question seems silly. I'm following the django tutorial and I'm stuck at the step when you use your own package The app mysite works and there was no error. I've setup all the required files according to the tutorial. I've run python3 setup.py sdist (inside django-polls folder) There's the file django-polls-0.1.tar.gz in django-polls/dist/ $ cd .. $ pip3 install --user django-polls/dist/django-polls-0.1.tar.gz Processing ./django-polls/dist/django-polls-0.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): django-polls==0.1 from file:///home/viet/webdev/django-polls/dist/django-polls-0.1.tar.gz in /home/viet/.local/lib/python3.6/site-packages Building wheels for collected packages: django-polls Running setup.py bdist_wheel for django-polls ... done Stored in directory: /home/viet/.cache/pip/wheels/ff/ec/8b/85c031efa2ba719d6bd909d20f61ca6b106c79345a1e875f08 Successfully built django-polls Then the tutorial says: With luck, your Django project should now work correctly again. Run the server again to confirm this. How? There's no manage.py file in /django-polls or in /home/viet/.cache/pip/wheels/ff/ec/8b/85c031efa2ba719d6bd909d20f61ca6b106c79345a1e875f08 So I tried this: $ pip3 uninstall django-polls Uninstalling django-polls-0.1: ... Proceed (y/n)? y Successfully uninstalled django-polls-0.1 $ pip3 install --user django-polls/dist/django-polls-0.1.tar.gz Processing ./django-polls/dist/django-polls-0.1.tar.gz Building wheels for collected packages: django-polls Running setup.py bdist_wheel for django-polls ... done Stored in directory: /home/viet/.cache/pip/wheels/ff/ec/8b/85c031efa2ba719d6bd909d20f61ca6b106c79345a1e875f08 Successfully built django-polls Installing collected packages: django-polls Successfully installed django-polls-0.1 I'm lost at this point. Update: Thank you for your suggestions, I understand now that I need to move the folder /polls out of my folder /mysite into the folder /django-po…

http://stackoverflow.com/comment/86422274
type: AnswerComment
comment on: http://stackoverflow.com/a/49704494
score: 0
has text: I totally agree. I'll was just about to edit further. Was checking other questions first (-:
type: Comment

http://stackoverflow.com/q/49733699
has comment: http://stackoverflow.com/comment/133862523
accepted answer: http://stackoverflow.com/a/49736916
score: 124
tagged with: python
tagged with: python-typing
has comment: http://stackoverflow.com/comment/86485221
has answer: http://stackoverflow.com/a/57916976
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58349659
possible better answer: http://stackoverflow.com/a/58349659
has answer: http://stackoverflow.com/a/49736916
has body: How should a context manager be annotated with Python type hints? import typing @contextlib.contextmanager def foo() -&gt; ???: yield The documentation on contextlib doesn't mention types much. The documentation on typing.ContextManager is not all that helpful either. There's also typing.Generator, which at least has an example. Does that mean I should use typing.Generator[None, None, None] and not typing.ContextManager? import typing @contextlib.contextmanager def foo() -&gt; typing.Generator[None, None, None]: yield
has title: Python type hints and context managers
has answer: http://stackoverflow.com/a/57209076
has comment: http://stackoverflow.com/comment/86483091
downvote count: 0
answer count: 7
upvote count: 124
has comment: http://stackoverflow.com/comment/86481416
has answer: http://stackoverflow.com/a/68097210
linked to: http://stackoverflow.com/q/56984315
favorite count: 0
type: Question
tagged with: mypy
has answer: http://stackoverflow.com/a/69674704
has answer: http://stackoverflow.com/a/70277752

http://stackoverflow.com/comment/86578660
score: 0
comment on: http://stackoverflow.com/a/49758373
type: AnswerComment
has text: There are lots of problems, I've detailed them above.
type: Comment

http://stackoverflow.com/comment/130648772
has text: Also a definition of `is_prime` would be nice - although it can be inferred - as it stands I find this example a bit confusing because of its lack of context.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/69167770
score: 0

http://stackoverflow.com/comment/86503757
type: QuestionComment
comment on: http://stackoverflow.com/q/49718057
score: 0
has text: yap i found it after posting it. Thanks a lot
type: Comment

http://stackoverflow.com/q/49716921
score: 0
has answer: http://stackoverflow.com/a/49716975
answer count: 1
has title: How to replacing multiple shell pipeline
type: Question
accepted answer: http://stackoverflow.com/a/49716975
tagged with: python
has body: In the Python 2.7 documentation of subprocess module, it provides a simple solution to replace the shell pipeline: p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] Source: https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline I want to have a wrapper function that can support multiple | in command. Yes, the easiest solution is to set Shell=True which makes the program vulnerable to shell injection. I'm wondering if there is a neat way to support both multiple | and keep Shell=False
type: AnsweredQuestion

http://stackoverflow.com/a/49611269
answers question: http://stackoverflow.com/q/49610858
has comment: http://stackoverflow.com/comment/86233199
has comment: http://stackoverflow.com/comment/86259156
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86230528
has comment: http://stackoverflow.com/comment/86230614
has comment: http://stackoverflow.com/comment/86229112
has body: Make sure that Python 3.5.3 is supported for Tensorflow, then install Microsoft Visual C++ 2015 Redistributable and try this command (note that you also need to uninstall the current Tensorflow first): python -m pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.1-cp35-cp35m-win_amd64.whl Update: Go to https://pypi.python.org/pypi/tensorflow to check for available built that works for you.

http://stackoverflow.com/q/49746928
has answer: http://stackoverflow.com/a/49747749
has body: I am trying to pick a date in this website: https://www.myrealtrip.com/offers/21989 The code I have so far is: option = selenium.webdriver.ChromeOptions() option.add_argument(" - incognito") browser = webdriver.Chrome(executable_path=r"chromedriver.exe") browser.get('https://www.myrealtrip.com/offers/21989') calendar = browser.find_element_by_name('.find_element_by_xpath('//*[@id="calendarBtn"]/input')') date = 2018-04-14, 토요일 calendar2.send_keys(date) The last line gives an error: selenium.common.exceptions.InvalidElementStateException: Message: invalid element state When is it appropriate to use send_key? calendar2 is an object of type WebElement, and so I thought it might work. Can someone help me? I've also tried clicking on the calendar and clicking on the specific date but found the layout very confusing.
type: Question
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/49747749
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/86510720
type: AnsweredQuestion
score: 0
has title: Problems passing in value to datepicker using Selenium via Python?
has answer: http://stackoverflow.com/a/49750700
accepted answer: http://stackoverflow.com/a/49750700
tagged with: datepicker
tagged with: selenium

http://stackoverflow.com/q/49690325
answer count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49691019
accepted answer: http://stackoverflow.com/a/49691019
has body: Code to reproduce: import numpy as np y1, y2 = [5, 3] print(np.arctan2(y1, y2)) # Output: 1.0303768265243125 print(np.arctan2(x1=y1, x2=y2)) # Output: #--------------------------------------------------------------------------- #ValueError Traceback (most recent call last) #&lt;ipython-input-13-b7d0f788df1f&gt; in &lt;module&gt;() #----&gt; 1 np.arctan2(x1=y1, x2=y2) #ValueError: invalid number of arguments I cannot explain the ValueError thrown. I'd expect both to be semantically identical. Is that something with Python, Numpy or with my lack of understanding? This is the definition of arctan2 in Numpy: def arctan2(x1, x2, *args, **kwargs) Versions I use: Linux-4.13.0-38-generic-x86_64-with-debian-stretch-sid Python 3.6.1 (default, Jun 16 2017, 16:00:03) [GCC 5.4.0 20160609] NumPy 1.14.2
has comment: http://stackoverflow.com/comment/86395167
tagged with: python
upvote count: 4
has title: numpy arctan2 arguments leads to ValueError depending on syntax
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86393972
downvote count: 1

http://stackoverflow.com/q/49718888
answer count: 2
upvote count: 1
has title: How to count an element in a list inside a list in Python
has answer: http://stackoverflow.com/a/49719062
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49719062
linked to: http://stackoverflow.com/q/19883015
tagged with: python
has answer: http://stackoverflow.com/a/49718970
accepted answer: http://stackoverflow.com/a/49718970
type: AnsweredQuestion
has body: Let's say I have a list like this: [(9600002, 42, 3), (9600001, 17, 3), (9600003, 11, 1), (9600002, 14, 5), (9600001, 17, 1), (9600003, 11, 4), (9600001, 17, 4), (9600001, 14, 3), (9600002, 42, 6), (9600002, 42, 1)] The first number is the user_id, the second is the tv_program_code, and the third is the season_id. My question How can I find out the program_code with more than 1 season subscribed, and then print the user_id and the tv_program_code? For example: 9600001 17 Or do you have any suggestion of which data structure I should apply?
tagged with: list
score: 0

http://stackoverflow.com/q/49675683
tagged with: python
has comment: http://stackoverflow.com/comment/86362698
type: Question
linked to: http://stackoverflow.com/q/49491048
has comment: http://stackoverflow.com/comment/86362779
has title: How to use pywinauto and selenium for login purpose?
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/49675903
tagged with: pywinauto
has body: I tried to write code to login using pywinauto and selenium, but my script is getting failed. I tried to find solution, but it seems there is no much info available on this. from pywinauto import application from selenium import webdriver driver=webdriver.Chrome() app=application.Application() driver.get("https://google.co.in")//url for google only as an example app = application.Application() app.connect(backend="uia") // getting issue in this line, what to write under bracket to connect to opened browser? app.window_().TypeKeys('username') // Is this proper way to type text in authentication window username field where cursor blinks by default? I am getting below error message pywinauto.findwindows.ElementAmbiguousError: There are 6 elements that match the criteria {'backend': u'win32'} Note : For login to my application, windows authentication popup appears which cannot be handled in selenium, so need to handle it using other tool. I had a solution to it earlier which is not working now, I had asked it here Windows authentication code no longer working now
favorite count: 0
has comment: http://stackoverflow.com/comment/86362542
score: 1

python
tags question: http://stackoverflow.com/q/49612045
tags question: http://stackoverflow.com/q/49701351
tags question: http://stackoverflow.com/q/49650369
tags question: http://stackoverflow.com/q/49636459
tags question: http://stackoverflow.com/q/49648327
tags question: http://stackoverflow.com/q/49681377
tags question: http://stackoverflow.com/q/49756461
tags question: http://stackoverflow.com/q/49615010
tags question: http://stackoverflow.com/q/49756433
tags question: http://stackoverflow.com/q/49674514
tags question: http://stackoverflow.com/q/49732587
tags question: http://stackoverflow.com/q/49696486
tags question: http://stackoverflow.com/q/49683956
tags question: http://stackoverflow.com/q/49621226
tags question: http://stackoverflow.com/q/49712632
tags question: http://stackoverflow.com/q/49706831
tags question: http://stackoverflow.com/q/49607704
tags question: http://stackoverflow.com/q/49633315
tags question: http://stackoverflow.com/q/49722474
tags question: http://stackoverflow.com/q/49736688
tags question: http://stackoverflow.com/q/49725631
tags question: http://stackoverflow.com/q/49610780
tags question: http://stackoverflow.com/q/49684037
tags question: http://stackoverflow.com/q/49697846
tags question: http://stackoverflow.com/q/49721810
tags question: http://stackoverflow.com/q/49661049
tags question: http://stackoverflow.com/q/49603452
tags question: http://stackoverflow.com/q/49635078
tags question: http://stackoverflow.com/q/49728033
tags question: http://stackoverflow.com/q/49705519
tags question: http://stackoverflow.com/q/49688181
tags question: http://stackoverflow.com/q/49612027
tags question: http://stackoverflow.com/q/49746006
tags question: http://stackoverflow.com/q/49750324
tags question: http://stackoverflow.com/q/49668147
tags question: http://stackoverflow.com/q/49683892
tags question: http://stackoverflow.com/q/49713561
tags question: http://stackoverflow.com/q/49641791
tags question: http://stackoverflow.com/q/49630723
tags question: http://stackoverflow.com/q/49693169
tags question: http://stackoverflow.com/q/49715016
tags question: http://stackoverflow.com/q/49706803
tags question: http://stackoverflow.com/q/49712546
tags question: http://stackoverflow.com/q/49751183
tags question: http://stackoverflow.com/q/49666085
tags question: http://stackoverflow.com/q/49717999
tags question: http://stackoverflow.com/q/49693649
tags question: http://stackoverflow.com/q/49620677
tags question: http://stackoverflow.com/q/49637805
tags question: http://stackoverflow.com/q/49723272
tags question: http://stackoverflow.com/q/49710850
tags question: http://stackoverflow.com/q/49715505
tags question: http://stackoverflow.com/q/49736782
tags question: http://stackoverflow.com/q/49720776
tags question: http://stackoverflow.com/q/49682449
tags question: http://stackoverflow.com/q/49747350
tags question: http://stackoverflow.com/q/49600454
tags question: http://stackoverflow.com/q/49721089
tags question: http://stackoverflow.com/q/49684432
tags question: http://stackoverflow.com/q/49712468
tags question: http://stackoverflow.com/q/49727152
tags question: http://stackoverflow.com/q/49728265
tags question: http://stackoverflow.com/q/49731142
tags question: http://stackoverflow.com/q/49628741
tags question: http://stackoverflow.com/q/49637965
tags question: http://stackoverflow.com/q/49619074
tags question: http://stackoverflow.com/q/49661612
tags question: http://stackoverflow.com/q/49649803
tags question: http://stackoverflow.com/q/49603215
tags question: http://stackoverflow.com/q/49611623
tags question: http://stackoverflow.com/q/49734446
tags question: http://stackoverflow.com/q/49739723
tags question: http://stackoverflow.com/q/49657972
tags question: http://stackoverflow.com/q/49637559
tags question: http://stackoverflow.com/q/49753156
tags question: http://stackoverflow.com/q/49612151
tags question: http://stackoverflow.com/q/49649606
tags question: http://stackoverflow.com/q/49686810
tags question: http://stackoverflow.com/q/49743993
tags question: http://stackoverflow.com/q/49683312

http://stackoverflow.com/comment/86248710
type: QuestionComment
comment on: http://stackoverflow.com/q/49620860
score: 0
has text: It contains just counts of each degree - there are 2 values per each key
type: Comment

http://stackoverflow.com/comment/86525237
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49755099
type: QuestionComment
has text: I can't find anything new on the networx library. The newest thing on there was a week ago, which suggests it shouldn't of worked yesterday.

http://stackoverflow.com/comment/86280589
type: AnswerComment
score: 0
has text: @piRSquared, need to start using assign :)
type: Comment
comment on: http://stackoverflow.com/a/49636335

http://stackoverflow.com/q/49646130
has answer: http://stackoverflow.com/a/49646219
type: Question
score: 0
answer count: 1
type: AnsweredQuestion
tagged with: linux
has title: renaming files in python causes Device or resource busy
accepted answer: http://stackoverflow.com/a/49646219
tagged with: python
has body: I am writing a script with python. First, let me show you the exception: Traceback (most recent call last): File "/home/jiewei/PycharmProjects/TestEngine/test/test_multiple_classes.py", line 23, in test_create_symlink_and_run_test_in_devbench_but_is_called_in_vdi self.sm.make_backups(self.dev_path) File "testengine/SymlinkManger.py", line 24, in make_backups self.make_backup(file_path) File "testengine/SymlinkManger.py", line 19, in make_backup os.rename(file_path, new_name) OSError: [Errno 16] Device or resource busy Then here are method causing the problem: def make_backup(self, file_path): name = os.path.basename(file_path) folder_path = os.path.dirname(file_path) if not name.startswith('backup_'): new_name = os.path.join(folder_path,"backup_"+name) os.rename(file_path, new_name) def make_backups(self, folder_path): for file in folder_path: file_path = os.path.join(folder_path, file) self.make_backup(file_path) Do I need to create threads to solve this problem? I guess the cause is os is been used by multiple progress and this cause the exception. Thanks for any help!

http://stackoverflow.com/comment/86483171
comment on: http://stackoverflow.com/a/49734052
type: AnswerComment
has text: @MelanieGerster Unfortunately, this question got put on hold so I cannot add another answer. However, you can take a look at [this gist](https://gist.github.com/AaronNBrock/a28f703f8cd5868d8000182c016807cd)
score: 0
type: Comment

http://stackoverflow.com/q/49656116
possible better answer: http://stackoverflow.com/a/49656196
has comment: http://stackoverflow.com/comment/86321710
has answer: http://stackoverflow.com/a/49656196
answer count: 3
has answer: http://stackoverflow.com/a/49666538
upvote count: 2
has title: How to access a column within a column using pandas
has body: All, I have a dataframe that looks like this: df'date','PRICE' df&gt;&gt; date Price PX_FIRST PX_LAST 2018-03-05 1.710 -0.511 2018-03-06 1.725 -0.513 2018-03-07 1.745 -0.511 2018-03-08 1.750 -0.512 how can I get a dataframe similar to this? in other words how can I access PX_FIRST and PX_LAST. When I do df'date','PRICE' it dont manage to access individual columns. date PX_FIRST PX_LAST 2018-03-05 1.710 -0.511 2018-03-06 1.725 -0.513 2018-03-07 1.745 -0.511 2018-03-08 1.750 -0.512
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86321426
type: Question
linked to: http://stackoverflow.com/q/14507794
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86321737
accepted answer: http://stackoverflow.com/a/49656168
tagged with: pandas
has comment: http://stackoverflow.com/comment/86321691
score: 1
has answer: http://stackoverflow.com/a/49656168
tagged with: python

http://stackoverflow.com/q/49606792
possible better answer: http://stackoverflow.com/a/49606820
tagged with: string
has comment: http://stackoverflow.com/comment/86221288
tagged with: sublist
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/4481724
has comment: http://stackoverflow.com/comment/86221238
has answer: http://stackoverflow.com/a/49606865
accepted answer: http://stackoverflow.com/a/49606865
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/86220210
has answer: http://stackoverflow.com/a/49610507
has body: I got a list like this: [['zai4'], [' '], ['tui1'], ['jin4'], [' '], ['shi2'], ['pin3'], [' '], ['an1'], ['quan2'], [' '], ['xin4'], ['xi1'], [' ']] how could I convert it into this kind: zai4 tui1 jin4 shi2 pin3 an1 quan2 xin4 xi1 Thank you. I think the unique part of my question is how to extract content from sub-list into string.
tagged with: python
has title: Python: extract items in sublist into string
has comment: http://stackoverflow.com/comment/86220396
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86221321
tagged with: list
has comment: http://stackoverflow.com/comment/86220299
answer count: 3
downvote count: 2
has answer: http://stackoverflow.com/a/49606820

http://stackoverflow.com/a/49605901
accepted answer of: http://stackoverflow.com/q/49605830
has body: When importing a file, Python only searches the current directory, the directory that the entry-point script is running from and sys.path. Modify test_fun.py as follows: import sys sys.path.insert(0, '../src/') from script1 import fun1 def test_fun1(): output1 = fun1() # check output assert output1=='result_from_2_plus_something'
type: Answer
upvote count: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49605830
score: 4
downvote count: 1

http://stackoverflow.com/comment/86300606
type: AnswerComment
has text: i tried your answer so now the function read all the existing files in the **QlistWidget**... thank you ... what i want is after the user enter the searched word the system override the existing list and display just the files that includes the matching expression.... i will add to the question a second function that make the search if it can be improved this will be great.
type: Comment
comment on: http://stackoverflow.com/a/49646040
score: 0

http://stackoverflow.com/comment/86504272
type: AnswerComment
score: 0
has text: It wont work, getting OSError: [WinError 87] The parameter is incorrect error...the xml file path need to be in double quotes.
type: Comment
comment on: http://stackoverflow.com/a/49744848

http://stackoverflow.com/a/49757760
has comment: http://stackoverflow.com/comment/86530768
score: 14
answers question: http://stackoverflow.com/q/49757674
type: Answer
has comment: http://stackoverflow.com/comment/86574884
has body: print has an explicit check for None. /* sys.stdout may be None when FILE* stdout isn't connected */ if (file == Py_None) Py_RETURN_NONE;
accepted answer of: http://stackoverflow.com/q/49757674
upvote count: 14
has comment: http://stackoverflow.com/comment/86561131
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86530481

http://stackoverflow.com/a/49639752
answers question: http://stackoverflow.com/q/49639609
type: Answer
has body: I believe this is what you are after if you want them output as a single string: mydict = {'AAA': {'', '111', '222'}, 'BBB': {'222', '999', '555'}} out = [] for keys, values in mydict.items(): [out.append(i) for i in values if i!=''] out = ','.join(set(out)) print(out) print(type(out)) Outputs: 555,222,111,999 &lt;class 'str'&gt;
score: 0

http://stackoverflow.com/a/49614802
has comment: http://stackoverflow.com/comment/86237144
has comment: http://stackoverflow.com/comment/86237178
score: 0
has body: Old-style classes don't have an mro method built-in; only new-style classes do. Also, notice that the actual example has O = object, not class O: pass, making these new-style classes. And the example is part of an exercise for the reader. So this paragraph is just saying that a lazy programmer who doesn't want to work through the exercise for the example, and doesn't yet have access to a 2.3 interpreter, can paste this code into a 2.2 interpreter and call A.mro() and get the answer—because this case happens to be one where the 2.2 and 2.3 new-style class rules give the same answer. A non-lazy programmer, by contrast, would want to learn when they do and do not give the same answer, not just count on the fact that sometimes they do.
answers question: http://stackoverflow.com/q/49614553
type: Answer

http://stackoverflow.com/comment/86454761
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49720590
type: Comment
has text: @Rory you are probably not running python 3.6 - the string interpolation syntax ( `f'text{variablename}'` ) was introduced. Try the older format syntax, that should work down to 2.7 or so : `f.writelines(repeat("Papa\n{}*31\nMama\n{}*31\n".format(x,y),T))`

http://stackoverflow.com/comment/86363414
type: Comment
type: QuestionComment
score: 0
has text: @DanilaGanchar I'll test out if that was the cause of the slow down
comment on: http://stackoverflow.com/q/49663567

http://stackoverflow.com/a/49940489
upvote count: 1
answers question: http://stackoverflow.com/q/49679800
has body: If you want to stop receiving those particular logs, the solution would be to use exclusion filters. That way you can precisely determine which logs you don't want to see. To do that, head to the Logging menu in the console and select "Resource usage". Inside that menu you will find an "Exclusion" tags. Once in that tab, select the "Create exclusion" option. You will be redirected to the Logging page, with an "Exclusion editor" side menu. There you can define the parameters for your exclusion, such as the name, a description of the log entries you want to exclude (such as those where "inconsistent digest name MD5" appears) and the percent to exclude (if you want all of those log entries gone, use 100). After that, click "Create exclusion" and the log exclusion process will begin. I hope this proves useful for you, however I wonder if the application is working correctly since you are getting that warning. Any clarification on that would be appreciated.
type: Answer
has comment: http://stackoverflow.com/comment/86904472
score: 1
has comment: http://stackoverflow.com/comment/86897426
downvote count: 0

http://stackoverflow.com/comment/86538704
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49715779
type: QuestionComment
has text: yes for my later purposes, i need to mange switches and so on. This is part of a controller program where it has all these functionality of broadcasting,communication between clients and so on and thats why i prefer broadcasting.

http://stackoverflow.com/q/49612437
type: AnsweredQuestion
score: 0
has title: Heuristics for determining whether something is a "word" or random data?
upvote count: 1
has answer: http://stackoverflow.com/a/49613140
accepted answer: http://stackoverflow.com/a/49613140
has comment: http://stackoverflow.com/comment/86238517
downvote count: 1
tagged with: heuristics
has comment: http://stackoverflow.com/comment/86231780
tagged with: nlp
has comment: http://stackoverflow.com/comment/86237432
favorite count: 0
type: Question
tagged with: nltk
answer count: 1
has body: I am writing a web crawler in python that downloads a list of URLS, extracts all visible text from the HTML, tokenizes the text (using nltk.tokenize) and then creates a positional inverted index of words in each document for use by a search feature. However, right now, the index contains a bunch of useless entries like: 1) //roarmag.org/2015/08/water-conflict-turkey-middle-east/ 2) ———- 3) ykgnwym+ccybj9z1cgzqovrzu9cni0yf7yycim6ttmjqroz3wwuxiseulphetnu2 4) iazl+xcmwzc3da== Some of these, like #1, are where URLs appear in the text. Some, like #3, are excerpts from PGP keys, or other random data that is embedded in the text. I am trying to understand how to filter out useless data like this. But I don't just want to keep words that I would find in an English dictionary, but also things like names, places, nonsense words like "Jabberwocky" or "Rumpelstiltskin", acronyms like "TANSTAAFL", obscure technical/scientific terms, etc ... That is, I'm looking for a way to heuristically strip out strings that are "jibberish". (1) exceedingly "long" (2) filled with a bunch of punctuation (3) composed of random strings of characters like afhdkhfadhkjasdhfkldashfkjahsdkfhdsakfhsadhfasdhfadskhkf ... I understand that there is no way to do this with 100% accuracy, but if I could remove even 75% of the junk I'd be happy. Are there any techniques that I can use to separate "words" from junk data like this?
tagged with: python
linked to: http://stackoverflow.com/q/3182268
tagged with: search

http://stackoverflow.com/a/49685347
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49685310
has body: Count the occurrences and only replace the first n-1 of them if n is odd. &gt;&gt;&gt; s, find, replace = "text*text*hello*text", "*", "k" &gt;&gt;&gt; s.replace(find, replace, 2*(s.count(find)//2)) 'textktextkhello*text'
type: Answer
upvote count: 2

http://stackoverflow.com/comment/86383755
comment on: http://stackoverflow.com/q/49686103
has text: If possible, you should switch to Python 3.6+. https://pythonclock.org/
type: Comment
type: QuestionComment
score: 0

knapsack-problem
type: Tag
tags question: http://stackoverflow.com/q/49715583
tag name: knapsack-problem

http://stackoverflow.com/comment/86456737
score: 0
has text: Yeah, I ran into that same issue of only being able to get the last item. The TextAreaForm will work great though!
comment on: http://stackoverflow.com/a/49721314
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86462633
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49724089
has text: This behavior is the same in Python 2.7
score: 0

http://stackoverflow.com/comment/86501411
comment on: http://stackoverflow.com/q/49743238
type: QuestionComment
has text: Which version of python? This looks like a python 2.x Windows code page thing.
score: 1
type: Comment

http://stackoverflow.com/a/49630619
answers question: http://stackoverflow.com/q/49627823
has body: There are two concepts relevant to your question, which you should consider separately. Similarity Measure: Independent of your scoring mechanism, you should find a similarity measure which suits your data best. It can be an Euclidean distance (not suitable for a 1500 dimensional space), a cosine (dot product based) distance, or a Hamiltonian distance (assuming your input features are completely independent, which rarely is the case). A lot can go on in your distance function, and you should find one which makes sense for your data. Scoring Mechanism: You mention total_distance_of_vectors in your question, which probably is not what you want. If n &gt;&gt; m, almost certainly the total sum of distances for n vectors is more than the total distance for m vectors. What you're looking for is most probably an average of the distances between the members of your sets. Then, depending on weather you want your average to be sensitive to outliers or not, you can go for average of the distances or average of squared distances. If you want to dig deeper, you can also get the mean and variance of the distances within the two sets and compare the distributions.
score: 0
type: Answer

http://stackoverflow.com/q/49750703
downvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49750836
tagged with: list
has comment: http://stackoverflow.com/comment/86515762
upvote count: 0
score: -5
has body: I have a text file that has an accnumber, PIN number,balance for many users. I want to read the text file and split its data into 3 different lists but don't know how. (I'm creating a bank management system for school assessment.) Example text file: 98768 8077.00 Jim McIntyre 58697 23233.99 Michael Murphy 35318 4545.12 Abigail Buckley 20454 23233.45 Marie Delaney
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86561011
type: Question
has title: how to populate 3 list python from text file
tagged with: python

http://stackoverflow.com/q/49645151
has answer: http://stackoverflow.com/a/51336288
has title: Distributed training using Keras model and tf.Estimator
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: keras
has body: Following the example here one can create a tf.Estimator from an existing keras model. In the beginning this page states that by doing so, one can use benefits of the tf.Estimator such as an increased training speed due to distributed training. Sadly, when I run the code only one of the GPUs in my system is used for computations; therefore, there is no increase of speed. How exactly can I use distributed learning with an estimator built from a keras model? I stumbpled upon this method: distributed_model = tf.keras.utils.multi_gpu_model(model, gpus=2) which sounds like it would take care of this problem. But this is not working at the moment, as it creates a graph which uses the get_slice(..) method defined in tensorflow/python/keras/_impl/keras/utils/training_utils.py and this method fails with the following error message: Traceback (most recent call last): File "hub.py", line 75, in &lt;module&gt; estimator = create_model_estimator() File "hub.py", line 67, in create_model_estimator estimator = tf.keras.estimator.model_to_estimator(keras_model=new_model, custom_objects={'tf': tf}, model_dir=model_dir, config=run_config) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 302, in model_to_estimator _save_first_checkpoint(keras_model, est, custom_objects, keras_weights) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 231, in _save_first_checkpoint custom_objects) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 109, in _clone_and_build_model model = models.clone_model(keras_model, input_tensors=input_tensors) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/models.py", line 1557, in clone_model return _clone_functional_model(model, input_tensors=input_tensors) File "/root/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/models.py", line 145…
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49696044
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Steaming a large file into BigQuery
has comment: http://stackoverflow.com/comment/86478959
has body: I am trying to tidy up a large (8gb) .csv file in python then stream it into BigQuery. My code below starts off okay, as the table is created and the first 1000 rows go in, but then I get the error: InvalidSchema: Please verify that the structure and data types in the DataFrame match the schema of the destination table. Is this perhaps related to the streaming buffer? My issue is that I will need to remove the table before i run the code again, otherwise the first 1000 entries will be duplicated due to the 'append' method. import pandas as pd destination_table = 'product_data.FS_orders' project_id = '##' pkey ='##' chunks = [] for chunk in pd.read_csv('Historic_orders.csv',chunksize=1000, encoding='windows-1252', names=['Orderdate','Weborderno','Productcode','Quantitysold','Paymentmethod','ProductGender','DeviceType','Brand','ProductDescription','OrderType','ProductCategory','UnitpriceGBP' 'Webtype1','CostPrice','Webtype2','Webtype3','Variant','Orderlinetax']): chunk.replace(r' *!','Null', regex=True) chunk.to_gbq(destination_table, project_id, if_exists='append', private_key=pkey) chunks.append(chunk) df = pd.concat(chunks, axis=0) print(df.head(5)) pd.to_csv('Historic_orders_cleaned.csv')
score: 0
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/86409999
type: Question
has answer: http://stackoverflow.com/a/49707857
has comment: http://stackoverflow.com/comment/86418354

http://stackoverflow.com/a/49615296
type: Answer
has body: This works def get_proxy(): try: proxy_manager = ProxyManager("proxies.txt") return proxy_manager.random_proxy().proxy_string except (OSError, IOError) as e: # couldn't load the file return None chrome_options = webdriver.ChromeOptions() proxy = get_proxy() if proxy: chrome_options.add_argument("--proxy-server=" + proxy) chrome = webdriver.Chrome(chrome_options=chrome_options) chrome.get("http://whatismyipaddress.com")
answers question: http://stackoverflow.com/q/49614686
score: 0

http://stackoverflow.com/a/49620225
has body: generate_password_hash is a function for securely hashing passwords. ItsDangerous is a library for securely signing (but not hashing or encrypting) arbitrary data. ItsDangerous would not be appropriate for hashing passwords. Since you're using Flask-Login, it will handle cookies for you. You would not use ItsDangerous directly in that case. Flask uses ItsDangerous behind the scenes to sign the session cookie.
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49619719
answers question: http://stackoverflow.com/q/49619719
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49668147
has comment: http://stackoverflow.com/comment/86349694
has answer: http://stackoverflow.com/a/49669874
upvote count: 0
tagged with: http://stackoverflow.com/tag/html
score: -6
favorite count: 0
type: Question
tagged with: beautifulsoup
has title: Beautiful Soup: extract all data between tags
has answer: http://stackoverflow.com/a/49669968
has comment: http://stackoverflow.com/comment/86349874
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86357398
has comment: http://stackoverflow.com/comment/86348647
has body: Insurtech .....Some data Biometrics I tried this: html_tags = soup.find_all('em') for i in range(len(html_tags)-1): start_tag = html_tags[i] end_tag = html_tags[i+1] between_tag = (soup_str.split(str(start_tag)))[1].split(str(end_tag))[0] soup1 = BeautifulSoup(between_tag, 'html.parser') I want all the data from first p->strong->em to the next p->strong->em tag.This is my sample data.Thanks in advance**
tagged with: tags
has comment: http://stackoverflow.com/comment/86348499
tagged with: python
has comment: http://stackoverflow.com/comment/86472952
has comment: http://stackoverflow.com/comment/86346577
downvote count: 6
answer count: 2

http://stackoverflow.com/comment/86234906
comment on: http://stackoverflow.com/q/49614096
has text: Recommending another package wouldn't help if you have troubles installing this one with pip
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86334123
score: 0
has text: Obscure? I think as of 3.7 they're finally mentioned in the docs somewhere. And, even better, the set-contents method is exposed to Python code, so you grub through a function's `__closure__` and change the captured values.
type: QuestionComment
comment on: http://stackoverflow.com/q/49661827
type: Comment

http://stackoverflow.com/q/49685416
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86382226
tagged with: django
score: 0
has body: I'm very new to django as well as python and working on a simple upload/download web app using django. So far, I've managed to complete the upload function and it works but I have difficulties with downloading the files uploaded. The code seems to work yet I receive 'Permission Denied' error. These are the codes I used: (views.py) def list(request): #file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): doc_file = Document(docfile=request.FILES['docfile']) print(doc_file) print(doc_file.uploaded_at) doc_file.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form #Load documents for the list page documents = Document.objects.all() #Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) def download(request): file_name = request.GET.get(' ') print(file_name) path_to_file = settings.MEDIA_ROOT + '/' + file_name print(path_to_file) with open(path_to_file, 'rb') as fh: response = HttpResponse(fh.read(), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(path_to_file) return response models.py class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_at = models.DateTimeField(default=datetime.now, blank=True) def size(self): filesize = self.docfile.size return filesize def filename(self): filename = self.docfile.name return filename.replace("documents/", "") list.html File upload/download {% csrf_token %} {{ form.docfile.label_tag }} {{ form.docfile }} {% if documents %} File Name File Size Uploaded Time {% for document in documents %} {{ document.filename }} {{document.uploaded_at}} {% endfor %} {% else %} not available. {% endif %} The error traceback : Environment: Request …
has comment: http://stackoverflow.com/comment/86388729
has comment: http://stackoverflow.com/comment/86385816
has comment: http://stackoverflow.com/comment/86382438
tagged with: python
has title: PermissionError at /myapp/download/ [Errno 13] Permission denied:

http://stackoverflow.com/q/49693826
has title: How to print list of strings with lambda?
accepted answer: http://stackoverflow.com/a/49694096
tagged with: lambda
favorite count: 0
has body: I have a list of strings that print out just fine using a normal loop: for x in listing: print(x) I thought it should be pretty simple to use a lambda to reduce the loop syntax, and kickstart my learning of lambdas in Python (I'm pretty new to Python). Given that the syntax for map is map(function, iterable, ...) I tried: map(lambda x: print(x), listing) But this does not print anything out (it also does not produce an error). I've done some searching through material online but everything I have found to date is based on Python 2, namely mentioning that with Python 2 this isn't possible but that it should be in Python 3, without explicitly mentioning how so. What am I doing wrong?
type: Question
score: 3
linked to: http://stackoverflow.com/q/1975250
downvote count: 1
tagged with: python
upvote count: 4
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49694718
possible better answer: http://stackoverflow.com/a/49694718
has answer: http://stackoverflow.com/a/49694096

http://stackoverflow.com/comment/86507206
score: 0
type: Comment
type: AnswerComment
has text: If the file is read somewhat correctly using UTF-8 it surely isn't UTF-16.
comment on: http://stackoverflow.com/a/49746146

http://stackoverflow.com/comment/86275142
score: 0
type: Comment
has text: ok i think you have a fair point Whatever you do, don't combine the FULLTEXT and LIKE searches in a single query ...is there any way i perform %like% query on the result of Full text query
type: AnswerComment
comment on: http://stackoverflow.com/a/49630276

http://stackoverflow.com/q/49668947
tagged with: python
has comment: http://stackoverflow.com/comment/86360185
has body: from Tkinter import * root = Tk() root.geometry('361mx203m') a = Label(root,text="hello everyone",font=('Helvetica',"25m"),anchor='center') a.place(x=0,y=0) b1 = Button(root,text="pal entry",height="100m",width="25m") b1.place(x=10,y=50) root.mainloop() TclError: expected integer but got "25m". Suggest me a code to convert this into millimeters
tagged with: python-2.7
answer count: 2
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/86348653
type: Question
has title: how can i change the Dimension from Pixels to any other like cm,millimeter etc
has answer: http://stackoverflow.com/a/49671937
has answer: http://stackoverflow.com/a/60528731
type: UnansweredQuestion

http://stackoverflow.com/comment/86264942
comment on: http://stackoverflow.com/q/49627185
type: Comment
type: QuestionComment
score: 0
has text: just like that you should follow same methodology for two project, means you need to create two files in for your two project instead of using single one

http://stackoverflow.com/a/49613091
answers question: http://stackoverflow.com/q/49609640
score: 0
has body: So, as it turns out I came up with a working solution: if len(BeautifulSoup(y.decode_contents(formatter="html"),'html.parser').find_all()) == 0 and y.decode_contents(formatter="html") != "": tmp.append(y.decode_contents(formatter="html")) This code checks, whether or not child elements are parseable HTML-elements or just text.
type: Answer

http://stackoverflow.com/q/49721695
has body: I am making a python to read temperature from a simple server in a lan network each 2 seconds, the problem is that sometimes the script is stuck without doing anything, I'm using requests with python 3.6 on windows import requests import time while True: s=time.time() r = requests.get("http://192.168.1.2/readtemp.php?id=1&amp;action=read") temp = r.text print (temp + ' - ' + str(time.time()-s) + ' Seconds') time.sleep(2) the response I get is this: 29°C - 0.272745847702026 Seconds 29°C - 0.64812617301941 Seconds 29°C - 0.294319868087769 Seconds but sometimes when I come back to my computer I find it stuck doing nothing, any ideas why it gets stuck, isn't it supposed to keep making the request till it gets a response like browsers do?
upvote count: 12
answer count: 1
accepted answer: http://stackoverflow.com/a/56941261
tagged with: python-requests
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/56941261
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86456628
has comment: http://stackoverflow.com/comment/86457276
has comment: http://stackoverflow.com/comment/86456726
has comment: http://stackoverflow.com/comment/86457195
tagged with: python
has title: python requests.get gets stuck
score: 11
has comment: http://stackoverflow.com/comment/86458006

http://stackoverflow.com/q/49650028
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49650174
has body: I've been making a function to search through two lists and check if a character is in both lists.The error "IndexError: list index out of range" keeps coming up. I put this through python Tutor and it seems like the while loop is totally ignored.I'm coding this search without using the in function in an if statement. Any help would be much appreciated! Here is my code: aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ] userInput = "TOE" userInputList = list(userInput) letterExists = 0 while (letterExists &lt; len(userInput)): for i in aList: if (i == userInputList[letterExists]): letterExists +=1 if (letterExists == len(userInput)): print("This word can be made using your tiles")
has comment: http://stackoverflow.com/comment/86308351
tagged with: python
has answer: http://stackoverflow.com/a/49650174
has answer: http://stackoverflow.com/a/49650331
has answer: http://stackoverflow.com/a/49650271
has title: While loop: list index out of range
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86308475
accepted answer: http://stackoverflow.com/a/49650331
type: Question

http://stackoverflow.com/comment/86454341
comment on: http://stackoverflow.com/q/49720357
type: Comment
score: 0
has text: What is the result when you run `print(content)`?
type: QuestionComment

http://stackoverflow.com/comment/86263719
score: 0
has text: That's correct. You haven't defined `cursor`, so it wouldn't have worked before, either. You proably want to create `cursor` like it's done in your `update_question()` method.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49626794

http://stackoverflow.com/a/49702299
has body: How about this? (?:^|\s+)(?=(\S+\s+\S+)) Demo
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49701953
type: Answer

http://stackoverflow.com/a/52463955
type: Answer
answers question: http://stackoverflow.com/q/49755565
has body: mypy-protobuf generates the type hint files. But as discussed here this works only from protobuf 3.0 and python 2.7 onwards.
accepted answer of: http://stackoverflow.com/q/49755565
type: AcceptedAnswer
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/comment/87118335
type: AnswerComment
comment on: http://stackoverflow.com/a/49758009
type: Comment
score: 0
has text: Thanks for the contribution @vivekkumar @roelant! The get_dummies function works perfectly and already helped me a lot. There is just one more problem: As in the screenshot, there are multiple genres listed for each movie. If I do get_dummies it obviously takes e.g. Horror|Action as one new column, even though I would like to have Horror as well as all other Genres as one column with the respective 0/1 value achieved through the get_dummies function. Have you any idea how to do that?

http://stackoverflow.com/a/49691304
type: Answer
score: -1
has body: As others have said you can use &gt;&gt;&gt; [max(i) for i in a] [2, 1, 2] But there is also this for the opposite of what you want &gt;&gt;&gt; [min(i) for i in a] [0, 0, 0]
upvote count: 0
answers question: http://stackoverflow.com/q/49690982
has comment: http://stackoverflow.com/comment/86395769
downvote count: 1

http://stackoverflow.com/a/49616358
answers question: http://stackoverflow.com/q/49616239
has body: Take a look at the skipIf decorator and applying it to your dependent tests based on a condition set in your first test. @unittest.skipIf(condition, reason) For example (from the above link): @unittest.skipIf(mylib.__version__ &lt; (1, 3), "not supported in this library version") There is also subTest(), but the docs describe the purpose of subTest as being for "When some of your tests differ only by a some [sic] very small differences."
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86245729
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86245179
accepted answer of: http://stackoverflow.com/q/49616239
type: Answer
has comment: http://stackoverflow.com/comment/86280614

http://stackoverflow.com/comment/86263497
type: AnswerComment
has text: I've added a final comment about that @idiaz01 (string literals and using r"")
comment on: http://stackoverflow.com/a/49628099
score: 0
type: Comment

http://stackoverflow.com/comment/86333580
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49661771
has text: You do not have to call `json.loads` for each JSON row. You need to pass a complete JSON as argument, e.g., `json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')`
type: Comment

http://stackoverflow.com/comment/86436967
comment on: http://stackoverflow.com/a/49711594
score: 16
has text: I thought they stopped doing this last year: https://github.com/Homebrew/homebrew-core/pull/14408
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49715719
has body: I have a test data frame here. import pandas as pd import numpy as np import seaborn as sns df = pd.DataFrame({'x': [1,2,3,4], 'y': [1,4,9,16], 'z' : ['A','B','C','D']}) This will look as x y z 0 1 1 A 1 2 4 B 2 3 9 C 3 4 16 D Now I want to do a seaborn scatter plot and put tool tips using the z column. Here is my seaborn scatter plot code g = sns.regplot(x=df["x"], y=df["y"], fit_reg=False, scatter_kws={'s':30}, color='red') g.set_title('My Plot') fig = g.get_figure() fig.savefig('myplot.png') And here is the figure. Now when I hover over the data point, I want the value of column z to be displayed for that row. How would I do that ?
favorite count: 0
type: Question
tagged with: seaborn
type: UnansweredQuestion
tagged with: matplotlib
linked to: http://stackoverflow.com/q/7908636
tagged with: python
has title: Tooltip in seaborn scatterplot
linked to: http://stackoverflow.com/q/31480921
has comment: http://stackoverflow.com/comment/86445062
answer count: 0
duplicate of: http://stackoverflow.com/q/7908636
has comment: http://stackoverflow.com/comment/104800602
downvote count: 0
score: 7
upvote count: 7

http://stackoverflow.com/comment/86302476
has text: True, I have a score for them but the RDD is so big that I'm trying basic versions before I extend the whole calculation. Let's say I have a column, amount_times_watched what'd be the way to include a sort? The column refers to the movie being watched totally by all users.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49647034

http://stackoverflow.com/comment/86483730
comment on: http://stackoverflow.com/q/49723266
type: Comment
type: QuestionComment
has text: @hoefling different exception this time: `ImportError: attempted relative import with no known parent package`
score: 0

http://stackoverflow.com/q/49733506
tagged with: python-3.6
has body: I'm not too familiar with threading, and probably not using it correctly, but I have a script that runs a speedtest a few times and prints the average. I'm trying to use threading to call a function which displays something while the tests are running. Everything works fine unless I try to put input() at the end of the script to keep the console window open. It causes the thread to run continuously. I'm looking for some direction in terminating a thread correctly. Also open to any better ways to do this. import speedtest, time, sys, datetime from threading import Thread s = speedtest.Speedtest() best = s.get_best_server() def downloadTest(tries): x=0 downloadList = [] for x in range(tries): downSpeed = (s.download()/1000000) downloadList.append(downSpeed) x+=1 results_dict = s.results.dict() global download_avg, isp download_avg = (sum(downloadList)/len(downloadList)) download_avg = round(download_avg,1) isp = (results_dict['client']['isp']) print("") print(isp) print(download_avg) def progress(): while True: print('~ ',end='', flush=True) time.sleep(1) def start(): now=(datetime.datetime.today().replace(microsecond=0)) print(now) d = Thread(target= downloadTest, args=(3,)) d.start() d1 = Thread(target = progress) d1.daemon = True d1.start() d.join() start() input("Complete...") # this causes progress thread to keep running
tagged with: python-3.x
downvote count: 0
upvote count: 1
score: 1
has title: Correctly terminating a thread in Python
answer count: 1
has comment: http://stackoverflow.com/comment/86481154
has comment: http://stackoverflow.com/comment/86481299
has comment: http://stackoverflow.com/comment/86481172
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86481505
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49733990
accepted answer: http://stackoverflow.com/a/49733990
tagged with: python
has comment: http://stackoverflow.com/comment/86481053

http://stackoverflow.com/comment/86480285
type: Comment
comment on: http://stackoverflow.com/a/49732728
type: AnswerComment
has text: But then is there a way to reload the data in the same way. Right now I'm doing `df = pd.read_pickle(path).values` which returns np.arrays of np.arrays... And It's pretty annoying to have list of tuple when I write, and arrays of arrays when I read :/
score: 0

http://stackoverflow.com/a/49698533
score: 2
upvote count: 2
has body: I don't know of such a document, but I think the main thing for you to understand is that C++ is statically typed, so variables must be declared before they can be used and this follows the form: type variableName; If you see a * or &amp; in the type, that's a pointer or reference, respectively, so just ignore it for this purpose. These forms: Type variable("argument"); Type variable = Type("argument"); Type* variable = new Type("argument"); Declare and instantiate variables. Translate them by calling the constructor: variable = Type("argument") Later uses won't have the type first, but translate them the same. In your example newColumn creates one object at the declaration (type given) and another near the end (no type given). If you see this: variable.foo; // non-pointer variable-&gt;foo; // pointer In Python just use the dot form: variable.foo C++ has a difference between pointers and values, so you can usually ignore * or &amp; in the use of the variable, e.g. function(*variable) or function(&amp;variable) in C++ will likely just be function(variable) in Python. The last wrinkle in this example is when you have &lt;&gt; in the type. Those are C++ templates and there is no direct equivalent in Python. Instead they will either give a fixed name for the whole type or let you use an alternate Python type instead. In this example it looks like they accept Python list objects rather than having a special name for QList&lt;QStandardItem*&gt;. Don't be thrown off by the unconventional naming of NewRow in your example, that is the variable name and not a type. Unfortunately QT uses a lot of preprocessor macros in the native code, which are by convention written in all-caps, like Q_OBJECT, SIGNAL, SLOT, etc. There is no general rule for translating these but many can just be ignored.
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49698060
has comment: http://stackoverflow.com/comment/86410611
accepted answer of: http://stackoverflow.com/q/49698060
type: Answer

http://stackoverflow.com/q/49652354
score: 2
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/49652860
has body: I'm trying to figure out a way to adjust the width and color of the contour lines in the seaborn plot below: I would like them all to be just thin black lines, although I have no idea how to pass the parameters... Providing 'linewidth' does not seem to work... The code: g = sns.jointplot(x="s_zscore", y="p_zscore", data=scatter_all, kind="kde", space=0, stat_func=None, marginal_kws={"color":"black", "lw":0.5}, color="black", shade=False, n_levels=10)
favorite count: 0
type: Question
upvote count: 2
tagged with: seaborn
tagged with: data-visualization
downvote count: 0
tagged with: python
has title: Contour line parameters in seaborn kde plot
has answer: http://stackoverflow.com/a/49652860
type: AnsweredQuestion

http://stackoverflow.com/comment/86424611
type: AnswerComment
score: 1
has text: @AmalSailendran Glad I could help. However when the answer you look for already has been answered the community prefer finding the dupes. It keeps the question amount low. In SO you can accept answers but upvote (+1) or downvote (-1) using the arrows. Thank you.
type: Comment
comment on: http://stackoverflow.com/a/49705551

http://stackoverflow.com/q/49721675
tagged with: python-3.x
linked to: http://stackoverflow.com/q/24657384
has comment: http://stackoverflow.com/comment/86572740
has comment: http://stackoverflow.com/comment/86610164
answer count: 0
type: UnansweredQuestion
has title: Module for plotting decision tree in Python3
upvote count: 1
tagged with: decision-tree
tagged with: python
tagged with: plot
has body: I would like to ask how to plot a decision tree in python. The functionality which I mean is similar to one in this question, but a picture is needed, not just text format. For example, having this dictionary structure MyNodeStructure = {'main': {'load': {'regA': None}, 'comupute': {'loop': {'regA': None, 'regB': None}}, 'store': None}} I would like to get something like this as an output: Example of desired tree. Do you know any module/easy way how to achieve this result in Python3?
score: 0
tagged with: pyqt5
linked to: http://stackoverflow.com/q/41564604
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86241041
comment on: http://stackoverflow.com/q/49616986
score: 0
type: Comment
has text: So to simplify the question: You're basically asking "is there a way to save and load enum values to json", right?
type: QuestionComment

http://stackoverflow.com/a/55031772
answers question: http://stackoverflow.com/q/49646583
has body: It wouldn't have been possible to add such a check to lists without breaking backward compatibility. For dicts, there was no such issue. In the old, pre-iterators design, for loops worked by calling the sequence element retrieval hook with increasing integer indices until it raised IndexError. (I would say __getitem__, but this was back before type/class unification, so C types didn't have __getitem__.) len isn't even involved in this design, and there is nowhere to check for modification. When iterators were introduced, the dict iterator had the size change check from the very first commit that introduced iterators to the language. Dicts weren't iterable at all before that, so there was no backward compatibility to break. Lists still went through the old iteration protocol, though. When list.__iter__ was introduced, it was purely a speed optimization, not intended to be a behavioral change, and adding a modification check would have broken backward compatibility with existing code that relied on the old behavior.
downvote count: 0
has comment: http://stackoverflow.com/comment/96816329
has comment: http://stackoverflow.com/comment/96831428
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/96816471
score: 9
has comment: http://stackoverflow.com/comment/96866353

http://stackoverflow.com/comment/127068446
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49631178
score: 0
has text: Surely a more conventional approach might be to use classes with methods.

http://stackoverflow.com/q/49615649
linked to: http://stackoverflow.com/q/1282945
has title: TypeError: 'float' object cannot be interpreted as an integer as numpy randon.randn python
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49615783
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/1282945
accepted answer: http://stackoverflow.com/a/49615783
has body: In this code N = 4 M = 30 # Generar datos a partir de 3 clusters diferentes: X1 = 10 + 2*np.random.randn(M/3,N) X2 = -10 + 5*np.random.randn(M/3,N) X3 = 1*np.random.randn(M/3,N) I get this error Traceback (most recent call last): File "/home/user/PycharmProjects/tema3/3.18_MDS.py", line 16, in &lt;module&gt; X1 = 10 + 2*int(np.random.randn(M/3,N)) # cluster 1 (dispersion media) File "mtrand.pyx", line 1420, in mtrand.RandomState.randn File "mtrand.pyx", line 1550, in mtrand.RandomState.standard_normal File "mtrand.pyx", line 167, in mtrand.cont0_array TypeError: 'float' object cannot be interpreted as an integer I'm not sure about the problem because I think I'm not pasing any float to randn.
score: 0
has comment: http://stackoverflow.com/comment/117573228
upvote count: 3
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86237996
has comment: http://stackoverflow.com/comment/86238013
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86238037
has comment: http://stackoverflow.com/comment/86238276
tagged with: python

tkinter
tags question: http://stackoverflow.com/q/49641710
tags question: http://stackoverflow.com/q/49699802
tags question: http://stackoverflow.com/q/49742812
tags question: http://stackoverflow.com/q/49636945
tags question: http://stackoverflow.com/q/49621420
tags question: http://stackoverflow.com/q/49619685
tags question: http://stackoverflow.com/q/49621671
tags question: http://stackoverflow.com/q/49619377
tags question: http://stackoverflow.com/q/49700870
tags question: http://stackoverflow.com/q/49724170
tags question: http://stackoverflow.com/q/49649952
tags question: http://stackoverflow.com/q/49702917
tags question: http://stackoverflow.com/q/49606850
tags question: http://stackoverflow.com/q/49742227
tags question: http://stackoverflow.com/q/49651995
tags question: http://stackoverflow.com/q/49655724
tags question: http://stackoverflow.com/q/49643351
tags question: http://stackoverflow.com/q/49600272
tags question: http://stackoverflow.com/q/49744985
tags question: http://stackoverflow.com/q/49601496
tags question: http://stackoverflow.com/q/49667646
tags question: http://stackoverflow.com/q/49611594
tags question: http://stackoverflow.com/q/49620635
tags question: http://stackoverflow.com/q/49726598
tags question: http://stackoverflow.com/q/49673910
tags question: http://stackoverflow.com/q/49651707
tags question: http://stackoverflow.com/q/49713475
tags question: http://stackoverflow.com/q/49744492
tags question: http://stackoverflow.com/q/49709271
tags question: http://stackoverflow.com/q/49707951
tags question: http://stackoverflow.com/q/49620011
tags question: http://stackoverflow.com/q/49624213
tags question: http://stackoverflow.com/q/49712038
tags question: http://stackoverflow.com/q/49663292
tags question: http://stackoverflow.com/q/49703958
tags question: http://stackoverflow.com/q/49636754
tags question: http://stackoverflow.com/q/49654129
tags question: http://stackoverflow.com/q/49748378
tags question: http://stackoverflow.com/q/49661770
tags question: http://stackoverflow.com/q/49701771
tags question: http://stackoverflow.com/q/49652206
tags question: http://stackoverflow.com/q/49656004
tags question: http://stackoverflow.com/q/49656013
tags question: http://stackoverflow.com/q/49742217
tags question: http://stackoverflow.com/q/49732807
tag name: tkinter
tags question: http://stackoverflow.com/q/49731031
tags question: http://stackoverflow.com/q/49634554
tags question: http://stackoverflow.com/q/49715456
tags question: http://stackoverflow.com/q/49737596
tags question: http://stackoverflow.com/q/49626794
tags question: http://stackoverflow.com/q/49728308
tags question: http://stackoverflow.com/q/49630752
tags question: http://stackoverflow.com/q/49712222
tags question: http://stackoverflow.com/q/49697298
tags question: http://stackoverflow.com/q/49713432
tags question: http://stackoverflow.com/q/49742325
tags question: http://stackoverflow.com/q/49642968
tags question: http://stackoverflow.com/q/49668337
tags question: http://stackoverflow.com/q/49649467
tags question: http://stackoverflow.com/q/49677522
tags question: http://stackoverflow.com/q/49645958
tags question: http://stackoverflow.com/q/49624631
tags question: http://stackoverflow.com/q/49724146
tags question: http://stackoverflow.com/q/49684132
tags question: http://stackoverflow.com/q/49663950
tags question: http://stackoverflow.com/q/49601432
tags question: http://stackoverflow.com/q/49635454
tags question: http://stackoverflow.com/q/49754385
tags question: http://stackoverflow.com/q/49722577
tags question: http://stackoverflow.com/q/49691852
tags question: http://stackoverflow.com/q/49638871
tags question: http://stackoverflow.com/q/49663794
tags question: http://stackoverflow.com/q/49727958
tags question: http://stackoverflow.com/q/49617807
tags question: http://stackoverflow.com/q/49658301
tags question: http://stackoverflow.com/q/49742157
tags question: http://stackoverflow.com/q/49688826
tags question: http://stackoverflow.com/q/49628757
tags question: http://stackoverflow.com/q/49710067

http://stackoverflow.com/a/49719662
type: Answer
has comment: http://stackoverflow.com/comment/86452327
has comment: http://stackoverflow.com/comment/86452200
has body: import re def substitue(sentence,target,replacement): x=re.sub("[^\w]", " ", sentence).split() x = [word.replace(target,replacement) for word in x] sent=" ".join(x) return sent try this
has comment: http://stackoverflow.com/comment/86452379
answers question: http://stackoverflow.com/q/49719514
has comment: http://stackoverflow.com/comment/86452299
score: 0
has comment: http://stackoverflow.com/comment/86452330

http://stackoverflow.com/q/49601425
has comment: http://stackoverflow.com/comment/86210087
downvote count: 4
tagged with: pycharm
answer count: 3
upvote count: 2
has answer: http://stackoverflow.com/a/63844121
score: -2
has body: I have a code that lasts half an hour to be executed completely. But I don't know how to access and see variables after running it. I mean when the program is easy, we can use print() and run the code over and over. But how can I do that without executing it again? I use Pycharm Edit: something like workspace in matlab. after a script is finished variables are still accesible.
has answer: http://stackoverflow.com/a/49601460
favorite count: 0
has comment: http://stackoverflow.com/comment/86210115
type: Question
has comment: http://stackoverflow.com/comment/86210605
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49601477
has comment: http://stackoverflow.com/comment/86210461
tagged with: python
has comment: http://stackoverflow.com/comment/86210342
has title: how to access variables when executing code is finished in pycharm?
has comment: http://stackoverflow.com/comment/86210171
possible better answer: http://stackoverflow.com/a/49601477
accepted answer: http://stackoverflow.com/a/63844121

http://stackoverflow.com/a/49665678
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49665291
has body: Here is an easily readable multi-line solution, which does not take into account the items of list2 that are not of string type: result = [] for sentence in list2: if isinstance(sentence, str): for word in list1: if word in sentence.split(): result.append(sentence) break print(result) Here is also a one-line style solution (I saw it has been already given by @grimek), which converts any items from list2 into stringtype: result = [sentence for sentence in list2 if any(word in str(sentence).split() for word in list1)] print(result)

http://stackoverflow.com/q/49675507
tagged with: python
score: -1
type: Question
has body: I am trying to format a string to pass to os.popen() so I can do some parsing in awk. I'm using python 2.7.10. When I try to format the string, python appears to think that I'm trying to assign a new key/value pair to a dictionary. &gt;&gt;&gt; path="xyz" &gt;&gt;&gt; string="awk {}".format(path) #&lt;--- This works as expected! &gt;&gt;&gt; string 'awk xyz' &gt;&gt;&gt; &gt;&gt;&gt; string="awk 'BEGIN{FS=\"\t\"}{print $1}' {}" #&lt;--- This works, but not what I want &gt;&gt;&gt; string 'awk \'BEGIN{FS="\t"}{print $1}\' {}' &gt;&gt;&gt; &gt;&gt;&gt; string="awk 'BEGIN{FS=\"\t\"}{print $1}' {}".format(path) #&lt;--- This fails b/c Python thinks I'm trying to do something with dictionaries? Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'FS="\t"' How do I format my string in the case where there are {} that are not intended to get formatted and ones that are?
upvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49675535
linked to: http://stackoverflow.com/q/5466451
has title: Formatting string with `{somestring}` in python causes python to confuse string with dictionary assignment
favorite count: 0
duplicate of: http://stackoverflow.com/q/5466451
downvote count: 1

google-api
tags question: http://stackoverflow.com/q/49625386
tags question: http://stackoverflow.com/q/49709197
tags question: http://stackoverflow.com/q/49663359
tags question: http://stackoverflow.com/q/49661229
tag name: google-api
tags question: http://stackoverflow.com/q/49622725
tags question: http://stackoverflow.com/q/49705020
tags question: http://stackoverflow.com/q/49645415
tags question: http://stackoverflow.com/q/49631111
type: Tag

http://stackoverflow.com/a/49756257
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49756084
has body: Docker RUN is a build step. It creates a new layer upon previous, and essentially creates a new image. So the answer to your question is "No". Consider using ENTRYPOINT and/or CMD, or compose a startup script for convenience. Scripting your RUN might also suit your needs: RUN my_deploy_for_venv.sh will execute in one layer, so if you start venv in script, you shall have it during it's execution. You will have to start it again on container startup, though.
answers question: http://stackoverflow.com/q/49756084
type: Answer
score: 2

flask
tags question: http://stackoverflow.com/q/49645765
tags question: http://stackoverflow.com/q/49625787
tags question: http://stackoverflow.com/q/49663355
tags question: http://stackoverflow.com/q/49720357
tags question: http://stackoverflow.com/q/49621478
tags question: http://stackoverflow.com/q/49602286
tags question: http://stackoverflow.com/q/49691115
tags question: http://stackoverflow.com/q/49624318
tags question: http://stackoverflow.com/q/49620503
tags question: http://stackoverflow.com/q/49746131
tags question: http://stackoverflow.com/q/49620585
tags question: http://stackoverflow.com/q/49714768
tags question: http://stackoverflow.com/q/49687071
tags question: http://stackoverflow.com/q/49615645
tags question: http://stackoverflow.com/q/49699221
tags question: http://stackoverflow.com/q/49743183
tags question: http://stackoverflow.com/q/49750711
tags question: http://stackoverflow.com/q/49631072
tags question: http://stackoverflow.com/q/49653960
tags question: http://stackoverflow.com/q/49720606
tags question: http://stackoverflow.com/q/49742393
tags question: http://stackoverflow.com/q/49627471
tags question: http://stackoverflow.com/q/49620502
tags question: http://stackoverflow.com/q/49632652
tags question: http://stackoverflow.com/q/49723926
tags question: http://stackoverflow.com/q/49693148
tags question: http://stackoverflow.com/q/49752592
tags question: http://stackoverflow.com/q/49641694
tags question: http://stackoverflow.com/q/49712385
tags question: http://stackoverflow.com/q/49636215
tags question: http://stackoverflow.com/q/49734227
tags question: http://stackoverflow.com/q/49744033
tags question: http://stackoverflow.com/q/49668987
tags question: http://stackoverflow.com/q/49691281
tags question: http://stackoverflow.com/q/49723499
tags question: http://stackoverflow.com/q/49656877
tags question: http://stackoverflow.com/q/49729918
tags question: http://stackoverflow.com/q/49679800
tags question: http://stackoverflow.com/q/49621169
tags question: http://stackoverflow.com/q/49629390
tags question: http://stackoverflow.com/q/49732664
tags question: http://stackoverflow.com/q/49722634
tags question: http://stackoverflow.com/q/49673546
tags question: http://stackoverflow.com/q/49626250
tags question: http://stackoverflow.com/q/49684813
tags question: http://stackoverflow.com/q/49743258
tags question: http://stackoverflow.com/q/49733221
tags question: http://stackoverflow.com/q/49615818
tags question: http://stackoverflow.com/q/49697157
tags question: http://stackoverflow.com/q/49737354
tags question: http://stackoverflow.com/q/49697545
tags question: http://stackoverflow.com/q/49634105
tags question: http://stackoverflow.com/q/49635819
tags question: http://stackoverflow.com/q/49664010
tags question: http://stackoverflow.com/q/49652084
tags question: http://stackoverflow.com/q/49743795
tags question: http://stackoverflow.com/q/49715050
tags question: http://stackoverflow.com/q/49727453
tags question: http://stackoverflow.com/q/49653966
tags question: http://stackoverflow.com/q/49619719
tags question: http://stackoverflow.com/q/49629419
tags question: http://stackoverflow.com/q/49672433
tags question: http://stackoverflow.com/q/49651353
tags question: http://stackoverflow.com/q/49654377
tags question: http://stackoverflow.com/q/49666707
tags question: http://stackoverflow.com/q/49713516
tags question: http://stackoverflow.com/q/49717961
tag name: flask
tags question: http://stackoverflow.com/q/49683367
tags question: http://stackoverflow.com/q/49734284
tags question: http://stackoverflow.com/q/49683892
tags question: http://stackoverflow.com/q/49691395
tags question: http://stackoverflow.com/q/49689581
tags question: http://stackoverflow.com/q/49664980
tags question: http://stackoverflow.com/q/49740741
tags question: http://stackoverflow.com/q/49743742
tags question: http://stackoverflow.com/q/49639311
tags question: http://stackoverflow.com/q/49619569
tags question: http://stackoverflow.com/q/49716257
tags question: http://stackoverflow.com/q/49642502

dataframe
tags question: http://stackoverflow.com/q/49677060
tags question: http://stackoverflow.com/q/49743414
tags question: http://stackoverflow.com/q/49661075
tags question: http://stackoverflow.com/q/49703974
tags question: http://stackoverflow.com/q/49699247
tags question: http://stackoverflow.com/q/49723491
tags question: http://stackoverflow.com/q/49675200
tags question: http://stackoverflow.com/q/49713860
tags question: http://stackoverflow.com/q/49751716
tags question: http://stackoverflow.com/q/49614328
tags question: http://stackoverflow.com/q/49636251
tags question: http://stackoverflow.com/q/49600157
tags question: http://stackoverflow.com/q/49692483
tags question: http://stackoverflow.com/q/49689723
tags question: http://stackoverflow.com/q/49749928
tags question: http://stackoverflow.com/q/49608088
tags question: http://stackoverflow.com/q/49702021
tags question: http://stackoverflow.com/q/49736311
tags question: http://stackoverflow.com/q/49640298
tags question: http://stackoverflow.com/q/49754509
tags question: http://stackoverflow.com/q/49697056
tags question: http://stackoverflow.com/q/49619194
tags question: http://stackoverflow.com/q/49717720
tags question: http://stackoverflow.com/q/49639619
tags question: http://stackoverflow.com/q/49711509
tags question: http://stackoverflow.com/q/49662291
tags question: http://stackoverflow.com/q/49627687
tags question: http://stackoverflow.com/q/49709405
tags question: http://stackoverflow.com/q/49691983
tags question: http://stackoverflow.com/q/49691923
tags question: http://stackoverflow.com/q/49675390
tags question: http://stackoverflow.com/q/49739639
tags question: http://stackoverflow.com/q/49639579
tags question: http://stackoverflow.com/q/49680490
tags question: http://stackoverflow.com/q/49678663
tags question: http://stackoverflow.com/q/49731494
tags question: http://stackoverflow.com/q/49746787
tags question: http://stackoverflow.com/q/49602592
tags question: http://stackoverflow.com/q/49697045
tags question: http://stackoverflow.com/q/49636021
tags question: http://stackoverflow.com/q/49654350
tags question: http://stackoverflow.com/q/49683175
tags question: http://stackoverflow.com/q/49628250
tags question: http://stackoverflow.com/q/49733632
tags question: http://stackoverflow.com/q/49724962
tags question: http://stackoverflow.com/q/49620680
tags question: http://stackoverflow.com/q/49604146
tags question: http://stackoverflow.com/q/49701752
tags question: http://stackoverflow.com/q/49753182
tags question: http://stackoverflow.com/q/49696146
tags question: http://stackoverflow.com/q/49737267
tags question: http://stackoverflow.com/q/49651595
tags question: http://stackoverflow.com/q/49677788
tags question: http://stackoverflow.com/q/49737489
tags question: http://stackoverflow.com/q/49632508
tags question: http://stackoverflow.com/q/49659649
tags question: http://stackoverflow.com/q/49656864
tags question: http://stackoverflow.com/q/49702440
tags question: http://stackoverflow.com/q/49669129
tags question: http://stackoverflow.com/q/49625148
tags question: http://stackoverflow.com/q/49680613
tags question: http://stackoverflow.com/q/49662734
tags question: http://stackoverflow.com/q/49607526
tags question: http://stackoverflow.com/q/49755027
tags question: http://stackoverflow.com/q/49696135
tags question: http://stackoverflow.com/q/49703873
tags question: http://stackoverflow.com/q/49629330
tags question: http://stackoverflow.com/q/49677717
tags question: http://stackoverflow.com/q/49748498
tags question: http://stackoverflow.com/q/49689608
tags question: http://stackoverflow.com/q/49735683
tags question: http://stackoverflow.com/q/49662807
tags question: http://stackoverflow.com/q/49615816
tags question: http://stackoverflow.com/q/49652404
tags question: http://stackoverflow.com/q/49669492
tags question: http://stackoverflow.com/q/49682673
tags question: http://stackoverflow.com/q/49703513
tags question: http://stackoverflow.com/q/49754676
tags question: http://stackoverflow.com/q/49656991
tags question: http://stackoverflow.com/q/49675300

http://stackoverflow.com/q/49730540
possible better answer: http://stackoverflow.com/a/49730681
downvote count: 2
accepted answer: http://stackoverflow.com/a/49730700
linked to: http://stackoverflow.com/q/13884177
has answer: http://stackoverflow.com/a/49730700
favorite count: 0
type: Question
has body: my question is about algorithms for extract data from 2 list of instances which share same ID. Here is a example: ClassA has 2 attributes: ID and info, classB has 1 attribute: ID listA listB instanceA1 instanceB1 instanceA2 instanceB2 instanceA3 instanceA4 what I did is very simple IDs_listB = [l.ID for l in listB] out_tab=[] for line in listA: if line.ID in IDs_listB: out_tab.append(line) But this way become very slow and heavy for large data, if listA has N lines and M lines for listB, O(N*M) the total complexity is too much...... I am thinking of cython or a automate, but is there any way better to so this job? thank you
tagged with: algorithm
tagged with: python
has answer: http://stackoverflow.com/a/49730681
score: -2
has comment: http://stackoverflow.com/comment/86474651
has title: better way to extract item of list A which contain ID from list B?
has comment: http://stackoverflow.com/comment/86474682
has answer: http://stackoverflow.com/a/49732580
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86474672
answer count: 3
upvote count: 0

http://stackoverflow.com/q/49680611
has body: I have a list. For example: [0, 0, 1, 0, 0, 1, 0] I'd like to know what is the most effective way to count the 1 -> 0 transitions. In this case for example the answer is 2 (in the 2-3 and in the 5-6 positions) I tried the following: stat=[0, 0, 1, 0, 0, 1, 0] pair1=stat[:-1] pair2=stat[1:] result=len([i for i in zip(pair1, pair2) if i==(1,0)]) I'm wondering if there is a better way
favorite count: 0
possible better answer: http://stackoverflow.com/a/49680736
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49680736
accepted answer: http://stackoverflow.com/a/49680750
has comment: http://stackoverflow.com/comment/86373015
tagged with: python
tagged with: counting
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: list
has title: Pythonic way to count specific neighbors in a list
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/49680872
has answer: http://stackoverflow.com/a/49680750

http://stackoverflow.com/comment/86509798
type: QuestionComment
comment on: http://stackoverflow.com/q/49747034
score: 0
has text: See my answer below. Why do you think that it needed just one line of code?
type: Comment

http://stackoverflow.com/comment/86409999
type: QuestionComment
comment on: http://stackoverflow.com/q/49696044
type: Comment
score: 1
has text: It is possible that your csv file has some invalid characters, such as non utf 8 data.

http://stackoverflow.com/q/49740343
has title: Python's plotly graph does not contain all the values
has comment: http://stackoverflow.com/comment/86495285
has answer: http://stackoverflow.com/a/49740559
has body: The following code is supposed to plot a graph using plotly library based on two lists: ambTime as X-Axes and domv1R1Temps as Y-Axes. The code is the following: import plotly.graph_objs as go import plotly.offline as ply from plotly import tools ambTime = ['10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:42.951', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:32:53.117', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:03.273', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:13.428', '10:33:23.584', '10:33:23.584', '10:33:23.584', '10:33:23.584', . . . . #This list contains 588 items. I shortened the list for the sake of time . . . . '10:35:47.713', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:35:57.884', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.695', '10:36:08.742', '10:36:08.742', '10:36:08.742'] domv1R1Temps = ['27', '27', '27', '27', '27', '27', '27', '27', '27', '28', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27', '27'] Trace1 = go.Scatter(x= ambTime,y = domv1R1Temps, name='DOMV1 R1 Temperatures') ambData =…
type: Question
tagged with: graph
has answer: http://stackoverflow.com/a/54718295
answer count: 2
upvote count: 1
type: UnansweredQuestion
favorite count: 0
tagged with: list
downvote count: 0
score: 1
tagged with: plotly
tagged with: python

http://stackoverflow.com/comment/86427034
comment on: http://stackoverflow.com/q/49683445
type: QuestionComment
has text: Thank you for the tip, added to Github. @ducminh I am new to Stack Overflow.
score: 0
type: Comment

http://stackoverflow.com/comment/86513465
comment on: http://stackoverflow.com/q/49669909
has text: What does your dictionary contain? Integers, floats, strings, a mixture?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86508649
comment on: http://stackoverflow.com/q/49747045
type: Comment
has text: sorry, just finished adding. each of the separateFuncs are pre-built off of pre-existing data; scipy.interpolate returns them as function objects.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86237860
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49615346
has text: Seems like new_obj.__setattr__(key,value) is working. Any other suggestions.
score: 0

http://stackoverflow.com/comment/86465137
has text: the time-series can span upto 2 years. However, that approach sounds hacky
type: QuestionComment
comment on: http://stackoverflow.com/q/49725631
score: 0
type: Comment

http://stackoverflow.com/comment/86329455
has text: Ahh, so if I use that and use exclusively TemporaryUploadedFiles I'll at least get it working. Thanks! That at least gets it working. Would be nice to have a way to do it with both InMemoryUploadedFiles and local files.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49658433

http://stackoverflow.com/comment/86237260
has text: Thansk @zwer, I added the reason why to the question. I tried doing what you suggested and the python interpreter still does not accept the '\n' passed to it as an end-of-line instruction to then execute the code. This does work when using the same set-up to remote into a Linux machine via ssh.
score: 0
comment on: http://stackoverflow.com/q/49612151
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49644460
type: Answer
has body: In keras each model has a layers attribute in which you can reuse the layers for rebuilding the model. Reusing those layers will result in weight sharing. There are two solution to your problem: In your second model build a new output layer with the right amount of output neurons which don't have weight sharing. (Not exactly what you want but easy to implement) Also you might want to freeze the previous layer depending on your usecase. Build a custom loss function. This will heavily depend on which loss function you use at the moment. But the trick is to slice your predictions, e.g. y_pred[:, :-2](the first dimension is the batch size). I personally wouldn't recommend the second approach. If you use activation function like softmax the weights corresponding to the the unused output neurons might still be updated. Also there is the possibility to somehow get the weights of the last layer, slice them and rebuilding a new layer with the right output. But this could get really ugly.
answers question: http://stackoverflow.com/q/49644124
score: 0

http://stackoverflow.com/q/49741469
type: Question
tagged with: python-3.x
tagged with: anaconda
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86587224
tagged with: spyder
tagged with: python
has body: Python 3.5 environment is installed on anaconda in Win10 system. When I try to launch Spyder, python.exe crashes. On the terminal, it shows [4596:5756:0409/160956.599:ERROR:broker_win.cc(59)] Error reading broker pipe: The pipe has ended (0x6D) [7064:1908:0409/160956.599:ERROR:broker_win.cc(59)] Error reading broker pipe: The pipe has ended (0x6D) However, when I change to the Python 3.6 environment, Spyder works normally. Does anyone has some ideas to fix the "broken pipe" issue? The whole story is like that. I want to install PIL package on Python 3.5 environment previously. Unfortunately, I use the wrong command "conda install PIL". As a result, python 2.7 is introduced in 3.5 environment. I guess the broken pipe comes from this operation. Then I tried to uninstall Spyder, python 3.5 and anaconda, but nothing works.
score: 0
has answer: http://stackoverflow.com/a/64045274
answer count: 1
has title: Python crashes when opening Spyder with python 3.5
has comment: http://stackoverflow.com/comment/86735899

http://stackoverflow.com/a/49613604
answers question: http://stackoverflow.com/q/49613525
upvote count: 4
score: 4
downvote count: 0
has body: Regex would work, or a simple split: short_version_string = '.'.join(version_string.split('.')[:2]) Or this, though it only works in Python 3: major, minor, *_ = version_string.split('.')
type: Answer

http://stackoverflow.com/q/49689748
has comment: http://stackoverflow.com/comment/86391018
has answer: http://stackoverflow.com/a/55844385
answer count: 3
tagged with: key
score: -6
tagged with: enter
downvote count: 7
favorite count: 0
type: Question
has title: how to include "enter key" in python
has body: import subprocess path = '/home/test/net.keystore' text = subprocess.Popen(['keytool', '-list', '-v', '-keystore', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) file = text.stdout.read().decode().splitlines() print file through subprocess i trying to fetch keystore certificate details I don't know password for keystore. If i press "enter key" twice then output is processing Is there any way to automate "Enter key" in python?
has comment: http://stackoverflow.com/comment/86391199
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50007069
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86393809
has answer: http://stackoverflow.com/a/76389791
has comment: http://stackoverflow.com/comment/86391027

http://stackoverflow.com/q/49654772
has body: I have the following List: List (user1,user2,user3,user4,user5, user...n) I need to show it like the following image: I don't know how to to take 3 users from list on each iteration to force to each row to has 3 users. Something like the following: {% for user,user2,user3 in user_list %} {{user.id}} {{user2.id}} {{user3.id}} {% endfor %}
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
has title: Django read 3 variables at once from list
answer count: 1
linked to: http://stackoverflow.com/q/845227
tagged with: django
accepted answer: http://stackoverflow.com/a/49655134
linked to: http://stackoverflow.com/q/11679411
has comment: http://stackoverflow.com/comment/86319291
type: Question
has answer: http://stackoverflow.com/a/49655134
has comment: http://stackoverflow.com/comment/86319169
has comment: http://stackoverflow.com/comment/86319102

http://stackoverflow.com/a/49664196
has body: The code will only fluke out and work if you enter in exactly two students. The main issue is a misunderstanding of the for loop at the end. for x, y in [1,2],[4,3]: print(x,y) Will print 1,2 4,3 It will not print 1,4 2,3 as you would like. This answers why you see incorrect formatting when you enter exactly two students. You'll want to use zip to join the two lists as pointed out in another answer. zip([1,2],[4,3]) will equal [(1,4),(2,3)] so your for loop will work as intended.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49664085

http://stackoverflow.com/comment/86613574
has text: https://docs.anaconda.com/anaconda/ says: *Anaconda2 includes Python 2.7 and Anaconda3 includes Python 3.6. However, it does not matter which one you download, because you can create new environments that include any version of Python packaged with `conda`.* There's no need to have more than one installation and it may mess up paths and so on if you do.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49735311
score: 0

http://stackoverflow.com/comment/135278650
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49643525
type: AnswerComment
has text: Took me a bit to puzzle this out, but I had to add Python to my path on an Macbook M1. `export PATH="/Users/hss151/Library/Python/3.9/bin:$PATH"` This was a bit unexpected. (Be sure you restart your terminal session in your IDE or source your .zprofile file.)

http://stackoverflow.com/comment/86396096
has text: @PauloAlmeida ok but how to do it like django admin?any link or example for doing this?
type: Comment
comment on: http://stackoverflow.com/q/49691443
score: 0
type: QuestionComment

http://stackoverflow.com/a/49683765
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49683437
answers question: http://stackoverflow.com/q/49683437
has comment: http://stackoverflow.com/comment/86379520
score: 1
type: Answer
has body: I deviated somewhat from your original code -- mostly because the intricacies of using a custom estimator to achieve your desired column select transformation proved to be too much overhead for me. This is my solution: from sklearn.datasets import california_housing from sklearn.pipeline import Pipeline from sklearn.linear_model import Ridge from sklearn.model_selection import GridSearchCV import pandas as pd from sklearn.preprocessing import FunctionTransformer cal_house = california_housing.fetch_california_housing() data = cal_house['data'] names = cal_house['feature_names'] df = pd.DataFrame(data, columns=names) df['houseval'] = cal_house['target'] def keep_columns(X, columns=("MedInc", "HouseAge")): column_indices = [ names.index(name) for name in columns ] return X[:, column_indices] pipe = Pipeline([ ("colselect", FunctionTransformer(keep_columns)), ("Ridge", Ridge()), ]) gridsearch = GridSearchCV( cv=5, scoring='r2', param_grid={ 'colselect__inv_kw_args': [ {"columns": columns} for columns in [ ['MedInc', 'HouseAge'], ['MedInc', 'Population', 'Latitude'], ['MedInc', 'AveRooms', 'AveOccup'] ] ], 'Ridge__alpha': [0.001, 0.01, 0.1, 1, 10] }, estimator=pipe ) X = df.drop('houseval', axis=1).values y = df.loc[:, 'houseval'].values gridsearch.fit(X=X, y=y) The main issues with your code: Using a custom class in the pipeline to achieve your transformation is excessive -- it is basically just an array access. Your transformation code in the class assumed a DataFrame, but gridsearch passes numpy.array objects instead. In this numpy array, accesses need to be done by index, so my code calculates these indices from your feature names array names. A custom estimator requires you to provide a method to copy estimators that must ensure proper copying of all parameters, otherwise it appears as though they become None, since sklearn.model_selection.GridSearchCV attempts to copy them without deep copy.

http://stackoverflow.com/comment/86246685
comment on: http://stackoverflow.com/a/49619689
score: 0
type: AnswerComment
has text: can you show that as an example on how can I create the JS module and pass parameter to it?
type: Comment

http://stackoverflow.com/q/49680490
has body: I'm writing a class definition to accomplish the following tasks: 1) Constructor: accepts a filename of a .csv file as an argument, creates a data frame from the information in the file and stores this permanently in the object, sets column names for the data frame, sets the index to the individual's name. The internal data frame is a private attribute - do not change this. 2) __in_frame: private method which checks if a contact exists in the data frame, based on the name (You do not need to modify this, but you may need to use it in other methods) 3) get_contact_info: accepts a name as an argument, returns a list with the phone number and email for that contact, you must consider the case where the user requests a contact that doesn't exist 4) get_phone: accepts a name as an argument, returns the phone number for that contact, you must consider the case where the user requests a contact that doesn't exist 5) get_email: accepts a name as an argument, returns the email for that contact, you must consider the case where the user requests a contact that doesn't exist 6) get_all_phones: takes no arguments, returns the Series containing all of the phone numbers in the data set 7) get_all_emails: takes no arguments, returns the Series containing all of the emails in the data set 8) add_change_contact: takes a name, phone, and email as arguments, should add the contact to the data frame if it is not already there, otherwise should modify the existing contact 9) delete_contact: accepts a name as an argument and deletes the contact from the data frame, you must consider the case where the user requests a contact that doesn't exist 10) __str__: return a string representation of the internal data frame Here's my following code: import pandas as pd class Contact_Frame: def __init__(self, filename): self.__frame = pd.read_csv(filename) self.__frame.columns = ['Name','Phone','Email'] self.__frame.set_index('Name') def __in_frame(self, name): return name in self.__frame.index def …
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49680596
has answer: http://stackoverflow.com/a/49680596
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86372968
answer count: 1
has title: Errors in class definition using data frame
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/88067547
comment on: http://stackoverflow.com/a/49742726
score: 0
type: AnswerComment
has text: this is not really a solution, just a list of things you tried. please only mark answers that are generally applicable or address the issue specifically
type: Comment

http://stackoverflow.com/comment/86417298
score: 0
type: Comment
has text: @PatrickArtner `"*******---".rfind("*")` although if you can mix the characters, ala `"***---***"` a more complex solution is needed.
type: AnswerComment
comment on: http://stackoverflow.com/a/49701538

http://stackoverflow.com/q/49738443
has comment: http://stackoverflow.com/comment/86491319
type: Question
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49738477
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49738520
has title: Convert string array that contains '[' , ']' to int array
answer count: 3
accepted answer: http://stackoverflow.com/a/49738477
downvote count: 0
has comment: http://stackoverflow.com/comment/86491442
has body: I'm attempting to convert an array of strings to array of floats using : arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' a1 = arr_str.split() [int(x) for x in a1] but throws error : &lt; ipython-input-57-f7f1eaba7ebd&gt; in &lt;listcomp&gt;(.0) 3 a1 = arr_str.split() 4 ----&gt; 5 [int(x) for x in a1] 6 7 # for a in arr_str.split(): ValueError: invalid literal for int() with base 10: '[1' Should pre-process the string and remove '[' and ']' ?
has answer: http://stackoverflow.com/a/49738482
possible better answer: http://stackoverflow.com/a/49738482
favorite count: 0

http://stackoverflow.com/q/49608041
linked to: http://stackoverflow.com/q/33818113
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/49003798
tagged with: python
duplicate of: http://stackoverflow.com/q/42276431
has answer: http://stackoverflow.com/a/49608103
duplicate of: http://stackoverflow.com/q/33818113
has title: Adding to a view of a numpy array
has body: &gt;&gt;&gt; a = np.array([0, 0]) &gt;&gt;&gt; a[[0, 0, 1, 1]] + [1, 2, 3, 4] array([1, 2, 3, 4]) &gt;&gt;&gt; a[[0, 0, 1, 1]] += [1, 2, 3, 4] &gt;&gt;&gt; a array([2, 4]) I understand that a[[0, 0, 1, 1]] returns a view of a, whose first two elements point to a[0] and last two elements point to a[1]. Now what if I want to get a = [3, 7]? Which is to say, what is the easiest way to accomplish the following? a = [0, 0] indices = [0, 0, 1, 1] values_to_add = [1, 2, 3, 4] for i in indices: a[i] += values_to_add[i]
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/86260492
type: Comment
type: QuestionComment
has text: @Schorsch its <class 'str'> but its only number
score: 0
comment on: http://stackoverflow.com/q/49626599

pandas
tags question: http://stackoverflow.com/q/49662325
tags question: http://stackoverflow.com/q/49631870
tags question: http://stackoverflow.com/q/49664978
tags question: http://stackoverflow.com/q/49702465
tags question: http://stackoverflow.com/q/49740139
tags question: http://stackoverflow.com/q/49754293
tags question: http://stackoverflow.com/q/49642057
tags question: http://stackoverflow.com/q/49702696
tags question: http://stackoverflow.com/q/49744913
tags question: http://stackoverflow.com/q/49728421
tags question: http://stackoverflow.com/q/49682673
tags question: http://stackoverflow.com/q/49703513
tags question: http://stackoverflow.com/q/49754676
tags question: http://stackoverflow.com/q/49656991
tags question: http://stackoverflow.com/q/49613734
tags question: http://stackoverflow.com/q/49602842
tags question: http://stackoverflow.com/q/49663958
tags question: http://stackoverflow.com/q/49675300
tags question: http://stackoverflow.com/q/49704687
tags question: http://stackoverflow.com/q/49649215
tags question: http://stackoverflow.com/q/49710393
tags question: http://stackoverflow.com/q/49641907
tags question: http://stackoverflow.com/q/49640490
tags question: http://stackoverflow.com/q/49637270
tags question: http://stackoverflow.com/q/49666426
tags question: http://stackoverflow.com/q/49721835
tags question: http://stackoverflow.com/q/49700794
tags question: http://stackoverflow.com/q/49746711
tags question: http://stackoverflow.com/q/49697830
tags question: http://stackoverflow.com/q/49729735
tags question: http://stackoverflow.com/q/49727535
tags question: http://stackoverflow.com/q/49668982
tags question: http://stackoverflow.com/q/49744942
tags question: http://stackoverflow.com/q/49668709
tags question: http://stackoverflow.com/q/49616277
tags question: http://stackoverflow.com/q/49658165
tags question: http://stackoverflow.com/q/49737760
tags question: http://stackoverflow.com/q/49665984
tags question: http://stackoverflow.com/q/49695681
tags question: http://stackoverflow.com/q/49711661
tags question: http://stackoverflow.com/q/49680412
tags question: http://stackoverflow.com/q/49602439
tags question: http://stackoverflow.com/q/49739183
tags question: http://stackoverflow.com/q/49755687
tags question: http://stackoverflow.com/q/49742196
tags question: http://stackoverflow.com/q/49744674
tags question: http://stackoverflow.com/q/49619897
tags question: http://stackoverflow.com/q/49644188
tags question: http://stackoverflow.com/q/49684037
tags question: http://stackoverflow.com/q/49705519
tags question: http://stackoverflow.com/q/49645667
tags question: http://stackoverflow.com/q/49690973
tags question: http://stackoverflow.com/q/49621727
tags question: http://stackoverflow.com/q/49604224
tags question: http://stackoverflow.com/q/49673005
tags question: http://stackoverflow.com/q/49709237
tags question: http://stackoverflow.com/q/49695751
tags question: http://stackoverflow.com/q/49608656
tags question: http://stackoverflow.com/q/49607418
tags question: http://stackoverflow.com/q/49712577
tags question: http://stackoverflow.com/q/49685846
tags question: http://stackoverflow.com/q/49676047
tags question: http://stackoverflow.com/q/49733918
tags question: http://stackoverflow.com/q/49645171
tags question: http://stackoverflow.com/q/49750172
tags question: http://stackoverflow.com/q/49715104
tags question: http://stackoverflow.com/q/49604736
tags question: http://stackoverflow.com/q/49634468
tags question: http://stackoverflow.com/q/49643751
tags question: http://stackoverflow.com/q/49738040
tags question: http://stackoverflow.com/q/49601979
tags question: http://stackoverflow.com/q/49683328
tags question: http://stackoverflow.com/q/49725112
tags question: http://stackoverflow.com/q/49697093
tags question: http://stackoverflow.com/q/49732049
tags question: http://stackoverflow.com/q/49721251
tags question: http://stackoverflow.com/q/49714337
tags question: http://stackoverflow.com/q/49724908
tags question: http://stackoverflow.com/q/49675071
tags question: http://stackoverflow.com/q/49719017

http://stackoverflow.com/comment/86471024
type: Comment
type: QuestionComment
has text: Possible duplicate of [What does \`Fatal Python error: PyThreadState\_Get: no current thread\` mean?](https://stackoverflow.com/questions/35640529/what-does-fatal-python-error-pythreadstate-get-no-current-thread-mean)
score: 0
comment on: http://stackoverflow.com/q/49728251

http://stackoverflow.com/comment/86272842
type: QuestionComment
has text: Look carefully at the code around `for form in formset.save(commit=False):`. Is that where you think the items should be saved? Add some printing or logging and make sure that every line does what you think it should do.
score: 0
comment on: http://stackoverflow.com/q/49604076
type: Comment

isinstance
tags question: http://stackoverflow.com/q/49624055
tags question: http://stackoverflow.com/q/49612815
tag name: isinstance
type: Tag
tags question: http://stackoverflow.com/q/49677311

http://stackoverflow.com/comment/86326342
comment on: http://stackoverflow.com/a/49630787
score: 0
type: AnswerComment
has text: Have a look at https://stackoverflow.com/questions/25694234/bulk-update-in-sqlalchemy-core-using-where. Using a Core `update()` construct with bindparams you could skip entirely fetching the ids and merging. Instead you'd simply construct an UPDATE statement with a WHERE clause using the `hash_val`.
type: Comment

http://stackoverflow.com/comment/86416384
type: Comment
type: AnswerComment
has text: Thank you! Makes perfect sense. Somehow missed relativedelta while searching for approaches
score: 1
comment on: http://stackoverflow.com/a/49701043

http://stackoverflow.com/comment/86376177
comment on: http://stackoverflow.com/q/49681973
has text: What docker image are you using? Maybe this will solve the problem: [https://github.com/pytorch/text/issues/77#issuecomment-319206865](https://github.com/pytorch/text/issues/77#issuecomment-319206865)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50045559
has body: The solution i found is: Create threads to run your functions outside the mainloop() The problem happens when we have any kind of loop going inside de mainloop() thread. i used that function to solve my problem Define your own name, mine is endTrue def endTrue(): global flag send_process = Thread(target=begin) send_process.start() flag = False variable to control the loop inside the new thread global flag target = function you want to execute in a side thread send_process = Thread(target=begin) start the new thread send_process.start() variable used to control the loop flag = False Hope this help someone in the future, gl and hf!
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49737596
answers question: http://stackoverflow.com/q/49737596
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86446908
comment on: http://stackoverflow.com/q/49716597
score: 0
has text: I don't understand your desired data set - can you elaborate?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49682204
has title: How to integrate object space acceleration to world space position (2D)
upvote count: 2
tagged with: numerical-methods
downvote count: 0
has comment: http://stackoverflow.com/comment/86510578
type: AnsweredQuestion
score: 2
tagged with: inertial-navigation
tagged with: differential-equations
tagged with: physics
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49759522
has body: I want to double integrate 2D acceleration data in object coordinates to get 2D position in world coordinates. The object always points in the direction of velocity (assume e.g. a train). So I tried to numerically integrate the acceleration values with velocity verlet integration, changing the direction at each step to the previous velocity in world coordinates, provided by the velocity verlet algorithm: import numpy as np from math import sqrt from matplotlib import pyplot as plt def rotate(a, newXAxis): r = newXAxis normX = r / sqrt(np.dot(r.T,r)) normY = [-normX[1], normX[0]] b = np.dot(np.array([normX, normY]).T, a) return(b) """return true if v > 1 km/h or any speed given""" def isMoving(deltaXPosition, deltaYPosition, deltaTime, fasterThankmh=1.0): x = deltaXPosition y = deltaYPosition t = deltaTime if t*t == 0.: return False if hasattr(x, "__len__"): x = x[0] if hasattr(y, "__len__"): y = y[0] if hasattr(t, "__len__"): t = t[0] speed = float(fasterThankmh) return((x*x + y*y) / (t*t) > 0.077160*speed*speed) def velocity_verlet_integration(Xacc, Yacc, x0=0., y0=0., vx_0=0, vy_0=0, forward=np.array([1.0, 0.0])): vx = np.zeros(len(Xacc)) vy = np.zeros(len(Xacc)) x = np.zeros(len(Xacc)) y = np.zeros(len(Xacc)) x[0] = x0 y[0] = y0 vx[0] = vx_0 vy[0] = vy_0 for i in range(len(Xacc)-1): dt = Xacc[i+1]-Xacc[i] a = rotate(Yacc[i,:], forward) x[i+1] = x[i] + vx[i]*dt + 1.0/2.0*a[0]*dt*dt y[i+1] = y[i] + vy[i]*dt + 1.0/2.0*a[1]*dt*dt if isMoving(x[i+1]-x[i], y[i+1]-y[i], dt): forward = np.array([x[i+1]-x[i], y[i+1]-y[i]]) aNext = rotate(Yacc[i+1,:], forward) vx[i+1] = vx[i] + dt*(a[0] + aNext[0])/2 vy[i+1] = vy[i] + dt*(a[1] + aNext[1])/2 return x, y Testing this with a simple circular motion with: """test circle""" centripetal=-0.2 N = 0.01 xCircle = np.array(range(int(100*10**N)))/float(10**N) yCircle = np.array([[0.0, centripetal] for i in xCircle]) xvvi, yvvi = velocity_verlet_integration(xCircle, yCircle, 0., 0., 1., 0.) #plot it plt.plot(xvvi, yvvi, ".-", label='po…
favorite count: 0
has comment: http://stackoverflow.com/comment/86516107
type: Question
has answer: http://stackoverflow.com/a/49759522

http://stackoverflow.com/q/49733668
score: 4
possible better answer: http://stackoverflow.com/a/49733789
has title: Ternary operator behavior
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49733789
has body: I recently started using ternary operator but I encountered a case where I needed to use multiple ternary operator in the same line, but they didn't seem to work as I expected. Can someone please give a explanation why those line give different result. x = 1 if True else 2 + 3 if False else 4 # x = 1, I expected 5 x = (1 if True else 2) + (3 if False else 4) # x = 5 If I add parentheses I get the expected result, but I don't understand what the parentheses change. And if I rotated the addition, without the parentheses, I get the correct value. 3 if False else 4 + 1 if True else 2 # x = 5 However, I get wrong result if the second ternary operator is False: 3 if False else 4 + 1 if False else 2 # x = 5 # x = 2 ??? Is it because you shouldn't multiple ternary operator in the same line, or is their an other reason?
answer count: 3
tagged with: ternary-operator
favorite count: 0
accepted answer: http://stackoverflow.com/a/49733771
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49733755
has answer: http://stackoverflow.com/a/49733771
downvote count: 0
tagged with: python

http://stackoverflow.com/q/49613958
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86234445
has comment: http://stackoverflow.com/comment/86234480
has answer: http://stackoverflow.com/a/49613997
score: 4
tagged with: string-concatenation
has title: How to join elements as strings with a delimiter from a group of arrays column-wise
has body: I have the following arrays (all the same length): array_1=[1,2,3] array_2=[4,5,6] array_3=[7,8,9] What I need is to concatenate each element in both arrays to get: array_4=['1-4-7','2-5-8','3-6-9'] This has to be done over about 30000 records, so I was looking for something compact.
has answer: http://stackoverflow.com/a/49614234
has answer: http://stackoverflow.com/a/49614198
has comment: http://stackoverflow.com/comment/86234416
downvote count: 1
tagged with: python
answer count: 4
favorite count: 0
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/49615434

http://stackoverflow.com/q/49656808
favorite count: 0
has comment: http://stackoverflow.com/comment/86327509
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86333676
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: python-2.7
answer count: 0
tagged with: pytest
has comment: http://stackoverflow.com/comment/86357876
has comment: http://stackoverflow.com/comment/86345644
downvote count: 0
has body: In my python unit tests, test_B depends on test_A. However, when I run the tests with pytest, it always SKIPS test_B with this message: SKIP [1] /home/shuklas/python3.6/site-packages/pytest_dependency.py:88: test_B depends on test_A What am i missing? @pytest.mark.dependency() def test_A(): .... @pytest.mark.dependency(depends=['test_A']) def test_B(): ....
has title: pytest skips test because it depends on another test
has comment: http://stackoverflow.com/comment/86373193

http://stackoverflow.com/comment/86329750
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49660097
has text: You appear to have confused `+=` with `=+`

http://stackoverflow.com/comment/86429482
has text: Good luck on your Python journey! :)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49707269
type: Comment

http://stackoverflow.com/q/49663950
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49664053
has comment: http://stackoverflow.com/comment/86337842
linked to: http://stackoverflow.com/q/8384737
tagged with: filenames
has body: I'm currently working with tkinter in Python (beginner), and I'm writing a small applet that requires one of the labels to dynamically change based on what the name of a selected .csv file is, without the '.csv' tag. I can currently get the filepath to the .csv file using askopenfilename(), which returns a string that looks something like "User/Folder1/.../filename.csv". I need some way to extract "filename" from this filepath string, and I'm a bit stuck on how to do it. Is this simply a regex problem? Or is there a way to do this using string indices? Which is the "better" way to do it? Any help would be great. Thank you. EDIT: The reason I was wondering if regex is the right way to do it is because there could be duplicates, e.g. if the user had something like "User/Folder1/hello/hello.csv". That's why I was thinking maybe just use string indices, since the file name I need will always end at [:-4]. Am I thinking about this the right way?
tagged with: python
tagged with: regex
has title: Should I Use Regex to Get a File Name?
score: 2
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2
answer count: 1
downvote count: 0
tagged with: string
accepted answer: http://stackoverflow.com/a/49664053
has comment: http://stackoverflow.com/comment/86337753

http://stackoverflow.com/comment/86223225
comment on: http://stackoverflow.com/a/49608166
score: 0
has text: @AmiHeines A single loop is more efficient than two list comprehensions, so it's justifiable to use a loop here.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49610993
tagged with: django-forms
linked to: http://stackoverflow.com/q/34687334
type: Question
has body: I don't understand how to build a specific form in Django. First of all here are my models: class Category(models.Model): name = models.CharField(max_length=200, unique=True) class Assessment(models.Model): name = models.CharField(max_length=200) pub_date = models.DateTimeField(verbose_name=_('date published'), default=timezone.now) classgroup = models.ForeignKey(ClassGroup, verbose_name=_('class'), on_delete=models.CASCADE, related_name='+') category = models.ManyToManyField(Category, through='AssessmentScale', through_fields=('assessment', 'category'),) total = models.IntegerField() class AssessmentScale(models.Model): assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) value = models.IntegerField() I would like to have a form like this html form. Actually, an assessment scale is sub-divided into different categories. So when I create an assessment, I'd like have a form field for each category allowing to add a value via my custom intermediary model AssessmentScale. But I really don't know the Django way to build this form. I read this post, which is similar I think, and someone advised the use of Inline model formsets. But I don't understand how to solve my problem with the latter. Could you help me?
has title: How to create a form field for every foreignkey in manytomany relationship in Django
tagged with: django
accepted answer: http://stackoverflow.com/a/50355246
tagged with: python
has answer: http://stackoverflow.com/a/50355246
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/comment/112265724
type: AnswerComment
has text: Glad to find this. I actually already had a bash script calling python, but it was using "exec", so python became proc id 1. Removed the exec, and zombies are gone
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49756925

http://stackoverflow.com/q/49715237
has body: I want to use this cURL command in (python with pycurl): curl -X POST --header "Authorization: key=AAAAWuduLSU:APA91bEStixxx" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"to" : "fC6xEWZwcu0:APA91xxx", "priority" : "high", "notification" : { "body" : "Background Message", "title" : "BG Title", "sound" : "default"}, "data" : { "title" : "FG Title", "message" : "Foreground Message" }}' My source code is like this import pycurl import re import io import json import requests data = {"to" : "fC6xEWZwcu0:APA91xxx", "priority" : "high", "notification" : { "body" : "Background Message", "title" : "BG Title", "sound" : "sound.mp3"}, "data" : { "title" : "FG Title", "message" : "Foreground Message" }} buffer = io.BytesIO() c = pycurl.Curl() c.setopt(c.URL, 'https://fcm.googleapis.com/fcm/send') c.setopt(c.POST, True) c.setopt(c.SSL_VERIFYPEER, False) c.setopt(pycurl.HTTPHEADER, [ 'Content-type:application/json charset=utf-8', 'Content-Length:0' 'Authorization: Basic key=AAAAWuduLSU:APA91bEStixxx' ]) c.setopt(c.WRITEDATA, buffer) ''' c.setopt(pycurl.HTTPBODY, [ 'test:test' ]) ''' print(buffer) # c.setopt(c.HEADERFUNCTION, header_function) c.perform() print('\n\nStatus: %d' % c.getinfo(c.RESPONSE_CODE)) print('TOTAL_TIME: %f' % c.getinfo(c.TOTAL_TIME)) c.close() body = buffer.getvalue() print(body)
accepted answer: http://stackoverflow.com/a/49716500
score: -3
has title: How to use cURL in python
tagged with: pyfcm
has comment: http://stackoverflow.com/comment/86443472
has comment: http://stackoverflow.com/comment/86443577
tagged with: python
tagged with: pycurl
tagged with: firebase
type: AnsweredQuestion
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/49716500
tagged with: curl
favorite count: 0
has comment: http://stackoverflow.com/comment/86443469
type: Question
has comment: http://stackoverflow.com/comment/86443478
upvote count: 0

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

http://stackoverflow.com/comment/86458006
comment on: http://stackoverflow.com/q/49721695
type: QuestionComment
score: 0
has text: requests doesnt retry nor have a timeout by default, as using a timeout would inform you about a potential (and the most likely, my oppinion) issue. Either catch the exception and retry later or you can go the more advanced route of a retry adapter. http://www.coglib.com/~icordasc/blog/2014/12/retries-in-requests.html
type: Comment

http://stackoverflow.com/q/49723769
linked to: http://stackoverflow.com/q/1732348
type: Question
has comment: http://stackoverflow.com/comment/86461252
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86462438
has body: I have a file which uses a xml schema. That looks like this: port=1521 user=test_user password=test_passwd 0 generatedlayout <widgets/> <rowstyles/> <fieldstyles/> </projectlayers> <properties> paswd user 5zdgf dgdgdgfdg <property key="labeling/textColorR" value="0"/> <property key="labeling/textTransp" value="0"/> <property key="labeling/upsidedownLabels" value="0"/> <property key="labeling/useSubstitutions" value="false"/> <property key="labeling/wrapChar" value=""/> <property key="labeling/xOffset" value="0"/> <property key="labeling/yOffset" value="0"/> <property key="labeling/zIndex" value="0"/> <property key="variableNames"/> <property key="variableValues"/> So I wanted to use python to delte the password and user part as well as the variables parts. I use the following code: import re with open('C:\myfile.txt') as oldfile, open('C:\myfile_withoutPW.txt', 'w') as newfile: oldText = oldfile.read() noPass = re.sub(r'(password=).*?(?=\s) ', '', oldText.rstrip()) noPass_noUser = re.sub(r'(user=).*?(?=\s) ', '', noPass.rstrip()) # fehlt noch newText = re.sub(re.escape(r'<property key="variableNames"/>'), '', noPass_noUser.rstrip()) newText = re.sub(re.escape(r'<property key="variableValues"/>'), '', newText.rstrip()) newfile.write(newText) This works, but not completly as I wanted it to, it deltes the parts but it leaves empty lines, like: <property key="labeling/wrapChar" value=""/> <property key="labeling/xOffset" value="0"/> <property key="labeling/yOffset" value="0"/> <property key="labeling/zIndex" value="0"/> 0 <featureBlendMo How can i solve this to completly delte those lines/parts form my txt file?
tagged with: regex
has comment: http://stackoverflow.com/comment/86467161
has comment: http://stackoverflow.com/comment/86462248
upvote count: 2
has answer: http://stackoverflow.com/a/49728250
answer count: 2
has title: Delte Specifc lines from file in python
score: 1
has comment: http://stackoverflow.com/comment/86462145
has comment: http://stackoverflow.com/comment/86467011
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49724153

http://stackoverflow.com/a/49612109
has body: You can decorate the post method of your class based view with name='post'. @method_decorator(auth0_login_required, name="post") class MyClass2(DetailView): ... def get(self, request, *args, **kwargs): ... def post(self, request, *args, **kwargs): ... Or you can decorate the post method directly. Since it's a method, you should still use method_decorator. class MyClass2(DetailView): ... def get(self, request, *args, **kwargs): ... @method_decorator(auth0_login_required) def post(self, request, *args, **kwargs): ... If you have a function based view, then you don't need to use method_decorator. @auth0_login_required def my_function_based_view(request, *args, **kwargs):
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49611488
accepted answer of: http://stackoverflow.com/q/49611488
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86231212

http://stackoverflow.com/comment/86471708
has text: What is this list input , is this the list of data we printed previously?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49728737

http://stackoverflow.com/comment/86479820
type: Comment
type: QuestionComment
has text: I'd go with a tentative "yes" for multiple inheritance, it can of course be a powerful tool. It's the kind of thing that gives you enough rope to hang yourself, but by following a couple of best practices and not being overzealous one can build amazing things. Learning about [method resolution order](http://python-history.blogspot.de/2010/06/method-resolution-order.html) is probably the best starting point.
comment on: http://stackoverflow.com/q/49731376
score: 1

python-2.7
tags question: http://stackoverflow.com/q/49748127
tags question: http://stackoverflow.com/q/49745307
tags question: http://stackoverflow.com/q/49744088
tags question: http://stackoverflow.com/q/49613734
tags question: http://stackoverflow.com/q/49706231
tags question: http://stackoverflow.com/q/49635526
tags question: http://stackoverflow.com/q/49628393
tags question: http://stackoverflow.com/q/49622152
tags question: http://stackoverflow.com/q/49640460
tags question: http://stackoverflow.com/q/49619732
tags question: http://stackoverflow.com/q/49645478
tags question: http://stackoverflow.com/q/49724714
tags question: http://stackoverflow.com/q/49726933
tags question: http://stackoverflow.com/q/49612151
tags question: http://stackoverflow.com/q/49649393
tags question: http://stackoverflow.com/q/49624932
tags question: http://stackoverflow.com/q/49744326
tags question: http://stackoverflow.com/q/49621811
tags question: http://stackoverflow.com/q/49624173
tags question: http://stackoverflow.com/q/49618352
tags question: http://stackoverflow.com/q/49691955
tags question: http://stackoverflow.com/q/49749808
tags question: http://stackoverflow.com/q/49690321
tags question: http://stackoverflow.com/q/49757063
tags question: http://stackoverflow.com/q/49699168
tags question: http://stackoverflow.com/q/49696885
tags question: http://stackoverflow.com/q/49718082
tags question: http://stackoverflow.com/q/49618983
tags question: http://stackoverflow.com/q/49676480
tags question: http://stackoverflow.com/q/49691232
tags question: http://stackoverflow.com/q/49729046
tags question: http://stackoverflow.com/q/49688094
tags question: http://stackoverflow.com/q/49734080
tags question: http://stackoverflow.com/q/49617180
tags question: http://stackoverflow.com/q/49725522
type: Tag
tags question: http://stackoverflow.com/q/49615153
tags question: http://stackoverflow.com/q/49673859
tags question: http://stackoverflow.com/q/49641241
tags question: http://stackoverflow.com/q/49629333
tags question: http://stackoverflow.com/q/49679486
tags question: http://stackoverflow.com/q/49665324
tags question: http://stackoverflow.com/q/49627457
tags question: http://stackoverflow.com/q/49663401
tags question: http://stackoverflow.com/q/49720780
tags question: http://stackoverflow.com/q/49619412
tags question: http://stackoverflow.com/q/49646871
tags question: http://stackoverflow.com/q/49608329
tags question: http://stackoverflow.com/q/49720878
tags question: http://stackoverflow.com/q/49612207
tags question: http://stackoverflow.com/q/49629390
tags question: http://stackoverflow.com/q/49606012
tags question: http://stackoverflow.com/q/49656116
tags question: http://stackoverflow.com/q/49702758
tags question: http://stackoverflow.com/q/49674960
tags question: http://stackoverflow.com/q/49651927
tags question: http://stackoverflow.com/q/49734759
tags question: http://stackoverflow.com/q/49699774
tags question: http://stackoverflow.com/q/49668168
tags question: http://stackoverflow.com/q/49601803
tags question: http://stackoverflow.com/q/49655566
tags question: http://stackoverflow.com/q/49627214
tags question: http://stackoverflow.com/q/49685677
tags question: http://stackoverflow.com/q/49661119
tags question: http://stackoverflow.com/q/49655444
tags question: http://stackoverflow.com/q/49701481
tags question: http://stackoverflow.com/q/49722777
tags question: http://stackoverflow.com/q/49734434
tags question: http://stackoverflow.com/q/49637808
tags question: http://stackoverflow.com/q/49727668
tags question: http://stackoverflow.com/q/49615380
tags question: http://stackoverflow.com/q/49617067
tags question: http://stackoverflow.com/q/49684815
tags question: http://stackoverflow.com/q/49631218
tags question: http://stackoverflow.com/q/49663355
tags question: http://stackoverflow.com/q/49689595
tags question: http://stackoverflow.com/q/49685882
tags question: http://stackoverflow.com/q/49606349
tags question: http://stackoverflow.com/q/49616485
tags question: http://stackoverflow.com/q/49655995

http://stackoverflow.com/q/49645806
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: I've run into a little problem lately, I'm using spyder to code, installed through anaconda, and I installed a custom numpy extension not available through anaconda: https://pypi.python.org/pypi/py_find_1st/1.1.1 The installation works fine, but every time I restart my computer, I'm not able to import it with spyder: ModuleNotFoundError: No module named 'utils_find_1st' Then, if I re-install it through the Visual Studio cmd, and restart spyder, it works fine, but it's a bit annoying having to do that everytime I restart my computer. Would anyone know what the issue is here? I'm not very experimented with extension on python, or how they work. Thanks! Logs of the CMD installation (I don't know if it's useful): D:\Chrome dl\py_find_1st-master\py_find_1st-master&gt;python setup.py install running install running bdist_egg running egg_info writing py_find_1st.egg-info\PKG-INFO writing dependency_links to py_find_1st.egg-info\dependency_links.txt writing top-level names to py_find_1st.egg-info\top_level.txt reading manifest file 'py_find_1st.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'py_find_1st.egg-info\SOURCES.txt' installing library code to build\bdist.win-amd64\egg running install_lib running build_py running build_ext creating build\bdist.win-amd64\egg creating build\bdist.win-amd64\egg\utils_find_1st copying build\lib.win-amd64-3.6\utils_find_1st\find_1st.cp36-win_amd64.pyd -&gt; build\bdist.win-amd64\egg\utils_find_1st copying build\lib.win-amd64-3.6\utils_find_1st\__init__.py -&gt; build\bdist.win-amd64\egg\utils_find_1st byte-compiling build\bdist.win-amd64\egg\utils_find_1st\__init__.py to __init__.cpython-36.pyc creating stub loader for utils_find_1st\find_1st.cp36-win_amd64.pyd byte-compiling build\bdist.win-amd64\egg\utils_find_1st\find_1st.py to find_1st.cpython-36.pyc creating build\bdist.win-amd64\egg\EGG-INFO copying py_find_1st.egg-info\PKG-INFO -&gt; build\bdist.win-amd64\egg\EGG-INFO copying py_find_1st.egg-in…
has comment: http://stackoverflow.com/comment/86300396
tagged with: python
has title: I need to re-install a numpy extension every time I restart my computer
has comment: http://stackoverflow.com/comment/86303465
score: 2
tagged with: anaconda
tagged with: python-module
has comment: http://stackoverflow.com/comment/86300995
favorite count: 0
has comment: http://stackoverflow.com/comment/86300787
type: Question
tagged with: numpy
tagged with: python-3.x

http://stackoverflow.com/q/49639152
has body: I am having trouble to convert json to CSV. I am kinda new to JSON parsing. All I want is to get from my JSON some "pretty" csv. So I can have data that I can read. I am trying f = csv.writer(open('data.csv', 'w+', encoding='utf-8', newline='')) for item in json_head: f.writerow(item) but all I get in data.csv is d,a,t,a i,n,c,l,u,d,e,d l,i,n,k,s m,e,t,a Json template that's in documentation looks like this { "data": { "type": "string", "id": "string", "attributes": { "createdAt": "string", "duration": 0, "gameMode": "string", "patchVersion": "string", "shardId": "string", "stats": {}, "tags": {}, "titleId": "string" }, "relationships": { "assets": { "data": [ { "type": "string", "id": "string" } ] }, "rosters": { "data": [ { "type": "string", "id": "string" } ] }, "rounds": {}, "spectators": {} }, "links": { "schema": "string", "self": "string" } }, "included": [ null ], "links": { "first": "string", "previous": "string", "self": "string", "next": "string" }, "meta": {} } And part of real JSON I received via API looks like this {"data": {"type":"match","id":"bdd8b91c-8866-47f1-b5ee-45de4163d3ad","attributes":{"createdAt":"2018-04-02T12:16:33Z","duration":1806,"gameMode":"squad-fpp","patchVersion":"","shardId":"pc-eu","stats":null,"tags":null,"titleId":"bluehole-pubg"},"relationships":{"assets":{"data":[{"type":"asset","id":"2609ba26-3674-11e8-b808-0a586466e20b"}]}, "rosters":{"data":[ {"type":"roster","id":"80a9215c-bed1-4c11-8ff7-e4c9d643befa"}, {"type":"roster","id":"1457bd01-80f9-45e3-b98f-aa9ea946f6b2"}]}, "rounds":{"data":[]},"spectators":{"data":[]}},"links":{"schema":"","self":"https://api.playbattlegrounds.com/shards/pc-eu/matches/bdd8b91c-8866-47f1-b5ee-45de4163d3ad"}}, "included":[ {"type":"participant","id":"f0d889c7-49e7-4c83-ac0b-d7f23d13e09f","attributes":{"actor":"","shardId":"pc-eu","stats":{"DBNOs":3,"assists":0,"boosts":2,"damageDealt":253.554047,"deathType":"byplayer","headshotKills":1,"heals":0,"killPlace":4,"killPoints":1182,"killPointsDelta":4…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86287019
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: Python JSON to CSV not working
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86286352
has comment: http://stackoverflow.com/comment/86286796
tagged with: python
has comment: http://stackoverflow.com/comment/86286764
has answer: http://stackoverflow.com/a/49639172
has comment: http://stackoverflow.com/comment/86286606
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86286721
answer count: 1
has comment: http://stackoverflow.com/comment/86286527

http://stackoverflow.com/a/49686456
has body: Option 1 dict(zip(zip(df['Column-1'], df['Column-2']), df['Column-3'])) {(1, 'A'): 'foo', (2, 'B'): 'bar'} Option 2 {(a, b): c for a, b, c in df.values} {(1, 'A'): 'foo', (2, 'B'): 'bar'}
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49686322

http://stackoverflow.com/q/49726646
tagged with: encoding
has title: Python encoding japanese characters
upvote count: 2
has answer: http://stackoverflow.com/a/49726871
has comment: http://stackoverflow.com/comment/86467537
tagged with: python
type: UnansweredQuestion
has body: I'm using python for code send request to server(crawl data). But parameter is japanese. I'm using str.encode(encoding='utf-8') for parameter sent, method post code request: response = requests.request(self.method, self.url,data=self.param.encode(encoding='Shift_JIS'), headers=headers) but it's result is wrong base on info network of developer tool. Example: right values: In: 千代田区 Out:%90%E7%91%E3%93c%8B%E6 In: 東京都 Out: %93%8C%8B%9E%93s If I use utf-8(wrong value): In:東京都 Out: \x93\x8c\x8b\x9e\x93s Can you please help me in this case! Thanks all!
downvote count: 1
has comment: http://stackoverflow.com/comment/86467370
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86474531
has comment: http://stackoverflow.com/comment/86467023
score: 1
tagged with: cjk

http://stackoverflow.com/comment/86423516
comment on: http://stackoverflow.com/q/49705106
type: Comment
type: QuestionComment
has text: Strings are immutable objects, you cannot change them in-place.You can instead do `s = 'ss' + s[2:]`.
score: 1

http://stackoverflow.com/q/49731376
has comment: http://stackoverflow.com/comment/86478374
favorite count: 0
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/86479177
has title: How to achieve Protocol Oriented Programming in Python?
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I'm new in Python programming with a strong background in Objective-C and Swift. One of the cool thing I love in Swift is the Protocol Oriented Programming with default implementation. I would like to know if it's possible to have the same behaviour in Python? I'm not sure if it would be a good solution because POP solve problems of the single inheritance but in python we can use multiple inheritance. The thing is that I've heard since the beginning of my programming journey that the multiple inheritance is bad. From what I think to do is to: Use a abstract class Implement some method of this abstract class Make a class inherit from the abstract class So I'm curious to know if people use POP in Python? And if yes how they do it?
linked to: http://stackoverflow.com/q/13646245
has comment: http://stackoverflow.com/comment/86478380
type: Question
has comment: http://stackoverflow.com/comment/86480860
tagged with: python
has comment: http://stackoverflow.com/comment/86479820
tagged with: swift-protocols

http://stackoverflow.com/comment/86357548
type: AnswerComment
score: 0
has text: The biggest problem with the nested lambda is that it incurs the overhead of an additional (user-defined) function call, which could be significant for large lists.
type: Comment
comment on: http://stackoverflow.com/a/49671991

http://stackoverflow.com/comment/86281555
type: AnswerComment
has text: @jameslarge you are correct and I was sloppy. Thanks for the clarification! After `join(timeout)` returns, one needs to call `is_alive` to check whether the thread is still running and (if it is) stop it -- ideally in a cooperative way [or forcefully](https://stackoverflow.com/q/323972/857390).
type: Comment
comment on: http://stackoverflow.com/a/49625323
score: 0

http://stackoverflow.com/q/49651927
score: 0
has comment: http://stackoverflow.com/comment/86312112
accepted answer: http://stackoverflow.com/a/49652391
has comment: http://stackoverflow.com/comment/86312338
has comment: http://stackoverflow.com/comment/86312250
has answer: http://stackoverflow.com/a/49652391
has answer: http://stackoverflow.com/a/49652269
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49656225
favorite count: 0
has comment: http://stackoverflow.com/comment/86312738
tagged with: beautifulsoup
type: Question
has title: Getting output 0 even if there are 25 same class
type: AnsweredQuestion
answer count: 5
has comment: http://stackoverflow.com/comment/86312150
tagged with: python
has answer: http://stackoverflow.com/a/49652192
possible better answer: http://stackoverflow.com/a/49652293
has comment: http://stackoverflow.com/comment/86312041
has body: Image of the HTML Link to the page I am trying to see how many of class are there on this page but the output is 0. And I have been using BeautifulSoup for a while but never saw such error. from bs4 import BeautifulSoup import requests result = requests.get("https://www.holonis.com/motivationquotes") c = result.content soup = BeautifulSoup(c) samples = soup.findAll("div", {"class": "ng-scope"}) print(len(samples)) Output 0 and I want the correct output at least more than 25
has answer: http://stackoverflow.com/a/49652293
tagged with: python-3.x
tagged with: python-2.7

http://stackoverflow.com/a/54270881
has body: In your test folder, you create __init__.py and initialize everything here. // __init__.py reset_database() run_migration() seed_data() Noted that, you should configure your project running test from root folder. For example, if your test inside app/tests/api/sample_api.py, your test should be run from app. In this case, __init__.py will always run before running your sample_api.py. Here is the command line I usually run for running all tests inside project: python -m unittest discover
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49674882
accepted answer of: http://stackoverflow.com/q/49674882
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49736503
has comment: http://stackoverflow.com/comment/86513434
type: Question
has comment: http://stackoverflow.com/comment/86493956
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49803943
has comment: http://stackoverflow.com/comment/86540149
has comment: http://stackoverflow.com/comment/86557417
has body: It works fine when I specify exactly what the data has to be by doing this form = forms.MakeSale(instance=Laptop.objects.get(Name="NameOfTheLaptop")) But as soon as I try and pass the value to view and query the model, I get the following error: Reverse for 'sale' with no arguments not found. 1 pattern(s) tried: ['sale\\/(?P<laptopname>[^/]+)$'] views.py def laptop_sale(request, laptopname): form = forms.MakeSale(instance=Laptop.objects.get(Name=laptopname)) if request.method == 'POST': form = forms.MakeSale(request.POST, request.FILES) if form.is_valid(): readyinstance = form.save(commit=False) readyinstance.added_by = request.user readyinstance.save() else: return render(request, 'laptops/laptop_sale.html', {'form': form}) return render(request, 'laptops/laptop_sale.html', {'form': form}) urls.py path('sale/<str:laptopname>', views.laptop_sale, name = "sale") details.html {%for detail in details%} Laptop #{{detail.id}} Name: {{detail.Name}} Specification: {{detail.specification}} Warranty: {{detail.warranty}} This laptop has been sold » {%endfor%}
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Passing parameter to view to populate form
has answer: http://stackoverflow.com/a/49803943
favorite count: 0
has comment: http://stackoverflow.com/comment/86488185

http://stackoverflow.com/comment/86498027
type: Comment
type: QuestionComment
has text: @DietrichEpp Holy shit, it has the old path, prior to adding anaconda. I have restarted emacs many times after the installation, so it's cached somewhere?
score: 0
comment on: http://stackoverflow.com/q/49741513

http://stackoverflow.com/a/49752916
type: Answer
score: 53
upvote count: 53
downvote count: 0
answers question: http://stackoverflow.com/q/49752808
has body: It is a guide for the "hard wrap" setting. Setting screenshots from IntelliJ IDEA (PyCharm should be similar):

http://stackoverflow.com/comment/86249088
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49620265
has text: OMG! You are a GENIOUS! hahahah Thanks, man! It worked flawlessly!!

http://stackoverflow.com/q/49753740
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49753861
type: Question
has title: In Django, whether the `session_key` is the `session id`?
tagged with: python
type: UnansweredQuestion
has body: In the Django database, whether the session_key is the session id? if is, why Django do not use session_id as the colum name?
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/86434626
score: 1
type: Comment
type: QuestionComment
has text: This question should be asked on [so]
comment on: http://stackoverflow.com/q/49710560

http://stackoverflow.com/q/49616980
has body: I have a file named 'ab9c_xy8z_12a3.pdf' . I want to capture part after the last underscore and before '.pdf'. Writing regular expression like : s = 'ab9c_xy8z_12a3.pdf' m = re.search(r'_.*?\.pdf',s) m.group(0) returns: '_xy8z_12a3.pdf' In this example, I would like to capture only '12a3' part. Thank you for your help.
has comment: http://stackoverflow.com/comment/86241104
has answer: http://stackoverflow.com/a/49618081
score: 1
has answer: http://stackoverflow.com/a/49617123
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: How to create non-greedy regular expression from right?
possible better answer: http://stackoverflow.com/a/49617123
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86240885
accepted answer: http://stackoverflow.com/a/49618081
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/86227234
type: Comment
type: QuestionComment
score: 0
has text: It's hard to grasp the task. You probably should be much more precise and formal (maths). But it sounds like a discrete-optimization problem where scipy won't help much. You probably have to switch to [pulp](https://github.com/coin-or/pulp) (which supports mixed-integer programming).
comment on: http://stackoverflow.com/q/49610050

http://stackoverflow.com/comment/86211521
type: QuestionComment
comment on: http://stackoverflow.com/q/49601259
score: 0
has text: ty. I tried it but it does not return any result
type: Comment

http://stackoverflow.com/q/49697250
has comment: http://stackoverflow.com/comment/87370860
linked to: http://stackoverflow.com/q/953477
tagged with: ssh
has answer: http://stackoverflow.com/a/49697422
tagged with: python
has body: I created a class method (this will only run on Linux) that sends a list of commands to a remote computer over SSH and returns the output using subprocess.Popen: def remoteConnection(self, list_of_remote_commands): ssh = subprocess.Popen(["ssh", self.ssh_connection_string], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True, bufsize=0) # send ssh commands to stdin for command in list_of_remote_commands: ssh.stdin.write(command + "\n") ssh.stdin.close() output_dict = {'stdin': list(ssh.stdin), 'stdout': list(ssh.stdout), 'stderr': list(ssh.stderr)} return output_dict Whilst I'm still getting to grips with the subprocess module I'd read quite a bit about Popen and no one ever mentioned closing it (SSH Connection with Python 3.0, Proper way to close all files after subprocess Popen and communicate, https://docs.python.org/2/library/subprocess.html) so I assumed that that wasn't a problem. However when testing this out in ipython outside of a function I noticed that the variable ssh still seemed active. I tried closing ssh.stdin, ssh.stdout and ssh.stderr and even ssh.close(), ssh.terminate() and ssh.kill() but nothing seemed to close it. I thought perhaps it doesn't matter but my function will be called many times for months or even years so I don't want it to spawn a new process everytime it is run otherwise I'm going to quickly use up my maximum processes limit. So I use ssh.pid to find the PID and look it up using ps aux | grep PID and it's still there even after doing all of the above. I also tried: with subprocess.Popen(["ssh", self.ssh_connection_string], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True, bufsize=0) as shh: instead of: ssh = subprocess.Popen(["ssh", self.ssh_connection_string], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True, bufsize=0) I also remember solving a similar problem a while back using ssh -T but even: ss…
score: 2
type: AnsweredQuestion
upvote count: 2
linked to: http://stackoverflow.com/q/10745138
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Can't close an SSH connection opened with Popen
tagged with: python-3.x
linked to: http://stackoverflow.com/q/27451182
accepted answer: http://stackoverflow.com/a/49697422

http://stackoverflow.com/q/49706231
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49706280
has comment: http://stackoverflow.com/comment/86425714
has comment: http://stackoverflow.com/comment/86425744
score: 1
has comment: http://stackoverflow.com/comment/86425783
downvote count: 0
possible better answer: http://stackoverflow.com/a/49706271
tagged with: string
answer count: 4
has answer: http://stackoverflow.com/a/49706271
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/6531482
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/86425745
has comment: http://stackoverflow.com/comment/86425866
has body: So i have two lists a normal list and a nested list say, list1 = ['john','amal','joel','george'] list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']] I would like to check if any of the string in list1 is present in list2 and if so, return the indices of the string (which is in both the lists) in list2. Sample code which demonstrates the required output is shown below: out = [(ind,ind2) for ind,i in enumerate(list2) for ind2,y in enumerate(i) if 'john' in y] print out it returns : [(0, 0), (1, 1), (2, 1)] the above code does output the indices but it is limited to the string that we manually input. Is it possible to do as i have explained above? any help would be appreciated.(fairly new to nested lists). Thanks!
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49706277
has title: Check if a string inside a list is present in another nested list and return it's index in nested list
has answer: http://stackoverflow.com/a/49706277
has comment: http://stackoverflow.com/comment/86425678
has answer: http://stackoverflow.com/a/49708321

django-rest-framework
tags question: http://stackoverflow.com/q/49688967
tags question: http://stackoverflow.com/q/49630444
tags question: http://stackoverflow.com/q/49631820
tags question: http://stackoverflow.com/q/49644934
tags question: http://stackoverflow.com/q/49617116
tags question: http://stackoverflow.com/q/49600772
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/49625464
tags question: http://stackoverflow.com/q/49745485
tags question: http://stackoverflow.com/q/49726089
tags question: http://stackoverflow.com/q/49610120
tags question: http://stackoverflow.com/q/49721089
tags question: http://stackoverflow.com/q/49671404
tags question: http://stackoverflow.com/q/49704754
tags question: http://stackoverflow.com/q/49703454
tags question: http://stackoverflow.com/q/49753316
tags question: http://stackoverflow.com/q/49712834
tags question: http://stackoverflow.com/q/49689863
tags question: http://stackoverflow.com/q/49722278
tags question: http://stackoverflow.com/q/49669647
tags question: http://stackoverflow.com/q/49661615
tags question: http://stackoverflow.com/q/49711107
tags question: http://stackoverflow.com/q/49756264
type: Tag
tags question: http://stackoverflow.com/q/49623781
tags question: http://stackoverflow.com/q/49693697
tags question: http://stackoverflow.com/q/49664413
tags question: http://stackoverflow.com/q/49704142
tags question: http://stackoverflow.com/q/49620189
tags question: http://stackoverflow.com/q/49727182
tags question: http://stackoverflow.com/q/49609196
tags question: http://stackoverflow.com/q/49635654
tags question: http://stackoverflow.com/q/49730012
tags question: http://stackoverflow.com/q/49640736
tags question: http://stackoverflow.com/q/49695960
tags question: http://stackoverflow.com/q/49751042
tags question: http://stackoverflow.com/q/49709364

http://stackoverflow.com/comment/86522340
score: 0
comment on: http://stackoverflow.com/q/49753892
type: Comment
type: QuestionComment
has text: You can define a context manager to do that, but it is bad design.

http://stackoverflow.com/a/49642093
has comment: http://stackoverflow.com/comment/86291808
has comment: http://stackoverflow.com/comment/86291820
accepted answer of: http://stackoverflow.com/q/49642077
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49642077
upvote count: 7
has body: You can create a mapping from Mapping: Token_Sentence=[['This','is','a','book'],['This','is','a','cat'],['Those','are','two','books']] Mapping=[['This',1],['is',2],['a',3],['book',4],['cat',5],['Those',6],['are',7],['two',8],['books',9]] d = dict(Mapping) new_sentence = [[d[b] for b in i] for i in Token_Sentence] Output: [[1, 2, 3, 4], [1, 2, 3, 5], [6, 7, 8, 9]
score: 7
type: Answer

http://stackoverflow.com/q/49660621
has title: Paramiko not working properly after cx_Freeze?
tagged with: paramiko
answer count: 0
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86441910
has body: so I've writing this code where I connect to a computer over SSH using Paramiko, the script works normally, but when I convert it to ".exe" using cx_Freeze the program stops working at "self.ssh.load_system_host_keys", so i remove that function from the script and it kept working as usual (maybe not always needed?), but then again, when I converted the script to .exe, it was the "self.ssh.connect" function of Paramiko which now seems to be stopping the program, and by that i mean, no exception raises, the code just stops running right there and nothing happens, any thoughts?. Are there any compatibility issues with Paramiko and cx_Freeze? Here's a simplified version of my code: session.py (Class in which I implemented the paramiko functionality) from paramiko import SSHClient, AutoAddPolicy class Session: def __init__(self, host, user, password): self.user = user self.password = password self.host = host self.is_connected = False self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) def assert_connection(self): # force connection time_start = time.time() while True: try: self.ssh.connect(self.host, username=self.user, password=self.password) self.is_connected = True return True except: print(time.time() - time_start) if (time.time() - time_start) &gt; 3: self.ssh.close() return False The "Main" Script import session import threading def create_session(self): self.session = session.Session(self, self.active_session.host, self.active_session.user, self.active_session.password) t = threading.Thread(target=self.connect_via_ssh) t.start() def connect_via_ssh(self): if self.session.assert_connection(): #Do something Any help would be much appreciated! Edit: I wasn't able to figure out what was going wrong, however i tryed using pyinstaller, and it did work! i bet there's some wierd bug with cx_freeze and paramiko.
favorite count: 0
has comment: http://stackoverflow.com/comment/86331423
type: Question
tagged with: cx-freeze
type: UnansweredQuestion
tagged with: ssh
tagged with: python

http://stackoverflow.com/q/49711402
answer count: 1
duplicate of: http://stackoverflow.com/q/3348460
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: -1
has body: I am trying to convert the data here which I put in a text file to convert into CSV file. This is the code: import csv txt_file = r"TestData1.txt" csv_file = r"TestData1.csv" in_txt = csv.reader(open(txt_file, "rt"), delimiter = '\t') out_csv = csv.writer(open(csv_file, 'wt')) out_csv.writerows(in_txt) It works but has a empty line every other line. How do I go fix that?
has answer: http://stackoverflow.com/a/49711532
tagged with: http://stackoverflow.com/tag/csv
upvote count: 0
linked to: http://stackoverflow.com/q/3348460
has title: Python 3- converting text to CSV. How to properly format it(has an empty line every other line)

http://stackoverflow.com/comment/86430411
comment on: http://stackoverflow.com/q/49705203
type: QuestionComment
score: 0
has text: Seems it's not complete code according to your Traceback.
type: Comment

http://stackoverflow.com/comment/86250267
score: 0
comment on: http://stackoverflow.com/q/49621621
type: QuestionComment
type: Comment
has text: Is `frag_texts` a list of pattern strings from your source code, or a list of pattern strings you loaded out of a file or input from the user or something similar?

http://stackoverflow.com/q/49703810
tagged with: pyspark
has comment: http://stackoverflow.com/comment/86429425
tagged with: python
has comment: http://stackoverflow.com/comment/86430217
has comment: http://stackoverflow.com/comment/86426551
score: 0
answer count: 0
tagged with: apache-spark
has body: I have a bunch of raw data in multiple JSON files (on Azure Blob Storage). I tried doing spark.read.json() which seem to work but very slow ... I wonder if theres a way to read in files one by one for processing? My processing is just filtering, I want to omit certain attributes and transform data like split strings and cast into numbers for example. from pyspark.sql import * from pyspark.sql.functions import split, lower, unix_timestamp, from_unixtime rawQuestionsDf = spark.read.json("wasb://....blob.core.windows.net/pquestionsjson/datajson%2F*.json") questionsDf = rawQuestionsDf.select('id', 'title', 'tags', 'owner_user_id', 'accepted_answer_id', 'view_count', 'answer_count', 'comment_count', 'creation_date', 'favorite_count') \ .withColumn('tags', split(df['tags'], '\|')) \ .withColumn('title', lower(df['title'])) \ .withColumn('view_count', df['view_count'].cast('integer')) \ .withColumn('answer_count', df['answer_count'].cast('integer')) \ .withColumn('comment_count', df['comment_count'].cast('integer')) \ .withColumn('favorite_count', df['favorite_count'].cast('integer')) \ .withColumn('creation_date', df['creation_date']) questionsDf.write.parquet("wasb://data@cs4225.blob.core.windows.net/filtered/questions.parquet") I wonder if theres a better way? would wholeTextFile be a better choice?
type: Question
has comment: http://stackoverflow.com/comment/86426821
type: UnansweredQuestion
has title: PySpark read in multiple files for processing with limited RAM

http://stackoverflow.com/a/49647531
has body: One way to solve it is to do the following in PyCharm: Go to Settings (Ctrl + Alt + S) Go to Project Interpreter Click on the + button on the right of the panel Find pycurl Click on Install Package The warning should disappear after that.
answers question: http://stackoverflow.com/q/49645581
score: 3
accepted answer of: http://stackoverflow.com/q/49645581
type: Answer
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/122242564

http://stackoverflow.com/q/49669466
upvote count: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49680695
accepted answer: http://stackoverflow.com/a/56459693
has answer: http://stackoverflow.com/a/58825968
has body: I have a Chart Placeholder, into which I have inserted a chart of chart_type 'DOUGHNUT'. I've added data labels to it and want to change their positions. For some reason, the method given in the documentation has no effect on my chart. Here is my code, please help if I'm doing something wrong - from pptx import Presentation from pptx.chart.data import ChartData from pptx.enum.chart import XL_CHART_TYPE, XL_LABEL_POSITION, XL_DATA_LABEL_POSITION, XL_TICK_MARK, XL_TICK_LABEL_POSITION chart_data = ChartData() chart_data.add_series('', tuple(input_chart_data[x] for x in input_chart_data)) graphic_frame = content_placeholder.insert_chart(XL_CHART_TYPE.DOUGHNUT, chart_data) chart = graphic_frame.chart chart.has_legend = False #Adding Data-Labels with custom text chart.plots[0].has_data_labels = True data_labels = chart.plots[0].data_labels i = 0 series = chart.series[0] for point in series.points: fill = point.format.fill fill.solid() fill.fore_color.rgb = RGBColor(&lt;color_code&gt;) point.data_label.has_text_frame = True #Assigning custom text for data label associated with each data-point point.data_label.text_frame.text = str(chart_data.categories[i].label) + "\n" + str(float(chart.series[0].values[i])) + "%" for run in point.data_label.text_frame.paragraphs[0].runs: run.font.size = Pt(10) i+=1 data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
possible better answer: http://stackoverflow.com/a/49680695
has title: Python-PPTX : Data Label Positions not working for Doughnut Chart
tagged with: python-pptx
has answer: http://stackoverflow.com/a/56459693
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/49675699
has body: You've missed out the r in through. Try: @receiver(m2m_changed, sender=Content.tags.through)
score: 2
accepted answer of: http://stackoverflow.com/q/49675647
type: Answer
answers question: http://stackoverflow.com/q/49675647
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86483835
type: QuestionComment
has text: I did read what nonlocal does but it doesn't answer how the index variable is stored between function calls. i know nonlocal makes a variable in the outer function scope mutable in the inner scope without creating a new var of the same name, but that doesn't answer my main question.
comment on: http://stackoverflow.com/q/49734879
score: 0
type: Comment

http://stackoverflow.com/q/49750450
type: Question
has answer: http://stackoverflow.com/a/49750451
upvote count: 0
type: UnansweredQuestion
has body: Using PySide, what should be the parameter to QPainter drawPoints() method? I did not find it clear in the PySide documentation. nor did i find an example.
tagged with: python
tagged with: qpainter
score: -1
has title: What to pass as parameter to QPainter drawPoints method using PySide
has comment: http://stackoverflow.com/comment/86515302
tagged with: pyside
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49606482
type: AnsweredQuestion
upvote count: 14
answer count: 3
has answer: http://stackoverflow.com/a/57891559
tagged with: autoencoder
has comment: http://stackoverflow.com/comment/86220982
tagged with: pytorch
has comment: http://stackoverflow.com/comment/86220757
score: 13
has title: How to resolve runtime error due to size mismatch in PyTorch?
downvote count: 1
has body: I am trying to implement a simple autoencoder using PyTorch. My dataset consists of 256 x 256 x 3 images. I have built a torch.utils.data.dataloader.DataLoader object which has the image stored as tensor. When I run the autoencoder, I get a runtime error: size mismatch, m1: [76800 x 256], m2: [784 x 128] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1518371252923/work/torch/lib/TH/generic/THTensorMath.c:1434 These are my hyperparameters: batch_size=100, learning_rate = 1e-3, num_epochs = 100 Following is the architecture of my auto-encoder: class autoencoder(nn.Module): def __init__(self): super(autoencoder, self).__init__() self.encoder = nn.Sequential( nn.Linear(3*256*256, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(True), nn.Linear(64, 12), nn.ReLU(True), nn.Linear(12, 3)) self.decoder = nn.Sequential( nn.Linear(3, 12), nn.ReLU(True), nn.Linear(12, 64), nn.ReLU(True), nn.Linear(64, 128), nn.Linear(128, 3*256*256), nn.ReLU()) def forward(self, x): x = self.encoder(x) #x = self.decoder(x) return x This is the code I used to run the model: for epoch in range(num_epochs): for data in dataloader: img = data['image'] img = Variable(img) # ===================forward===================== output = model(img) loss = criterion(output, img) # ===================backward==================== optimizer.zero_grad() loss.backward() optimizer.step() # ===================log======================== print('epoch [{}/{}], loss:{:.4f}' .format(epoch+1, num_epochs, loss.data[0])) if epoch % 10 == 0: pic = show_img(output.cpu().data) save_image(pic, './dc_img/image_{}.jpg'.format(epoch))
has comment: http://stackoverflow.com/comment/86220938
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86220825
has answer: http://stackoverflow.com/a/49607525
has comment: http://stackoverflow.com/comment/86221109
has answer: http://stackoverflow.com/a/62448603
tagged with: python
possible better answer: http://stackoverflow.com/a/57891559
accepted answer: http://stackoverflow.com/a/49607525

http://stackoverflow.com/q/49659648
type: UnansweredQuestion
tagged with: upload
tagged with: django
has comment: http://stackoverflow.com/comment/134746449
tagged with: python
has comment: http://stackoverflow.com/comment/86329960
has body: I'm trying to save a file to disk, not in a class or anything just straight to disk but I can't for the life of me figure out how. So far I've got: View: ` def uploadview(request): uploadtestvar='Uploadpage!' request.session['test']='Is this working?' if request.method == 'POST': form=UploadForm(request.POST, request.FILES) if form.is_valid(): forcetitle='test' try: pass except: pass return HttpResponseRedirect('/test/') else: form=UploadForm() return render(request, 'test/uploads.html',{'uploadtestvar':uploadtestvar, 'form':form})` Form stolen directly from Django: from django import forms class UploadForm(forms.Form): title=forms.CharField(max_length=50) file=forms.FileField() I've searched countless threads and found none that gives an example simple enough for me to understand how to get that request.FILES['file'] saved to disk somewhere. The possible filetypes are png, jpg, and pdf.
has title: Django save uploaded file to disk
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49676210
answer count: 1
tagged with: file-upload
has comment: http://stackoverflow.com/comment/86329672
linked to: http://stackoverflow.com/q/5871730
favorite count: 0
has comment: http://stackoverflow.com/comment/86328933
type: Question
linked to: http://stackoverflow.com/q/3702465

http://stackoverflow.com/a/49639427
answers question: http://stackoverflow.com/q/49639352
type: AcceptedAnswer
has body: so you want to compute the average of a list of integers and then append them to a file? def AddSongLengths(): conn = sqlite3.connect("xxxxx.db") c=conn.cursor() PlaylistInput = input("Select which Playlist you want to calculate the mean of: ") Length = c.execute('SELECT "Length" FROM {0}'.format(PlaylistInput)) file=open("Integers.txt", "w") sum = 0 count = 0 for row in c.fetchall(): TrackSeconds = TrackIntoSeconds("{0}".format(row[0])) file.writelines(""" {0}""".format(TrackSeconds)) try: sum += int(row[0]) count += 1 avg = sum / count file.writelines("{}".format(avg)) file.close() this should work - it might require a little debugging :)
type: Answer
accepted answer of: http://stackoverflow.com/q/49639352
score: 0

pycharm
tags question: http://stackoverflow.com/q/49674552
tags question: http://stackoverflow.com/q/49728251
tags question: http://stackoverflow.com/q/49687860
tags question: http://stackoverflow.com/q/49698526
tags question: http://stackoverflow.com/q/49755639
tags question: http://stackoverflow.com/q/49681424
tags question: http://stackoverflow.com/q/49714910
tags question: http://stackoverflow.com/q/49659099
tags question: http://stackoverflow.com/q/49744601
tags question: http://stackoverflow.com/q/49754666
tags question: http://stackoverflow.com/q/49749981
tags question: http://stackoverflow.com/q/49752808
tags question: http://stackoverflow.com/q/49721886
tags question: http://stackoverflow.com/q/49676174
tags question: http://stackoverflow.com/q/49647160
tags question: http://stackoverflow.com/q/49714173
tags question: http://stackoverflow.com/q/49755941
tags question: http://stackoverflow.com/q/49744942
tags question: http://stackoverflow.com/q/49644188
tag name: pycharm
tags question: http://stackoverflow.com/q/49665655
tags question: http://stackoverflow.com/q/49626073
tags question: http://stackoverflow.com/q/49737648
tags question: http://stackoverflow.com/q/49641873
tags question: http://stackoverflow.com/q/49614096
tags question: http://stackoverflow.com/q/49676480
tags question: http://stackoverflow.com/q/49705338
type: Tag
tags question: http://stackoverflow.com/q/49721400
tags question: http://stackoverflow.com/q/49601425
tags question: http://stackoverflow.com/q/49649283
tags question: http://stackoverflow.com/q/49637853
tags question: http://stackoverflow.com/q/49714322
tags question: http://stackoverflow.com/q/49628808
tags question: http://stackoverflow.com/q/49705675
tags question: http://stackoverflow.com/q/49605102
tags question: http://stackoverflow.com/q/49599846
tags question: http://stackoverflow.com/q/49683959
tags question: http://stackoverflow.com/q/49713132
tags question: http://stackoverflow.com/q/49647855
tags question: http://stackoverflow.com/q/49646211
tags question: http://stackoverflow.com/q/49661492
tags question: http://stackoverflow.com/q/49617465
tags question: http://stackoverflow.com/q/49615355

http://stackoverflow.com/comment/86457398
type: Comment
has text: Sorry you are right, my bad. Super thanks for the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49721803

http://stackoverflow.com/a/49599795
answers question: http://stackoverflow.com/q/49599735
has comment: http://stackoverflow.com/comment/86207221
has comment: http://stackoverflow.com/comment/86206817
has comment: http://stackoverflow.com/comment/86206945
has body: You get the join functio wring. It merges the array into a string, separating the elements by the string on which you are calling it. In your case the space. If you want spaces at the front and the end of your string, you have to do this by hand. print(' ', ' '.join(mergesort(a[i]))) This should do the trick.
score: 0
type: Answer

http://stackoverflow.com/a/49714544
answers question: http://stackoverflow.com/q/49699477
type: AcceptedAnswer
has body: One simplest way to achieve this is to trick py.test to assume there are multiple combination of tests using pytest.mark.parametrization. Here I am just using dummy parameter count to trick py.test there are multiple variants of the test. This is simplest approach, If you have more conditions for your tests , you can use pytest_generate_tests(metafunc): to fine tune your needs. import pytest @pytest.fixture() def user_number(worker_id): return "user number : %s" %worker_id @pytest.mark.parametrize("count", [1, 2,3]) def test_add(user_number, count): print("Adding 1+1 and returning the result and user number: {}".format(user_number)) return 1+1 @pytest.mark.parametrize("count", [1, 2 ,3]) def test_subtract(count): print("subtracting 2-1 and returning the result and user number: {}".format(user_number)) return 2-1 $ py.test test.py -n 2 -s -vv ======================================== test session starts ======================================== platform darwin -- Python 2.7.13, pytest-2.9.2, py-1.5.3, pluggy-0.3.1 -- bin/python2.7 cachedir: .cache rootdir: , inifile: plugins: xdist-1.17.1, repeat-0.4.1, cov-1.8.1 [gw0] darwin Python 2.7.13 cwd: [gw1] darwin Python 2.7.13 cwd: [gw1] Python 2.7.13 (default, Dec 17 2016, 23:03:43) -- [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] [gw0] Python 2.7.13 (default, Dec 17 2016, 23:03:43) -- [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] gw0 [6] / gw1 [6] scheduling tests via LoadScheduling test.py::test_add[1] test.py::test_add[2] [gw1] PASSED test.py::test_add[2] [gw0] PASSED test.py::test_add[1] test.py::test_subtract[1] [gw1] PASSED test.py::test_subtract[1] test.py::test_add[3] [gw0] PASSED test.py::test_add[3] test.py::test_subtract[3] test.py::test_subtract[2] [gw0] PASSED test.py::test_subtract[3] [gw1] PASSED test.py::test_subtract[2]
downvote count: 0
has comment: http://stackoverflow.com/comment/86587173
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49699477
score: 5

http://stackoverflow.com/comment/86337626
score: 0
has text: Server language is python3 (running flask)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49663720

http://stackoverflow.com/a/74265629
type: Answer
answers question: http://stackoverflow.com/q/49666591
has body: python-docx doesn't yet support this scenario very well but here's one way to approach it: from docx.api import Document doc = Document("demo.docx") for table_index, table in enumerate(doc.tables): for row_index, row in enumerate(table.rows): for cell_index, cell in enumerate(row.cells): blips = cell._element.xpath('*/*/*/*/*/*/*/*/a:blip') if type(blips) is list: for blip in blips: # sample output: # table[12] row[2] cell[0] link_to_image[rId17] print('table[{}] row[{}] cell[{}] link_to_image[{}]' .format(table_index, row_index, cell_index, blip.embed)) # write to file image_part = doc.part.related_parts[blip.embed] with open('demo.png', 'wb') as f: f.write(image_part.blob) Not ideal, but does the trick.
score: 0

http://stackoverflow.com/q/49621849
type: UnansweredQuestion
score: 0
has body: I'm heading away for work/vacation with a macbook pro with OSX High Sierra 10.13.4 installed. I've got a series of tools to write and test. Some use PyQt4, some will need porting to PyQt5. Can I have PyQt 4 and 5 installed for both Python 2 and 3 for OSX? If so, anyone wanna shed some light how they did it? Would it be possible to also do this with Pyside/2 with OSX?
has comment: http://stackoverflow.com/comment/86250607
type: Question
has title: Installing PyQt4 and PyQt5 for both Python 2 and Python 3 Mac OS
tagged with: pyside
has comment: http://stackoverflow.com/comment/86293121
tagged with: python
tagged with: macos
answer count: 0
has comment: http://stackoverflow.com/comment/86250675
tagged with: pyqt

http://stackoverflow.com/comment/86378863
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49683375
has text: It may be that your DataFrame actually holds a column of *strings* that look like lists, whereas I assumed your column held Python lists. See my edited answer: I added two lines at the beginning to convert the strings in `config['SEQUENCE']` to Python lists. The rest of the code should work after that.
score: 0

http://stackoverflow.com/comment/86288718
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49640513
has text: Try an administrator command prompt

http://stackoverflow.com/q/49708945
tagged with: python
has body: I'm trying to create a LocallyConnected1D autoencoder in Keras by repurposing a 'simplest possible' Dense autoencoder from this tutorial. I keep getting the error bellow, which I believe is being caused by the dimensions of my input_shape. Traceback (most recent call last): File "localdendritic.py", line 38, in &lt;module&gt; kernel_size=6) File "localdendritic.py", line 15, in __init__ activation='relu')(input_placeholder) File "/Users/me/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 573, in __call__ self.assert_input_compatibility(inputs) File "/Users/me/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 472, in assert_input_compatibility str(K.ndim(x))) ValueError: Input 0 is incompatible with layer encoded_layer: expected ndim=3, found ndim=2 My code is below. I've tried changing the input_shape array into [None, 1, input_size], [1, 1, input_size], [1, input_size] and [None, input_size], but it doesn't seem to change anything. I think I'm missing some insight about the shape of the input. import numpy as np from keras.models import Model, Sequential from keras.layers import Input, LocallyConnected1D class Localautoencoder: def __init__(self, input_size, encoded_size, kernel_size, **kwargs): input_shape = np.array([input_size]) input_placeholder = Input(shape=(input_size, 1)) encoded = LocallyConnected1D(encoded_size, kernel_size, input_shape=input_shape, name='encoded_layer', activation='relu')(input_placeholder) decoded = LocallyConnected1D(input_size, kernel_size, activation='sigmoid', name='decoded_layer')(encoded) self.localae = Model(input_placeholder, decoded) self.encoder = Model(input_placeholder, encoded) encoded_input = Input(shape=(1, encoded_size)) decoded_layer = self.localae.layers[-1] self.decoder = Model(encoded_input, decoded_layer(encoded_input)) self.localae.compile(optimizer='adam', loss='binary_crossentropy') from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x…
type: AnsweredQuestion
tagged with: autoencoder
has title: locallyconnected1D autoencoder in keras
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: keras
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49709077
accepted answer: http://stackoverflow.com/a/49709077

http://stackoverflow.com/a/49734094
has comment: http://stackoverflow.com/comment/86494971
type: AcceptedAnswer
has body: Try with a simpler code just to establish the connection. Simple echo server with hardcoded value, single send, single receive. On the server side print the addr got from recvfrom. On the server side verify that the socket is correctly binded netstat -pnlt | grep 5001 and verify the firewall let you in iptables -L INPUT | grep 5001, on the client side verify the port is accessible nmap -sU -p 5001 &lt;server address&gt;. The commands are for linux, google is your friend if your server/client is running on windows -1 for over complicated example, you have network issues, not "how to do an udp speedtest" issue.
answers question: http://stackoverflow.com/q/49726643
accepted answer of: http://stackoverflow.com/q/49726643
type: Answer
has comment: http://stackoverflow.com/comment/86598354
score: 0

http://stackoverflow.com/a/49698422
has comment: http://stackoverflow.com/comment/86533851
has body: A bulk write operation guarantees query ordering by default. This means that the queries are executed sequentially. from pymongo.operations import DeleteOne, InsertOne def left_shift_insert(collection, doc, cap=60): ops = [] variance = max((collection.count() + 1) - cap, 0) delete_ops = [DeleteOne({})] * variance ops.extend(delete_ops) ops.append(InsertOne(doc)) return collection.bulk_write(ops) left_shift_insert(db.timestamp, new_data)
type: Answer
has comment: http://stackoverflow.com/comment/86510357
score: 0
has comment: http://stackoverflow.com/comment/86464569
answers question: http://stackoverflow.com/q/49694585

swi-prolog
tag name: swi-prolog
type: Tag
tags question: http://stackoverflow.com/q/49731420

http://stackoverflow.com/comment/86557139
has text: Thanks. The issue was that in my urls.py I routed all urls that didnt match my API urls to the IndexView. I have changed that line to url('^(?!(?:api)/)', IndexView.as_view(), name='index') and now I get a proper 404.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49707954

http://stackoverflow.com/comment/86421096
comment on: http://stackoverflow.com/a/49703496
score: 0
type: AnswerComment
has text: One thing I just thought of: once you get the string, you'll need to extract just the JSON portion for json.loads. To do that, you could use regex, like other commenters mentioned. Another simple way would be to use string.split('=') on the script tag's string, and then get the last element, so something like: script_dict = json.loads (script_tag_string.split('=')[-1])
type: Comment

http://stackoverflow.com/comment/86525456
score: 0
has text: Yes you are right, I mean calling the class. I've seen on some forum people using threads and queue, but it is far too complicated for my level. So it seems that I am stuck with my problems? But then why does the Text widget updates correctly?
type: QuestionComment
comment on: http://stackoverflow.com/q/49754385
type: Comment

http://stackoverflow.com/comment/86398719
has text: Possible duplicate of [open url from pythonanywhere](https://stackoverflow.com/questions/32597390/open-url-from-pythonanywhere)
score: 2
comment on: http://stackoverflow.com/q/49691395
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49624690
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/86256419
answers question: http://stackoverflow.com/q/49624029
has comment: http://stackoverflow.com/comment/86696086
accepted answer of: http://stackoverflow.com/q/49624029
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86256568
downvote count: 0
has comment: http://stackoverflow.com/comment/86256302
has body: In the following loop you are overwriting variable X with a single column (Series) in each loop iteration: for column in data.columns: if data[column].dtype == type(object): le = LabelEncoder() data[column] = le.fit_transform(data[column]) X = data[column] X = data[column] # &lt;------- NOTE: Y = data[target] actually you can define X and Y after the loop as follows: X = data.drop(target, 1) Y = data[target] the vast majority of sklrean methods do accept pandas DataFrames and Series as input data sets...
score: 3
has comment: http://stackoverflow.com/comment/86256521

http://stackoverflow.com/comment/86246749
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49619843
has text: Thank you for clarifying that heaps won't support that operation.
type: AnswerComment

http://stackoverflow.com/comment/86307820
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49641694
has text: @Roman the id's in my case are from fpds.gov so they are duns numbers.

http://stackoverflow.com/q/49619628
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am working on understanding how to use RNNs in Tensorflow for Seq2Seq models, and I get to the last step of doing a dynamic RNN and I get a dynamic dynamic_decode step and I get the error: "ValueError: Input 0 of layer gru_cell_3 is incompatible with the layer: expected ndim=2, found ndim=1. Full shape received: [None]" import tensorflow as tf data_inputs = tf.placeholder(tf.float32,[None,102,300]) batch_lengths = tf.cast(tf.reduce_sum(tf.reduce_max(tf.sign(data_inputs),2),1),tf.int32) encoder_cell_forward = tf.nn.rnn_cell.GRUCell(num_units = 150) encoder_cell_backward = tf.nn.rnn_cell.GRUCell(num_units = 150) _ , state = tf.nn.bidirectional_dynamic_rnn( encoder_cell_forward,encoder_cell_backward, data_inputs,sequence_length = batch_lengths, dtype = tf.float32 ) state = tf.concat(state,1) decoder_cell = tf.nn.rnn_cell.GRUCell(num_units = 300) helper = tf.contrib.seq2seq.TrainingHelper(state,batch_lengths) projection_layer = tf.layers.Dense( units = 300,activation= None,trainable =True ) decoder = tf.contrib.seq2seq.BasicDecoder( decoder_cell, helper, state, output_layer=projection_layer) final_outputs, final_state, final_sequence_lengths = tf.contrib.seq2seq.dynamic_decode( decoder,maximum_iterations= 102,impute_finished=False) What am I doing wrong here?
type: UnansweredQuestion
tagged with: python
has title: Seq2Seq in Tensorflow, but I get ValueError: Input 0 of layer gru_cell_3 is incompatible with the layer:
has answer: http://stackoverflow.com/a/49633657
score: 1
answer count: 1

http://stackoverflow.com/a/49643031
has body: def checkout(): total = 0 count = 0 moreItems = True while moreItems: price = float(input('Enter price of item (0 when done): ')) if price != 0: count = count + 1 total = total + price print('Subtotal: $', total) else: moreItems = False average = total / count print('Total items:', count) print('Total $', total) print('Average price per item: $', average) checkout() Note Try to convert this example to your problem.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49642754

graph
tags question: http://stackoverflow.com/q/49730947
tags question: http://stackoverflow.com/q/49665799
tags question: http://stackoverflow.com/q/49634279
tags question: http://stackoverflow.com/q/49740343
tags question: http://stackoverflow.com/q/49725516
tags question: http://stackoverflow.com/q/49614427
tags question: http://stackoverflow.com/q/49743649
tags question: http://stackoverflow.com/q/49718082
tag name: graph
tags question: http://stackoverflow.com/q/49678649
type: Tag
tags question: http://stackoverflow.com/q/49747583
tags question: http://stackoverflow.com/q/49699499
tags question: http://stackoverflow.com/q/49619627
tags question: http://stackoverflow.com/q/49713065
tags question: http://stackoverflow.com/q/49755721
tags question: http://stackoverflow.com/q/49698328

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

http://stackoverflow.com/a/49706555
type: Answer
score: -1
has body: Don't use openCV for this. Better use from PIL import ImageGrab ImageGrab.grab().save("screen_capture.jpg", "JPEG")
has comment: http://stackoverflow.com/comment/86427131
has comment: http://stackoverflow.com/comment/86426942
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/86426405
answers question: http://stackoverflow.com/q/49706503

http://stackoverflow.com/a/49731940
score: 3
has body: Use numpy.diagonal(): np.diagonal(a, axis1=1, axis2=2) Example: In [10]: a = np.arange(3*4*5).reshape(3,4,5) In [11]: a Out[11]: array([[[ 0, 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, 37, 38, 39]], [[40, 41, 42, 43, 44], [45, 46, 47, 48, 49], [50, 51, 52, 53, 54], [55, 56, 57, 58, 59]]]) In [12]: np.diagonal(a, axis1=1, axis2=2) Out[12]: array([[ 0, 6, 12, 18], [20, 26, 32, 38], [40, 46, 52, 58]])
type: Answer
accepted answer of: http://stackoverflow.com/q/49731792
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49731792

http://stackoverflow.com/a/49641377
downvote count: 0
score: 1
type: Answer
has body: We can't really turn this into a dictionary comprehension, for the reason I explained in my comment, but we can certainly simplify what you have. Using get() to access the domainAggregator element, we can provide a default of 0 if the key doesn't exist, eliminating that if statement. for cpPtr in cpdomains: domainKeys = self.domainSplitter(cpPtr.split(" ")[1]) for domainKey in domainKeys: domainAggregator[domainKey] = ( domainAggregator.get(domainKey, 0) + int(cpPtr.split(" ")[0]))
upvote count: 1
answers question: http://stackoverflow.com/q/49641277

http://stackoverflow.com/a/49704588
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49704528
has comment: http://stackoverflow.com/comment/86422847
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: %timeit on my laptop gives 13.4us for deepcopy vs. 594 ns for copy, so it takes about 23x longer. This seems reasonable. The copy only has to copy one 2-element list; the deepcopy has to copy one 2-element list and two 3-element lists, and it's also got some extra overhead from the recursion. If the lists were a lot longer, but the nesting not a lot deeper, I'd expect the difference to get smaller, but still, it will always be substantial. Laurent LAPORTE's [list(i) for i in l] takes 2.01us on my laptop—only 3x as slow as a copy instead of 23x. Of course it only has a fixed depth (2, in the specific case of his answer) rather than unlimited, but in this case, we've got a fixed-depth list, and that's not too unusual. But performance will rarely be a good reason to choose one over the other. That assignment to the shallow copy's s[0][0] = 1 is going to change the original list's l[0][0] to 1 as well. If you want that, use copy (or, more simply in this case, just list). If you don't, use deepcopy. And if you want exactly a specific depth, use a specific depth. (Getting the answer you need is always better than getting the wrong answer fast.)
has comment: http://stackoverflow.com/comment/86422816
has comment: http://stackoverflow.com/comment/86422897
accepted answer of: http://stackoverflow.com/q/49704528

merge
type: Tag
tags question: http://stackoverflow.com/q/49699069
tags question: http://stackoverflow.com/q/49741509
tags question: http://stackoverflow.com/q/49699678
tags question: http://stackoverflow.com/q/49608419
tags question: http://stackoverflow.com/q/49719580
tag name: merge
tags question: http://stackoverflow.com/q/49711509
tags question: http://stackoverflow.com/q/49731163
tags question: http://stackoverflow.com/q/49705754
tags question: http://stackoverflow.com/q/49725629
tags question: http://stackoverflow.com/q/49704687
tags question: http://stackoverflow.com/q/49640490

http://stackoverflow.com/comment/86581294
score: 0
type: Comment
has text: @Cracoras I think `process_function` should be a coroutine because it calls other coroutines. But it's really hard to tell what's going on without seeing the code. Can you create a minimal reproducible example that still demonstrates the problem?
type: AnswerComment
comment on: http://stackoverflow.com/a/49665627

http://stackoverflow.com/q/49698691
has comment: http://stackoverflow.com/comment/86410876
tagged with: selenium
accepted answer: http://stackoverflow.com/a/49698733
has comment: http://stackoverflow.com/comment/86410666
tagged with: python
has answer: http://stackoverflow.com/a/49698733
has body: I am facing a problem of downloading a csv file from a website that requires login. I have successfully logged in using Selenium. However I don't know how to download the csv file by clicking on a button. I have tried to inspect but i Failed. plus there is no copy url of the csv file that is provided in the website. can anyone help me with the code. this is so far what I have written. from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import time chromedriver = "/webdrivers/chromedriver" driver = webdriver.Chrome(chromedriver) driver.get('https://user.sensogram.com/signin') #driver.get(url)-- We get url by using driver which we initialy load. print ("Opened sensogram") time.sleep(5) #Just wait for sometime. email = driver.find_element_by_xpath("//input[@name='usernameSignIn']") #Find email textaera. email.send_keys('****') #Send email to this text area. password = driver.find_element_by_xpath("//input[@name='passwordSignIn']") #Find password textarea. password.send_keys('*******') #send password to the password field. button = driver.find_element_by_xpath("//button[@ng- click='submitted=true']") #Find login button. button.click() #Click on login button. and this is the code I get when i inspect the csv file button. <g class="highcharts-button highcharts-contextbutton highcharts-button-normal" style="cursor:pointer;vertical-align:center;font-size:12;font-weight:500;" stroke-linecap="round" transform="translate(399,8)"> Chart context menu Download CSV </g> Download CSV Download CSV
type: AnsweredQuestion
score: 0
answer count: 1
has title: downloading csv file button from a website
type: Question
has comment: http://stackoverflow.com/comment/86434265
has comment: http://stackoverflow.com/comment/86411702
has comment: http://stackoverflow.com/comment/86411492
has comment: http://stackoverflow.com/comment/86410831
has comment: http://stackoverflow.com/comment/86411923

http://stackoverflow.com/q/49643907
downvote count: 0
has answer: http://stackoverflow.com/a/73028082
tagged with: python
has answer: http://stackoverflow.com/a/69331279
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48406578
has answer: http://stackoverflow.com/a/73801059
has answer: http://stackoverflow.com/a/74090710
has answer: http://stackoverflow.com/a/51255361
has answer: http://stackoverflow.com/a/62839575
has answer: http://stackoverflow.com/a/50185257
has answer: http://stackoverflow.com/a/76208532
upvote count: 74
score: 74
tagged with: matplotlib
has answer: http://stackoverflow.com/a/78864187
has answer: http://stackoverflow.com/a/74453219
favorite count: 0
tagged with: normalization
has answer: http://stackoverflow.com/a/58646678
type: Question
has body: I tried to run the graph cut algorithm for a slice of an MRI after converting it into PNG format. I keep encountering the following problem: Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers). This is even after setting vmin and vmax as follows: plt.imshow(out, vmin=0, vmax=255)
answer count: 12
has answer: http://stackoverflow.com/a/76725710
has title: Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers)

http://stackoverflow.com/a/49710776
score: 0
has comment: http://stackoverflow.com/comment/86435378
has comment: http://stackoverflow.com/comment/86435231
answers question: http://stackoverflow.com/q/49710566
has comment: http://stackoverflow.com/comment/86435357
has body: You have to store your questions and answers in database becouse when you click button you call a view which sends always last question and answer to template. And then when your data is in database, you simply get all questions and answers and send it to template and show using {% for %}
type: Answer

http://stackoverflow.com/q/49701525
type: Question
tagged with: numpy
tagged with: dimensions
type: UnansweredQuestion
tagged with: python
has title: skin color segmentation using YCbCr colorspace
tagged with: opencv
answer count: 0
has comment: http://stackoverflow.com/comment/86417455
score: 1
downvote count: 0
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86423008
upvote count: 1
has comment: http://stackoverflow.com/comment/86416845
has body: I am trying to execute this code but I am getting the below stated error. It says that the array size doesn't match. I have tried a few solutions given on the internet. Changed the values of the color and also tried by removing the np.array from the code in the concerned lines skin_ycrcb_min = np.array((0, 138, 67)) skin_ycrcb_max = np.array((255, 173, 133)) Bellow is the code: import cv2 import numpy as np import util as ut import svm_train as st import re model=st.trainSVM(17) #create and train SVM model each time coz bug in opencv 3.1.0 svm.load() https://github.com/Itseez/opencv/issues/4969 cam=int(raw_input("Enter Camera number: ")) cap=cv2.VideoCapture(cam) font = cv2.FONT_HERSHEY_SIMPLEX def nothing(x) : pass text= " " temp=0 previouslabel=None previousText=" " label = None while(cap.isOpened()): _,img=cap.read() cv2.rectangle(img,(900,100),(1300,500),(255,0,0),3) # bounding box which captures ASL sign to be detected by the system img1=img[100:500,900:1300] img_ycrcb = cv2.cvtColor(img1, cv2.COLOR_BGR2YCR_CB) blur = cv2.GaussianBlur(img_ycrcb,(11,11),0) skin_ycrcb_min = np.array((0, 138, 67)) skin_ycrcb_max = np.array((255, 173, 133)) mask = cv2.inRange(blur, skin_ycrcb_min, skin_ycrcb_max); # detecting the hand in the bounding box using skin detection contours,hierarchy = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL, 2) cnt=ut.getMaxContour(contours,4000) # using contours to capture the skin filtered image of the hand if cnt!=None: gesture,label=ut.getGestureImg(cnt,img1,mask,model) # passing the trained model for prediction and fetching the result if(label!=None): if(temp==0): previouslabel=label if previouslabel==label : previouslabel=label temp+=1 else : temp=0 if(temp==40): if(label=='P'): label=" " text= text + label if(label=='Q'): words = re.split(" +",text) words.pop() text = " ".join(words) #text=previousText print text cv2.imshow('PredictedGesture',gesture) # showing the best match or prediction cv2.putText(img,label,(50,150), font,8,(0,125,155),…
favorite count: 0

http://stackoverflow.com/a/49694550
type: Answer
downvote count: 0
has body: Here's a vectorized solution that finds the start, stop indices and hence lengths of islands of zeros and finally uses argmax to get the starting index of the first island satisfying the criteria of zeros count being &gt;= n - def first_occ_index(w, n): idx = np.flatnonzero(np.r_[True, w, True]) lens = np.diff(idx) - 1 return idx[(lens &gt;= n).argmax()] Sample run - In [107]: w Out[107]: array([ True, False, True, True, False, False, False]) In [108]: first_occ_index(w, n=1) Out[108]: 1 In [109]: first_occ_index(w, n=3) Out[109]: 4
upvote count: 7
answers question: http://stackoverflow.com/q/49693770
score: 7

http://stackoverflow.com/comment/86505363
type: Comment
type: AnswerComment
score: 0
has text: @AF.Neto If my answer helped you do not forget to mark it as correct, that is the best way to thank. : D
comment on: http://stackoverflow.com/a/49724242

http://stackoverflow.com/q/49616658
answer count: 1
tagged with: pip
upvote count: 1
has body: After know that jwt package is incompatible with python2, I am trying to install it with pip3: sudo pip3 install jwt I am getting the following output: Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2482, in _dep_map return self.dep_map File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2344, in __getattr raise AttributeError(attr) AttributeError: _DistInfoDistribution__dep_map During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/usr/lib/python3/dist-packages/pip/req.py", line 1266, in prepare_files req_to_install.extras): File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2291, in requires dm = self._dep_map File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2484, in _dep_map self.__dep_map = self._compute_dependencies() File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2508, in _compute_dependencies parsed = next(parse_requirements(distvers)) File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2605, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2583, in scan_list "Expected ',' or end-of-list in",line,"at",line[p:] ValueError: ("Expected ',' or end-of-list in", 'cryptography &lt;2.,>=1.7.2', 'at', ',>=1.7.2') Any help?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: jwt
tagged with: python
type: AnsweredQuestion
has title: Python3 - error installing jwt with pip3 on Ubuntu 14
accepted answer: http://stackoverflow.com/a/49616730
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49616730

http://stackoverflow.com/comment/132891418
comment on: http://stackoverflow.com/a/53250584
type: AnswerComment
type: Comment
has text: There's not much point making this a generator: `sorted()` will force evaluation of `dirlist` in its entirely so the whole `os.walk()` call has to complete before it can `yield` the first item. You might as well just return the result of `sorted()` directly. And as such, this is fine if you either have a small tree or don't care about latency.
score: 0

http://stackoverflow.com/q/49756667
has comment: http://stackoverflow.com/comment/86529188
has title: How to show sigma instead of inter quartile range with a seaborn violin plot?
has comment: http://stackoverflow.com/comment/86528920
has comment: http://stackoverflow.com/comment/86530030
answer count: 0
tagged with: seaborn
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: plot
favorite count: 0
type: Question
tagged with: matplotlib
has body: I'd like to create Violinplots using Seaborn as shown here. These distributions show dotted lines for the median and the +/- interquartile range. Would it be possible to instead show the +/- 1sigma from the distributions instead? Their example code: import seaborn as sns sns.set(style="whitegrid", palette="pastel", color_codes=True) # Load the example tips dataset tips = sns.load_dataset("tips") # Draw a nested violinplot and split the violins for easier comparison sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True, inner="quart", palette={"Male": "b", "Female": "y"}) sns.despine(left=True) plt.show() Will produce this:
tagged with: python

http://stackoverflow.com/a/49737811
type: Answer
accepted answer of: http://stackoverflow.com/q/49736960
has comment: http://stackoverflow.com/comment/86493168
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86492564
answers question: http://stackoverflow.com/q/49736960
score: 1
has body: Start by converting your list to pd.DatetimeIndex and finding the ideal distribution of time stamps between start and end: import pandas as pd import numpy as np ls = pd.to_datetime(['2016-01-30 12:10:00', '2016-01-30 12:23:35', '2016-01-30 12:24:14', '2016-01-30 12:24:51', '2016-01-30 12:25:00', '2016-01-30 12:26:49', '2016-01-30 12:27:36']) n = 50 dt = (ls.max() - ls.min())/n ls_temp = pd.date_range(start=ls.min(), end=ls.max(), freq=dt) Then find out where to put the original measurements, for example by replacing the entry with the smallest absolute difference: idx = np.abs(ls[:,None] - ls_temp[None, :]).argmin(axis=1) ls_temp = pd.Series(ls_temp) ls_temp[idx] = pd.Series(ls) Note that this strategy might fail in some edge cases (where one index is being replaced by two values or something like that). At the end, you can convert it back to your format for example with: ls = list(map("{:%Y-%m-%d %H:%M:%S}".format, ls_temp.tolist())) Output: ['2016-01-30 12:10:00', '2016-01-30 12:10:21', '2016-01-30 12:10:42', '2016-01-30 12:11:03', '2016-01-30 12:11:24', '2016-01-30 12:11:45', '2016-01-30 12:12:06', '2016-01-30 12:12:27', '2016-01-30 12:12:48', '2016-01-30 12:13:10', '2016-01-30 12:13:31', '2016-01-30 12:13:52', '2016-01-30 12:14:13', '2016-01-30 12:14:34', '2016-01-30 12:14:55', '2016-01-30 12:15:16', '2016-01-30 12:15:37', '2016-01-30 12:15:59', '2016-01-30 12:16:20', '2016-01-30 12:16:41', '2016-01-30 12:17:02', '2016-01-30 12:17:23', '2016-01-30 12:17:44', '2016-01-30 12:18:05', '2016-01-30 12:18:26', '2016-01-30 12:18:48', '2016-01-30 12:19:09', '2016-01-30 12:19:30', '2016-01-30 12:19:51', '2016-01-30 12:20:12', '2016-01-30 12:20:33', '2016-01-30 12:20:54', '2016-01-30 12:21:15', '2016-01-30 12:21:36', '2016-01-30 12:21:58', '2016-01-30 12:22:19', '2016-01-30 12:22:40', '2016-01-30 12:23:01', '2016-01-30 12:23:22', '2016-01-30 12:23:35', '2016-01-30 12:24:14', '2016-01-30 12:24:25', '2016-01-30 12:24:51', '2016-01-30 12:25:00', '2016-01-30 12:25:29', '2016-…

http://stackoverflow.com/q/49629011
has title: Pymongo Aggregate with multiple conditions: lookup, unwind, redact, cond, sort and limit
tagged with: python
type: Question
tagged with: lookup
tagged with: mongodb
tagged with: aggregate
upvote count: 3
answer count: 1
tagged with: pymongo
downvote count: 0
accepted answer: http://stackoverflow.com/a/49643258
favorite count: 0
has answer: http://stackoverflow.com/a/49643258
type: AnsweredQuestion
score: 3
has body: done_status = ['BAD_PU', 'TO_WH', 'RCVDPORT', 'RCVD', 'BAD_DEL', 'MISSFLT', 'OFFLOAD'] shipments = db.db_shipment.aggregate([{ "$lookup":{ "from":"db_shipment_status_history", "localField":"_id", "foreignField":"fk_shipment_id", "as":"shipment_status_history_collection" } }, {"$unwind": "$shipment_status_history_collection"}, {"$redact":{"$cond":{ "$if": { "status_value": {"$in": done_status } } }, "$then": "$$KEEP" ,"$else":"$$PRUNE" } }, {"$sort": {'shipment_status_history_collection.rec_timestamp':-1}}, {"$limit":1}, {"$project":{"pkey":"$pkey","_code":"$_code"}} ]) error: pymongo.errors.OperationFailure: An object representing an expression must have exactly one field: { $cond: { $if: { status_value: { $in: [ "BAD_PU", "TO_WH", "RCVDPORT", "RCVD", "BAD_DEL", "MISSFLT", "OFFLOAD" ] } } }, $else: "$$PRUNE", $then: "$$KEEP" } how to fix this error? Im trying to add the latest shipment status history in the shipment record where the status value is in the given status value.

http://stackoverflow.com/q/49720400
has body: celery.py import os from celery import Celery from django.conf import settings from twitterdata.services import TwitterService os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TwitterApiProxy.settings') app = Celery('TwitterApiProxy') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): print("calling load_tweets task") sender.add_periodic_task(10.0, TwitterService.load_tweets.s(), name='add every 10') Tweet.py model from django.db import models class Tweet(models.Model): id = models.BigIntegerField title = models.CharField image = models.CharField url = models.CharField @classmethod def create(cls, tweet_id, dictionary): print(dictionary) tweet = cls(id=tweet_id, title=dictionary['title'], image=dictionary['image'], url=dictionary['url']) return tweet services.py import twitter import requests from celery import shared_task from twitterdata.models import Tweet class TwitterService: @staticmethod @shared_task def load_tweets(): print("Loading Tweets") error Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/conf/__i…
tagged with: celery
type: Question
accepted answer: http://stackoverflow.com/a/49721471
has answer: http://stackoverflow.com/a/49721471
tagged with: python
has title: Django: Error while importing a model in custom services file
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: django

http://stackoverflow.com/comment/86424327
type: Comment
score: 0
has text: @hpaulj Sorry, I thought I specified my problem quite clear. I can't find a solution to let "add" accept more arguments to be run like: "python script.py add file1.txt" or "python script.py add all". I don't want any flags between add and file1.txt The only way it's working now to have "if" under main
type: QuestionComment
comment on: http://stackoverflow.com/q/49691897

http://stackoverflow.com/comment/86261656
type: QuestionComment
has text: keep them both in separate files like [this](https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04)
score: 0
comment on: http://stackoverflow.com/q/49627185
type: Comment

http://stackoverflow.com/a/49717243
has body: If you are happy using a 3rd party library, this can be vectorised via pandas: import pandas as pd # read csv file df = pd.read_csv('file.csv') # filter column B, group by A, sum C res = df.loc[df['B'].between(1990, 2000)]\ .groupby('A')['C'].sum()\ .reset_index() Result: A C 0 1 133 1 2 69 2 4 29 3 5 85
downvote count: 0
answers question: http://stackoverflow.com/q/49716841
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/49720764
downvote count: 0
answers question: http://stackoverflow.com/q/49711589
score: 2
has comment: http://stackoverflow.com/comment/86454639
type: Answer
has body: You obviously need to choose epsilon appropriately for your coordinate system. If you scale the data, the epsilon will no longer be the same. A hack that you max find simpler (but that is not the 'proper' solution) is to simply compute the mean using the unscaled data. But the means of DBSCAN clusters are not reliable anyway. Judging by your axes, you probably need to decrease epsilon by a factor of 100. As your data apparently is coordinates, you should use Haversine distance because Earth is not flat, and choose epsilon based on a distance that makes sense for your problem. The exact scaling may be a bit tricky. It's probably radians, so you need to convert miles to radians to translate distances.
has comment: http://stackoverflow.com/comment/86454929
upvote count: 2

http://stackoverflow.com/q/49690572
has body: I'm trying to extract text data from companies' website using python Scrapy. The code below scrapes texts with no errors, but the output seems some further processes are required for NLP. Spider code: # -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from ..items import ScrapingtestItem from scrapy_splash import SplashRequest from scrapy.utils.log import configure_logging import re class TestscraperSpider(scrapy.Spider): name = 'Testscraper' global search_pages search_pages = ['https://www.impossiblefoods.com/', 'http://www.ycombinator.com/'] list_allow = search_pages list_allow_parse = search_pages custom_settings = {"DOWNLOAD_DELAY": 1,} # interval seconds rules = ( Rule(LinkExtractor(allow=list_allow,), follow=True), Rule(LinkExtractor(allow=list_allow_parse, unique=True), callback='start_requests'), ) def start_requests(self): for url in search_pages: yield SplashRequest(url=url, callback=self.parse) def parse(self, response): item = ScrapingtestItem() try: item['extracted_ptag'] = response.xpath('//p/text()').extract() except: item['extracted_ptag'] = None try: item['extracted_atag'] = response.xpath('//a/text()').extract() except: item['extracted_atag'] = None try: item['extracted_pretag'] = response.xpath('//pre/text()').extract() except: item['extracted_pretag'] = None try: item['extracted_strongtag'] = response.xpath('//strong/text()').extract() except: item['extracted_strongtag'] = None yield item Item code # -*- coding: utf-8 -*- import scrapy class ScrapingtestItem(scrapy.Item): extracted_ptag= scrapy.Field() extracted_atag= scrapy.Field() extracted_pretag= scrapy.Field() extracted_strongtag= scrapy.Field() The output json file: [ {"extracted_text_ptag": ["It\u2019s here. A delicious burger made entirely from plants for people who love meat. No more compromises. Ready for an introduction?", "We're committed to creating a better planet and better meat, from plants. Meet heme,…
tagged with: scrapy
tagged with: nlp
type: Question
upvote count: 4
has title: How to process Scrapy output for NLP?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86394071
tagged with: python
downvote count: 1
favorite count: 0
score: 3

http://stackoverflow.com/comment/86392104
has text: With the limited data you provide it is really hard to help you!
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49690152

http://stackoverflow.com/comment/86224956
comment on: http://stackoverflow.com/q/49609028
type: Comment
has text: you can tell in other way; imagine a rabbit with a lot of carrots ahead; you set the rabbit with greedy regex, the rabbit gets up to eat all of it, now if you set the rabbit to be greedy but skips white carrots, the rabbit would not eat the white ones, the greedy functionality holds its priority at that moment.
type: QuestionComment
score: 0

http://stackoverflow.com/a/49629683
type: AcceptedAnswer
has body: In Python getattr() is used for getting attributes based on variables. As an addition, you don't need to query the whole model object and all its attributes, if all you want is just one: def get_value(self, table, key): # Note the comma after value. It unpacks the 1-tuples. for value, in self.session.query(getattr(table, key)): print(value)
accepted answer of: http://stackoverflow.com/q/49629431
answers question: http://stackoverflow.com/q/49629431
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86266272

http://stackoverflow.com/comment/101225803
comment on: http://stackoverflow.com/q/49730159
score: 0
type: Comment
has text: An update resource, for anyone interested in how lightgbm handles categorical features: **Categorical feature support:** https://lightgbm.readthedocs.io/en/latest/Advanced-Topics.html#categorical-feature-support **Optimal split algorithm for categorical features:** https://lightgbm.readthedocs.io/en/latest/Features.html#optimal-split-for-categorical-features
type: QuestionComment

http://stackoverflow.com/q/49616506
answer count: 1
has comment: http://stackoverflow.com/comment/86240142
has comment: http://stackoverflow.com/comment/86240217
type: Question
has comment: http://stackoverflow.com/comment/86240196
has title: I get the message "No module named django" even though it is installed and is in the system path
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86240434
has comment: http://stackoverflow.com/comment/86240273
has body: I am setting up django on my system using this tutorial, https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment. I did everything exactly as it told me to, but when I run the command "py -3 -m django --version", I get the message : "C:\Users\Vivek\AppData\Local\Programs\Python\Python36-32\python.exe: No module named django". I checked and the django installation is in the system path, and I can import django in python. What can I do to fix this error?
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49617078
has comment: http://stackoverflow.com/comment/86240149
has comment: http://stackoverflow.com/comment/86240303
score: 0
has comment: http://stackoverflow.com/comment/86240206

http://stackoverflow.com/a/49619793
answers question: http://stackoverflow.com/q/49619443
score: 1
upvote count: 1
has body: You want to split on the hyphen (if any), and return the substring ending in 'Mill' or 'POM': def extract_mill_name(s): """Extract the substring which ends in 'Mill' or 'POM'""" for subs in s.split('–'): subs = subs.strip(' ') if subs.endswith('Mill') or subs.endswith('POM'): return subs return None # parsing error. Could raise Exception instead df.mill.apply(extract_mill_name) 0 Company A Palm Oil Mill 1 Company X POM 2 DDDD Mill 3 R Mill 4 Great World POM
type: Answer
downvote count: 0

http://stackoverflow.com/a/49634245
answers question: http://stackoverflow.com/q/49633893
upvote count: 2
has body: I assume that you're expecting Child.add_2(5) to return 9 based on the fact that: Child.add_1 adds 2 to the argument it receives (initially 5) Child.add_2 (inherited from Parent) calls Child.add_1 twice (so it would make sense that 5 + 2 + 2 = 9) The problem is in Parent.add_2: plus_1 = cls.add_1(number) plus_2 = cls.add_1(number) cls.add_1 is called twice, but the result of the 1st call (plus_1) is ignored, and the 2nd call starts from number which is 5, resulting 7. To correct the problem (which I think it's a typo due to copy/paste), modify cls.add_1 2nd call to: plus_2 = cls.add_1(plus_1) to take the result of the 1st call into account.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86277540
type: Answer
accepted answer of: http://stackoverflow.com/q/49633893
score: 2

http://stackoverflow.com/comment/86365746
comment on: http://stackoverflow.com/q/49677060
score: 2
has text: I ended up using `df[df['currency' == '']].shape[0]`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86492537
has text: Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49738845

http://stackoverflow.com/a/49638076
answers question: http://stackoverflow.com/q/49638038
has comment: http://stackoverflow.com/comment/86284065
has comment: http://stackoverflow.com/comment/108596808
has body: You're telling keras to recompile the model every time you call model.compile() and you're doing that everytime you call update_model with: model.compile(loss='mean_squared_error', optimizer='adam') Remove that line and training will continue from previous state.
downvote count: 0
has comment: http://stackoverflow.com/comment/86284253
has comment: http://stackoverflow.com/comment/86298398
has comment: http://stackoverflow.com/comment/86291267
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49638571
tagged with: utc
tagged with: python
has answer: http://stackoverflow.com/a/49641430
has comment: http://stackoverflow.com/comment/86285856
tagged with: timestamp
type: AnsweredQuestion
score: 0
has title: Python - Convert 12 hour time in UTC in epoch format
has body: I have a text box that displays time in following local time format - 04/03/2018 02:59:44 PM I'm using Selenium in python to get this time and convert it (local time) to epoch time (UCT). But it's converting to a time that is 11 hours 30 mins earlier (April 3, 2018 3:29:44 AM). here is my code: next_chk_dt = myDriver.find_element_by_xpath("(//input[@id='dateIDVisible'])[6]").get_attribute('value') # displays 04/03/2018 02:59:44 PM if you print the value temp_Time2 = datetime.datetime.strptime(next_chk_dt, '%m/%d/%Y %H:%M:%S %p') epoch_Time1 = calendar.timegm(temp_Time2.timetuple()) print (epoch_Time1) # You get 1522726184, which is incorrect. it should be 1522781984
accepted answer: http://stackoverflow.com/a/49638987
type: Question
has answer: http://stackoverflow.com/a/49638987
answer count: 2
has comment: http://stackoverflow.com/comment/86285144
possible better answer: http://stackoverflow.com/a/49641430

http://stackoverflow.com/comment/86310573
comment on: http://stackoverflow.com/q/49651085
score: 0
type: Comment
type: QuestionComment
has text: Have you modified any admin templates or do you have any errors in the console when viewing the page?

http://stackoverflow.com/a/49796237
has body: Squeezing out maximum performance On vectorized operations you clearly have a bad cache behaviour. But the calculation itsef is also slow due to not exploiting modern SIMD instructions (AVX2,FMA). Fortunately it isn't really complicated to overcome this issues. Example import numpy as np import numba as nb @nb.njit(fastmath=True,parallel=True) def norm_loop_improved(M, v): n = M.shape[0] d = np.empty(n,dtype=M.dtype) #enables SIMD-vectorization #if the arrays are not aligned M=np.ascontiguousarray(M) v=np.ascontiguousarray(v) for i in nb.prange(n): dT=0. for j in range(v.shape[0]): dT+=(M[i,j]-v[j])*(M[i,j]-v[j]) d[i]=dT return d Performance M = np.random.random_sample((1000, 1000)) norm_loop_improved: 0.11 ms**, 0.28ms norm_loop: 6.56 ms norm_einsum: 3.84 ms M = np.random.random_sample((10000, 10000)) norm_loop_improved:34 ms norm_loop: 223 ms norm_einsum: 379 ms ** Be careful when measuring performance The first result (0.11ms) comes from calling the function repeadedly with the same data. This would need 77 GB/s reading-throuput from RAM, which is far more than my DDR3 Dualchannel-RAM is capable of. Due to the fact that calling a function with the same input parameters successively isn't realistic at all, we have to modify the measurement. To avoid this issue we have to call the same function with different data at least twice (8MB L3-cache, 8MB data) and than divide the result by two to clear all the caches. The relative performance of this methods also differ on array sizes (have a look at the einsum results).
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49632993
type: Answer

http://stackoverflow.com/comment/86422899
comment on: http://stackoverflow.com/a/49704484
type: Comment
score: 0
type: AnswerComment
has text: You are ignoring an exception. Use `try ... finally ...` instead. Or, better, don’t modify the list before removing the item.

windows
tags question: http://stackoverflow.com/q/49727290
tags question: http://stackoverflow.com/q/49718246
tags question: http://stackoverflow.com/q/49694087
tags question: http://stackoverflow.com/q/49612151
tags question: http://stackoverflow.com/q/49608065
tags question: http://stackoverflow.com/q/49709309
tags question: http://stackoverflow.com/q/49634506
tags question: http://stackoverflow.com/q/49671215
tags question: http://stackoverflow.com/q/49653161
type: Tag
tags question: http://stackoverflow.com/q/49621671
tags question: http://stackoverflow.com/q/49756765
tags question: http://stackoverflow.com/q/49615928
tags question: http://stackoverflow.com/q/49701448
tags question: http://stackoverflow.com/q/49640513
tags question: http://stackoverflow.com/q/49706430
tags question: http://stackoverflow.com/q/49637808
tags question: http://stackoverflow.com/q/49756437
tags question: http://stackoverflow.com/q/49604763
tags question: http://stackoverflow.com/q/49752070
tags question: http://stackoverflow.com/q/49677623
tags question: http://stackoverflow.com/q/49675767
tags question: http://stackoverflow.com/q/49625311
tags question: http://stackoverflow.com/q/49620862
tags question: http://stackoverflow.com/q/49757063
tags question: http://stackoverflow.com/q/49624730
tag name: windows
tags question: http://stackoverflow.com/q/49676420
tags question: http://stackoverflow.com/q/49708711
tags question: http://stackoverflow.com/q/49604784
tags question: http://stackoverflow.com/q/49601829
tags question: http://stackoverflow.com/q/49691285
tags question: http://stackoverflow.com/q/49687815
tags question: http://stackoverflow.com/q/49695990
tags question: http://stackoverflow.com/q/49675458

http://stackoverflow.com/q/49653597
has title: What's the best way to hint types of return values in python
upvote count: 1
answer count: 1
has body: There are many ways in python to hint value type, like this: def func(a: int, b: int) -&gt; int: return a+b But first, it will makes declaration looks complex. Seconds, it will cause some errors in a lower version of python. I also used :rtype: and :param value: in docstrings to hint type, but it seems not a very popular way and not that beautiful. I look into some open source library, but I didn't find out how they hint value type (or in some way I don't know). So what's the most popular and beautiful way to hint value type? Better some way in docstring. By the way, I'm using Vscode, and eager to know some way to help autocomplete know what's the type of value actually be returned by the function.
has comment: http://stackoverflow.com/comment/86315959
has comment: http://stackoverflow.com/comment/86316139
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/35230635
has comment: http://stackoverflow.com/comment/86316397
tagged with: visual-studio-code
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86316282
tagged with: python
has answer: http://stackoverflow.com/a/49653733
score: 0

http://stackoverflow.com/q/49641137
tagged with: apache-spark
has title: installing pyspark on windows
has answer: http://stackoverflow.com/a/71989196
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/73466819
has body: I can do a pip install pyspark on my windows. When I try to run a sample script below it tells me my SPARK_HOME is not set. Do i need to set my SPARK_HOME still and how do I go about doing it? The blogs which I have referred online do a manual extraction of the spark files from the spark website and then later they have to put the SPARK_HOME and the PYTHONPATH. However, I thought this was elimated with pip install pyspark. import findspark findspark.init() import pyspark # only run after findspark.init() from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() df = spark.sql('''select 'spark' as hello ''') df.show() For intellij, do I still need to do additional configuration once i have installed in pyspark and set up as necessary?
answer count: 2
score: 5
type: UnansweredQuestion
upvote count: 5
tagged with: pyspark
downvote count: 0
tagged with: python

http://stackoverflow.com/a/49731053
upvote count: 1
has body: I think the cost function is the summation of errors between the predicted label and the actual label which we want to minimise. The J function given above is the hypothesis function.
answers question: http://stackoverflow.com/q/49709352
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86483198
has text: Can you elaborate a little bit on what exactly you are trying to do and how the result of the code you posted differs from what you expect it to do?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49734446
type: QuestionComment

http://stackoverflow.com/comment/86291694
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49641953
has text: What do you think is a more Pythonic way to implement `flatten`? I almost always prefer EAFP, but somehow I always come back to LBYL for this one. For example - which exception(s) to catch, is just `TypeError` enough? It's hard to say.

http://stackoverflow.com/a/69602710
downvote count: 0
answers question: http://stackoverflow.com/q/49605830
has body: Try running python -m pytest I don't know why but this worked for me without changing the code in any of the files
score: 2
has comment: http://stackoverflow.com/comment/123026381
type: Answer
upvote count: 2

http://stackoverflow.com/comment/86321188
score: 0
type: Comment
has text: Probably you are right and it is not possible to simplify. I want to reduce 3 lines (temp=false, temp=true, if temp) into 1 line (else). So i don't think a new function will simplify the code :D
type: AnswerComment
comment on: http://stackoverflow.com/a/49655683

recursion
type: Tag
tags question: http://stackoverflow.com/q/49619930
tags question: http://stackoverflow.com/q/49707800
tags question: http://stackoverflow.com/q/49686764
tags question: http://stackoverflow.com/q/49653568
tags question: http://stackoverflow.com/q/49703263
tags question: http://stackoverflow.com/q/49721621
tag name: recursion
tags question: http://stackoverflow.com/q/49708682
tags question: http://stackoverflow.com/q/49728723
tags question: http://stackoverflow.com/q/49746552
tags question: http://stackoverflow.com/q/49720930
tags question: http://stackoverflow.com/q/49678981

http://stackoverflow.com/a/49604880
has comment: http://stackoverflow.com/comment/87810614
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49604782
upvote count: 2
has body: Use wildcards for haplotypes 1 and 2 in rule all. See here to learn more about adding targets via rule all reference_file = "ref.txt" rule all: input: expand("haplotypes/{sample}.hap{hap_no}.fna", sample=["A", "B"], hap_no=["1", "2"]) rule consensus1: input: vcf="variants/phased.vcf.gz", tbi="variants/phased.vcf.gz.tbi", bam="alignments/{sample}.sorted.bam" output: "haplotypes/{sample}.hap{hap_no}.fna" params: sample="{sample}", hap_no="{hap_no}" shell: "bcftools consensus -i -s {params.sample} -H {params.hap_no} \ -f {reference_file} {input.vcf} &gt; {output}"
has comment: http://stackoverflow.com/comment/87811407
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/86238183
answers question: http://stackoverflow.com/q/49604782
score: 2

http://stackoverflow.com/comment/86247218
has text: use python subprocess instead?
type: Comment
comment on: http://stackoverflow.com/q/49620132
score: 1
type: QuestionComment

http://stackoverflow.com/a/54337427
has comment: http://stackoverflow.com/comment/123875727
has comment: http://stackoverflow.com/comment/108294689
has body: As of 1.12, tf.data.experimental.sample_from_datasets provides this functionality: https://www.tensorflow.org/api_docs/python/tf/data/experimental/sample_from_datasets EDIT: Looks like in earlier versions this can be accessed by tf.contrib.data.sample_from_datasets
score: 8
accepted answer of: http://stackoverflow.com/q/49749706
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/127041940
type: Answer
answers question: http://stackoverflow.com/q/49749706

http://stackoverflow.com/comment/86489946
type: Comment
has text: Does the error still exists if you try using `sudo` in front of pip
type: QuestionComment
comment on: http://stackoverflow.com/q/49737799
score: 0

http://stackoverflow.com/a/49736523
answers question: http://stackoverflow.com/q/49663952
has comment: http://stackoverflow.com/comment/86544657
type: Answer
has comment: http://stackoverflow.com/comment/133058578
score: 1
accepted answer of: http://stackoverflow.com/q/49663952
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86506842
has body: Unless I am mistaken, you only need to access nth as an instance variable, by putting this. in front of it. Edit: You also need to use the "fat arrow" =&gt; in your filter, so that this is properly bound (otherwise this is undefined in that context). ticks.major = ticks.major.filter((element, index) =&gt; index % this.nth == 0)

list
tags question: http://stackoverflow.com/q/49698314
tags question: http://stackoverflow.com/q/49635593
type: Tag
tags question: http://stackoverflow.com/q/49744416
tags question: http://stackoverflow.com/q/49716702
tags question: http://stackoverflow.com/q/49733101
tags question: http://stackoverflow.com/q/49665291
tags question: http://stackoverflow.com/q/49708606
tags question: http://stackoverflow.com/q/49666036
tags question: http://stackoverflow.com/q/49713204
tags question: http://stackoverflow.com/q/49666523
tags question: http://stackoverflow.com/q/49658383
tags question: http://stackoverflow.com/q/49694848
tags question: http://stackoverflow.com/q/49642873
tags question: http://stackoverflow.com/q/49708469
tags question: http://stackoverflow.com/q/49666779
tags question: http://stackoverflow.com/q/49659881
tags question: http://stackoverflow.com/q/49718888
tags question: http://stackoverflow.com/q/49651202
tags question: http://stackoverflow.com/q/49732748
tags question: http://stackoverflow.com/q/49653126
tags question: http://stackoverflow.com/q/49720579
tags question: http://stackoverflow.com/q/49729810
tags question: http://stackoverflow.com/q/49702876
tags question: http://stackoverflow.com/q/49633222
tags question: http://stackoverflow.com/q/49671660
tags question: http://stackoverflow.com/q/49690613
tags question: http://stackoverflow.com/q/49700936
tags question: http://stackoverflow.com/q/49626310
tags question: http://stackoverflow.com/q/49646795
tags question: http://stackoverflow.com/q/49719353
tags question: http://stackoverflow.com/q/49660432
tags question: http://stackoverflow.com/q/49671970
tags question: http://stackoverflow.com/q/49621478
tags question: http://stackoverflow.com/q/49685426
tags question: http://stackoverflow.com/q/49642077
tags question: http://stackoverflow.com/q/49653107
tags question: http://stackoverflow.com/q/49649141
tags question: http://stackoverflow.com/q/49604693
tags question: http://stackoverflow.com/q/49618427
tags question: http://stackoverflow.com/q/49704401
tags question: http://stackoverflow.com/q/49696350
tags question: http://stackoverflow.com/q/49672676
tags question: http://stackoverflow.com/q/49700443
tags question: http://stackoverflow.com/q/49687402
tags question: http://stackoverflow.com/q/49639242
tags question: http://stackoverflow.com/q/49755496
tags question: http://stackoverflow.com/q/49712849
tags question: http://stackoverflow.com/q/49642143
tags question: http://stackoverflow.com/q/49654031
tags question: http://stackoverflow.com/q/49670289
tags question: http://stackoverflow.com/q/49654261
tags question: http://stackoverflow.com/q/49752739
tags question: http://stackoverflow.com/q/49750816
tags question: http://stackoverflow.com/q/49624967
tags question: http://stackoverflow.com/q/49743790
tags question: http://stackoverflow.com/q/49700794
tags question: http://stackoverflow.com/q/49746071
tags question: http://stackoverflow.com/q/49603867
tags question: http://stackoverflow.com/q/49635591
tags question: http://stackoverflow.com/q/49757660
tags question: http://stackoverflow.com/q/49683215
tags question: http://stackoverflow.com/q/49731425
tags question: http://stackoverflow.com/q/49675412
tags question: http://stackoverflow.com/q/49734582
tags question: http://stackoverflow.com/q/49625407
tags question: http://stackoverflow.com/q/49647860
tags question: http://stackoverflow.com/q/49711793
tags question: http://stackoverflow.com/q/49652846
tags question: http://stackoverflow.com/q/49601920
tags question: http://stackoverflow.com/q/49620158
tags question: http://stackoverflow.com/q/49697844
tags question: http://stackoverflow.com/q/49676276
tags question: http://stackoverflow.com/q/49752855
tags question: http://stackoverflow.com/q/49684082
tags question: http://stackoverflow.com/q/49716462
tags question: http://stackoverflow.com/q/49658148
tags question: http://stackoverflow.com/q/49646583
tags question: http://stackoverflow.com/q/49601240
tags question: http://stackoverflow.com/q/49641150

http://stackoverflow.com/comment/86457894
type: QuestionComment
comment on: http://stackoverflow.com/q/49722278
has text: OK. So what is your question?
score: 1
type: Comment

http://stackoverflow.com/comment/86538714
type: AnswerComment
comment on: http://stackoverflow.com/a/49743670
has text: @ekhumoro My previous comment related to your first comment. About your second comment, you sure about that? Thanks to point it out, I'll test it later on my machine and I'll update the answer if it's so
score: 0
type: Comment

http://stackoverflow.com/a/49618434
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86244016
type: Answer
has comment: http://stackoverflow.com/comment/86283959
has comment: http://stackoverflow.com/comment/86270911
accepted answer of: http://stackoverflow.com/q/49618233
score: 0
has comment: http://stackoverflow.com/comment/86259741
has comment: http://stackoverflow.com/comment/86281271
answers question: http://stackoverflow.com/q/49618233
has body: It looks like for what you want you could simply use pd.read_csv by passing it the path to your downloaded file instead: output_frame = pd.read_csv("C:/Users/USER/" + file)
has comment: http://stackoverflow.com/comment/86282766

http://stackoverflow.com/comment/86523474
score: 1
type: Comment
type: QuestionComment
has text: Why don't you go for `.select()` instead of `.find_all()`? Selector are very easy to control when it comes to deal with complex structure of `DOM`. That would definitely be tidier.
comment on: http://stackoverflow.com/q/49749996

http://stackoverflow.com/q/49684310
has answer: http://stackoverflow.com/a/57849506
favorite count: 0
possible better answer: http://stackoverflow.com/a/49684360
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49732802
has title: Value Error on computing matrix elements sum
tagged with: python
answer count: 6
accepted answer: http://stackoverflow.com/a/49684551
has answer: http://stackoverflow.com/a/67284352
type: AnsweredQuestion
has body: I am trying to write a function that adds all elements in a matrix. The special condition is if an element in the matrix is 0, we count the element below this 0 also 0. For example: matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]] Should return 9 because 1+1+2+5=9 Here is what I have for my code, I got this error, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Can someone please help? import numpy as np def matrixElementsSum(matrix): a=np.array([matrix]) sumofcolumn=0 sum=0 for x in range(len(a)): # x in matrix row for y in range(len(a[0])): #y in matrix col if a[x][y]==0: a[x+1][y]==0 #set next row same column=0 sumofcolumn+=a[x][y] #sumofcolumn is a column sum for x in sumofcolumn: sum+=x return sum
has answer: http://stackoverflow.com/a/49684551
has answer: http://stackoverflow.com/a/49684395
has answer: http://stackoverflow.com/a/49684360
tagged with: matrix
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86342378
has text: I thought, it was O(m*k) because of the 2 loops, but thanks for your answer. Is the comment of arbanert under my question also what you meant? "And O(m + 2k) = O(m+k)"
type: Comment
comment on: http://stackoverflow.com/a/49665982
score: 0
type: AnswerComment

http://stackoverflow.com/a/49704365
accepted answer of: http://stackoverflow.com/q/49702989
answers question: http://stackoverflow.com/q/49702989
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86507016
has body: This seems to work faster for building the constraints than the above approach: cover_rows = [np.nonzero(t)[0] for t in C] for i in range(numDemands): m.addConstr(quicksum(X[j] for j in cover_rows[i]) &gt;= 1)
type: Answer

http://stackoverflow.com/q/49705263
has comment: http://stackoverflow.com/comment/86423852
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49705422
type: AnsweredQuestion
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86423749
has comment: http://stackoverflow.com/comment/86423920
has comment: http://stackoverflow.com/comment/86423898
tagged with: python-3.x
has title: Python 3 recognized an element as a string
upvote count: 2
has body: I'm defining a loss function L(X,Y,c,b,d), where X and Y should be arrays, and c, b, d are floats. Here are my codes: def L(X,Y,c,b,d): error=0 a=Y[0] for i in range(len(X)): error = error + ((c*X[i]+(a/b)*np.sqrt(b**2-X[i]**2)+d)-Y[i])**2 return error I'm getting "TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'", which seems to mean that python recognized X[i] as a string. What should I do? Here are the full code, and X is a column of numbers. def L(X,Y,c,b,d): error=0 a=Y[0] for i in range(len(X)): error = error + ((c*X[i]+(a/b)*np.sqrt(b**2-X[i]**2)+d)-Y[i])**2 return error def L_prime_c(X,Y,c,b,d): p=0 for i in range(len(X)): p=p+2*L(X,Y,c,b,d)*X[i] return p def L_prime_d(X,Y,c,b,d): r=0 for i in range(len(X)): r=r+2*L(X,Y,c,b,d) return r def fit(X,Y,learning_rate=1e-3,max_iter=20000,epsilon=1e-5): c=1 b=1 d=Y[0] for i in range(max_iter): gradient_c = L_prime_c(X,Y,c,b,d) c_new = c - learning_rate * gradient_c gradient_b = L_prime_b(X,Y,c,b,d) b_new = b - learning_rate * gradient_b gradient_d = L_prime_d(X,Y,c,b,d) d_new = d - learning_rate * gradient_d if np.abs(c_new - c) &lt; epsilon and np.abs(d_new - d) &lt; epsilon and np.abs(b_new - b) &lt; epsilon: break c=c_new b=b_new d=d_new return np.array([c,b,d]) #getting X, Y In = xlrd.open_workbook(r'C:\Users\gris_\Desktop\calculation4.xlsx') isheet = In.sheet_by_name('Sheet1') X=isheet.col_values(0) Y=isheet.col_values(1) a=Y[0] #Calculation &amp; Output result=fit(X,Y,learning_rate=1e-3,max_iter=20000,epsilon=1e-5) Problem solved: I have 6 columns of different length, so when reading data from one column, python actually adds these " to make shorter ones the same length as the longest one. When I delete the other columns, things work out fine. Many thanks for your help! :D
has comment: http://stackoverflow.com/comment/86423863
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86423872
accepted answer: http://stackoverflow.com/a/49705422

http://stackoverflow.com/comment/86272017
comment on: http://stackoverflow.com/a/49632378
type: Comment
type: AnswerComment
has text: now the output is of type list, can we use these columns to construct a dataframe, which is the type of df.
score: 0

http://stackoverflow.com/q/49676116
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/49676284
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/49676261
has answer: http://stackoverflow.com/a/49676261
downvote count: 0
upvote count: 1
has title: Why can't scipy.optimize.curve_fit fit my data using a numpy.sinc function?
type: AnsweredQuestion
has body: I can't use scipy.optimize.curve_fit to fit data generated with numpy.sinc. Even when I do (or at least I think I do) the exact same thing as in the scipy documentation. Here is my simple try: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit xdata = np.arange(-10, 10, 0.1) y = 100*np.sinc(xdata - 3) + 1 y_noise = np.random.normal(3, 2, 200) ydata = y + y_noise def func(x, a, h, k): return(a*np.sinc(x - h) + k) popt, pcov = curve_fit(func, xdata, ydata) plt.plot(xdata, ydata) plt.plot(xdata, func(xdata, *popt)) plt.show() Here is the result:
score: 1
possible better answer: http://stackoverflow.com/a/49676284

http://stackoverflow.com/comment/86364672
type: Comment
has text: My window is supposed to keep up though, and thanks but I found a solution which was adding bt.image = food_image which should save the reference
comment on: http://stackoverflow.com/q/49675629
type: QuestionComment
score: 1

http://stackoverflow.com/q/49662776
has answer: http://stackoverflow.com/a/49663257
accepted answer: http://stackoverflow.com/a/49663257
has title: interaction of pandas and numpy
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86336742
tagged with: pandas
answer count: 1
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
has body: I am trying to understand exactly how numpy and pandas interact. In particular, a pandas.Series object is an ndarray with labels according to the docstring. numpy methods seem to work just fine on these types of objects.. is there casting somewhere under the hood? The best I have been able to dig up is that numpy.asanyarray() is called to convert the pandas.Series to an ndarray in some of the numpy functions. Is there anything else happening internally?
downvote count: 0

long-integer
tags question: http://stackoverflow.com/q/49685541
tag name: long-integer
type: Tag

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/49704679
tags question: http://stackoverflow.com/q/49660848
tags question: http://stackoverflow.com/q/49691946
tags question: http://stackoverflow.com/q/49667742
tags question: http://stackoverflow.com/q/49663551
tags question: http://stackoverflow.com/q/49751339
tags question: http://stackoverflow.com/q/49734227
tags question: http://stackoverflow.com/q/49722214
tags question: http://stackoverflow.com/q/49666360
tags question: http://stackoverflow.com/q/49629782
tags question: http://stackoverflow.com/q/49656877
tags question: http://stackoverflow.com/q/49666261
tags question: http://stackoverflow.com/q/49711851
tags question: http://stackoverflow.com/q/49673546
tags question: http://stackoverflow.com/q/49738811
tags question: http://stackoverflow.com/q/49625006
tags question: http://stackoverflow.com/q/49671889
tags question: http://stackoverflow.com/q/49682135
tags question: http://stackoverflow.com/q/49645306
tags question: http://stackoverflow.com/q/49641701
tags question: http://stackoverflow.com/q/49750393
tags question: http://stackoverflow.com/q/49665316
tags question: http://stackoverflow.com/q/49678261
tags question: http://stackoverflow.com/q/49698836
tags question: http://stackoverflow.com/q/49677428
tags question: http://stackoverflow.com/q/49683367
tags question: http://stackoverflow.com/q/49668147
tags question: http://stackoverflow.com/q/49734694
tags question: http://stackoverflow.com/q/49623647
tags question: http://stackoverflow.com/q/49610154
tags question: http://stackoverflow.com/q/49691696
tags question: http://stackoverflow.com/q/49669516
tags question: http://stackoverflow.com/q/49717500
tags question: http://stackoverflow.com/q/49713808
tags question: http://stackoverflow.com/q/49629678
tags question: http://stackoverflow.com/q/49690564
tags question: http://stackoverflow.com/q/49612023
tags question: http://stackoverflow.com/q/49738635
type: Tag
tags question: http://stackoverflow.com/q/49638063
tags question: http://stackoverflow.com/q/49698515
tags question: http://stackoverflow.com/q/49630772
tag name: html
tags question: http://stackoverflow.com/q/49654198
tags question: http://stackoverflow.com/q/49708728
tags question: http://stackoverflow.com/q/49724326
tags question: http://stackoverflow.com/q/49676621
tags question: http://stackoverflow.com/q/49628274
tags question: http://stackoverflow.com/q/49726855
tags question: http://stackoverflow.com/q/49630374
tags question: http://stackoverflow.com/q/49720357
tags question: http://stackoverflow.com/q/49609640
tags question: http://stackoverflow.com/q/49710566
tags question: http://stackoverflow.com/q/49702760
tags question: http://stackoverflow.com/q/49699221
tags question: http://stackoverflow.com/q/49705803
tags question: http://stackoverflow.com/q/49666015
tags question: http://stackoverflow.com/q/49631072
tags question: http://stackoverflow.com/q/49607418
tags question: http://stackoverflow.com/q/49712430

http://stackoverflow.com/comment/86494801
comment on: http://stackoverflow.com/q/49739465
type: Comment
type: QuestionComment
score: 0
has text: @CristiFati, this is not a Python issue. Python is one tool available for a solution, though you might call it overkill.

http://stackoverflow.com/a/52575608
has body: IF(@c=T1.total_revenue,@rowNo:=@rowNo,@rowNo:=@rowNo+1) AS rowNo, \ @c:=T1.total_revenue try IF(@c=T1.total_revenue,@rowNo:=@rowNo,@rowNo:=@rowNo+1) AS rowNo, \ (@c:=T1.total_revenue)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49642091

http://stackoverflow.com/comment/86323029
score: 0
type: Comment
has text: Strictly speaking, I think that is true. However, the implementation of the Python `Dataset` class I think creates the graph nodes lazily, so it _might_ still work if you return the same Python object. But you really shouldn't do that (and [official](https://github.com/tensorflow/models/blob/r1.7.0/official/resnet/imagenet_main.py#L157) [examples](https://github.com/tensorflow/models/blob/r1.7.0/official/mnist/mnist.py#L197) [don't](https://github.com/tensorflow/tpu/blob/6038242542fc8ff21f19d3c04bea214bc907d214/models/official/retinanet/dataloader.py#L106) either). Hope that helps.
type: AnswerComment
comment on: http://stackoverflow.com/a/49643876

http://stackoverflow.com/q/49672671
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I use a lot numba's jit decorator and I recently realize that new features have been added to numba, in particular parallel option and stencil decorator. Stencil is very nice for making cleaner code, but after a few tests, it seems that it is just beautiful, not efficient. Here is a sample code : @numba.njit def nb_jit(A, out): for i in range(1, A.shape[0]-1): out[i] = 0.5*(A[i+1] - A[i-1]) return out @numba.njit(numba.float64[:](numba.float64[:], numba.float64[:])) def nb_jit_typed(A, out): for i in range(1, A.shape[0]-1): out[i] = 0.5*(A[i+1] - A[i-1]) return out @numba.njit(parallel=True) def nb_jit_paral(A, out): for i in numba.prange(1, A.shape[0]-1): out[i] = 0.5*(A[i+1] - A[i-1]) return out @numba.stencil def s2(A): return 0.5*(A[1] - A[-1]) @numba.njit def nb_stencil(A): return s2(A) @numba.njit(parallel=True) def nb_stencil_paral(A): return s2(A) I tested these functions with the following arrays : import numpy as np arr = np.random.rand(100000) res = arr.copy() and it gives me the following execution times (Of course, I executed each function one time before the timeit !): ____________________________________________________ | %timeit nb_jit(arr, res) | 36 us | | %timeit nb_jit_typed(arr, res) | 68 us | | %timeit nb_jit_paral(arr, res) | 151 us | | %timeit nb_stencil(arr) | 59 us | | %timeit nb_stencil_paral(arr) | 241 us | ____________________________________________________ So I was wondering : Why nb_jit_typed is slower than nb_jit ? In my memory, it was the opposite last time I tested this. Why nb_jit_parallel is so slow ? Did I use stencil correctly ? I mean, using stencil this way leads to a loss of performance, so why should we use it ? Note : import numba numba.__version__ '0.37.0' import multiprocessing multiprocessing.cpu_count() 4 Edit: Timing the same functions over 10000 repetitions with arrays of dimensions (1000000, ) with time.time() (without any GUI) : jit | 16.37 s jit typed | 17.22 s jit parallel | 18.45 s stencil | 21.95 s stencil paral…
has comment: http://stackoverflow.com/comment/86356338
tagged with: numba
favorite count: 0
has comment: http://stackoverflow.com/comment/86375831
has comment: http://stackoverflow.com/comment/86358862
tagged with: python
has comment: http://stackoverflow.com/comment/86373873
has comment: http://stackoverflow.com/comment/86359368
has title: Numba performances
type: Question
upvote count: 5
score: 5

path
tags question: http://stackoverflow.com/q/49660548
tags question: http://stackoverflow.com/q/49732290
tags question: http://stackoverflow.com/q/49606213
tags question: http://stackoverflow.com/q/49757063
tags question: http://stackoverflow.com/q/49634471
tags question: http://stackoverflow.com/q/49613851
type: Tag
tags question: http://stackoverflow.com/q/49728799
tags question: http://stackoverflow.com/q/49631146
tags question: http://stackoverflow.com/q/49600464
tags question: http://stackoverflow.com/q/49701927
tags question: http://stackoverflow.com/q/49756369
tags question: http://stackoverflow.com/q/49669589
tags question: http://stackoverflow.com/q/49717462
tag name: path

http://stackoverflow.com/q/49618233
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86245609
tagged with: pandas
has body: I'm pulling in a file from FTP that I want to put in a Pandas dataframe eventually. I am stuck up on decoding the output into a string that can be read by pd.read_csv. def fetch_data(): ftp = FTP('hostname') ftp.login('username','password') files = ftp.nlst() output = [] for file in files: filedata = open("C:/Users/USER/" + file, 'w+b') ftp.retrbinary("RETR " + file, filedata.write) ftp.quit() decoded_data = bytes.decode(filedata) output_frame = pd.read_csv(decoded_data) output.append(output_frame) Here's the traceback: Traceback (most recent call last): File "dataframe.py", line 70, in &lt;module&gt; fetch_data() File "dataframe.py", line 32, in fetch_data decoded_data = bytes.decode(filedata) TypeError: descriptor 'decode' requires a 'bytes' object but received a'_io.BufferedRandom' I think I am misunderstanding the binary information coming from ftp.retrbinary. What's the best way to decode this information so that it can be read by pd.read_csv?
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49618434
type: Question
has comment: http://stackoverflow.com/comment/86244473
has title: How to decode bytes object from FTP retrbinary function in Python?
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49618434
has comment: http://stackoverflow.com/comment/86244849
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/86420929
comment on: http://stackoverflow.com/a/49700900
score: 0
type: AnswerComment
has text: It is working. In real life, I have object with all those values in dataframe. I don't need to hard code. However, how I make thoses with commas? (like 98,100 etc). This is my object 0 98 1 200 2 113 3 98 4 113 5 64 6 113 7 30 8 113 9 281 Name: site_seqno, dtype: int64
type: Comment

http://stackoverflow.com/comment/116514229
has text: This solution has already been posted, see [Kamal's answer](https://stackoverflow.com/a/55620248/2227743).
type: AnswerComment
comment on: http://stackoverflow.com/a/65894851
score: 1
type: Comment

http://stackoverflow.com/q/49742975
has comment: http://stackoverflow.com/comment/86501387
has comment: http://stackoverflow.com/comment/86501026
answer count: 0
has comment: http://stackoverflow.com/comment/86501447
tagged with: scipy
has comment: http://stackoverflow.com/comment/86501017
type: Question
linked to: http://stackoverflow.com/q/27890052
has comment: http://stackoverflow.com/comment/86500682
tagged with: performance
has comment: http://stackoverflow.com/comment/86501038
linked to: http://stackoverflow.com/q/43146266
type: UnansweredQuestion
has body: I have a list of size N which contains lists of integers (rows) of different lengths which I'd like to convert to a N x M numpy array. I'd like to do this by adding the trailing integer X to the end of every row so that the size of the row becomes M. The main issue is doing this very quickly. N ~= 10^6 M ~= 4200 import numpy as np def addTrailingZeros(data,M,X): for i in range(len(data)): data[i] = data[i]+[X]*(M-len(data[i])) return np.array(data, dtype=int) data = [[0],[1],[3,3],[8,4,9,3,2,0,5]] data2 = addTrailingZeros(data,10,0) print('data: ',data) print('data2: ',data2)
has title: Add Trailing Xs Fast
tagged with: python
duplicate of: http://stackoverflow.com/q/43146266
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/86500732
has comment: http://stackoverflow.com/comment/86501532
has comment: http://stackoverflow.com/comment/86501415

http://stackoverflow.com/comment/86287539
comment on: http://stackoverflow.com/a/49619169
score: 0
type: Comment
type: AnswerComment
has text: This question is for [tag:python], which your answer does not appear to be written in...

http://stackoverflow.com/comment/86446645
score: 0
has text: @abarnert that if i want to pass a string like dirname or path so i can concatenate it to command but if my argument not a string like an image or array of elements
type: QuestionComment
comment on: http://stackoverflow.com/q/49657513
type: Comment

http://stackoverflow.com/comment/86464185
type: Comment
type: AnswerComment
score: 1
has text: Great! no problem, `Happy Coding.`
comment on: http://stackoverflow.com/a/49725068

http://stackoverflow.com/a/70155692
answers question: http://stackoverflow.com/q/49717507
type: Answer
score: 0
has body: You can find great heuristics how to structurize project responsibilities in DDD (Domain Driven Design) approach. The project usually has domain logic (some business rules and actions) and application logic (orchestration of the business process, like executing domain objects methods, database access, external service requests, etc.). Domain logic should be implemented in entites and domain services, while application logic should be implemented within application services. You said that behaviour should not be bind to database access layer. You are right, but the solution is not to move business logic to service layer (application layer), but to seperate domain and persistance models (and keep domain logic in domain model). How to do it in python? You can find solutions here: Persist POJOs in Python using a DDD approach https://jorzel.hashnode.dev/persistence-and-domain-model-separation-using-sqlalchemy-orm

http://stackoverflow.com/q/49628353
has answer: http://stackoverflow.com/a/49628453
tagged with: python
has comment: http://stackoverflow.com/comment/86264020
has title: Convert Python Dictionary to Pandas Dataframe
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/49628388
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/49628453
has answer: http://stackoverflow.com/a/49628388
favorite count: 0
type: Question
has body: I am converting a python list/dictionary to a pandas dataframe: import numpy as np import pandas as pd points = [ {'coords': (100.5, 100), 'class': 1}, {'coords': (300, 300), 'class':2}, {'coords': (50, 200), 'class':4}, {'coords': (550, 400), 'class':10}, {'coords': (550, 300), 'class':1} ] # pandas data frame data = np.array('x', 'y', 'class') for point in points: row = [point['coords'][0], point['coords'][1], point['class']] data = np.vstack((data, row)) df = pd.DataFrame(data[1:]) df.columns = data[0:1].tolist() This gives following df: x y class 0 100.5 100.0 1.0 1 300 300 2 2 50 200 4 3 550 400 10 4 550 300 1 However, if I now try to do a calculation like: df['mult'] = df['x'] * df['y'] I get an error with: ValueError: Wrong number of items passed 2, placement implies 1

http://stackoverflow.com/q/49645171
has answer: http://stackoverflow.com/a/49645218
accepted answer: http://stackoverflow.com/a/49645218
favorite count: 0
type: Question
has body: I have 2 pandas dataframes like this: date value 20100101 100 20100102 150 date value 20100102 150.01 20100103 180 The expected output should be: date value 20100101 100 20100102 150 20100103 180 The 2nd dataframe always contains newest value that I'd like to add into the 1st dataframe. However, the value on the same day may differ slightly between the two dataframes. I would like to ignore the same dates and focus on adding the new date and value into the 1st dataframe. I've tried outer join in pandas, but it gives me two columns value_x and value_y because the value are not essentially the same on same dates. Any solution to this?
has title: pandas how to outer join without creating new columns
downvote count: 0
has comment: http://stackoverflow.com/comment/86298385
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86298470
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1

http://stackoverflow.com/q/49737803
answer count: 0
tagged with: orm
has comment: http://stackoverflow.com/comment/86489942
has title: How to make Django ORM query database through reverse ForeignKey work faster?
type: Question
has comment: http://stackoverflow.com/comment/86490464
type: UnansweredQuestion
has body: I have 3 models connected with ForeignKey: class Product(TimeStampedModel): product_id = models.AutoField(primary_key=True, ) shop = models.ForeignKey('Shop', related_name='products', to_field='shop_name', on_delete=models.CASCADE) brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name', on_delete=models.CASCADE) class Meta: indexes = [ models.Index(fields=['title', 'shop', 'sale']), models.Index(fields=['shop', 'brand', 'price', 'title']), ] class Brand(models.Model): brand_id = models.AutoField(primary_key=True,) brand_name = models.CharField(max_length=50, unique=True, blank=False, null=False) class Shop(models.Model): shop_id = models.AutoField(primary_key=True,) shop_name = models.CharField(max_length=30, unique=True, blank=False, null=False, db_index=True) From my view I try to filter Brands where available for this Shop, accessing Shop via Product ForeignKey: brands = Brand.objects.filter(products__shop__shop_name=shop).distinct('brand_name').order_by('brand_name') The problem is that this query takes a long time to process: from 1-3+ seconds. Is there a way to make it work faster? May be I can add some Indexes? I have already tried some combinations (you can find them in Product - Meta class), but it seems like that doesn't help. select_related('product') - throws an error: Invalid field name(s) given in select_related: 'product'. Choices are: (none) Or may be there is a better way when I create a Brand entry - add a some kind available_in_shops = ListField(...)(I have found this can be made with JSONField, but I don't know yet how this works exactly)? And store there a list of shops where that Brand is available?
has comment: http://stackoverflow.com/comment/86489900
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86490080
has comment: http://stackoverflow.com/comment/86490690
tagged with: postgresql
score: 0

http://stackoverflow.com/a/49669891
has comment: http://stackoverflow.com/comment/86381938
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86384395
accepted answer of: http://stackoverflow.com/q/49667461
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49667461
has body: Thinking that this post might help you, here is a way to get your required output using fold operation import scala.io.Source Source.fromFile("fileName").getLines() .toList.tail //remove headers .foldLeft(Map.empty[Int,Map[String,Int]]){ //use fold with seed (map, line) =&gt; { val words = line.split("\\W+") //split each line into words val lineNumber = words.apply(0).toInt //get line number this can throw error var existingCount = map.getOrElse(lineNumber, Map.empty[ String, Int]) //check for existing count words.tail.map(word =&gt; { val result: Int = existingCount.getOrElse(word,0) existingCount = existingCount + (word -&gt; (result + 1)) }) map + (lineNumber -&gt; existingCount) } }.foreach(e =&gt; println(e._1+ " | "+e._2.map(x =&gt; "("+x._1+", "+x._2+")"))) // 1 | List((Interface, 3), (MEth0, 2), (BMAC69RT01, 1), (null, 1), (1, 3), (on, 2), (Down, 3), (0, 2), (Gi0, 1), (2, 1), (node, 2)) // 2 | List((Interface, 2), (null, 1), (Fa0, 1), (on, 1), (Down, 1), (0, 4), (FastEthernet0, 1), (Up, 1), (node, 1))

http://stackoverflow.com/comment/86248912
score: 1
comment on: http://stackoverflow.com/q/49620969
has text: `v = df.isnull().sum(); v.index[v.gt(0)].tolist()`?
type: Comment
type: QuestionComment

odata
tag name: odata
type: Tag
tags question: http://stackoverflow.com/q/49635758

http://stackoverflow.com/q/49647855
upvote count: 0
has answer: http://stackoverflow.com/a/49648117
tagged with: input
tagged with: python
score: -1
tagged with: interactive
downvote count: 1
has title: How do I accept yes/no input from user and continue notifying them if they select no
has comment: http://stackoverflow.com/comment/86304128
accepted answer: http://stackoverflow.com/a/49648097
has comment: http://stackoverflow.com/comment/86303859
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49648097
has body: I hope to accept user's input as yes/no, if user input yes, the code will continue run the avaliable code, it user input no, the code will notifying user again and code will not run until user input 'yes' finally Here is the brief introdcution: # Here is part1 of code a = input('Have you finished operation?(Y/N)') if a.lower() == {'yes','y' } # user input 'y', run part2 code if a.lower() == {'no', 'n'} # user input no # code should notifying user again "'Have you finished operation?(Y/N)'" # part2 code will run until user finally input 'y' if a.lower() !={'yes','y', 'no', 'n'}: # user input other words # code should notifying user again "'Have you finished operation?(Y/N)'" # here is part2 of code Do you have any ideas on how to solve this problem, I would appreciate if you can provide some suggestions Update here is the code I'm tring yes = {'yes','y',} no = {'no','n'} print(1) print(2) while True: a = input('Have you create ''manually_selected_stopwords.txt'' ???(Y/N)''') if a.lower().split() == yes: break if a.lower().split() == no: continue print(3) print(4) When I run it, it shows as follows, the first time I tried input 'n' and then 'y', this will always notifying me, even I type into 'y' and will not print 3 and 4 1 2 Have you create manually_selected_stopwords.txt ???(Y/N)&gt;? n Have you create manually_selected_stopwords.txt ???(Y/N)&gt;? y Have you create manually_selected_stopwords.txt ???(Y/N)&gt;? y Have you create manually_selected_stopwords.txt ???(Y/N)&gt;? y Have you create manually_selected_stopwords.txt ???(Y/N)
has comment: http://stackoverflow.com/comment/86303681
has comment: http://stackoverflow.com/comment/86304018
has comment: http://stackoverflow.com/comment/86303919
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86304268
tagged with: python-3.x
answer count: 2
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/49648117
linked to: http://stackoverflow.com/q/23294658

http://stackoverflow.com/q/49610120
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49610304
tagged with: django
tagged with: python
has title: Get request through postman with JWT
type: AnsweredQuestion
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/49610304
answer count: 1
has body: I have installed pip install djangorestframework-jwt i have modified settings to REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } I have got a token by giving my credentials and then passing that token through bearer token in authorization in postman When I do a api call through postman it gives me error saying { "detail": "Authentication credentials were not provided." } The api call is for a BookViewSet. Why does it say details not provided after giving the token also. plz help me, Thanks.
tagged with: django-rest-framework

http://stackoverflow.com/a/49658805
type: Answer
score: 1
has body: I think part of the abysmal performance is that you keep creating new strings, because strings are immutable in python. So when you do processed += text[i] a new string of size processed + 1 is allocated. You want to avoid that allocation to be faster, so you transform the string into a list of char, and mutate that. Ideally you compute the space you will need and prefill the output list to avoid unnecessary allocations.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49658698

http://stackoverflow.com/comment/86434882
has text: @user9587850 I'm not quite sure I understand, could you post that code?
type: Comment
comment on: http://stackoverflow.com/a/49710462
score: 0
type: AnswerComment

configuration-files
type: Tag
tag name: configuration-files
tags question: http://stackoverflow.com/q/49719257

http://stackoverflow.com/a/49671383
has body: You just need to add parenthesis when calling get_cost() cost = stamp.get_cost() The reason your code didn't cause an error is because in Python, functions are first-class objects, i.e. you can use them as arguments to other functions, assign them to a variables etc. In your code you were assigning the actual function itself to a variable, rather than calling the function, and having the return value assigned. For more on this read up on functional programming languages (here's a good article https://www.quora.com/Is-Python-a-functional-language)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49671282

http://stackoverflow.com/comment/86406682
type: Comment
type: QuestionComment
score: 0
has text: @Nita Please _read_ the link I posted...
comment on: http://stackoverflow.com/q/49696850

http://stackoverflow.com/comment/86278548
type: QuestionComment
comment on: http://stackoverflow.com/q/49630981
has text: What is in your nginx error.log ?
score: 0
type: Comment

http://stackoverflow.com/q/49680934
duplicate of: http://stackoverflow.com/q/9884132
has comment: http://stackoverflow.com/comment/86374058
tagged with: python
has comment: http://stackoverflow.com/comment/86374090
has comment: http://stackoverflow.com/comment/86373944
type: AnsweredQuestion
score: 0
tagged with: iterator
upvote count: 2
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/49681110
has answer: http://stackoverflow.com/a/49681110
has comment: http://stackoverflow.com/comment/86373935
tagged with: iterable
has comment: http://stackoverflow.com/comment/86373854
has body: First of all i have to say i read lot of SO posts before coming to this one because I could not find what I was looking for or maybe I didn't understood. So here it goes I kind of understand what Iterables and Iterators are. So any container object like Lists/Tuples/Sets which contains items, which you can iterate over are called Iterables. Now to iterate over the Iterables you need Iterators and the way it happens is because of __iter__ method which gives you the Iterator object for the type and then calling the __next__ on the Iterator object to extract the values. So to make any object iterable you need to define iter and next methods, and i suppose that is true for Lists as well. But here comes the weird part which I discovered recently. l1 = [1,2,3] hasattr(l1, "__next__") Out[42]: False g = (x for x in range(3)) hasattr(g, "__next__") Out[44]: True Now because the lists do support Iterator protocol why the __next__ method is missing from their implementation, and if it indeed is missing then how does iteration for a list work ? list_iterator = iter(l1) next(list_iterator) Out[46]: 1 next(list_iterator) Out[47]: 2 next(list_iterator) Out[48]: 3 next(list_iterator) Traceback (most recent call last): File "C:\Users\RJ\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-49-56e733bbb896&gt;", line 1, in &lt;module&gt; next(list_iterator) StopIteration gen0_iterator = iter(g) gen_iterator = iter(g) next(gen_iterator) Out[57]: 0 next(gen_iterator) Out[58]: 1 next(gen_iterator) Out[59]: 2 next(gen_iterator) Traceback (most recent call last): File "C:\Users\RJ\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-60-83622dd5d1b9&gt;", line 1, in &lt;module&gt; next(gen_iterator) StopIteration gen_iterator1 = iter(g) next(gen_iterator1) Traceback (most recent …
favorite count: 0
type: Question
tagged with: python-3.x
has title: Why Generators are exhaustive and Lists/Tuples are not?

http://stackoverflow.com/a/49754886
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49754679
type: Answer
has body: From your code, I spotted the following issues for s in l: l is a line of text, the for loop will loop through each character, not word The f.split('\n') expression will generate an error because f is a file object, and it does not have the .split() method, string does With that in mind, here is a rewrite of your code to make it works: dic = {} with open("f1.txt" ,'r') as f: for l in f: for w in l.split(): dic[w] = dic.get(w,0)+1 print ('\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]))
score: 1

http://stackoverflow.com/comment/86380751
comment on: http://stackoverflow.com/a/49684702
type: Comment
has text: No need to explicitly cast to string, just use `format` or `%` -1
score: 0
type: AnswerComment

http://stackoverflow.com/q/49685426
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49685454
linked to: http://stackoverflow.com/q/13673060
tagged with: python
has comment: http://stackoverflow.com/comment/86382115
has answer: http://stackoverflow.com/a/49685479
tagged with: list
has comment: http://stackoverflow.com/comment/86382248
score: 1
has body: I'm trying to get a list of substrings of a given length out of a string. For example, if I have a string word = "PYTHON" and the specified substring length is 4, how can I obtain the following list? ['PYTH', 'YTHO', 'THON'] Here is my attempt: size = 4 win = [] word = "PYTHON" i = iter(word) for x in range(0,size): win.append(next(i)) print(win) for e in i: win = win[1:] + [e] print(win)
linked to: http://stackoverflow.com/q/8269916
downvote count: 0
has answer: http://stackoverflow.com/a/49685501
has answer: http://stackoverflow.com/a/49685484
upvote count: 1
has answer: http://stackoverflow.com/a/56713863
tagged with: string
favorite count: 0
type: Question
has title: How to get a list of substrings by using a sliding window iterator
answer count: 5

http://stackoverflow.com/q/49723040
score: -1
has body: I would like to match exactly a target word with a regular expression in the way that the desired word could be anywhere in the sentence/string (even at the end). Also, case insensitivity is a requirement. Below is an example of how the procedure should work. reg_expr = r'^(.*?(\bfoo\b)[^$]*)$' #Case 1 re.match(reg_expr,'foo abc',re.IGNORECASE) &lt;_sre.SRE_Match object; span=(0, 7), match='foo abc'&gt; # MATCH #Case 2 re.match(reg_expr,'foos abc',re.IGNORECASE) # NO MATCH, WE WANT EXACTLY A foo MATCH #Case 3 re.match(reg_expr,'abc foo',re.IGNORECASE) &lt;_sre.SRE_Match object; span=(0, 7), match='abc foo'&gt; # MATCH Furthermore, I have to match tons of sentences and try to match with many target keywords in a single regex. As an example I added the word bar in the regex with the alternation operand |: reg_expr2 = r'^(.*?(\bfoo|bar\b)[^$]*)$' #Case 1 re.match(reg_expr2,'foo abc',re.IGNORECASE) &lt;_sre.SRE_Match object; span=(0, 7), match='foo abc'&gt; # MATCH #Case 2 re.match(reg_expr2,'foos abc',re.IGNORECASE) &lt;_sre.SRE_Match object; span=(0, 8), match='foos abc'&gt; # MATCH #Case 3 re.match(reg_expr2,'abc foo',re.IGNORECASE)+ &lt;_sre.SRE_Match object; span=(0, 7), match='abc foo'&gt; # MATCH Just by adding the alternation operator | we can see that case 2 does not work as intended because the string contains foos and not foo. Could somebody explain why does this occur? What would be the correct regex for my purpose?
has title: Regex alternation operator | not working as intended - Python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49723103
upvote count: 0
answer count: 1
tagged with: match
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86459895
type: Question
has comment: http://stackoverflow.com/comment/86514772
has comment: http://stackoverflow.com/comment/86459977
has answer: http://stackoverflow.com/a/49723103
tagged with: python
tagged with: regex

http://stackoverflow.com/a/49660203
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86330011
has body: You were pretty close @Simpson! Here's a slightly changed version that should give you what you're looking for :) Let me know if you have any questions! #A text program that is a simple number guessing game. import random #Setting up the A.I. def AI(): counter = 1 number = random.randint(1,101) guess = int(input("Can you guess what number I'm Thinking of?: ")) while guess != number: if guess &lt; number: print("Sorry, thats to low. try again!") else: print("nope, too high") counter += 1 guess = int(input("Can you guess what number I'm Thinking of?: ")) print("Congragulations! you win! You guessed " + str(counter) + " times") time.sleep(60) quit() AI()
type: Answer
has comment: http://stackoverflow.com/comment/86330081
answers question: http://stackoverflow.com/q/49660097

http://stackoverflow.com/q/49711843
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86437262
has comment: http://stackoverflow.com/comment/86437292
answer count: 0
has title: Send non blocking requests in while loop
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: request
tagged with: python-3.6
score: 1
has body: I'm currently creating a small application (in python 3.6) and have some problems with sending a non blocking request to a server. This is my code: def foo(): x = get_input_and_pre_process() # synchronous send_non_blocking_request(x) # don't await response of the request do_something_else(x) # synchronous while True: foo() So basically the case is the following: I'm reading live data from an input and once I made some small changes to it, I want to send it to a server. But since I'm reading the data live I cannot afford awaiting the answer from the server and want to immediately continue with do_something_else() after sending the request and then continue with the next iteration of the while loop. I'm not expecting any special response from the server, the key point is just to send out the data. I read some articles about asynchronous programming with asyncio and aiohttp, but I'm not sure if this does the job here. I also thought about executing the requests in a new thread but then I would be spawning thousands of new threads in the while-loop (which is also not that great of an idea I guess). What is the best way to do this?

http://stackoverflow.com/comment/86301908
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49646840
has text: Yes, you got my point. So that looks I used wrong methods to do the calculation. Thank you @icza.
type: Comment

http://stackoverflow.com/comment/86459812
has text: Please check out, how to ask a question on stackoverflow.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49722561
score: 0

http://stackoverflow.com/a/49744135
has body: I’m unable to interpret “Asking a question should not change the answer”, I read the ppt wikipedia linked which takes an example of ‘light’ sign inside and outside of channel. It did not illustrate the relationship between a question and an answer. Light? essentially asks "Is the light on?" It returns True or False. The wrong thing for Light? to do is to turn the light on if it's off, or to turn the light off if it's on. In the absence of any other confounding code, executing Light? three times in a row should return the same value three times. Asking a question should not change the answer. But if asking the question Light? changed the answer, you'd get "True, False, True" or "False, True, False". In my perception, It should be “Answering a question should not change the question” No, because answers (return values) can't change questions (method calls). But questions can change answers (if you code your methods that way).
type: Answer
answers question: http://stackoverflow.com/q/49743954
score: 0

http://stackoverflow.com/comment/86517881
has text: Have you considered mentioning that important information in your question?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49751627
type: QuestionComment

http://stackoverflow.com/a/49729071
has comment: http://stackoverflow.com/comment/86485637
accepted answer of: http://stackoverflow.com/q/49725629
type: AcceptedAnswer
downvote count: 0
score: 3
upvote count: 3
has body: You can use pd.DataFrame.update (an in-place operation) before pd.DataFrame.combine_first: New_df.update(Master_df) res = New_df.combine_first(Master_df) # color price tastey # name # Anise Brown NaN NaN # Apples Red Low Always # Avocados Black NaN Sometimes # Bananas Yellow Medium NaN # Berries Red High NaN
type: Answer
answers question: http://stackoverflow.com/q/49725629

http://stackoverflow.com/comment/86356688
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49672808
has text: Hi, I edited the main post to show the desired output.
score: 0

http://stackoverflow.com/comment/86358632
type: Comment
has text: Thanks for your reply
type: QuestionComment
comment on: http://stackoverflow.com/q/49672500
score: 0

http://stackoverflow.com/a/49738909
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49738489
has body: reset_index() will do &gt;&gt;&gt; df.reset_index()["Meses"] The code you're using (link) is setting multi index and one column though index = pd.MultiIndex.from_tuples(keylist, names=dimension_names) ... df = pd.DataFrame(values, index=index, columns=["Values"]) Just reset the index to make it a flat df.
accepted answer of: http://stackoverflow.com/q/49738489

http://stackoverflow.com/q/49612874
linked to: http://stackoverflow.com/q/427453
score: 0
has comment: http://stackoverflow.com/comment/86232273
answer count: 0
has comment: http://stackoverflow.com/comment/86232482
has body: I am currently using online python interpreter. The problem is here, there are some pre-loaded variables or functions which do not appear on the interactive editor, just there is an instruction which informs their name and their final output. The question here is, how to find out the structure of the functions or in other words how to print their scopes? For instance, instruction indicates the name of a function is get_mse() and It operates Mean Squared Error and also gets three arguments, then It is ready to use but I want to know what It consists of. Note: These imported functions are not built-in and certainly manipulated and imported from other python files which are not available from the source.
has comment: http://stackoverflow.com/comment/86232606
has comment: http://stackoverflow.com/comment/86232246
has title: How to print the body of imported method or function in python?
type: Question
tagged with: python-import
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/427453
has comment: http://stackoverflow.com/comment/86232613
has comment: http://stackoverflow.com/comment/86232662
has comment: http://stackoverflow.com/comment/86232247
tagged with: python
linked to: http://stackoverflow.com/q/15432499
has comment: http://stackoverflow.com/comment/86232425

http://stackoverflow.com/q/49641446
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/86313122
score: 0
tagged with: winapi
has comment: http://stackoverflow.com/comment/86290758
type: Question
has answer: http://stackoverflow.com/a/49664150
has body: I'm trying to use the example from https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch07s14.html to connect to a database that another account on my network has access to. The error I'm given is: r'DSN=Test' LookupError: unknown encoding: utf-16le import win32security, win32con class Impersonate: def _ _init_ _(self, login, password): self.domain = 'bedrock' self.login = login self.password = password def logon(self): self.handle = win32security.LogonUser(self.login, self.domain, self.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(self.handle) def logoff(self): win32security.RevertToSelf( ) # terminates impersonation self.handle.Close( ) # guarantees cleanup if __name__=='__main__': a = Impersonate('barney', 'bambam') try: a.logon() # become the user try: # Do whatever you need to do, e.g.,: print win32api.GetUserName() # show you're someone else cnxn = pyodbc.connect( r'DSN=Test;' ) finally: a.logoff() # Ensure return-to-normal no matter what except: print 'Exception:', sys.exc_type, sys.exc_value
has comment: http://stackoverflow.com/comment/86300480
type: UnansweredQuestion
has title: pyodbc unkown encoding error when impersonating user using win32 security
answer count: 1

http://stackoverflow.com/a/49684083
has body: You can use the built-in df.plot.scatter() function and pass the flag column to the color argument: import pandas as pd idx = [1,2,3] value = [0., 0.03, 0.13] flag = [0, 0, 1] df = pd.DataFrame(dict(idx=idx, value=value, flag=flag)) df.plot.scatter('idx', 'value', c='flag', cmap='RdBu_r')
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49684037
type: Answer
answers question: http://stackoverflow.com/q/49684037
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86430513
comment on: http://stackoverflow.com/q/49701183
type: QuestionComment
score: 0
has text: Well, did you forget `/` in your format string then? Should it be `"%s/bot/%s/%s"`?
type: Comment

http://stackoverflow.com/a/49630800
answers question: http://stackoverflow.com/q/49628250
has body: You can use itertools and zip to help with this: from itertools import chain import pandas as pd df = pd.DataFrame({'Numbers': list(chain.from_iterable(A)), 'State/UT Capital': [' '.join([i[0], j[0]]) for i, j in zip(B, C)]}) Result: Numbers State/UT Capital 0 1 Andaman and Nicobar Islands Port Blair 1 2 Andhra Pradesh Hyderabad 2 3 Arunachal Pradesh Itanagar 3 4 Assam Dispur .........
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49609196
tagged with: django-views
has answer: http://stackoverflow.com/a/49609270
has body: I am creating the object with just only related field id. I have searched a lot but couldn't get the answer. Here is my code models.py: class Resturant(models.Model): name = models.CharField(_('name'), max_length=100) class Menu(models.Model): resturant_id = models.OneToOneField(Resturant, related_name='resturant', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) serializers.py: class MenuSerializer(serializers.ModelSerializer): resturant_id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Menu fields = ['id', 'created_at', 'resturant_id'] views.py: class CreateMenuAPIView(APIView): def post(self, request, *args, **kwargs): serializer = MenuSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) I am getting this error while sending { "resturant_id": 2 } in POST request. DETAIL: Failing row contains (14, 2018-04-02 09:36:43.261849+00, null). The above exception (null value in column "resturant_id" violates not-null constraint Any help would be appreciated !
tagged with: django-models
has title: Related field id in POST request in Django Rest Framework
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/49609440
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49621429
has comment: http://stackoverflow.com/comment/86225387
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/86225530
has answer: http://stackoverflow.com/a/49609711

http://stackoverflow.com/comment/86303408
comment on: http://stackoverflow.com/q/49646334
type: Comment
has text: Yes, it is true. Some flags enable/disable parallelism, some enable/disable use of GPU, some enable/disable optimisations (SIMD and others), some permit faster/less accurate maths and so on... I mean it is true that some flags will make OpenCV faster, some will also make it slower so it is not necessarily true that compiling from source is faster - it could be slower if you set the flags sub-optimally (geek-speak for *"badly"*)
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86486254
score: 0
has text: try running `pip install setuptools_scm` individually to see what happens?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49720618

http://stackoverflow.com/a/49705790
type: Answer
answers question: http://stackoverflow.com/q/49705754
has body: Use concat with filter second DataFrame by boolean indexing: print (data1.iloc[-1, 0]) 554 df = pd.concat([data1, data2[data2[0] &gt; data1.iloc[-1, 0]]], ignore_index=True) print (df) 0 1 0 4 4 1 75 6 2 2 67 3 5 6 4 84 4 5 2 5 6 6 8 7 5 5 8 554 8 9 555 1 10 556 3 11 557 5 12 558 3 13 559 1 14 560 5 Also for general solution compare by max value: df = pd.concat([data1, data2[data2[0] &gt; data1[0].max()]], ignore_index=True) Solution if custom columns names: data1 = pd.DataFrame(data1, columns=list('ab')) data2 = pd.DataFrame(data2, columns=list('ab')) print (data1.iloc[-1, data1.columns.get_loc('a')]) 554 data22 = data2[data2['a'] &gt; data1.iloc[-1, data1.columns.get_loc('a')]] df = pd.concat([data1, data22], ignore_index=True) print (df) a b 0 4 4 1 75 6 2 2 67 3 5 6 4 84 4 5 2 5 6 6 8 7 5 5 8 554 8 9 555 1 10 556 3 11 557 5 12 558 3 13 559 1 14 560 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86431501
accepted answer of: http://stackoverflow.com/q/49705754
score: 3
upvote count: 3

http://stackoverflow.com/comment/86485673
type: QuestionComment
has text: To clarify my question above: How do I convert xlist above to a list of lists. ie replace the '(' with '[' and make it a list?
comment on: http://stackoverflow.com/q/49732890
score: 0
type: Comment

http://stackoverflow.com/q/49676188
score: 0
linked to: http://stackoverflow.com/q/8039636
has body: I want to find each cluster's center and radius. What can I do? Please help me. Here is my code it contain dbscan and meanshifts two result. The points is random and now i want to find each cluster's center and radius. import numpy as np import matplotlib.pyplot as plt from sklearn import cluster def cluster_plots(set, colours1='gray', colours2='gray', title1='Plot 1', title2='Plot 2'): fig, (ax1, ax2) = plt.subplots(1, 2) fig.set_size_inches(6, 3) ax1.set_title(title1, fontsize=14) ax1.set_xlim(min(set[:, 0]), max(set[:, 0])) ax1.set_ylim(min(set[:, 1]), max(set[:, 1])) ax1.scatter(set[:, 0], set[:, 1], s=8, lw=0, c=colours1) ax2.set_title(title2, fontsize=14) ax2.set_xlim(min(set[:, 0]), max(set[:, 0])) ax2.set_ylim(min(set[:, 1]), max(set[:, 1])) ax2.scatter(set[:, 0], set[:, 1], s=8, lw=0, c=colours2) fig.tight_layout() plt.show() def data_generator(): clust1 = np.random.normal(5, 2, (1000, 2)) clust2 = np.random.normal(15, 3, (1000, 2)) clust3 = np.random.multivariate_normal([17, 3], [[1, 0], [0, 1]], 1000) clust4 = np.random.multivariate_normal([2, 16], [[1, 0], [0, 1]], 1000) return np.concatenate((clust1, clust2, clust3, clust4)) datapoints = data_generator() bandwidths = [cluster.estimate_bandwidth(dataset, quantile=0.1) for dataset in [datapoints]] meanshifts = [cluster.MeanShift(bandwidth=band, bin_seeding=True).fit(dataset) for dataset, band in zip([datapoints], bandwidths)] dbscan = cluster.DBSCAN(eps=1, min_samples=10, metric='euclidean').fit_predict(datapoints) cluster_plots(datapoints, dbscan,meanshifts[0].predict(datapoints),title1='DBScan', title2='Meanshifts') I don't know what should I add can get what i want.
answer count: 1
has title: Using DBSCAN to find each cluster center, radius in Python?
has answer: http://stackoverflow.com/a/49699762
type: Question
tagged with: dbscan
has comment: http://stackoverflow.com/comment/86412760
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49732220
type: Question
tagged with: django
has body: when im setting Django to Debug=False, I am getting an error 500 when running via gunicorn or via manage.py. when running via manage I do not get any errors in console. my settings file has the allowed hosts set to ['*']. As soon as I change Debug=True everything works again. where would I get the output of the 500 if not from the console when running manage.py? here is my settings file: ''' Django settings for itapp project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ ''' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import ldap BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *********** # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'home.apps.HomeConfig', 'oncall.apps.OncallConfig', 'tools.apps.ToolsConfig', 'sites.apps.SitesConfig', 'maintenance.apps.MaintenanceConfig', 'service.apps.ServiceConfig', 'monitoring.apps.MonitoringConfig', 'mgmt.apps.MgmtConfig', 'config.apps.ConfigConfig', 'circuits.apps.CircuitsConfig', 'storages', 'imagekit', 'django_celery_results', 'debug_toolbar', 'simple_history', 'crispy_forms', ) MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthe…
has comment: http://stackoverflow.com/comment/86478433
has comment: http://stackoverflow.com/comment/86478512
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86478369
score: 0
has title: Django error 500 when Debug=False - allowed hosts set to *. nothing in console
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49732404
has answer: http://stackoverflow.com/a/49732404

http://stackoverflow.com/a/49649636
score: 0
answers question: http://stackoverflow.com/q/49647182
type: AcceptedAnswer
has body: If I understand correctly, your problem is that you want to take a 2D box out of a 3D array. If you want the 2D box to be expressed still as a 3D array with one axis which is of length one, you can use: template = mrc[64:77, 50:51, 9:32] # shape (13, 1, 23) If instead you really want just a 2D array, this simplifies to: template = mrc[64:77, 50, 9:32] # shape (13, 23) Hope this helps.
type: Answer
accepted answer of: http://stackoverflow.com/q/49647182

http://stackoverflow.com/a/53586478
has body: once and for all clarification when you get this python or pip is not recognised error in windows command prompt happens often when multiple IDE installations Go to environmental variables then to system variables where you change or add this sometimes your anaconda3 path maybe in allusers if you install it as administator so go through the C drive to get that example C:\Users\All Users\anaconda3 If not try py -m pip install yourpackage
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49616399

http://stackoverflow.com/a/49642744
type: Answer
has comment: http://stackoverflow.com/comment/86313388
answers question: http://stackoverflow.com/q/49642651
has comment: http://stackoverflow.com/comment/86317184
score: 1
has comment: http://stackoverflow.com/comment/86320884
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86317225
has body: At a first look, it looks like your new callback is missing a self field? The original function was def rotaryChange(self, pin): self.clickedOnce = True But your implementation is: def rotaryChange(pin, host): host.clickedOnce = True If this function sits inside a class it needs to have a self parameter

http://stackoverflow.com/a/49666750
has body: How about type(None)? Just do: type(x) in (list, set, str, type(None)) seems to work for me, and is quite clear to me at least. Since there is only one value of NoneType, using it as a literal is hardly "magic".
has comment: http://stackoverflow.com/comment/86343493
has comment: http://stackoverflow.com/comment/86343866
score: 5
has comment: http://stackoverflow.com/comment/86344234
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/86343590
has comment: http://stackoverflow.com/comment/86343306
has comment: http://stackoverflow.com/comment/86343987
has comment: http://stackoverflow.com/comment/86343674
downvote count: 0
answers question: http://stackoverflow.com/q/49666705

http://stackoverflow.com/comment/86565926
type: Comment
comment on: http://stackoverflow.com/a/49728599
type: AnswerComment
has text: thanks. what entity should consume the output that's full? parent process? don't understand also how communicate fixes it. it's written in its docs that `do not use this method if the data size is large or unlimited`
score: 1

http://stackoverflow.com/a/49668012
upvote count: 1
has body: The problem here is actually your loss function. Since you already have 1-hot encoded y vectors then you should not be using the sparse categorical cross entropy, but rather you should use categorical cross entropy. Try this Categorical cross entropy Let's just make some dummy data for dimensions sake. X_train = np.zeros((2464, 150, 1)) y_train = np.zeros((2464,)) X_val = np.zeros((2464, 150, 1)) y_val = np.zeros((2464,)) X_train_r = X_train.reshape(2464,150,) X_val_r = X_val.reshape(2464,150,) input_shape = (150,) print(X_train_r.shape) print(X_val_r.shape) (2464, 150) (2464, 150) Now we will get our one hot encoded outputs for our labels. num_classes = 5 # Convert class vectors to binary class matrices. This uses 1 hot encoding. y_train_binary = keras.utils.to_categorical(y_train, num_classes) y_val_binary = keras.utils.to_categorical(y_val, num_classes) print(y_train_binary.shape) print(y_val_binary.shape) (2464, 5) (2464, 5) Now we will make our model as follows model = Sequential() model.add(Dense(16, activation='relu',input_shape=input_shape)) model.add(Dense(16, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.summary() history=model.fit(X_train_r, y_train_binary, epochs=5, batch_size=8, validation_data=(X_val_r, y_val_binary)) This will work for you. Sparse categorical cross entropy If you want to use sparse categorical cross entropy then you should not use 1-hot encoded labels. Like this X_train = np.zeros((2464, 150, 1)) y_train = np.zeros((2464,)) X_val = np.zeros((2464, 150, 1)) y_val = np.zeros((2464,)) X_train_r = X_train.reshape(2464,150,) X_val_r = X_val.reshape(2464,150,) input_shape = (150,) num_classes = 5 model = Sequential() model.add(Dense(16, activation='relu',input_shape=input_shape)) model.add(Dense(16, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='sp…
has comment: http://stackoverflow.com/comment/86346931
has comment: http://stackoverflow.com/comment/86349003
has comment: http://stackoverflow.com/comment/86346624
answers question: http://stackoverflow.com/q/49667863
type: Answer
has comment: http://stackoverflow.com/comment/86346149
has comment: http://stackoverflow.com/comment/86347501
has comment: http://stackoverflow.com/comment/86346446
has comment: http://stackoverflow.com/comment/86347953
has comment: http://stackoverflow.com/comment/86346994
accepted answer of: http://stackoverflow.com/q/49667863
has comment: http://stackoverflow.com/comment/86349281
score: 1
has comment: http://stackoverflow.com/comment/86349380
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86346325

http://stackoverflow.com/q/49719404
score: -1
has answer: http://stackoverflow.com/a/49719787
has comment: http://stackoverflow.com/comment/86452158
has comment: http://stackoverflow.com/comment/86452052
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/49719784
has comment: http://stackoverflow.com/comment/86452002
has answer: http://stackoverflow.com/a/49719857
has comment: http://stackoverflow.com/comment/86451971
has comment: http://stackoverflow.com/comment/86452344
downvote count: 1
favorite count: 0
has body: I have a list path. Initially, it looks like this: path = [2, 1, 3, 0] I will have to run many operations on path in different steps of my process. But I have to store the contents of path after each step. I mean, path = [2, 1, 3, 0] path.pop() # need to store path.pop() # same path.append(9) # same path.append(5) # same So, after each of these steps path will look like this: path = [2, 1, 3, 0] path = [2, 1, 3] path = [2, 1] path = [2, 1, 9] path = [2, 1, 9, 5] As I need each of these so I want to store them in a 2D list. Therefore, in the end, the 2D list will look like this: But the problem is, initially I don't know how large custom_list can grow? It's decided only at runtime. So what I thought is that after each step I will append the path to my custom_list so when the process is finished custom_list will store all the path's content as mentioned above. Like this: custom_list = [[2, 1, 3, 0], [2, 1, 3], [2, 1], [2, 1, 9], [2, 1, 9, 5]] But for this .append does not work. How to solve this problem? Also is this efficient to implement this with list or should I choose any other way i.e. numpy array or anything else? If so then kindly mention and explain Edit Code: list = [2,1,3,0] my_list = [[]] my_list.append(list) list.pop() list.pop() list.append(9) my_list.append(list) list.append(5) my_list.append(list) my_list &gt;&gt;&gt;[[], [2, 1, 9, 5], [2, 1, 9, 5], [2, 1, 9, 5]]
type: Question
has title: How to store sets of new list in a 2d list in python?
has comment: http://stackoverflow.com/comment/86452513
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86452370
tagged with: python

http://stackoverflow.com/comment/86327834
has text: @sascha, the error occurs in the `lil.__setitem__` method. If `x` is sparse, it does `x.toarray()`. I found the `np.zeros` line in `sparse.base` `_process_toarray_args` method. The OP has withheld vital information!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49652985
type: Comment

http://stackoverflow.com/comment/86458593
type: QuestionComment
has text: Sorry I was just playing around trying to fix it and added `request`. If I remove it, I get error: Reverse for 'confirm' with keyword arguments '{'email': 'email'}' not found. 1 pattern(s) tried: ['book/booking_confirmation/$']. Basically I wanted to have a personalised confirmation at the end, where it displays the fact we sent a confirmation to the email.
comment on: http://stackoverflow.com/q/49721830
score: 0
type: Comment

http://stackoverflow.com/a/59829393
has body: The above solution takes lot of time, hence use below code instead for better performance(Note fillna used to fillup default values when match not found):- df['state'].map(state_map).fillna(0) df['country'].map(country_map).fillna(0)
answers question: http://stackoverflow.com/q/49727668
type: Answer
score: 0

http://stackoverflow.com/comment/130698121
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/60781433
has text: Unfortunately your example doesn't compile, and even fixing those errors, it has runtime errors because `submit` doesn't map list elements into function parameters. I'm not sure if you downvoted my answer, but if there's something wrong with it please leave a comment explaining why, thanks.
type: Comment

http://stackoverflow.com/q/49644298
has comment: http://stackoverflow.com/comment/86301617
answer count: 1
downvote count: 3
score: 1
has body: How to plot a x versus y line? By x versus y, I mean how to plot x vs y line if the x and y axes have already fixed, as if the axes are reversed for this line. Update: Some one asked me why not just reverse the arguments and axes labels. Here is my reason: this x vs y line is only a part of a 2D plot (the main plot) and the main axes are for the 2D plot. What's more, there are also y vs x lines in the same 2D plot. I do this because I want to show certain line clearly. Update: Here is a example what I want: I want to plot the black line in the figure which I draw manually (actually I want to draw Gaussian curve). It is time vs voltage. I still want to keep the existed blue line and I should not reverse the time/voltage labels.
has comment: http://stackoverflow.com/comment/86301840
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86301718
accepted answer: http://stackoverflow.com/a/49647497
has answer: http://stackoverflow.com/a/49647497
tagged with: python
has title: How to plot x versus y lines using matplotlib?
tagged with: plot
has comment: http://stackoverflow.com/comment/86299515
has comment: http://stackoverflow.com/comment/86301801
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86299485
has comment: http://stackoverflow.com/comment/86297686
tagged with: matplotlib

matplotlib
tags question: http://stackoverflow.com/q/49749778
tags question: http://stackoverflow.com/q/49707863
tags question: http://stackoverflow.com/q/49729748
tags question: http://stackoverflow.com/q/49709030
tags question: http://stackoverflow.com/q/49739769
tags question: http://stackoverflow.com/q/49672963
tags question: http://stackoverflow.com/q/49736849
tags question: http://stackoverflow.com/q/49684811
tags question: http://stackoverflow.com/q/49601800
tags question: http://stackoverflow.com/q/49621994
tags question: http://stackoverflow.com/q/49609543
tags question: http://stackoverflow.com/q/49662964
tags question: http://stackoverflow.com/q/49612037
tags question: http://stackoverflow.com/q/49713675
tags question: http://stackoverflow.com/q/49661405
tags question: http://stackoverflow.com/q/49677504
tags question: http://stackoverflow.com/q/49613341
tags question: http://stackoverflow.com/q/49630260
tags question: http://stackoverflow.com/q/49697830
tags question: http://stackoverflow.com/q/49635428
tags question: http://stackoverflow.com/q/49655812
tags question: http://stackoverflow.com/q/49755687
tags question: http://stackoverflow.com/q/49718346
tags question: http://stackoverflow.com/q/49601486
tags question: http://stackoverflow.com/q/49604179
tags question: http://stackoverflow.com/q/49661414
tags question: http://stackoverflow.com/q/49714222
tags question: http://stackoverflow.com/q/49721251
tags question: http://stackoverflow.com/q/49695528
tags question: http://stackoverflow.com/q/49725631
tags question: http://stackoverflow.com/q/49688718
tags question: http://stackoverflow.com/q/49712546
tags question: http://stackoverflow.com/q/49658412
tags question: http://stackoverflow.com/q/49719479
tags question: http://stackoverflow.com/q/49645809
tags question: http://stackoverflow.com/q/49601248
tags question: http://stackoverflow.com/q/49699499
tags question: http://stackoverflow.com/q/49743901
tags question: http://stackoverflow.com/q/49738472
tags question: http://stackoverflow.com/q/49711626
tags question: http://stackoverflow.com/q/49710192
tags question: http://stackoverflow.com/q/49643907
tags question: http://stackoverflow.com/q/49732899
tags question: http://stackoverflow.com/q/49746374
tags question: http://stackoverflow.com/q/49661247
tags question: http://stackoverflow.com/q/49651639
tags question: http://stackoverflow.com/q/49703211
tags question: http://stackoverflow.com/q/49630447
tags question: http://stackoverflow.com/q/49736440
tags question: http://stackoverflow.com/q/49713432
tags question: http://stackoverflow.com/q/49713065
tags question: http://stackoverflow.com/q/49601890
tags question: http://stackoverflow.com/q/49660174
tags question: http://stackoverflow.com/q/49654550
tags question: http://stackoverflow.com/q/49698328
tags question: http://stackoverflow.com/q/49757799
tags question: http://stackoverflow.com/q/49722298
tags question: http://stackoverflow.com/q/49685545
tag name: matplotlib
tags question: http://stackoverflow.com/q/49635059
tags question: http://stackoverflow.com/q/49742812
tags question: http://stackoverflow.com/q/49703938
tags question: http://stackoverflow.com/q/49616403
tags question: http://stackoverflow.com/q/49621420
tags question: http://stackoverflow.com/q/49663390
tags question: http://stackoverflow.com/q/49652354
tags question: http://stackoverflow.com/q/49755078
tags question: http://stackoverflow.com/q/49692440
tags question: http://stackoverflow.com/q/49608903
tags question: http://stackoverflow.com/q/49746787
tags question: http://stackoverflow.com/q/49602592
tags question: http://stackoverflow.com/q/49715719
tags question: http://stackoverflow.com/q/49720033
tags question: http://stackoverflow.com/q/49693560
tags question: http://stackoverflow.com/q/49714376
tags question: http://stackoverflow.com/q/49715776
tags question: http://stackoverflow.com/q/49602969
tags question: http://stackoverflow.com/q/49749229
tags question: http://stackoverflow.com/q/49714845
tags question: http://stackoverflow.com/q/49723026

http://stackoverflow.com/comment/86524851
type: AnswerComment
has text: I cannot open GDrive links for security. Can you post sample rows in body of question?
score: 0
comment on: http://stackoverflow.com/a/49738535
type: Comment

http://stackoverflow.com/q/49702042
has answer: http://stackoverflow.com/a/49702910
has title: Concatenate strings in a matrix python
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86418177
downvote count: 0
has comment: http://stackoverflow.com/comment/86418014
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
tagged with: string-concatenation
has body: I have a matrix with strings as follows, array([['', '', 'C'], ['A', '', 'C'], ['', 'B', '']], dtype='|S9') I need to concatenate columns in each row to get an output similar to following, array([['C'], ['A C'], ['B']]) The size of the matrix I need to apply this is very large. Is there something similar to column sum in python as np.sum(matrix, axis=0) to do this string concatenation?

http://stackoverflow.com/q/49696818
tagged with: data-conversion
has comment: http://stackoverflow.com/comment/86406710
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86406783
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
has body: I am using pandas and matplotlib to evaluate an excel sheet that I have converted to a dataframe. However, two of my columns have zeros as values in some of the rows, which I need to remove. We are talking a couple thousand rows for the dataframe total. The zeros only appear in two of my 8 columns. I'd like to remove any rows that have zeros in one or both of those two columns. Does anyone know how I may go about doing this? I've tried df.loc[(df!=0).any(1)] but to no avail. Any and all help would be greatly appreciated.
type: UnansweredQuestion
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49696972
downvote count: 1
has title: Removing zeros from a column with pandas and matplotlib
score: 0
tagged with: pandas

http://stackoverflow.com/q/49647487
downvote count: 0
has answer: http://stackoverflow.com/a/49647609
favorite count: 0
type: Question
tagged with: django
tagged with: python
has body: Let's say I have the following simplistic model, for demonstration purposes: class Something(models.Model): date = models.DateField() time = models.TimeField() timestamp = models.DateTimeField() price = models.DecimalField() manufacturer = models.CharField() If I want to get the total count of every manufacturer I can do something like below: Something.objects.all().values("manufacturer").annotate(frequency=Count(field)) My aim is to do something similar based on the date and time. For example the total count for every month. My first thought since there are already data based on the model above is to add a custom property, but you can not use it with values. Next, I thought to add the neccessary fields(day,month,year,...) to the model and add a custom save method to calculate them. Another way is to load the queryset into pandas and do the calculations there. Is there a more appropriate way to do something like this ?
has title: How do I perform aggregation on date and time in Django?
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/49674063
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86359818
has answer: http://stackoverflow.com/a/49675321
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86359625
has comment: http://stackoverflow.com/comment/86359475
has body: Hello I am trying to make a simple multiple choice quiz in pygame. This is the code I wrote and it works as intended. from random import choice qUsed=[] qEasy = [ { "question": "What year is it", "choices": {"a": "2009", "b": "2016", "c": "2010"}, "answer": "b" }, { "question": "Another Question", "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"}, "answer": "a" }, { "question": "Another Question", "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"}, "answer": "a" }, { "question": "Another Question", "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"}, "answer": "a" }, { "question": "Another Question", "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"}, "answer": "a" } ] def Quiz(qLevel): global qUsed if qLevel == []: # if qLevel becomes empty qLevel = qUsed # dump everything from qUsed to qLevel qUsed = [] # reset qUsed to an empty list x = choice(qLevel) # assign x to a random question in qLevel print(x.get('question')) # print the question answer = input(x.get('choices')).lower() # print the choices if answer == x.get('answer'): # if answer is correct print("You got it") else: print("Wrong") qLevel.remove(x) # remove used question from list qUsed.append(x) # add it to an empty unused list (qUsed) Quiz(qEasy) Quiz(qEasy) The problem arises here when I wrote a pygame script to open a window with the question as a header and the three possible answers randomly blitted on three black rectangles. What I want to do is to randomly pick a question from the list, blit it on the screen where it says "Insert question here" and randomly assign answers to the three rectangles. If you were to press the right rectangle then the rectangle changes colour to green, otherwise, it becomes red. But I cannot figure out how to do it. def Screen(): mouse.set_visible(1) clock = time.Clock() # The button is just a rect. A1 = Rect(30, 100, 175, 250) A2 = Rect(230, 100, 175, 250) A3 = Rect(430, 100, 175, 250) while True: screen.fill(WHITE) draw.…
possible better answer: http://stackoverflow.com/a/49675321
tagged with: python
has title: How to randomly assign variables in python?
tagged with: pygame
accepted answer: http://stackoverflow.com/a/49677426
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49677426
answer count: 2
has comment: http://stackoverflow.com/comment/86359375

http://stackoverflow.com/q/49705831
downvote count: 0
has answer: http://stackoverflow.com/a/49711318
tagged with: tensorflow
favorite count: 0
type: Question
has title: Automatic broadcasting in Tensorflow
accepted answer: http://stackoverflow.com/a/49711318
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 3
has body: What is the best way of dynamically broadcasting a 1D vector such that it can perform element-wise multiplication with rows of the supplied tensor? At the moment, I have the following verbose "solution", which tf.tiles the coef (the 1D vector) across to the shape of the second argument on a case by case basis: import tensorflow as tf tf.reset_default_graph() iterSession = tf.InteractiveSession() coef = tf.constant([1., 2, 3]) # shape = (3,) LL_grads = { 'a': tf.constant([[1.], [2], [3]]), # shape = (3, 1) 'b': tf.constant([[1., 2], [3, 4], [5, 6]]), # shape = (3, 2) 'c': tf.constant([[[1.], [2]], [[3], [4]], [[5], [6]]]) # shape = (3, 2, 1) } avg_grad_stacked = {} for x in ['a', 'b', 'c']: LL_grad = LL_grads[x] dim = len(LL_grad.get_shape()) if dim == 1: avg_grad_stacked[x] = LL_grad * coef elif dim == 2: # Manually broadcast to (3, 2) avg_grad_stacked[x] = LL_grad * tf.tile(tf.reshape(coef, (-1, 1)), [1, tf.shape(LL_grad)[1]]) elif dim == 3: # Manually broadcast to (3, 2, 1) avg_grad_stacked[x] = LL_grad * tf.tile(tf.reshape(coef, (-1, 1, 1)), [1, tf.shape(LL_grad)[1], tf.shape(LL_grad)[2]]) I would ideally have liked to have something simple and Pythonic as: avg_grad_stacked_2 = {x:coef * y for x, y in LL_grads.items()} However, this fails with the error: ValueError: Dimensions must be equal, but are 3 and 2 for 'mul_4' (op: 'Mul') with input shapes: [3], [3,2]. So is there an automatic way of broadcasting a vector?
upvote count: 3

http://stackoverflow.com/a/49695944
has comment: http://stackoverflow.com/comment/86407136
type: Answer
has body: convert response column to numeric, the string will be na then groupby and aggregate import pandas as pd import numpy as np import StringIO data = '''name;question;response Smith, John;Q1;10 Smith, John;Q2;7 Smith, John;Q3;10 Smith, John;Q4;8 Smith, John;Q5;10 Smith, John;Q8;8 Smith, John;level;graduate Smith, John;colleg;science Smith, John;Q9;4 Jones, Mary;Q3;10 Jones, Mary;Q2;10 Jones, Mary;Q1;10 Jones, Mary;Q4;10 Jones, Mary;level;undergraduate Jones, Mary;college;education Jones, Mary;Q6;10 Jones, Mary;Q7;10 Jones, Mary;Q9;10''' df = pd.read_csv(StringIO.StringIO(data), delimiter=';') df['response'] = pd.to_numeric(df['response'], errors='coerce') df.groupby('name').agg(np.mean).reset_index().sort_values(by='response') output name response 1 Smith, John 8.142857 0 Jones, Mary 10.000000
answers question: http://stackoverflow.com/q/49695382
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86407303

http://stackoverflow.com/q/49649102
has title: Check file has changed or not?
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: file
has answer: http://stackoverflow.com/a/49650665
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/86306809
linked to: http://stackoverflow.com/q/182197
linked to: http://stackoverflow.com/q/977491
tagged with: operating-system
tagged with: python
has body: My requirement is to checks to see if a file has changed since the last run. I have made an attempt to do with this os.stat and I'm not sure whether it is a correct way or not. import os import json file_info = os.stat("cli.py") with open("log.txt", "r") as file: line = json.loads(file.readline()) if list(set(line)-set(list(file_info))): print("Changes in file") with open ("log.txt", "w+") as f: f.write(str(list(file_info))) I looking for is there any better ideas or am I doing it in correct way or not. Any help is appreciated
has comment: http://stackoverflow.com/comment/86306386
has comment: http://stackoverflow.com/comment/86306471
type: Question
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/comment/86231171
type: QuestionComment
comment on: http://stackoverflow.com/q/49611488
score: 0
has text: @Alasdair Corrected it
type: Comment

http://stackoverflow.com/comment/86491022
comment on: http://stackoverflow.com/q/49710943
has text: Okey thank you, I didn't realize what was the problem. It turned out that when downloading and deleting the files from the server, the startup scripts which were hidden on the cluster were deleted, and therefore it did not work. Now everything works fine
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86448341
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49716237
has text: @magicleon No, server is azure's VM.
score: 0

http://stackoverflow.com/q/49716307
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49716745
has title: Subtract values in between Dictionaries in a RDD on PySpark
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86446052
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/49716745
tagged with: python
tagged with: dictionary
tagged with: rdd
type: AnsweredQuestion
score: 2
tagged with: apache-spark
upvote count: 2
has body: I have created and RDD where every element is a dictionary. 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 subtract the other values having the same key and then find the final sum That is: (1-0)+(0-1)+(0-1)= -1 Since this is in RDD form what I tried to do is: d1=rdd.filter(lambda x: x['name']=='brad').first() {'actor': 'brad', 'good': 1, 'bad': 0, 'average': 0,} d2=rdd.filter(lambda x: x['name']=='tom').first() {'actor': 'tom', 'good': 0, 'bad': 1, 'average': 1,} This gives me the dictionary with the value 'brad' and 'tom'. How do I proceed with the arithmetic operation? I tried doing this by : d3 = {key: d1] - d2.get(key, 0) for key in d1.keys()} But this is giving me errors. Is there a better way to do this my manipulating the dictionaries in the RDD itself rather than breaking it down to the basic dictionary? Thank you

http://stackoverflow.com/comment/86448285
has text: Hey @Alasdair thanks alot that worked for me! i dont have a blog-id 1 but instead i have my blog-ids being started from 2 that is the 1st blog id is 2 and the 2nd blog id is 3! How can i make them clear with 1,2,3,etc
comment on: http://stackoverflow.com/q/49716568
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49733450
score: 2
has comment: http://stackoverflow.com/comment/86482176
upvote count: 2
has comment: http://stackoverflow.com/comment/86481137
has comment: http://stackoverflow.com/comment/86482458
type: AcceptedAnswer
downvote count: 0
has body: A more pythonic approach would use the &amp; (intersection) operator for sets: common = set(x[:-7] for x in list_1) &amp; set(x[:5] for x in list_2) list_1b = [x + '_pp.csv' for x in common] list_2b = [x + '.json' for x in common] EDIT : If you need to split on a specific character (see comment) for each list, here is an updated version (search for the last '_' in list_1 and search for the last '.' in list_2): common = set(x[:x.rindex('_')] for x in list_1) &amp; set(x[:x.rindex('.')] for x in list_2)
answers question: http://stackoverflow.com/q/49733101
has comment: http://stackoverflow.com/comment/86482234
type: Answer
accepted answer of: http://stackoverflow.com/q/49733101
has comment: http://stackoverflow.com/comment/86481492

http://stackoverflow.com/q/49686876
has comment: http://stackoverflow.com/comment/86385558
has comment: http://stackoverflow.com/comment/86385400
has comment: http://stackoverflow.com/comment/86430466
has comment: http://stackoverflow.com/comment/86424809
answer count: 0
has comment: http://stackoverflow.com/comment/86385715
has title: SQLAlchemy Engine hanging
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86385619
has comment: http://stackoverflow.com/comment/86387396
type: Question
has comment: http://stackoverflow.com/comment/86427568
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86385752
has body: I have a multi-threaded program that shares one instance of Engine among all threads. It uses SQLAlchemy to access MySQL as well as Redshift. I have a DbProvider class that is used to obtain Engine instances: (It is subclassed for MySQL and Redshift) def get_db_engine(self) -&gt; Engine: if not self._engine: self._engine = create_engine(self._get_connection(), pool_size=_POOL_SIZE, max_overflow=_MAX_OVERFLOW, connect_args={'sslmode': 'verify-ca'}) # verify-ca to avoid certificate domain mismatch error when CNAME forwarding to AWS endpoint return self._engine The program hangs randomly and I haven't been able to find a way to reproduce this behaviour. However, after much effort, I've found two places where it hangs (which one happens depends on an input parameter): url = db_provider.get_db_engine().url or db_provider.get_db_engine().execute(script) where db_provider is an instance of DbProvider and script is a string. My understanding is that Engine is thread-safe. I am going to try having a separate Engine for each instance, but this happens so randomly and scarcely that I can't rest until I know what the real problem is. Besides, separate engines also means separate connection pools which is likely to have a performance penalty. Update: It seems that the program hangs at create_engine. Additionally, I sometimes get this error in logs: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pkg_resources/_vendor/packaging/requirements.py", line 90, in __init__ req = REQUIREMENT.parseString(requirement_string) File "/usr/local/lib/python3.6/site-packages/pkg_resources/_vendor/pyparsing.py", line 1617, in parseString raise exc File "/usr/local/lib/python3.6/site-packages/pkg_resources/_vendor/pyparsing.py", line 1607, in parseString loc, tokens = self._parse( instring, 0 ) File "/usr/local/lib/python3.6/site-packages/pkg_resources/_vendor/pyparsing.py", line 1379, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File …
tagged with: sqlalchemy

http://stackoverflow.com/a/49617487
score: -1
has body: it's not a loop. you can use a pivot table to find your answer: https://pandas.pydata.org/pandas-docs/stable/reshaping.html
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49616277
type: Answer

http://stackoverflow.com/comment/86303572
comment on: http://stackoverflow.com/q/49647205
type: QuestionComment
type: Comment
score: 0
has text: @JoeT.Boka In my answer I have placed an explanation of the operation of the QThread with a worker, check it. :D

http://stackoverflow.com/comment/86457769
type: Comment
has text: You're registering that view twice. You don't need a router for a standalone view. (Note, you really shouldn't call it a viewset in the first place if it is not one.)
type: AnswerComment
score: 3
comment on: http://stackoverflow.com/a/49721133

http://stackoverflow.com/a/49745080
accepted answer of: http://stackoverflow.com/q/49744750
has comment: http://stackoverflow.com/comment/86528877
answers question: http://stackoverflow.com/q/49744750
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Debasish is right about the split-apply-combine approach. For a simple example: # Use groupby to find the average by date; sub in w/e func for mean df['Column2'] = df.groupby(level='Date').transform('mean') # Replace Column1 with the desired value df['Column1'] = df['Column2'] - df['Column1'] The above example was for clarity, but here is the better, one-liner: df['Column1'] = df.groupby(level='Date')['Column1'].transform('mean').sub(df['Column1'])
has comment: http://stackoverflow.com/comment/86578705
score: 1
type: Answer

http://stackoverflow.com/q/49661206
type: UnansweredQuestion
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/86332366
tagged with: python
has title: Regex to pull particular value from the field in Python
tagged with: regex
tagged with: text-manipulation
upvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86333363
answer count: 2
has comment: http://stackoverflow.com/comment/86332313
has answer: http://stackoverflow.com/a/49661353
has comment: http://stackoverflow.com/comment/86332288
has comment: http://stackoverflow.com/comment/86332235
has comment: http://stackoverflow.com/comment/86332350
favorite count: 0
type: Question
has body: I have below type of components in jira.I am trying to create the regex to fetch the value from these components .This value could be anything e.g 1.1 or 1.a or a.a or nothing for any components but remember I don't need anything like R or (U1) just need 1.0,1.1,1.a,a.1,1.x so I need only the first character or number before period(.) and first character or number after period(.) or if there is no period(.) then blank need PCN 9.4U1 (Act)----------------------------1.4 PCN 9.5 (Act)------------------------------1.5 PCN 9.6 (Act)------------------------------1.6 R AA 7.5U5 (Arch)--------------------------2.5 R AA 7.6U2 (Rel)--------------------------2.6 R AA 37.7R (Arch)---------------------------2.7 R TEST 1.x (Fut)-------------------------2.x R testp U2---------------------------------------no value I am using the below regex to get the value Fixversionmat = re.findall(r"(\d+\.\d+)", jsonToPython['name']) but this gives me result only when value is something like that 1.1 and in other cases it fails.
has comment: http://stackoverflow.com/comment/86332285
has comment: http://stackoverflow.com/comment/86332396
has comment: http://stackoverflow.com/comment/86332782
has answer: http://stackoverflow.com/a/49661411

http://stackoverflow.com/comment/86441249
type: Comment
comment on: http://stackoverflow.com/q/49713675
score: 0
type: QuestionComment
has text: People here really do have a culture of downvoting if they don't know the answer. There are no questions like this and most don't even know how to do this.

http://stackoverflow.com/comment/86242022
has text: you're going to want to edit that into your question as well as show the expected output
comment on: http://stackoverflow.com/q/49617401
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86304095
has text: what do you mean?
comment on: http://stackoverflow.com/q/49647703
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49727982
has comment: http://stackoverflow.com/comment/88734495
accepted answer of: http://stackoverflow.com/q/49682271
score: 1
downvote count: 0
has body: The appropriate solution is to execute the blocking task in another thread, and send the data to the GUI that is in the main thread through signals, Qt prohibits updating the GUI from another than the main one, using processEvents is forcing the GUI to update some parameters which does not guarantee a correct operation, you can read more about this topic in the following link: Should I use QCoreApplication::processEvents() or QApplication::processEvents()?. In the following example I will use the native python threads next to 2 signals, one will send the text and the other the data. import random import sys import time from threading import Thread import pandas as pd from PyQt5.QtCore import QObject, pyqtSignal, Qt from PyQt5.QtWidgets import QApplication, QFileDialog, QStyleFactory, QMainWindow from PyQt5.uic import loadUi parametros = 'Area', 0, 5 def generar_aleatorio(): return random.uniform(*parametros[0][1:]) def area(x1): area = 3.1416 * x1 ** 2 return area class Helper(QObject): send_signal = pyqtSignal(str) data_signal = pyqtSignal(list) helper = Helper() def estado(starttime, last_print, contador, n, area): acttime = time.time() if acttime - last_print &lt;= 2: avg_time_per_run = (acttime - starttime) / (contador + 1) timestr = time.strftime("%H:%M:%S", time.gmtime(round(avg_time_per_run * (n - (contador + 1))))) text = 'Simulacion %i de %i - Tiempo estimado restante: %s\n' % (contador, n, timestr) \ + 'Area = %5.3f\n\n' % area helper.send_signal.emit(text) def montecarlo(n): data = [] text = 'Iniciando iteraciones con {} repeticiones...\n\n'.format(n) helper.send_signal.emit(text) ult_print = time.time() starttime = time.time() for contador in range(n): z = generar_aleatorio() y = area(z) estado(starttime, ult_print, contador + 1, n, y) ult_print = time.time() time.sleep(0.001) data.append([z, y]) helper.data_signal.emit(data) class simulacion(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) loadUi('simulacion.ui', sel…
has comment: http://stackoverflow.com/comment/86497858
has comment: http://stackoverflow.com/comment/88734386
has comment: http://stackoverflow.com/comment/88681707
has comment: http://stackoverflow.com/comment/88681634
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86498045
type: Answer
answers question: http://stackoverflow.com/q/49682271
upvote count: 1

http://stackoverflow.com/a/49748960
type: Answer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86512710
has body: You could use a tabbed view and switch the tabs according to the difficulty selected (see tkinter notebooks https://docs.python.org/3.1/library/tkinter.ttk.html#notebook) Or you could have the quiz in their selected difficulty in their own windows.
answers question: http://stackoverflow.com/q/49748378
score: 2

http://stackoverflow.com/comment/86352417
has text: Is what you're actually after a file of N many random bytes? Otherwise - I'm not quite sure what you're after as what you're trying to do doesn't really make much sense...
type: QuestionComment
comment on: http://stackoverflow.com/q/49671116
score: 0
type: Comment

http://stackoverflow.com/comment/86413771
type: AnswerComment
score: 1
has text: I was going to post the same thing but I will add the comment that the title implies that OP wants unique values. In which case you can do a set comp instead of a list comp: `list({x for x in y for y in s})`.
type: Comment
comment on: http://stackoverflow.com/a/49700235

http://stackoverflow.com/a/49754735
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49754398
downvote count: 0
has comment: http://stackoverflow.com/comment/86524376
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49754398
score: 3
has body: Let's try this: df['FeeMonthly'] = df.groupby(['ID','year'])['Fee'].diff().fillna(df.Fee) Output: ID month year Fee FeeMonthly 0 68119 February 2015 25 25.0 1 68119 March 2015 25 0.0 2 68119 April 2015 25 0.0 3 68119 May 2015 25 0.0 4 200 February 2015 50 50.0 5 200 March 2015 375 325.0 6 200 April 2015 375 0.0 7 200 May 2015 375 0.0 8 200 June 2015 375 0.0 9 200 July 2015 375 0.0 10 200 August 2015 375 0.0
type: Answer

http://stackoverflow.com/comment/86214985
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49603890
score: 0
has text: Nope, it will fill the other 2 sublists after the loop is done.

http://stackoverflow.com/comment/87631548
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50035506
type: Comment
has text: @Mozillaa, I'm not sure about the problem. But you can try to put the imshow method on the main thread, and just the capture frame process on the others threads, I did this way on my c++ system and is working with multiple cameras. I'm going to upload it to github this weekend, I tell you.

http://stackoverflow.com/q/49619719
has body: I am learning how to create a Flask app using a MongoDB database by putting together a user authentication system. When I went through the code with my superior at work, he said using werkzeug.security for hashing passwords may not be a good idea and asked me to make use of itsdangerous library in my code (below). What has been driving me insane is I couldn't find anywhere online why using werkzeug.security on its own is a bad idea. As far as I can gather itsdangerous package lets you use a login serialiser to encrypt and decrypt the cookie token when you use the remember me option in Flask-Login (I am not using this option). I found this article explaining Flask-Login tokens. Is it still important to use itsdangerous even if I don't use the remember me option? from flask import Flask, url_for, redirect, render_template, request from flask_mongoengine import MongoEngine from wtforms import form, fields, validators from werkzeug.security import generate_password_hash, check_password_hash import flask_login # Create application app = Flask(__name__) # Create a secret key so we can use sessions app.config['SECRET_KEY'] = 'super-secret' # MongoDB settings app.config['MONGODB_SETTINGS'] = {'DB': 'mymongodb'} db = MongoEngine() db.init_app(app) # Create user document (MongoDB documents are like rows in a relational table). class User(db.Document): login = db.StringField(max_length=80, unique=True) password = db.StringField(max_length=80) email = db.StringField(max_length=80) name = db.StringField(max_length=80) # Flask-Login integration def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return str(self.id) # Define login and registration forms (for flask-login) class LoginForm(form.Form): login = fields.StringField(validators=[validators.required()]) password = fields.PasswordField(validators=[validators.required()]) def validate_login(self, field): user = self.get_user() if user is None: raise v…
tagged with: itsdangerous
accepted answer: http://stackoverflow.com/a/49620225
type: AnsweredQuestion
tagged with: flask-login
tagged with: werkzeug
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Is it more secure to use itsdangerous with Flask-Login without the remember me option? Why or why not?
favorite count: 0
has answer: http://stackoverflow.com/a/49620225
type: Question
tagged with: python
tagged with: flask

http://stackoverflow.com/q/49644827
tagged with: python
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/86320802
downvote count: 2
tagged with: openpyxl
tagged with: django
type: UnansweredQuestion
upvote count: 1
answer count: 1
has title: What response should I return when returning an excel document in Django REST framework
type: Question
has body: I use openpyxl create a workbook, and return a Response like this: from openpyxl import Workbook wb = Workbook() response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xlsx"' return response but frontend coder said he accept gibberish, you should return a bytearray like 0101010101,he can analysis and download Now I return a response like this, he use node.js not vue download through a complex process I am confused, what should I do?
has answer: http://stackoverflow.com/a/49645178

http://stackoverflow.com/comment/86461574
type: Comment
type: QuestionComment
has text: @PaulRooney Yep, I understand what you meant now. These recursive functions are confusing; I needed to return the value of the function's reference to itself? I tried that and it fixed my problem. Thanks!
score: 0
comment on: http://stackoverflow.com/q/49723357

http://stackoverflow.com/q/49713250
answer count: 1
tagged with: django
upvote count: 1
downvote count: 1
tagged with: django-context
type: Question
has answer: http://stackoverflow.com/a/49713294
duplicate of: http://stackoverflow.com/q/19776056
score: 0
tagged with: django-class-based-views
tagged with: django-views
has title: difference between using super() and super(ViewName,self)
tagged with: python
accepted answer: http://stackoverflow.com/a/49713294
favorite count: 0
type: AnsweredQuestion
has body: I have been using in generic views (CBVs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) but I've noticed that people here do: context = super(ClassViewName,self).get_context_data(**kwargs) is there is a difference ?
linked to: http://stackoverflow.com/q/19776056

http://stackoverflow.com/comment/86387792
score: 0
type: Comment
type: QuestionComment
has text: Have you tried deleting the folder ~/.PyCharmxxxx.xx/system/python_stubs as mentioned in this question: https://stackoverflow.com/questions/30311954/pycharm-warns-for-unresolved-reference-builtin-datetime-module
comment on: http://stackoverflow.com/q/49687860

http://stackoverflow.com/q/49718428
has answer: http://stackoverflow.com/a/74550947
score: 7
downvote count: 0
tagged with: python-unittest
upvote count: 7
has body: I want to test the function is_myclass. Please help me understand how to write a successful test. def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() Docs The Python Docs for unittest.mock illustrate three ways of addressing the isinstance problem: Set the spec parameter to the real class. Assign the real class to the __class__ attribute. Use spec in the patch of the real class. __class__ Normally the __class__ attribute of an object will return its type. For a mock object with a spec, __class__ returns the spec class instead. This allows mock objects to pass isinstance() tests for the object they are replacing / masquerading as: &gt;&gt;&gt; mock = Mock(spec=3) &gt;&gt;&gt; isinstance(mock, int) True __class__ is assignable to, this allows a mock to pass an isinstance() check without forcing you to use a spec: &gt;&gt;&gt; mock = Mock() &gt;&gt;&gt; mock.__class__ = dict &gt;&gt;&gt; isinstance(mock, dict) True [...] If you use spec or spec_set and patch() is replacing a class, then the return value of the created mock will have the same spec. &gt;&gt;&gt; Original = Class &gt;&gt;&gt; patcher = patch('__main__.Class', spec=True) &gt;&gt;&gt; MockClass = patcher.start() &gt;&gt;&gt; instance = MockClass() &gt;&gt;&gt; assert isinstance(instance, Original) &gt;&gt;&gt; patcher.stop() Tests I have written five tests each of which attempts firstly to reproduce each of the three solutions and secondly to carry out a realistic test of the target code. The typical pattern is assert isinstance followed by a call to is_myclass. All tests fail. Test 1 This is a close copy of the example provided in the docs for the use of spec. It differs from the docs by using spec=&lt;class&gt; instead of spec=&lt;instance&gt;. It passes a local assert test but the call to is_myclass fails because MyClass is not mocked. This is equivalent to Michele d’Amico’s answer to the similar question in isinstance and Mocking…
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: mocking
accepted answer: http://stackoverflow.com/a/49718531
has title: How can I mock patch a class used in an isinstance test?
has answer: http://stackoverflow.com/a/49718531
tagged with: python
linked to: http://stackoverflow.com/q/11146725
has answer: http://stackoverflow.com/a/64941532
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/74550947
answer count: 3

http://stackoverflow.com/q/49713281
tagged with: python
accepted answer: http://stackoverflow.com/a/49713588
has comment: http://stackoverflow.com/comment/86440656
has answer: http://stackoverflow.com/a/49713588
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86441708
upvote count: 1
has comment: http://stackoverflow.com/comment/86441711
has comment: http://stackoverflow.com/comment/86440664
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python-multithreading
has body: I've wrote this script here to read data from a txt file and process it. But it seems that if I give it a big file and a high number of threads, the more it reads from the list, the slower the script gets. Is there a way to avoid waiting for all the threads to finish and start a new one whenever a thread is done with the work? Also it seems that when it finishes processing, the script doesn't exit. import threading, Queue, time class Work(threading.Thread): def __init__(self, jobs): threading.Thread.__init__(self) self.Lock = threading.Lock() self.jobs = jobs def myFunction(self): #simulate work self.Lock.acquire() print("Firstname: "+ self.firstname + " Lastname: "+ self.lastname) self.Lock.release() time.sleep(3) def run(self): while True: self.item = self.jobs.get().rstrip() self.firstname = self.item.split(":")[0] self.lastname = self.item.split(":")[1] self.myFunction() self.jobs.task_done() def main(file): jobs = Queue.Queue() myList = open(file, "r").readlines() MAX_THREADS = 10 pool = [Work(jobs) for i in range(MAX_THREADS)] for thread in pool: thread.start() for item in myList: jobs.put(item) for thread in pool: thread.join() if __name__ == '__main__': main('list.txt')
has title: Avoid waiting for threads to finish in Python
linked to: http://stackoverflow.com/q/3044580

http://stackoverflow.com/comment/116969718
comment on: http://stackoverflow.com/a/49635797
score: 0
type: Comment
has text: @mkl At the time I posted this answer (Apr '18), this solution worked with Matlab '18 and the corresponding matlab engine. I cannot guarantee it will work on any future version and I do not think this is a valid reason to downvote.
type: AnswerComment

http://stackoverflow.com/q/49637830
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86283721
has title: Python 3 argparse help menu
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49637997
tagged with: argparse
has answer: http://stackoverflow.com/a/49637997
has comment: http://stackoverflow.com/comment/86284092
has comment: http://stackoverflow.com/comment/86284165
type: Question
has body: Why when I do a simple store, does it goof up the help menu? It's adding the all caps destination for some reason and I dont know how to turn it off. Below you can see the difference. The first is using store_const which doesn't goof up the help menu, but of course doesn't suit my needs. The second is the simple store. See the difference? Constant Store dev@taco:~/argparse$ python3 arg-0.0.1.py -h usage: arg-0.0.1.py [-h] [-s] [-e] [-v] Example list of options optional arguments: -h, --help show this help message and exit -s, --start enter the starting value -e, --end enter the ending value -v, --version show program's version number and exit Simple Store dev@taco:~/argparse$ python3 arg-0.0.1.py -h usage: arg-0.0.1.py [-h] [-s START] [-e END] [-v] Example list of options optional arguments: -h, --help show this help message and exit -s START, --start START enter the starting value -e END, --end END enter the ending value -v, --version show program's version number and exit Here is the actual code for both simple and constant: #! /usr/bin/env python3 import argparse parser = argparse.ArgumentParser(description='Example list of options', add_help=True) parser.add_argument('-s', '--start', dest='start', action='store_const', const='1', help='enter the starting value') parser.add_argument('-e', '--end', dest='end', action='store_const', const='1000', help='enter the ending value') parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.1') results = parser.parse_args() print ('Starting value = ', results.start) print ('Ending value = ', results.end) #! /usr/bin/env python3 import argparse parser = argparse.ArgumentParser(description='Example list of options', add_help=True) parser.add_argument('-s', '--start', dest='start', action='store', help='enter the starting value') parser.add_argument('-e', '--end', dest='end', action='store', help='enter the ending value') parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.1') …
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/86284213
has comment: http://stackoverflow.com/comment/86288149
upvote count: 2
has comment: http://stackoverflow.com/comment/86283682
downvote count: 2
answer count: 1

http://stackoverflow.com/a/49619722
accepted answer of: http://stackoverflow.com/q/49619631
answers question: http://stackoverflow.com/q/49619631
downvote count: 0
score: 1
upvote count: 1
has body: You can use the getExistingDirectory() method of QFileDialog by applying the necessary filters: import sys from PyQt5 import QtWidgets, QtCore app = QtWidgets.QApplication(sys.argv) directory = QtWidgets.QFileDialog.getExistingDirectory(None, "Select Directory", QtCore.QDir.currentPath()) print(directory)
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/86375184
type: QuestionComment
has text: Use the fully-qualified path to "boot.py" instead of depending on the working directory. CMD can be configured more securely to ignore the working directory, which would break your script. If "boot.py" itself depends on the working directory, except in a few cases, it's likely that it's badly written. If it's your code, it's best to fix the problem at the source instead of hacking around it. In the bigger picture, there should be no reason to use the shell for this. Depending on the .py file association is fragile. Run `sys.executable` directly.
comment on: http://stackoverflow.com/q/49675767
type: Comment
score: 0

http://stackoverflow.com/a/49698611
has comment: http://stackoverflow.com/comment/135528216
type: Answer
has body: The core wtforms DateTimeField provides just a text input. I think what you want is: from wtforms import StringField, BooleanField from wtforms.fields.html5 import DateTimeLocalField class NameForm(FlaskForm): date = DateTimeLocalField('Which date is your favorite?', format='%m/%d/%y', validators=[Required()])
accepted answer of: http://stackoverflow.com/q/49697545
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49697545
score: 9
upvote count: 9

http://stackoverflow.com/a/49707286
downvote count: 0
answers question: http://stackoverflow.com/q/49707152
type: Answer
has body: Hash halving (SHA256-half, SHA512-half...) is generating a hash and truncating it to half its size, thus SHA512-half becomes equivalent to SHA256. While a larger hash function accepts larger input, once truncated it has the same collision rate as a non-truncated hash of the said size, and if the hashes we're talking about are solid and vetted (like both SHA256 and SHA512), halving a larger hash to fit the size of the smaller one can only add to perceived security but technically is no different than just generating the smaller hash. Anyway, if you really don't want to just generate a SHA256, you can halve a SHA512 hash as: halved_sha512 = hashlib.sha512(b"input").digest()[:32] For bytes, or: halved_sha512 = hashlib.sha512(b"input").hexdigest()[:64] For a hex string.
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49707152
type: AcceptedAnswer

http://stackoverflow.com/a/49604687
score: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49602551
type: Answer
has body: You're correct, running the application locally is using a datastore emulation, contained inside dev_appserver.py. The data is not stored in memory, but on the local disk. So even if the development server restarts it will still find the "datastore" data written in a previous execution. You can check the data actually saved using the local development server's admin interface at http://localhost:8000/datastore
accepted answer of: http://stackoverflow.com/q/49602551
upvote count: 2

http://stackoverflow.com/q/49716237
has comment: http://stackoverflow.com/comment/86448317
has title: Server not able to listen to the client?
type: Question
has comment: http://stackoverflow.com/comment/86446681
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86448341
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/86447594
has comment: http://stackoverflow.com/comment/86448798
has body: I am new to Socket programming and trying to run a simple client-server code. server.py host="" port=80 from socket import * s=socket(AF_INET, SOCK_STREAM) s.bind((host,port)) s.listen(1) print "Listening for connections.. " q,addr=s.accept() data=input("Enter data to be send: ") q.send(data) s.close() client.py host = "52.170.194.29" port=80 from socket import * s=socket(AF_INET, SOCK_STREAM) s.connect((host,port)) msg=s.recv(1024) print ("Message from server : " + msg.strip().decode('ascii')) s.close() # End of code Both scripts compile successfully. As such, server.py goes blank or does nothing after printing waiting for connections and similar happens for client.py. Can I have some idea where am I going wrong ?
score: 0
has comment: http://stackoverflow.com/comment/86448608
answer count: 0

http://stackoverflow.com/q/49701826
answer count: 1
tagged with: machine-translation
has comment: http://stackoverflow.com/comment/86417383
tagged with: iteration
has body: I'm trying to have the bottom part of the code iterate over some files. These files should be corresponding and are differentiated by a number, so the counter is to change the number part of the file. The file names are generated by looking through the given files and selecting files containing certain things in the title, then having them ordered using the count. This code works independently, in it's own (lonely) folder, and prints the correct files in the correct order. However when i use this in my main code, where file_1 and file_2 are referenced (the decoder and encoder parts of the code) I get the error in the title. There is no way there is any typo or that the files don't exist because python made these things itself based on existing file names. import os count = 201 while 205 &gt; count: indir = 'absolute_path/models' for root, dirs, filenames in os.walk(indir): for f in filenames: if 'test-decoder' in f: if f.endswith(".model"): if str(count) in f: file_1 = f print(file_1) indir = 'absolute_path/models' for root, dirs, filenames in os.walk(indir): for f in filenames: if 'test-encoder' in f: if f.endswith(".model"): if str(count) in f: file_2 = f print(file_2) decoder1.load_state_dict( torch.load(open(file_1, 'rb'))) encoder1.load_state_dict( torch.load(open(file_2, 'rb'))) print(getBlueScore(encoder1, decoder1, pairs, src, tgt)) print_every=10 print(file_1 + file_2) count = count + 1 i then need to use these files two by two.
type: Question
has comment: http://stackoverflow.com/comment/86417354
tagged with: python
has answer: http://stackoverflow.com/a/49702194
has title: IOError: [Errno 2] No such file or directory: when the name was made by looping over existing files
score: 0
tagged with: deep-learning
type: UnansweredQuestion

http://stackoverflow.com/q/49618942
answer count: 2
has comment: http://stackoverflow.com/comment/86244902
has body: I have the format day/month/year And I have a task to define a function that takes a date and returns the date with 1 day increased Example: next_day("13/1/2018") returns 14/1/2018 next_day("31/3/2018") returns 1/4/2018 How can I do that, I don't know how to do this when the function takes date not day, month, year.
has comment: http://stackoverflow.com/comment/86764606
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49619169
downvote count: 2
has comment: http://stackoverflow.com/comment/86244907
has comment: http://stackoverflow.com/comment/86245480
upvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49619005
has comment: http://stackoverflow.com/comment/86244981
has comment: http://stackoverflow.com/comment/86244916
tagged with: datetime
tagged with: python-2.x
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86245003
has title: Add one day to date (string format) when the input string format is not known

http://stackoverflow.com/q/49607339
type: UnansweredQuestion
has body: I took a look at this question here: Missing value imputation in python using KNN I don't believe I can use fancyimpute or download the sklearn knn impute code from github (I'm doing this on a python platform where I can't just download additional code). Would there be a way to use sklearn's kNN to do this manually? If I have data missing for some columns I don't think sklearn's kNN will run right?
answer count: 1
tagged with: scikit-learn
tagged with: python
has answer: http://stackoverflow.com/a/49607967
score: 0
tagged with: pandas
has title: Using kNN to impute missing data with sklearn
linked to: http://stackoverflow.com/q/45321406
tagged with: fancyimpute
tagged with: knn
type: Question

nan
tags question: http://stackoverflow.com/q/49640437
tags question: http://stackoverflow.com/q/49724908
tags question: http://stackoverflow.com/q/49677568
type: Tag
tags question: http://stackoverflow.com/q/49643187
tags question: http://stackoverflow.com/q/49667026
tags question: http://stackoverflow.com/q/49735028
tags question: http://stackoverflow.com/q/49640751
tags question: http://stackoverflow.com/q/49677099
tag name: nan

http://stackoverflow.com/a/49656492
accepted answer of: http://stackoverflow.com/q/49656129
has body: You can also use LabelEncoder from sklearn library. from sklearn.preprocessing import LabelEncoder lbl = LabelEncoder() # sample data df = pd.DataFrame({'V1': ['a','b','a','d'], 'V2':['c','d','d','c']}) # apply function df.apply(lbl.fit_transform) V1 V2 0 0 0 1 1 1 2 0 1 3 2 0
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49656129
score: 3
type: Answer

http://stackoverflow.com/q/49673257
has answer: http://stackoverflow.com/a/49673739
has title: Replacing special character in string not working
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86358015
has answer: http://stackoverflow.com/a/49673634
has comment: http://stackoverflow.com/comment/86357381
tagged with: encoding
has answer: http://stackoverflow.com/a/49673968
tagged with: python
has comment: http://stackoverflow.com/comment/86357100
has comment: http://stackoverflow.com/comment/86357157
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86357253
answer count: 3
accepted answer: http://stackoverflow.com/a/49673739
possible better answer: http://stackoverflow.com/a/49673968
has comment: http://stackoverflow.com/comment/86357695
has body: I have a long string, which includes the text Your Sunday evening order with Uber Eats\nTo: test@email.com\n\n\n[image: map]\n\n[image: Uber logo]\n\xe2\x82\xac17.50\nThanks for choosing Uber, I am trying to replace '\xe2\x82\xac' with 'EUR' in Python 3.6 If I print the string, I see that it is preceded by b, i.e. it is a byte literal. b'&lt;div dir="ltr"&gt;&lt;br ...' etc. I cannot encode it (html = html.encode('UTF-8')), because then I get a bytes-like object is required, not 'str' nor can I decode it ('str' object has no attribute 'decode') I have tried: html = html.replace(u"\xe2\x82\xac","EUR") html = html.replace(u'\xe2\x82\xac',"EUR") html = html.replace('\xe2\x82\xac',"EUR") html = html.replace(u"€","EUR") None of these work. html.decode("utf-8") gets me an error 'str' object has no attribute 'decode'. For context, the string is generated by reading the content of an e-mail with the mailbox library: for message in mbox: for part in message.walk(): html = str(part.get_payload(decode=True))

http://stackoverflow.com/comment/86229481
has text: what does the command `print(type()img)` and `print(img.shape)` give you?
comment on: http://stackoverflow.com/q/49611403
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49659606
has comment: http://stackoverflow.com/comment/86328729
has comment: http://stackoverflow.com/comment/86328733
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49659651
has comment: http://stackoverflow.com/comment/86328815
score: 0
has body: Hey So i typed in this code: opennote = open('C:\\Users\\My_username\\coolnotepad.txt') (with my username ofc) yet i keep getting this TypeError: 'str' object is not callable Helpp!
has title: How to open a text file in python 3.0
has comment: http://stackoverflow.com/comment/86328738
answer count: 1
tagged with: file
tagged with: string
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86328805

http://stackoverflow.com/q/49674382
has body: In Python's zipfile module, when you create a zip file with only one file, it is correctly transformed into the unzipped form. But once I add another file, it is transformed into the redundant directory, and I muse traverse one step further to obtain a file I want. For example: import zipfile a = zipfile.ZipFile("test.zip", "w") a.write("test.txt") a.close() This creates a file test.zip. When I open it, it is transformed into test.txt, not test. But the following code is transformed into test, not test.txt and test.csv: import zipfile a = zipfile.ZipFile("test.zip", "w") a.write("test.txt") a.write("test.csv") a.close() So can I prevent zipfile from creating the directory test?
has comment: http://stackoverflow.com/comment/86359995
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86359878
tagged with: python
has comment: http://stackoverflow.com/comment/86360385
score: 0
answer count: 0
has title: Can I prevent zipfile from creating a redundant directory when I archive multiple files?
has comment: http://stackoverflow.com/comment/86362236
has comment: http://stackoverflow.com/comment/86359999
tagged with: python-zipfile
type: Question

http://stackoverflow.com/comment/86420333
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49703211
score: 0
has text: and my guess on taking the abs(f)**2 is bc what you're getting is a probability density

http://stackoverflow.com/a/49704738
has body: I think need: A = pd.Series([0.005077], index=[326]) date = pd.Series(['2011-01-18 16:00:00'], index=[4300]) B = pd.Series([ 0.004077], index=[5]) df = pd.DataFrame([np.concatenate([A, B])], columns=['A','B'], index=date) print (df) A B 2011-01-18 16:00:00 0.005077 0.004077 EDIT: for scalar is necessary create one item list: A = pd.Series([0.005077], index=[326]) date = pd.Series(['2011-01-18 16:00:00'], index=[4300]) B = pd.Series([ 0.004077], index=[5]) C = 0 df = pd.DataFrame([np.concatenate([A, B, [C] ])], columns=['A','B','C'], index=date) print (df) A B C 2011-01-18 16:00:00 0.005077 0.004077 0.0
has comment: http://stackoverflow.com/comment/86422835
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86422739
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49704687
has comment: http://stackoverflow.com/comment/86422986
accepted answer of: http://stackoverflow.com/q/49704687
type: Answer
has comment: http://stackoverflow.com/comment/86422871

http://stackoverflow.com/q/49749033
favorite count: 0
tagged with: generator
downvote count: 0
has title: Checking my assumption of how generators work in python 3
score: 1
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86512662
answer count: 0
linked to: http://stackoverflow.com/q/685046
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86512640
tagged with: scrapy
has body: I'm writing a blog post about generators in the context of screenscaping, or making lots of requests to an API, based on the contents of a large-ish text file, and after reading this nifty comic by Julia Evans, I want to check something. Assume I'm on linux or OS X. Let's say I'm making a screenscraper with scrapy (it's not so important to know scrapy this qn, but it might be useful context) If I have an open file like so, and I went to be able to return a scrapy.Request for every line I pull out of a largeish csv file. with open('top-50.csv') as csvfile: urls = gen_urls(csvfile) for url in urls: yield scrapy.Request(url=url, callback=self.parse) gen_urls is a function that looks like this. def gen_urls(file_object): while True: # Read a line from the file, by seeking til you hit something like '\n' line = file_object.readline() # Drop out if there are no lines left to iterate through if not line: break # turn '1,google.com\n' to just 'google.com' domain = line.split(',')[1] trimmed_domain = domain.rstrip() yield "http://domain/api/{}".format(trimmed_domain) This works, but I want to understand what's happening under the hood. When I pass the csvfile to the gen_urls() like so: urls = gen_urls(csvfile) In gen_urls my understanding is that it works by pulling out a line at a time in the while loop with file_object.readline(), then yielding with yield "http://domain/api/{}".format(trimmed_domain). Under the hood, I think is a reference to some file descriptor, and readline() is essentially seeking forwards through the file, until it finds the next newline \n character, and the yield basically pauses this function until the next call to __.next__() or the builtin next(), at which point it resumes the loop. This next is called implicitly in the loop in the snippet that looks like: for url in urls: yield scrapy.Request(url=url, callback=self.parse) Because we're only pulling a line at the time from the file descriptor then 'pausing' the function with yield , we don't end …
has comment: http://stackoverflow.com/comment/86514620

http://stackoverflow.com/a/49712978
upvote count: 1
has comment: http://stackoverflow.com/comment/86452455
answers question: http://stackoverflow.com/q/49712729
type: Answer
has body: First, Python does have optional static typing if you want it. The syntax is a little different from C#, but it's the same as many other languages: customer: Customer = ReadCustomerRecord(12345) If you then run your code through Mypy, or another static type checker or analyzer (many IDEs have then integrated, so you don't have to do anything), it will be able to verify that the only things you ever store in customer are values of Customer type, and you never do anything with it that isn't legal for values of that type. However, even if you're using static type checking, you don't need to specify the type of every variable, because most of them can be automatically inferred. Again, this is different from C#, but it's the same as many other languages—including statically-typed languages with stricter rules and more powerful type systems than C# like Swift, Rust, or F#. "Inference" means that if you don't specify a type, the static checker figures out that customer must be a Customer because that's what ReadCustomerRecord returns. And then it can verify all the same stuff as before. Just as in Swift or Go, it's idiomatic in Python to not specify the types of variables unless it's either showing something non-obvious or otherwise helpful to human readers, or resolving something ambiguous to the static checker. Among modern languages, it's really only the languages in the C family (C, C++, Java, C#, etc.) that require you to specify the type of everything by name even when it's blindingly obvious—and even many of them give you something like auto that can be used to tell the compiler to infer the type. But the big difference between Python and the other languages I mentioned is that Python is dynamically typed. The static checker can verify your variable types, but the actual compiler and interpreter don't care about them. In fact, under the covers, variables don't actually have types at all. In Python, it's values that have types. Variables are just names for values, an…
accepted answer of: http://stackoverflow.com/q/49712729
has comment: http://stackoverflow.com/comment/86458470
has comment: http://stackoverflow.com/comment/86458401
has comment: http://stackoverflow.com/comment/86440048
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86219242
comment on: http://stackoverflow.com/a/49605637
score: 0
has text: This works perfectly, However, I am still a bit confused, in the original code, I thought I was sorting a list of its element as dict type. instead of sorting a dict Maybe I need to go through the basic about python again
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86374359
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49673030
has text: Do you want solutions only in Python or any (legit, non-golfing) language?
score: 0

http://stackoverflow.com/q/49723269
score: 1
upvote count: 1
answer count: 1
tagged with: collections
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has body: I have the following code: def myFunc(word): for id, sList in enumerate(word): counts = Counter(sList) print(counts) myFunc([['Apple', 'Orange', 'Banana'], ["Banana", "Orange"]]) Output: Counter({'Apple': 1, 'Orange': 1, 'Banana': 1}) Counter({'Banana': 1, 'Orange': 1}) This is great. But what if I want the output dictionary like this: {'Apple': {'Orange':1, 'Banana': 1}, 'Orange': {'Apple':1, 'Banana':2}, 'Banana': {'Apple':1, 'Orange':2}} Which means the keys should be all the different words in my lists. The values are all the words count including only lists where the key appeared.
accepted answer: http://stackoverflow.com/a/49724343
tagged with: counter
tagged with: count
tagged with: python
type: Question
has title: How to use Counter in collections to count words from different lists in Python?
downvote count: 0
has answer: http://stackoverflow.com/a/49724343

http://stackoverflow.com/q/49727037
linked to: http://stackoverflow.com/q/12453580
has comment: http://stackoverflow.com/comment/86467895
tagged with: string
favorite count: 0
duplicate of: http://stackoverflow.com/q/12453580
type: Question
has comment: http://stackoverflow.com/comment/86468154
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49727067
tagged with: arrays
has body: Let's say this is my list: current_fruits = ['apple', 'orange', 'lemon'] My goal is to loop through each fruit in the list and add the name of the fruit onto a certain formatted string somehow. For example, this could be the string format for that list: "Fruits: apple, orange, lemon" so it would have commas and spaces after each item. I know I could do this manually by adding each index/place in the list onto the string, but I want it to be dynamic since the fruits in current_fruits change around.
tagged with: python
score: -1
has title: How can I treat a string like a list?
tagged with: list
downvote count: 2
upvote count: 1
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/49728637
type: Answer
has body: I think there is no need for dictionary. When you split the row, it creates a list of sub strings where 1st element would be the column number indicating the sentence number and another element would have the substring of your sentence. So you can generate your sentence on the go which would save the Space Complexity needed by Dictionary and maybe somewhat faster too. separator=' ' string=[] for line in open("answers.txt"): columns = line.split(separator) if columns[0]== '0': answer_0 += " "+ columns[1] elif columns[0]== '1': answer_1 += " "+ columns[1]
has comment: http://stackoverflow.com/comment/86480644
answers question: http://stackoverflow.com/q/49728401
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86632104
type: AnswerComment
type: Comment
has text: the solution worked, thanks, I put the app as apphook and it works very well, I guess that's the difference between plugin and apphook the complexity of the application.
comment on: http://stackoverflow.com/a/49796959
score: 0

http://stackoverflow.com/q/49679537
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86371574
downvote count: 4
has title: Make a function that takes in 3 inputs from the user and validates them
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/86370750
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49679734
type: Question
has body: Im trying to make a function that takes in 3 different inputs from the user and validates them to make sure they are all positive integers. Here's my current code def get_positive_number(prompt): condition = False while condition == False: time = (input("Number of time units:")) if not time.isnumeric() or int(time) == 0: print("{} is not a valid number".format(time)) condition = False elif int(time) &gt; 0 timeInt = int(time) condition = True while condition == False: atoms = (input("Number of atoms to simulate:")) if not atoms.isnumeric() or int(atoms) == 0: print("{} is not a valid number".format(atoms)) condition = False elif int(atoms) &gt; 0 atomInt = int(atoms) condition = True while condition == False: radius = (input("Radius of beaker:")) if not radius.isnumeric() or int(radius) == 0: print("{} is not a valid number".format(radius)) condition = False elif int(radius) &gt; 0 RadInt = int(time) condition = True pass

http://stackoverflow.com/comment/86491528
comment on: http://stackoverflow.com/a/49735965
type: Comment
type: AnswerComment
has text: Nice one. Unfortunately, `lambda` tends to make me sick :(. Only good in small doses!
score: 2

http://stackoverflow.com/a/49620974
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49615194
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86262014
has body: This is a pretty vague question. Do you have an example of what you're trying to do? Conceptually, the simple answer is yes. Consider the following problem: I need to create a small video that circles around a single object To accomplish this, you would create a script that would: Create an cube at 0,0,0 Add a camera to the scene and zoom to the selected object (the cube) Change the location / rotation of the camera Create a keyframe on location / rotation of the object on a frame in the future Repeat 3 &amp; 4 until camera goes full circle (this can be done through looping) Set render parameters on the camera Render the scene All of the above can be done via python scripting. You can learn how to invoke all the methods above by reading the api documentation Here. There is also a lot of resources available at the Blender Stack Exchange. I hope this helps. This is the best I can do with the limited information provided.
accepted answer of: http://stackoverflow.com/q/49615194

http://stackoverflow.com/q/49665247
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
tagged with: google-app-engine
has title: Python fails to import when accessed from web server
tagged with: python
has comment: http://stackoverflow.com/comment/86340374
accepted answer: http://stackoverflow.com/a/49676166
has body: Python does not import when accessed from web server I am new to Python and Google App Engine, may that is why I can not figure out this simple problem. I just started Google App Engine and completed Hello world thing. I started web server and I could see hello world in my browser. It worked fine. Since I need tensorflow to develop my app, I imported it like the line 2 below. import webapp2 import tensorflow class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, World!') app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) Now it does not work and produce ImportError: No module named tensorflow. Tensorflow is in fact properly installed and the script works fine from my command line. I wrote other scripts and they always properly import using command line but can not import when accessed from the web server. My wild guess is that this is the permission issue of the web server process (since it is the one accessing to the python script in question) but I am not sure. Please help. [UPDATE and Supplemental info 1] In the original post, I made the issue simple for ease of communication. Yet in fact I want to import 6 libraries like below. import webapp2 import base64 import json import tensorflow as tf from googleapiclient import discovery from google.oauth2 import service_account All of them are successfully imported when the script is run via command line of Cloud Shell. However, when accessed from web server, first 3 libraries (i.e. webapp2, base64, joson) were successfully imported, but last 3 libraries (i.e. tensorflow, Googleapiclient, googel.oauth2) were not imported. In Google App Engine, how can python script not import google libraries when access from web server process? [UPDATE and Supplemental info 2] I have not changed the folder and it is very simple. In hello_world folder, there are four files, app.yaml, main.py, main.pyc, requirements.txt I left the app.yaml un-tu…
type: Question
has answer: http://stackoverflow.com/a/49676166
has comment: http://stackoverflow.com/comment/86342151
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86380146
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/86231316
score: 1
type: QuestionComment
has text: You need generate a new random number inside the inner while. while `play_again: ...(number = randbelow(1, 101))`. Tip you can just '''while True"" and then use a break instead of while `play_again: play_again = True
type: Comment
comment on: http://stackoverflow.com/q/49612316

http://stackoverflow.com/a/49605206
has body: Try this (assuming your string is called s): re.findall('(.*)(?:.*\n){5}.*TTU Back Panel Log Out', s) which returns: ['[01112017 110228 700][1][INFO]&gt; Cash Unit Info - 2 Value 03 BILL LKR 5000 1000 0999 001 OK'] (?:.*\n){5} is a non-capturing group (due to the ?:), but searches for any characters occuring before a new line 5 times. The (.*) preceding it is the group you're capturing
answers question: http://stackoverflow.com/q/49605180
has comment: http://stackoverflow.com/comment/86217781
score: 0
accepted answer of: http://stackoverflow.com/q/49605180
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86217698
type: Answer

http://stackoverflow.com/comment/86498045
score: 0
type: Comment
type: AnswerComment
has text: @Peter one of the python's philosophies is: better explicit than implicit, by default the connection is Qt.AutoConnection, with that flag you indicate to PyQt to decide, and it will see which one is better, but this can be dangerous. the flag Qt.QueuedConnection is oriented for connections between elements that live in different threads, so it is better to make explicit the type of connection, if you want to know more read: http://doc.qt.io/qt-5/qt.html#ConnectionType-enum
comment on: http://stackoverflow.com/a/49727982

deep-learning
tags question: http://stackoverflow.com/q/49705406
tags question: http://stackoverflow.com/q/49746668
tags question: http://stackoverflow.com/q/49624167
tags question: http://stackoverflow.com/q/49721691
tags question: http://stackoverflow.com/q/49607704
tags question: http://stackoverflow.com/q/49661612
tags question: http://stackoverflow.com/q/49720697
tags question: http://stackoverflow.com/q/49655656
tags question: http://stackoverflow.com/q/49741328
tags question: http://stackoverflow.com/q/49674860
tags question: http://stackoverflow.com/q/49699572
tags question: http://stackoverflow.com/q/49708891
tags question: http://stackoverflow.com/q/49642414
tags question: http://stackoverflow.com/q/49702179
type: Tag
tags question: http://stackoverflow.com/q/49674079
tags question: http://stackoverflow.com/q/49691932
tags question: http://stackoverflow.com/q/49633303
tags question: http://stackoverflow.com/q/49701826
tags question: http://stackoverflow.com/q/49739356
tags question: http://stackoverflow.com/q/49643622
tags question: http://stackoverflow.com/q/49606805
tags question: http://stackoverflow.com/q/49604079
tags question: http://stackoverflow.com/q/49605958
tags question: http://stackoverflow.com/q/49713848
tags question: http://stackoverflow.com/q/49719616
tags question: http://stackoverflow.com/q/49755610
tags question: http://stackoverflow.com/q/49750367
tags question: http://stackoverflow.com/q/49716558
tags question: http://stackoverflow.com/q/49604812
tags question: http://stackoverflow.com/q/49609247
tags question: http://stackoverflow.com/q/49702026
tags question: http://stackoverflow.com/q/49658880
tags question: http://stackoverflow.com/q/49717115
tags question: http://stackoverflow.com/q/49645003
tags question: http://stackoverflow.com/q/49622896
tags question: http://stackoverflow.com/q/49605666
tags question: http://stackoverflow.com/q/49619627
tags question: http://stackoverflow.com/q/49754939
tags question: http://stackoverflow.com/q/49731355
tag name: deep-learning
tags question: http://stackoverflow.com/q/49720109
tags question: http://stackoverflow.com/q/49646304
tags question: http://stackoverflow.com/q/49651354
tags question: http://stackoverflow.com/q/49746321
tags question: http://stackoverflow.com/q/49627267
tags question: http://stackoverflow.com/q/49729362
tags question: http://stackoverflow.com/q/49731937
tags question: http://stackoverflow.com/q/49623497
tags question: http://stackoverflow.com/q/49676466
tags question: http://stackoverflow.com/q/49669124
tags question: http://stackoverflow.com/q/49668169
tags question: http://stackoverflow.com/q/49751619
tags question: http://stackoverflow.com/q/49649236
tags question: http://stackoverflow.com/q/49757054

http://stackoverflow.com/q/49713860
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has title: pandas: ValueError: Can only compare identically-labeled Series objects
accepted answer: http://stackoverflow.com/a/49713921
upvote count: 1
tagged with: dataframe
tagged with: python
has body: I have 2 csv files as below, I want to find if an individual performance (in df1) is above/below class average (in df2) using come compare function after finding their values. df1: Name Class Test1 Test2 Test3 John 9A 75 83 77 David 9B 65 67 55 Peter 9A 85 90 88 Tom 9C 74 92 78 df2: Class Test1 Test2 Test3 9A 80 82 84 9B 84 75 77 9C 75 78 80 Here's my method, feel free to correct/guide me if I'm wrong. I first find the Class of an individual in df1, e.g., John is 9A, then return the other columns such as Test1 or Test2 in df2 based on 9A target_class = df1.loc[df1['Name'] == 'John', 'Class'] print(target_class) &gt;&gt;&gt;&gt;9A Test1_avg = df2.loc[df2['Class'] == target_class, 'Test1'] # ideally it should return 80 And I got this ValueError: Can only compare identically-labeled Series objects Or simply, how would you compare John's Test1 in df1 vs Class 9A's Test1 in df2? Is there any easier method than mine? Thanks for your help! Update: I'll then use a compare function like this to return a score if it fulfills the criteria def comparison(a, b): return 2 if a &gt; b else 1 if a == b else -1
has answer: http://stackoverflow.com/a/49713921

http://stackoverflow.com/comment/86312177
type: Comment
type: AnswerComment
has text: Yes that is expected, because it determines the bounding box for the currently used dpi. If you need to save the figure, **first** save it with the option `bbox_inches='tight'`, only **after** that call this custom method.
score: 1
comment on: http://stackoverflow.com/a/49650052

http://stackoverflow.com/comment/86288879
comment on: http://stackoverflow.com/q/49638005
type: Comment
score: 1
type: QuestionComment
has text: Your handler.py should probably sleep at the end of its loop (even if just a second or two) or its going to hammer the CPU and filesystem constantly.

http://stackoverflow.com/q/49693758
has comment: http://stackoverflow.com/comment/86400877
answer count: 1
has body: I have a pandas dataframe which contains 3 columns df = | id | product_details | taxo | 100 [Sales Package=6 Pair slipper, Strap Material=Rubber, qty=1, categoryPath=Footwear&gt;Men&gt;Slippers &amp; Flip Flops, 1 codAvailable=true, detailedSpecs=Multicolor Color, None Character Type Slippers For Men Sole Material Rubber] 200 [Brand Fit=Regular, Fabric=Cotton Polyester Blend, Fabric Care=Hand wash, Fit=Regular, Ideal For=Mens, Neck Type=Round Neck, Pack of=1, Pattern=Graphic Print, 2 Reversible=No, Sales Package=1 T-Shirt, Size=M, Sleeve=Half Sleeve, Sleeve Type=Wide, Suitable For=Western Wear, categoryPath=Apparels&gt;Men&gt;Polos &amp; T-Shirts, codAvailable=true, detailedSpecs=Fabric Cotton Polyester Blen Regular Fit Round Neck T-shirt Pattern Graphic Print Sleeve Type Wide Half Sleeve, discountPercentage=0] i want to find keyword categoryPath in product_details column of dataframe and return some text in front of it, till first occurrence of comma and write it into new dataframe (df_new) i have over 8 million rows in my dataframe. Expected output: df_new | id | category_path | 100 Footwear&gt;Men&gt;Slippers &amp; Flip Flops 200 Apparels&gt;Men&gt;Polos &amp; T-Shirts
has comment: http://stackoverflow.com/comment/86400690
has comment: http://stackoverflow.com/comment/86400575
has comment: http://stackoverflow.com/comment/86400977
has comment: http://stackoverflow.com/comment/86401098
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86401321
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/86400884
tagged with: regex
has comment: http://stackoverflow.com/comment/86400487
type: Question
has title: find the match keyword and return some text in front of matched keyword till first occurrence of comma
has answer: http://stackoverflow.com/a/49694167
accepted answer: http://stackoverflow.com/a/49694167

http://stackoverflow.com/a/49617894
accepted answer of: http://stackoverflow.com/q/49617401
has comment: http://stackoverflow.com/comment/86243191
answers question: http://stackoverflow.com/q/49617401
has body: Slicing strings to get date components is bad practice. You should convert to datetime and extract directly. In this case, it seems you can just use pd.to_datetime, but below I also demonstrate how you can extract the various components once you have performed the conversion. df = pd.DataFrame({'Date': ['2017-01-15 14:55:42', '2017-11-10 12:15:21', '2017-12-05 22:05:45']}) df['Date'] = pd.to_datetime(df['Date']) df'year', 'month', 'day', 'hour', 'minute', 'sec' = \ df['Date'].apply(lambda x: (x.year, x.month, x.day, x.hour, x.minute, x.second)).apply(pd.Series) Result: Date year month day hour minute sec 0 2017-01-15 14:55:42 2017 1 15 14 55 42 1 2017-11-10 12:15:21 2017 11 10 12 15 21 2 2017-12-05 22:05:45 2017 12 5 22 5 45
type: Answer
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49607418
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86225116
has body: I have extracted a HTML table using BeautifulSoup and would like to import it into a pandas DataFrame. However, data from the original table is spread out across multiple rows. Here are two entries for reference: Record : 1 of 749 Patients Name : Andrew Smith Admit Date : 20-MAR-2018 Group Number : 17 Address : 123 Sunshine Ave Postal Code : 12345 Blood Type : A Ward Class : A Age : 45 Height : 174cm Weight : 102kg ID : 013 Record : 2 of 749 Patients Name : Margaret Chow Admit Date : 19-MAR-2018 Group Number : 14 Address : 5 Mango Beach Postal Code : 54321 Blood Type : B Ward Class : B2 Age : 32 Height : 154cm Weight : 52kg ID : 051 I have used the following code to extract the above table into a pandas DataFrame: import pandas as pd table = str(table) df = pd.read_html(table) df = pd.DataFrame(df) df My df looks like this: but I would like it to be a DataFrame with columns ['Patients Name', 'Admit Date', 'Group Number', 'Address', 'Postal Code', 'Blood Type', 'Ward Class', 'Age', 'Height', 'Weight', 'ID']. Am new to this. Greatly appreciate any advice!
tagged with: pandas
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/49609298
tagged with: python
has answer: http://stackoverflow.com/a/49609298
type: Question
has title: Reading HTML table with data spread across rows
answer count: 1
tagged with: data-cleaning
tagged with: beautifulsoup

http://stackoverflow.com/comment/86384296
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49680181
has text: [this link](https://anaconda.org/auto/pytesseract) tells that conda has very old version of pytesseract (v0.1), while current version is v0.2.1. Try installing with pip as described in [pytesseract github page](https://github.com/madmaze/pytesseract/blob/master/README.rst#installation)
score: 1

http://stackoverflow.com/a/49669665
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49669516
has body: Solution with regexes: from bs4 import BeautifulSoup import re with open(r"C:\Users\sourabhk076\Documents\CBS_1.html") as fp: soup = BeautifulSoup(fp.read(), 'html.parser') Let's find the div that matches the following regular expression: background:\s*#fdc431;. \s matches a single Unicode whitespace character. I assumed that there can be 0 or more whitespaces so I added the * modifier to match 0 or more repetitions of the preceding RE. You can read more about regexes here as they sometimes come in handy. I also recommend you this online regex tester. div = soup.find('div', attrs={'style': re.compile(r'background:\s*#fdc431;')}) This however is equivalent to: div = soup.find('div', style=re.compile(r'background:\s*#fdc431;')) You can read about that in the official documentation of BeautifulSoup Worth reading are also the sections about the kinds of filters you can provide to the find and other similar methods. You can supply either a string, regular expression, list, True or a function, as shown by Keyur Potdar in his anwser. Assuming the div exists we can get its text by: &gt;&gt;&gt; div.text '42263 - Unencrypted Telnet Server'
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86266808
comment on: http://stackoverflow.com/q/49628139
score: 0
has text: A good option for you is to consider installing `pip` using one of OSX's sources, like the `apt` program in Debian-based distributions, rather than `easy_install`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86279477
type: QuestionComment
score: 0
has text: Keeping just the first element of the subarrays changes the problem significantly. Though I'm not sure it makes it easier or harder.
type: Comment
comment on: http://stackoverflow.com/q/49635509

http://stackoverflow.com/q/49695909
tagged with: arraylist
score: 0
duplicate of: http://stackoverflow.com/q/4663306
tagged with: list
linked to: http://stackoverflow.com/q/4978787
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86404667
has comment: http://stackoverflow.com/comment/86404583
has answer: http://stackoverflow.com/a/49695956
upvote count: 1
linked to: http://stackoverflow.com/q/7368789
has answer: http://stackoverflow.com/a/49695988
has title: User input as a list of integers in python 3
downvote count: 1
has comment: http://stackoverflow.com/comment/110529298
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49696029
has body: I have this python 3 script which should compare two lists and find equal numbers. It'a a Cows and Bulls game. Not going to go too much into details but here is the problem. When I ask for user input as a list it returns list of Strings and not integers, hence I can't compare elements with my given list if integers. Please advise how to cast userinput list into list of digits: Script below: import random numtoguess = [random.randrange(0,10,1) for _ in range (4)] print(numtoguess) userinput = [] while numtoguess != userinput: userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :&gt; ")) print(userinput) cows = 0 bulls = 0 counter = 0 for i in userinput: if i in numtoguess and i == numtoguess[counter]: bulls += 1 elif i in numtoguess and i != numtoguess[counter]: cows += 1 counter += 1 print('Cows: ' + str(cows)) print('Bulls: ' + str(bulls))
linked to: http://stackoverflow.com/q/4663306
has answer: http://stackoverflow.com/a/49695947
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/86404739

http://stackoverflow.com/a/49655277
answers question: http://stackoverflow.com/q/49619995
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: One can control the repetitions by the tf.data.Dataset.repeat(num_epochs) one sets in the input_fn(). The training function will run until the number of epochs is consumed, then the evaluation function will run, then the training function will run again until the number of epochs, and so on; finally, the train_and_eval method will stop when the max_steps define in TrainSpec is reached. This is a conclusion I draw from a few experiments, corrections are welcome.

http://stackoverflow.com/q/49640489
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/97001476
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86987787
tagged with: pyqt
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: So I have several (it changes) plots that are stacked vertically. They all have the same x-axes, so I only show the x-axis labels on the bottom plot since if there are a large number of plots, repeating the x-axis labels clutters things up. What this ends up doing however is making the bottom plot area smaller because the labels take up some area (the plotItems are the same size I think) I can't seem to figure out how to make it so all the plot areas (viewboxes) are the same size. Any suggestions? Here is some simple code that will reproduce the problem... from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg app = QtGui.QApplication([]) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) p1 = win.addPlot(y=np.random.normal(size=100), pen=(255,0,0)) p1.getAxis('bottom').setStyle(showValues=False) win.nextRow() p2 = win.addPlot(y=np.random.normal(size=100)) p2.getAxis('bottom').setStyle(showValues=False) win.nextRow() p3 = win.addPlot(y=np.random.normal(size=100), pen=(0,0,255)) p3.setLabel('bottom', "Time (s)") if __name__ == '__main__': import sys QtGui.QApplication.instance().exec_()
has title: how to make all plots the same height?
has comment: http://stackoverflow.com/comment/86288702
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/49652176
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49651142
upvote count: 1
has comment: http://stackoverflow.com/comment/86313650
has body: You can see that the row which has a new platform, has 3 columns, while others have 2. You can use that to change the platform. You can see that rows like PlayStation have a column (&lt;td&gt; tag) with colspan="2" class="center" attributes. Use this to handle cases like PlayStation. Code: url_credit = "http://www.mobygames.com/game/wheelman/view-moby-score" response = requests.get(url_credit, headers=headers) soup = BeautifulSoup(response.text, "lxml") table = soup.find("table", class_="reviewList table table-striped table-condensed table-hover").select('tr[valign="top"]') platform = '' total_votes, total_score = None, None for row in table[1:]: # handle cases like playstation if row.find('td', colspan='2', class_='center'): platform = row.find('td').text total_score, total_votes = None, None print('{} | {} | {} | {} | {}'.format(platform, total_votes, None, None, total_score)) continue cols = row.find_all('td') if len(cols) == 3: platform = cols[0].text total_votes = cols[1].text total_score = cols[2].text continue print('{} | {} | {} | {} | {}'.format(platform, total_votes, cols[0].text, cols[1].text, total_score)) Output: PlayStation 3 | None | None | None | None Windows | 6 | Acting | 4.2 | 4.1 Windows | 6 | AI | 3.7 | 4.1 Windows | 6 | Gameplay | 4.0 | 4.1 Windows | 6 | Graphics | 4.2 | 4.1 Windows | 6 | Personal Slant | 4.3 | 4.1 Windows | 6 | Sound / Music | 4.3 | 4.1 Windows | 6 | Story / Presentation | 3.8 | 4.1 Xbox 360 | 5 | Acting | 3.8 | 3.5 Xbox 360 | 5 | AI | 3.2 | 3.5 Xbox 360 | 5 | Gameplay | 3.4 | 3.5 Xbox 360 | 5 | Graphics | 3.6 | 3.5 Xbox 360 | 5 | Personal Slant | 3.6 | 3.5 Xbox 360 | 5 | Sound / Music | 3.4 | 3.5 Xbox 360 | 5 | Story / Presentation | 3.8 | 3.5 Note: By print, I mean save those values in whatever list/DataFrame you are using. I'm just using print() to show how to change the platform variable as and when needed.
has comment: http://stackoverflow.com/comment/86312789
has comment: http://stackoverflow.com/comment/86312827
score: 1
answers question: http://stackoverflow.com/q/49651142
type: Answer
has comment: http://stackoverflow.com/comment/86312724

http://stackoverflow.com/a/49760991
has body: You can use whatever method of tracking time you like (other than pygame.time.get_ticks() I suppose), and use a similar approach as in that pygame code. You'd want to store previous_time as a member of the environment instead of just a local variable, because you want it to persist across function calls. It's not easy to actually prevent your Reinforcement Learning agent (assuming you're using gym for RL) from selecting the fire action altogether, but you can simply implement the step() function in such a way that the agent does not do anything at all if they select the fire action too quickly. As for measuring time, you could measure wall clock time, but then the power of your CPU is going to influence how often your agent is allowed to shoot (it might be able to shoot a new bullet every step on very old hardware, but only be allowed to shoot one bullet every 100 steps on powerful hardware), that's probably a bad idea. Instead, I'd recommend measuring "time" simply by counting the step() calls. For example, using only the code from your question above, the step() function could look like: def step(action): self.step_counter += 1 # other step() code here if action == FIRE: if self.step_counter - self.previous_time &gt; 10: # or any other number self.previous_time = self.step_counter bullets.append([x + 25, y + 24]) # other step() code here Don't forget that you'll also want to reset your newly added member variables in reset(): def reset(): self.step_counter = 0 self.previous_time = -100 # some negative number such that your agent can fire at start # other reset() code here
accepted answer of: http://stackoverflow.com/q/49737552
type: Answer
answers question: http://stackoverflow.com/q/49737552
upvote count: 1
has comment: http://stackoverflow.com/comment/86555360
has comment: http://stackoverflow.com/comment/86539399
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86411400
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49699077
type: QuestionComment
has text: Your code will just check whether one of the letters are in the `secretWord` or not. You will have to check all the letters.. Maintain a count of the number of letters found in the secret word, and in the end see if the count is equal to the the length of the string `secretWord`.

http://stackoverflow.com/a/49654598
answers question: http://stackoverflow.com/q/49653155
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49653155
type: Answer
has comment: http://stackoverflow.com/comment/86323465
has body: Put your variables into your ~/.bash_profile using whatever text editor you use export SQL_HOST='11.11.81.7011' export SQL_USER='dsufghsd' export SQL_PWD='tfjb2379gfweiu' export SQL_DB='fwenf249ftgwieufgefw7f' Don't forget to do source ~/.bash_profile Then you call on them as such import os conf = {'host': os.environ['SQL_HOST'], 'user': os.environ['SQL_USER'], 'password': os.environ['SQL_PWD'], 'db': os.environ['SQL_DB']} conf.update({'charset': 'utf8mb4', 'cursorclass': pymysql.cursors.SSDictCursor}) conn = pymysql.connect(**conf)
score: 0
has comment: http://stackoverflow.com/comment/86360458
has comment: http://stackoverflow.com/comment/86321012

http://stackoverflow.com/a/49873543
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49705338
score: 3
has body: This was fixed few days after your question: https://youtrack.jetbrains.com/issue/PY-29313 You should update your PyCharm to 2018.1.1 or higher.
answers question: http://stackoverflow.com/q/49705338

http://stackoverflow.com/comment/86238276
has text: Even though this is a dupe, and OP *should* have tried debugging the program with a few print statements, I think the downvotes here are a little harsh. The change in behavior of the `/` operator is not obvious.
comment on: http://stackoverflow.com/q/49615649
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86385678
type: AnswerComment
comment on: http://stackoverflow.com/a/49687065
score: 1
type: Comment
has text: That looks to me like replacing one non numpy lib with another non numpy lib.

http://stackoverflow.com/a/49672198
has body: If you need to wait until a certain point in your program to actually allocate the dict, define a function that creates and returns it so that you can control when it gets called. In dictFile.py: import numpy as np def create_mydict(): myDict = {} myDict['a'] = np.array(...) ... Then in your code, myDict = dictFile.create_mydict() If you really need myDict to exist as a module-level variable, then you can declare it as such and have create_mydict() populate the global. import numpy as np myDict = None def create_mydict(): global myDict myDict['a'] = ... ... You can also conditionally call create_mydict as needed: if dictFile.myDict is None: dictFile.create_mydict() This requires you to use import dictFile, not from dictFile import myDict, as the latter creates a separate global name from dictFile.myDict that isn't affected by the call to create_mydict.
has comment: http://stackoverflow.com/comment/86384730
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49671985

ubuntu-17.10
tags question: http://stackoverflow.com/q/49647452
type: Tag
tag name: ubuntu-17.10

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

http://stackoverflow.com/q/49605958
tagged with: deep-learning
has title: what's the purpose of tf.nn.dropout?
tagged with: python
type: Question
has body: I notice there are two APIs in TensorFlow concerning with dropout, one is tf.nn.dropout, the other is tf.layers.dropout. I just wonder what's the purpose of tf.nn.dropout? According to https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf, there should be a parameter to distinguish between training and testing stage. I see tf.layers.dropout provides the proper behavior, so why another function tf.nn.dropout? Anyone has any idea? Thanks.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49606249
answer count: 1
has comment: http://stackoverflow.com/comment/86218687
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86218874
linked to: http://stackoverflow.com/q/44395547
score: 0

http://stackoverflow.com/q/49719643
tagged with: python
tagged with: python-cryptography
has title: from cryptography.hazmat.bindings._constant_time import lib ImportError: No module named _constant_time
type: AnsweredQuestion
score: 0
has body: I am basically deploying a flask app in app engine that uses pywebpush(https://github.com/web-push-libs/pywebpush). I followed the following tutorial to deploy(https://cloud.google.com/appengine/docs/standard/python/getting-started/python-standard-env) But i am constantly getting the error in app engine while it works fine in local system. The Error is: "from cryptography.hazmat.bindings._constant_time import lib ImportError: No module named _constant_time". Can Someone help me to over come this?
answer count: 1
accepted answer: http://stackoverflow.com/a/49734460
has answer: http://stackoverflow.com/a/49734460
type: Question
tagged with: google-app-engine

http://stackoverflow.com/a/49612405
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49612207
upvote count: 1
has comment: http://stackoverflow.com/comment/86232015
has comment: http://stackoverflow.com/comment/86232533
has body: Breaking things down: Slices ([::] syntax) will address all possible values in the range. That means all of these are true. ['cat'][0:1] == ['cat'] ['cat'][1:2] == [] ['cat'][-1:2] == ['cat'] ['cat'][-10000:] == ['cat'] Accessing something by index on the other hand ([x] will fail if the index does not exist. That means these fail: ['cat'][1] ['cat'][-2] Your comprehension means "take all lines that meet the following: If you rstrip them they are not empty (remember an empty string is NOT a digit) The substring representing the last character is a digit You might want this instead: [line.rstrip() for line in f if not line.rstrip() or line.rstrip()[-1].isdigit()] That will include your blank lines. As a clarification, you are at no point getting values from outside of the string ''[-123:] will pass. ''[-123] (no colon) will fail.
type: Answer

http://stackoverflow.com/q/49755973
answer count: 1
upvote count: 1
has body: I'm trying to make this oval move fluidly on this canvas using tkinter, but despite having a fixed speed, it seems to accelerate the more I move it. Even when debugging I've noticed that my speed variables do not increase above the desired values. I can't manage to identify what is causing this acceleration, can someone please point out what's going on? Here's my code: from tkinter import* window = Tk() canvas = Canvas(window, width = 300, height = 300, bg ='white') canvas.focus_set() speedx = 0 speedy = 0 speed = 1 x1=40 y1=40 oval=canvas.create_oval(x1-10,y1-10,x1+10,y1+10,width=2,fill='orange') def key_press(event): global x1, y1 global speedx, speedy, speed button = event.keysym if button == 'Up': speedx = 0 speedy = -speed elif button == 'Down': speedx = 0 speedy = speed elif button == 'Right': speedx = speed speedy = 0 elif button == 'Left': speedx = -speed speedy = 0 move() def move(): global x1,y1 global oval global speedx, speedy x1 += speedx y1 += speedy canvas.delete(oval) oval = canvas.create_oval(x1+10,y1-10,x1-10,y1+10,width=2,fill='orange') window.after(10, move) def key_release(event): global speedx, speedy speedx = 0 speedy = 0 canvas.bind('&lt;KeyPress&gt;', key_press) canvas.bind("&lt;KeyRelease&gt;", key_release) canvas.pack(padx =5, pady =5) window.mainloop()
has comment: http://stackoverflow.com/comment/86527235
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86527526
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/49756882
downvote count: 0
has answer: http://stackoverflow.com/a/49756882
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86527153
has title: Why does my tkinter oval accelerate despite having a fixed speed?
score: 1

http://stackoverflow.com/q/49757032
tagged with: sockets
has answer: http://stackoverflow.com/a/49758373
tagged with: python
accepted answer: http://stackoverflow.com/a/49758373
type: AnsweredQuestion
downvote count: 0
has title: having trouble with sockets in unity3d
score: 1
upvote count: 1
answer count: 1
has body: Made a Hololens application that communicates with a python script. The python script sends PLC(Siemens S7-1200) variables to the hololens in the form of JSON. The C# script processes the JSON. While the script reads data from the plc, It's also possible to control the variables with the sendMessage method inside the C# script. I've made a seperate python script that controls the plc, this I won't share. my Unity3d C# script: using UnityEngine; using System; using System.IO; using System.Text; using System.Linq; using HoloToolkit.Unity; using System.Collections.Generic; using UnityEngine.UI; using Newtonsoft.Json; #if !UNITY_EDITOR using Windows.Networking.Sockets; using Windows.Networking.Connectivity; using Windows.Networking; #endif #if !UNITY_EDITOR public class RootObject { public int Index { get; set; } public bool Moto { get; set; } public bool Start { get; set; } public bool StartWINCC { get; set; } public bool Stop { get; set; } public bool StopWINCC { get; set; } public bool Tag1 { get; set; } public bool Tag2 { get; set; } } #endif public class UDPCommunication : Singleton&lt;UDPCommunication&gt; { // Connection variables public string port = "8000"; public string externalIP = "172.16.24.136"; public string externalPort = "8000"; // UI/Text elements public Text testert; public Image moto; public Image start; public Image startwincc; public Image stop; public Image stopwincc; public Image tag1; public Image tag2; public String uitext; // Sets up a Queue public readonly static Queue&lt;Action&gt; ExecuteOnMainThread = new Queue&lt;Action&gt;(); #if !UNITY_EDITOR // Socket initialization DatagramSocket socket; #endif #if !UNITY_EDITOR // use this for initialization async void Start() { Debug.Log("Waiting for a connection..."); socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; HostName IP = null; try { var icp = NetworkInformation.GetInternetConnectionProfile(); IP = Windows.Networking.Connectivity.NetworkInformation.GetHostName…
tagged with: s7-1200
favorite count: 0
type: Question
tagged with: unity-game-engine
tagged with: c#

http://stackoverflow.com/q/49711793
has comment: http://stackoverflow.com/comment/86437154
favorite count: 0
has body: Hi I want to have an efficient code for returning the next alphabetic item after that word. For example in the list below return the lion when dog is entered. I need to specify input over and over again and therefore could benefit from a presorted list and save the O(nlogn) time everytime. The code is running as intended, I just want it to make faster for a very long list. a = ['donkey','alligator','zebra','monkey','dog','cat','lion','bull','ant'] ## Output of dog should be: lion input_word ='dog' def get_next(input_word): b = sorted(a[a.index(input_word):]) d = {j:i for i,j in enumerate(b)} try: return(b[d[input_word]+1]) except: if len(d)==1: return("Last value") else: return("No value greater than input") print(get_next(input_word)) Edit: The next element should be alphabetically next to dog, so the first element that has alphabet starting after the alphabet 'd' and after the 'dog' in the list is lion. Edit2: More examples, if the list is a = ['x', 'z', 'y'] If input is x the result should be y, if input is y the output should be 'Last word' and if the input is z then the output should be 'No value greater than input'
has title: Returning the next alphabetic item in a list after that word, improve performance
has answer: http://stackoverflow.com/a/49733325
type: Question
has comment: http://stackoverflow.com/comment/86451067
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86451516
has comment: http://stackoverflow.com/comment/86489567
tagged with: python
tagged with: sorting
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86487352
score: -3
possible better answer: http://stackoverflow.com/a/49733325
has comment: http://stackoverflow.com/comment/86487221
has comment: http://stackoverflow.com/comment/86451468
tagged with: list
tagged with: performance
accepted answer: http://stackoverflow.com/a/49736808
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49736808
downvote count: 3

http://stackoverflow.com/comment/131273045
type: Comment
has text: How can we add progress bar during each download of object using tqdm in this program
type: AnswerComment
comment on: http://stackoverflow.com/a/61979699
score: 0

http://stackoverflow.com/q/49696350
has answer: http://stackoverflow.com/a/49697280
tagged with: python
has comment: http://stackoverflow.com/comment/86405518
accepted answer: http://stackoverflow.com/a/49696605
tagged with: list
has comment: http://stackoverflow.com/comment/86405527
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49696605
score: 3
upvote count: 3
possible better answer: http://stackoverflow.com/a/49697280
has comment: http://stackoverflow.com/comment/86405526
favorite count: 0
has body: I have several lists of items. There are no duplicates, each item appears at most once per list (and normally, only once in all lists). I also have a list of items to remove from this dataset. How can it be done in the cleanest and most efficient way? I have read that in python, creating a new object is often simplier and faster than filtering an existant one. But I do not observe that in my basic tests : data = [[i*j for j in range(1, 1000)] for i in range(1, 1000)] kill = [1456, 1368, 2200, 36, 850, 9585, 59588, 60325, 9520, 9592, 210, 3] # Method 1 : 0.1990 seconds for j in kill: for i in data: if j in i: i.remove(j) # Method 2 : 0.1920 seconds for i in data: for j in kill: if j in i: i.remove(j) # Method 3 : 0.2790 seconds data = [[j for j in i if j not in kill] for i in data] Which method is the best to use in Python ?
has comment: http://stackoverflow.com/comment/86405612
type: Question
has title: Most efficient way to remove several items in several lists in python?
answer count: 2
downvote count: 0

http://stackoverflow.com/q/49655525
score: 20
tagged with: django-templates
answer count: 2
upvote count: 20
possible better answer: http://stackoverflow.com/a/58057178
downvote count: 0
tagged with: authentication
tagged with: django
has answer: http://stackoverflow.com/a/58057178
favorite count: 0
accepted answer: http://stackoverflow.com/a/49656032
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49656032
has body: I´m working on a course exercise and I'm stuck for a few hours and I'm not sure what is causing the app to break, next, you will find the files involved and perhaps you can find out the solution. Thanks for your help! Project structure This error is being thrown when I log in: Internal Server Error: /account/login/ ... django.urls.exceptions.NoReverseMatch: Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name. [04/Apr/2018 17:12:15] "POST /account/login/ HTTP/1.1" 500 151978 At the end of the settings.py file from django.urls import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_REDIRECT_URL = reverse_lazy('logout') The urls.py file from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'account' urlpatterns = [ # path('login/', views.user_login, name='login'), path('', views.dashboard, name='dashboard'), # login / logout urls path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), ] The views.py file from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) The base.html template {% load staticfiles %} {% block title %}{% endblock %} Bookmarks {% if request.user.is_authenticated %} {% if section == "dashboard" %}class="selected"{% endif %}>My dashboard {% if section == "images" %}class="selected"{% endif %}Images {% if section == "people" %}class="selected"{% endif %}People {% endif %} {% if request.user.is_authenticated %} Hello {{ request.user.fir…
tagged with: python
has title: Django 2.0 - Not a valid view function or pattern name (Customizing Auth views)
type: Question

http://stackoverflow.com/comment/86489860
has text: http://pyfound.blogspot.com/2017/01/time-to-upgrade-your-python-tls-v12.html
type: QuestionComment
comment on: http://stackoverflow.com/q/49737799
score: 0
type: Comment

http://stackoverflow.com/comment/86503371
comment on: http://stackoverflow.com/q/49743824
type: Comment
type: QuestionComment
has text: Are they always same value for abc or a1b1c1 ? \
score: 0

http://stackoverflow.com/comment/86405018
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49694832
has text: Also, can you post the entire traceback? It should actually be telling you which pickling method was being called, which will immediately tell you which options you have for overriding it without diving into the ctypes code or experimenting trial-and-error.

http://stackoverflow.com/q/49638108
has title: Matplotlib shared horizontal colorbar aligned with bottom axis in subplots
has comment: http://stackoverflow.com/comment/86288685
linked to: http://stackoverflow.com/q/13784201
answer count: 0
tagged with: colorbar
has comment: http://stackoverflow.com/comment/86287949
score: 1
has comment: http://stackoverflow.com/comment/86288642
has comment: http://stackoverflow.com/comment/86288316
upvote count: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86288533
has comment: http://stackoverflow.com/comment/86287798
downvote count: 0
duplicate of: http://stackoverflow.com/q/13784201
favorite count: 0
has body: While I was following the way to add a shared colorbar to subplots from this: Matplotlib 2 Subplots, 1 Colorbar but for a horizontal colorbar, I could not find the attribute or method giving the correct position of the axes for positioning the new colorbar axis using the add_axes() method. For example: import numpy as np import matplotlib matplotlib.use('macosx') import matplotlib.pyplot as plt im = np.random.rand(512, 512) fig, axs = plt.subplots(3,1, figsize=(4, 9)) ims = [axs[i].imshow(im, cmap='gray', origin='lower') for i in range(3)] pos = axs[-1].get_position() fig.subplots_adjust(bottom = 0.2) cbar_ax = fig.add_axes([pos.x0, 0.1, pos.width, 0.04]) fig.colorbar(ims[2], cax=cbar_ax, orientation='horizontal') Which gives the following results: where the colorbar clearly does not align with the horizontal axis before it, which I guess comes from the inappropriate values given by get_position() I also tried, instead, using the other method involving: divider = make_axes_locatable(axs[-1]) cax_bottom = divider.append_axes('bottom', size="5%", pad=0.5) fig.colorbar(ims[-1], cax=cax_bottom) But this resizes the bottom figure and so my 1st attempt seems to be more accurate although I'm still missing the parameter giving the appropriate position of the axis to make this work. [EDIT] I also looked at the other link provided in the comment. None of the solution answers this. The 2nd answer in that SO link had a 3rd option that I didn't try, which uses another subplot for the colorbar itself, but it does not fix things either: # Using an axis for colorbar within subplots fig, axs = plt.subplots(4,1, figsize=(4, 9), gridspec_kw={"height_ratios":[1, 1, 1, 0.05]}) ims = [axs[i].imshow(im, cmap='gray', origin='lower') for i in range(3)] fig.colorbar(ims[2], cax=axs[-1], orientation='horizontal') [EDIT 2] Adapting the solution in the duplicate question, here is a working solution: import numpy as np import matplotlib matplotlib.use('macosx') import matplotlib.pyplot as plt fr…
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86288786
tagged with: python

http://stackoverflow.com/comment/86440320
type: Comment
comment on: http://stackoverflow.com/q/49713444
score: 3
type: QuestionComment
has text: The problem here isn't multiple inheritance. It's that `ClassB` and `ClassC` are calling a method that, as far as they are concerned, shouldn't exist. Most statically typed OOP languages wouldn't even admit this code. I would argue that, since `ClassB` and `ClassC` call a `ClassA` method, then *they* should both inherit from it in this case.

http://stackoverflow.com/comment/86296090
comment on: http://stackoverflow.com/q/49644188
has text: before using writer, add this line - frame = frame'Case index', 'Similarity', 'Case description'. this will work
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49652460
has comment: http://stackoverflow.com/comment/86315528
upvote count: 3
has comment: http://stackoverflow.com/comment/86316370
score: 3
tagged with: python
has body: When I deploy my Django project on elastic beanstalk I get a 500 Internal Server error. I have tried everything,The EB dashboard looks okay health is perfect and no mention of any errors in there. Can anyone shed some light on this? ============= i-03980c0f6a1094e3c ============== ------------------------------------- /var/log/httpd/error_log ------------------------------------- [Wed Apr 04 13:15:51.669498 2018] [suexec:notice] [pid 3065] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Apr 04 13:15:51.684578 2018] [http2:warn] [pid 3065] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Wed Apr 04 13:15:51.684588 2018] [http2:warn] [pid 3065] AH02951: mod_ssl does not seem to be enabled [Wed Apr 04 13:15:51.685042 2018] [lbmethod_heartbeat:notice] [pid 3065] AH02282: No slotmem from mod_heartmonitor [Wed Apr 04 13:15:51.686951 2018] [mpm_prefork:notice] [pid 3065] AH00163: Apache/2.4.27 (Amazon) mod_wsgi/3.5 Python/3.6.2 configured -- resuming normal operations [Wed Apr 04 13:15:51.686971 2018] [core:notice] [pid 3065] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Wed Apr 04 13:16:13.037691 2018] [mpm_prefork:notice] [pid 3065] AH00169: caught SIGTERM, shutting down [Wed Apr 04 13:16:14.092208 2018] [suexec:notice] [pid 3287] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Apr 04 13:16:14.107856 2018] [so:warn] [pid 3287] AH01574: module wsgi_module is already loaded, skipping [Wed Apr 04 13:16:14.110001 2018] [http2:warn] [pid 3287] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This i…
has comment: http://stackoverflow.com/comment/86316115
has comment: http://stackoverflow.com/comment/86314824
has title: Django app not launching on Elastic Beanstalk AWS
type: Question
linked to: http://stackoverflow.com/q/32586612
has comment: http://stackoverflow.com/comment/86314922
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86313369
has answer: http://stackoverflow.com/a/49653854
tagged with: django
tagged with: amazon-web-services
tagged with: amazon-elastic-beanstalk
has comment: http://stackoverflow.com/comment/86316187
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/49637161
tagged with: python
accepted answer: http://stackoverflow.com/a/49637676
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86282938
tagged with: pandas
score: 0
answer count: 1
has body: I am writing a script that connects to a Teradata DB, reads in data from a single table, and runs some analysis on that table. The script I have below (made generic for this question) works fine for the most part but I have 2 questions... How can I combine some of the results onto a single tab? For example the MIN and MAX, currently are seperated into their own tabs (because I dont know how to do it otherwise). What I would like is those combined in one tab, Column A has the columns listed, Column B has MIN values Column C has MAX values. Same with the 2 NULL checks shown as well Seems like a simple question, but how can I get the row count at the bottom exported to the same Excel sheet as it's own tab? This throws an error "int has no object to_excel' Thanks EDIT figured out question 1. I just added: startcol=0 or startcol=1 and added them to the same sheet import teradata import pandas as pd def main(): writer = pd.ExcelWriter('table_results.xlsx', engine='xlsxwriter') udaExec = teradata.UdaExec(appName="test", version="1.0", logConsole=True) def func_1(): #connect to Teradata and run SELECT statement on single table with udaExec.connect(method="odbc", dsn="xxx", username="xxx", password="xxx") as session: query = "Select * from TableA" # read in records df = pd.read_sql(query, session) # print top 20 records head = df.head(20) head.to_excel(writer, sheet_name='Top_20') # columns with NULL values -- returns True/False null_columns = df.isnull().any() null_columns.to_frame(name='HasNullValues').to_excel(writer, sheet_name='Null_Columns') # count of NULL values per column null_columns_sum = df.isnull().sum() null_columns_sum.to_frame(name='NumNullValues').to_excel(writer, sheet_name='Null_Column_Count') # max value per numeric column max_val = df.max(numeric_only=True) max_val.to_frame(name='max').to_excel(writer, sheet_name='Max_Val') # min value per numeric column min_val = df.min(numeric_only=True) min_val.to_frame(name='max').to_excel(writer, sheet_name='Min_Val…
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/49637676
has title: Grouping certain pandas results into single Excel tab

http://stackoverflow.com/comment/86379583
type: AnswerComment
has text: I believe `if word.encode("utf-8") == w` would be enough. `w` is already `utf-8` encoded
score: 0
comment on: http://stackoverflow.com/a/49683942
type: Comment

http://stackoverflow.com/comment/86502130
type: AnswerComment
comment on: http://stackoverflow.com/a/49724759
has text: Thank you. I was able to generate the key-value pairs in the dictionary. But these are reversed. For example, samsung: sumsing is showing up as sumsing:samsung (of these, Samsung, which is the correct spelling, is present in the first column, and sumsing is present in one of the other columns of the same row). This is an important difference, because I need to paste Samsung in the first sheet, not sumsing.
type: Comment
score: 0

http://stackoverflow.com/a/49684397
type: Answer
has comment: http://stackoverflow.com/comment/114617807
has comment: http://stackoverflow.com/comment/114632492
answers question: http://stackoverflow.com/q/49684095
has body: Does it matter to you what the file encoding is? If not, then use utf-8 encoding: f=open("test.txt", "w+", encoding="utf-8") f.write(stringU) If you want the file to be cp1252-encoded, which apparently is the default on your system, and to ignore unencodable values, add errors="ignore": f=open("test.txt", "w+", errors="ignore") f.write(stringU)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49684095
type: AcceptedAnswer
upvote count: 18
score: 18

http://stackoverflow.com/comment/115389393
type: Comment
type: QuestionComment
has text: Normally, ```brew rm python; rm -rf /usr/local/opt/python; brew prune; brew install python``` should do the trick
comment on: http://stackoverflow.com/q/49622185
score: 0

http://stackoverflow.com/comment/86553326
has text: I am looking for a case if my outlook credentials got expired and tried to login with my new credentials or my system was restarted .. mean while i got 3 mails ... can you suggest me how to proceed with these 2 cases . .also can you put some sample code for the above comment.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49695160
type: QuestionComment

http://stackoverflow.com/comment/86269081
type: Comment
has text: @Schorsch I didn't know that. Thanks :)
comment on: http://stackoverflow.com/q/49626599
score: 0
type: QuestionComment

http://stackoverflow.com/q/49647008
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86302347
tagged with: python
tagged with: regex
has title: How to remove XML tags using regular expression in python?
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/49648952
accepted answer: http://stackoverflow.com/a/49648952
score: 0
linked to: http://stackoverflow.com/q/48560748
upvote count: 1
has body: A string in python can contain certain plain text as well as few XML tags containing certain information. For example: The student XYZ abc has been terminated from the institute. you can find the details of student below: <user_detail> <first_name>ABC</first_name> <last_name>XYZ</last_name> <contact_details> <contact_number> <number_type>landline</number_type> 1234567 </contact_number> <address_field1> lorem ipsum, qwerty </address_field1> <address_field2> lorem ipsum2, qwerty2 </address_field2> asdfgh zxcvbn India </contact_details> </user_detail> <flight_detail> ... </flight_detail> Lorem ipsum dolor sit amet, pro ea dicat velit regione, modo putant sensibus pri id, ut bonorum scripserit sit. Ex nec tation alienum, est ut nemore efficiendi interpretaris, vis te reque eleifend. <xml_tag> ... </xml_tag> Laudem delectus reprehendunt ei mei, has nisl dolorem mnesarchum no, ad eos modo singulis euripidis. Quo no consul offendit. Eu alia utroque argumentum vix, no case primis eum. <xml_tag> .... </xml_tag> It is not fixed that the opening tag of XML will be , it can be anything like and in this case, ending tag will be . Currently, I am removing this xml tags using data = re.sub(r'<[^<]+>', "", data) But, now I want to remove all XML content from this text.The final output that I want now is: The student XYZ abc has been terminated from the institute. you can find the details of student below: Lorem ipsum dolor sit amet, pro ea dicat velit regione, modo putant sensibus pri id, ut bonorum scripserit sit. Ex nec tation alienum, est ut nemore efficiendi interpretaris, vis te reque eleifend. Laudem delectus reprehendunt ei mei, has nisl dolorem mnesarchum no, ad eos modo singulis euripidis. Quo no consul offendit. Eu alia utroque argumentum vix, no case primis eum. I tried matching using </\S+>, but it will remove till first closing XML tag. How can I remove all the XML content from plain text string that can contain simple text also.
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86302388
favorite count: 0
type: Question

http://stackoverflow.com/comment/86293973
type: Comment
score: 0
has text: If your blocks all have the same length have a look at the `grouper` (not `groupby`) recipe on [this page](https://docs.python.org/3/library/itertools.html).
type: QuestionComment
comment on: http://stackoverflow.com/q/49642607

http://stackoverflow.com/q/49708543
answer count: 1
linked to: http://stackoverflow.com/q/1325905
type: Question
duplicate of: http://stackoverflow.com/q/1325905
has title: How to write an new line and string after the first occurrence of a string in in an file Python
accepted answer: http://stackoverflow.com/a/49708597
has answer: http://stackoverflow.com/a/49708597
has body: I would like to write an new line and string after the first the first occurrence of a string in Python For example my text file is like: 123456 example string&lt;random&gt; asdfg zxc example string&lt;random&gt; I would like it to change to 123456 example string&lt;random&gt; Python inputted string asdfg zxc example string&lt;random&gt; &lt;- Stays the same
tagged with: python
has comment: http://stackoverflow.com/comment/86430622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86430722
score: 0
has comment: http://stackoverflow.com/comment/86430740

http://stackoverflow.com/comment/86263247
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49627957
type: QuestionComment
has text: @Rohi Your link explains the difference between threads and processes. It has nothing to do with this question.

http://stackoverflow.com/a/49756934
accepted answer of: http://stackoverflow.com/q/49748899
has comment: http://stackoverflow.com/comment/86532068
upvote count: 3
answers question: http://stackoverflow.com/q/49748899
downvote count: 0
has comment: http://stackoverflow.com/comment/95741429
type: AcceptedAnswer
has body: jsonlines.Reader accepts iterable as an arg ("The first argument must be an iterable that yields JSON encoded strings" not json-encoded single string as in your example), but, after .decode("utf-8"), log would be a string, which happen to support iterable interface. So when reader calls under the hood next(log) it will get first item of a log string, i.e. character { and will try to process it as an json-line which would be obviously invalid. Try log = log.split() before passing log to the Reader.
score: 3
type: Answer

http://stackoverflow.com/a/50029336
type: Answer
score: 0
has body: jpp's answer is pretty comprehensive, just wanted to mention that as of pandas v22 parquet is very convenient and fast option with almost no drawbacks vs csv (accept perhaps the coffee break). read parquet write parquet At time of writing you'll need to also pip install pyarrow In terms of adding information you have the metadata which is attached to the data import pyarrow as pa import pyarrow.parquet as pq import pandas as pd import numpy as np df = pd.DataFrame(np.random.normal(size=(1000, 10))) tab = pa.Table.from_pandas(df) tab = tab.replace_schema_metadata({'here' : 'it is'}) pq.write_table(tab, 'where_is_it.parq') pq.read_table('where_is_it.parq') which then yield a table Pyarrow table 0: double 1: double 2: double 3: double 4: double 5: double 6: double 7: double 8: double 9: double __index_level_0__: int64 metadata -------- {b'here': b'it is'} To get this back to pandas: tab.to_pandas()
answers question: http://stackoverflow.com/q/49740190

http://stackoverflow.com/q/49750169
has comment: http://stackoverflow.com/comment/86514749
answer count: 1
tagged with: tensorflow
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/89228
tagged with: python
has title: TensorFlow example eager.py -> SyntaxError: invalid syntax
has comment: http://stackoverflow.com/comment/86514877
has body: Background: I am learning how to work with TesorFlow and I tried my first example eager.ipynb from the get started section. Obviously the notebook is working, but I encountered an Error after I downloaded the eager.py file and ran it locally: !head - n5 {train_dataset_fp} ^ SyntaxError: invalid syntax I am not familiar with !head instruction, what is it supposed to do and hot to solve the error? Here are the recommendations I get from PyCharm: Import from ... pip._vendor.requests.head() tensorflow.python.estimator.canned.head tensorflow.contrib.estimator.python.estimator.head tensorflow.contrib.timeseries.python.timeseries.head tensorflow.contrib.gen.python.estimator.python.head tensorflow.contrib.learn.python.learn.estimators.head TensorFlow version: 1.7.0
type: Question
has answer: http://stackoverflow.com/a/49750345
accepted answer: http://stackoverflow.com/a/49750345

http://stackoverflow.com/q/49714222
type: Question
has title: Can matplotlib.imshow coordinates start at 0 instead of -0.5?
has comment: http://stackoverflow.com/comment/88402315
has comment: http://stackoverflow.com/comment/86459235
tagged with: python
has comment: http://stackoverflow.com/comment/88392601
has answer: http://stackoverflow.com/a/67330238
has body: I'm trying to draw a box on a scaled image, and I notice that when the image is very small, the box seems to be drawn with an offset (see second row of the image): This behavior seems to be because I'm expecting the top left of the top left pixel to be aligned with the point (0, 0), but it seems that this point is actually aligned with the middle of the pixel. So, the coordinate of the top left corner of the image seems to actually be (-0.5, -0.5). Is there a way to change the behavior of matplotlib.imshow so coordinates are aligned with the top left of each pixel instead of the centers?
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/67330238
favorite count: 0

http://stackoverflow.com/q/49751398
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49757680
score: 1
tagged with: python
has body: I am trying to access all href-links from a website, the search-results to be precise. My first intention is to get all the links, and then to look further on it. The problem is --> I get some links from the website, but not the links of the search-results. Here is one version of my code. from selenium import webdriver from htmldom import htmldom dom = htmldom.HtmlDom("myWebsite") dom = dom.createDom() p_links = dom.find("a") for link in p_links: print("URL: " +link.attr("href")) Here is screen of the HTML of that particular website. In the screen, I marked the href-link I try to access in the future. I am open for any help given, be it in Selenium, htmldom, b4soup, etc.
accepted answer: http://stackoverflow.com/a/49758046
tagged with: dom
type: Question
has answer: http://stackoverflow.com/a/49758046
possible better answer: http://stackoverflow.com/a/49757680
answer count: 2
upvote count: 2
tagged with: selenium
tagged with: web-scraping
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/86522087
has title: Access all href-links in a deep-class hierarchy

http://stackoverflow.com/comment/86452002
comment on: http://stackoverflow.com/q/49719404
score: 0
type: Comment
type: QuestionComment
has text: appending a list within a list doesn't give the format like `custom_list` as I mentioned. It just adds like this: `custom_list = [2, 1, 3, 0, 2, 1 ,3]

http://stackoverflow.com/a/49758140
has comment: http://stackoverflow.com/comment/86544819
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/132524023
has comment: http://stackoverflow.com/comment/86573129
upvote count: 15
score: 15
downvote count: 0
type: Answer
has body: In my opinion, you should always prefer using a Timestamp - it can easily transform back into a numpy datetime in the case it is needed. numpy.datetime64 is essentially a thin wrapper for int64. It has almost no date/time specific functionality. pd.Timestamp is a wrapper around a numpy.datetime64. It is backed by the same int64 value, but supports the entire datetime.datetime interface, along with useful pandas-specific functionality. The in-array representation of these two is identical - it is a contigous array of int64s. pd.Timestamp is a scalar box that makes working with individual values easier. Going back to the linked answer, you could write it like this, which is shorter and happens to be faster. %timeit (df.index.values &gt;= pd.Timestamp('2011-01-02').to_datetime64()) &amp; \ (df.index.values &lt; pd.Timestamp('2011-01-03').to_datetime64()) 192 µs ± 6.78 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
accepted answer of: http://stackoverflow.com/q/49757871
answers question: http://stackoverflow.com/q/49757871

http://stackoverflow.com/q/49677773
type: UnansweredQuestion
has body: I have written a code to give me water level in terms of percentage.The water_level variable gives the channel display in continuous form. I am trying to display this data in terms of percentage in continuous form. However,after callibration it does not display any value. Here is my code: import RPi.GPIO as GPIO import time import Adafruit_ADS1x15 import datetime GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) adc=Adafruit_ADS1x15.ADS1115() while True: water_level=(adc.read_adc(0,2)) #Read Water Channel A0 #Minimum Water Level = 150 #Maximum Water Level = 32767 # water_level1 = water_level callibrated_water_level= water_level/32617*100 try: print "Time : ",time.time()," ", "Water Level: " ,callibrated_water_level , " % " except Exception as e: print( e) time.sleep(1)
has comment: http://stackoverflow.com/comment/86368009
has comment: http://stackoverflow.com/comment/86367778
has comment: http://stackoverflow.com/comment/86368019
type: Question
has comment: http://stackoverflow.com/comment/86368687
tagged with: python
answer count: 0
has title: Cannot display continuous data from sensor after conversion-Python
score: 0

http://stackoverflow.com/comment/86389265
has text: @Aquarius_Girl QMainWindow is a window class that is used as a container, so the other widgets will be on top of the CityscapesLabelTool covering your drawing, what you do is just move the drawing to Window.
comment on: http://stackoverflow.com/a/49687256
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49695330
answers question: http://stackoverflow.com/q/49616914
has body: I tried reproducing this using a Python Flask Cloud Foundry app and a Db2 on Cloud Lite plan instance. My connections seem to stay alive for hours. It might be the python application you are running that has some kind of timeout.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86409869
has comment: http://stackoverflow.com/comment/86409618
accepted answer of: http://stackoverflow.com/q/49616914
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/49701092
possible better answer: http://stackoverflow.com/a/49701148
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49701546
answer count: 2
has comment: http://stackoverflow.com/comment/86416585
has comment: http://stackoverflow.com/comment/86417074
has comment: http://stackoverflow.com/comment/86416208
has body: import os #Folders Creation for folderName, subfolders, filenames in os.walk('I:\DATA\Train'): print('The current folder is ' + folderName) for filename in filenames: filename=os.path.splitext(filename)[0] os.makedirs(filename, exist_ok=True) print(filename) print('') #Sub Folders Creation path="C:\DATA" for folderName, subfolders, filenames in os.walk(path): print('The current folder is ' + folderName) for subfolder in subfolders: print('SUBFOLDER OF ' + folderName + ': ' + subfolder) mypath = os.path.join(path,str(subfolder)) os.chdir(mypath) os.getcwd() os.makedirs("test",exist_ok=True) os.makedirs("train",exist_ok=True) os.close print('') This code works but also throw error but when i create test and train folder on path then error goes away how to solve this without creating test and train in path Getting this error FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\DATA\\test'
has comment: http://stackoverflow.com/comment/86417443
has comment: http://stackoverflow.com/comment/86417144
type: Question
has answer: http://stackoverflow.com/a/49701148
has comment: http://stackoverflow.com/comment/86416552
has comment: http://stackoverflow.com/comment/86415826
has comment: http://stackoverflow.com/comment/86417478
tagged with: python
has comment: http://stackoverflow.com/comment/86416364
tagged with: python-3.x
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49701546
has title: getting error while creating subfolder in Directory python

http://stackoverflow.com/comment/86371384
comment on: http://stackoverflow.com/q/49679587
type: Comment
has text: I might replace `-l` with a subcommand `read` and add a (seemingly redundant) subcommand `write`. IMO, the best way to handle the requirement that at least one of a group of options be used is to just raise an error after parsing if `mode`, `season` and `present` are all `None`. Otherwise, you might define the `write` parser to take one more more "tagged" positional arguments from `m:on`, `m:off`, `m:auto`, `s:winter`, `s:summer` ,`p0`, and `p1` rather than strictly optional options.
type: QuestionComment
score: 0

http://stackoverflow.com/q/49757077
has title: Tensorflow-gpu installation issue on ubuntu16.04
has body: I have a linux machine running Ubuntu16.04, NVIDIA GEFORCE1060. I am running python3.6 (installed using anaconda) and CUDA9.1 I was happily coding in tensorlow with CPU with no issues. Then I wanted to install tensorflow-gpu and that's where I am having issues. First installed cudnn7.1.2 successfully (make and run mnist-cudnn completed successfully) pip3 install tensorflow_gpu-1.7.0-cp36-cp36m-manylinux1_x86_64.whl import tensorflow as tf I am getting the following errors Traceback (most recent call last): File "/home/bony/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/home/bony/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/home/bony/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/home/bony/anaconda3/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/home/bony/anaconda3/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/bony/anaconda3/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * # pylint: disable=redefined-builtin File "/home/bony/anaconda3/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/home/bony/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in &lt;modul…
tagged with: python
has answer: http://stackoverflow.com/a/49772423
has answer: http://stackoverflow.com/a/49757414
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/86456706
score: 0
type: Comment
has text: Is the solution I gave [here](https://stackoverflow.com/a/49713491/7328782) not good enough in any way? It gives you the rectangles for each of the cells. Please let me know if it's useful and if it got you any further along.
type: QuestionComment
comment on: http://stackoverflow.com/q/49714258

http://stackoverflow.com/q/49710301
downvote count: 5
has comment: http://stackoverflow.com/comment/86434106
tagged with: python
has body: This is my code: for files in os.listdir('C:/Users/Tatheer Hussain/Desktop//ChatBot/chatterbot-corpus-master/chatterbot_corpus/data///english/'): data = open('C:/Users/Tatheer Hussain/Desktop//ChatBot/chatterbot-corpus-master/chatterbot_corpus/data///english/'+ files , 'r').readlines() bot.train(data) i get this SyntaxError: EOL while scanning string literal
type: AnsweredQuestion
upvote count: 0
tagged with: chatbot
score: -5
has comment: http://stackoverflow.com/comment/86434331
has comment: http://stackoverflow.com/comment/86434123
has answer: http://stackoverflow.com/a/49710402
accepted answer: http://stackoverflow.com/a/49710402
has comment: http://stackoverflow.com/comment/86434163
has title: chatbot error EOL while scanning string literal
favorite count: 0
has answer: http://stackoverflow.com/a/51132618
type: Question
possible better answer: http://stackoverflow.com/a/51132618
answer count: 2

http://stackoverflow.com/comment/86345013
score: 0
comment on: http://stackoverflow.com/q/49657046
type: Comment
has text: Hi, thanks for the reply. Yes, I think I understood that, but logically, in order for the values to be set, the loop would have to iterate through the query set multiple times. The loop only increments by one, so after only one pass I was expecting the highest order number to be 2 (i.e. 1+1!), so my question is about the mechanics of the script - how are they all resolved up to their final values in a single pass? Are they evaluated in parallel or something?
type: QuestionComment

http://stackoverflow.com/q/49663947
has title: File upload through SFTP (Paramiko) in Python gives IOError: Failure
type: Question
tagged with: sftp
score: 3
tagged with: ssh
tagged with: python
tagged with: paramiko
upvote count: 4
has answer: http://stackoverflow.com/a/49665603
type: UnansweredQuestion
answer count: 1
has body: Aim: I am trying to use SFTP through Paramiko in Python to upload files on server pc. What I've done: To test that functionality, I am using my localhost (127.0.0.1) IP. To achieve that I created the following code with the help of Stack Overflow suggestions. Problem: The moment I run this code and enter the file name, I get the "IOError: Failure", despite handling that error. Here's a snapshot of the error: import paramiko as pk import os userName = "sk" ip = "127.0.0.1" pwd = "1234" client="" try: client = pk.SSHClient() client.set_missing_host_key_policy(pk.AutoAddPolicy()) client.connect(hostname=ip, port=22, username=userName, password=pwd) print '\nConnection Successful!' # This exception takes care of Authentication error& exceptions except pk.AuthenticationException: print 'ERROR : Authentication failed because of irrelevant details!' # This exception will take care of the rest of the error& exceptions except: print 'ERROR : Could not connect to %s.'%ip local_path = '/home/sk' remote_path = '/home/%s/Desktop'%userName #File Upload file_name = raw_input('Enter the name of the file to upload :') local_path = os.path.join(local_path, file_name) ftp_client = client.open_sftp() try: ftp_client.chdir(remote_path) #Test if remote path exists except IOError: ftp_client.mkdir(remote_path) #Create remote path ftp_client.chdir(remote_path) # At this point, you are in remote_path in either case ftp_client.put(local_path, '.') ftp_client.close() client.close() Can you point out where's the problem and the method to resolve it? Thanks in advance!
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86521253
type: QuestionComment
score: 0
has text: @ciprian I have added this answer with an explanation.
comment on: http://stackoverflow.com/q/49752344
type: Comment

http://stackoverflow.com/comment/90651317
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49664501
has text: its the service account that is going to be charged for the storage space.
type: Comment

http://stackoverflow.com/q/49740980
tagged with: python
has body: I have been using python 3 on OS X for ~6 months now and have recently been turned onto iPython. I have installed some python packages using the pip install tool as follows: python3.6 -m pip install matplotlib I installed iPython (running python3.6) using the pip install tool as well, however, once in iPython, the packages previously installed are not recognized. I'm sure there is a way to 'point' iPython to the locations of the packages, I just don't know what it is. I know this is a basic question, but any help would be appreciated.
tagged with: macos
tagged with: ipython
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49741367
has comment: http://stackoverflow.com/comment/86496496
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86496753
upvote count: 1
has title: Python Packages not recognized by iPython
has comment: http://stackoverflow.com/comment/86540501
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86496763
has answer: http://stackoverflow.com/a/49741367
score: 1

http://stackoverflow.com/comment/86453164
score: 1
has text: @AntonvBR, OK, I see that now. To be honest, I didn't look *that closely* at your solution. I've upvoted yours, looks fine to me.
type: Comment
comment on: http://stackoverflow.com/a/49713293
type: AnswerComment

http://stackoverflow.com/comment/86519052
comment on: http://stackoverflow.com/a/49752082
type: Comment
has text: one more question, np.cov(x,y) returns an array where [0][0] is basically variance of x, but the values dont match for me: np.var(x) = 1.0763793197998102 and np.cov(x,y) = [[ 0.79680529 -0.16501283] [-0.16501283 0.40492357]]. any ideas?
score: 0
type: AnswerComment

http://stackoverflow.com/q/49752100
type: Question
accepted answer: http://stackoverflow.com/a/49755354
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86525671
score: 5
has answer: http://stackoverflow.com/a/49755354
tagged with: python
tagged with: marshmallow
upvote count: 6
type: AnsweredQuestion
has body: I've been searching for a while about how to validate if a dictionary's key has value (required) and this value's type is bytes using Marshmallow, but I didn't find anything that could work. There's no "basic" field type in the Marshmallow reference documentaiton which matches with bytes data type. So I asume that it has to be a custom field. Does anyone has already faced this problem? Any clue to solve it? Thank you
tagged with: odm
answer count: 1
has title: Python marshmallow blob/bytes field
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86460569
has text: `things` is `list`, so doesn't have an `all()` method. (You're calling `things.all()` in the `for` loop.
score: 0
comment on: http://stackoverflow.com/q/49722785
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86270810
has text: @AshwiniChaudhary I see, so that's it then, it's just faster because it's in C? I really feel there should be a `[].join([lst1, lst2, ...])` syntax for lists (and maybe tuples), it's a rather common operation that most likely many developers are not implementing as well as it could be because it is kind of cumbersome (and a dedicated `join` method could probably do it even faster).
score: 0
comment on: http://stackoverflow.com/q/49631326
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86289329
score: 0
has text: @WiktorStribiżew Sorry, I'll marked it solved tomorrow, I'm busy finishing something up.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49600142

http://stackoverflow.com/q/49607526
score: 5
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: dask-distributed
has title: Dask groupby with multiple columns issue
favorite count: 0
type: Question
tagged with: dask
upvote count: 5
has body: I have the following dataframe created by using dataframe.from_delayed method tha has the following columns _id hour_timestamp http_method total_hits username hour weekday. Some details on the source dataframe: hits_rate_stats._meta.dtypes _id object hour_timestamp datetime64[ns] http_method object total_hits object username object hour int64 weekday int64 dtype: object meta index: RangeIndex(start=0, stop=0, step=1) When I execute the following code my_df_grouped = my_df.groupby(['username', 'http_method', 'weekday', 'hour']) my_df_grouped.total_hits.sum().reset_index().compute() I get the following exception: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-27-b24b24fc86db&gt; in &lt;module&gt;() ----&gt; 1 hits_rate_stats_grouped.total_hits.sum().reset_index().compute() /home/avlach/virtualenvs/enorasys_sa_v2/local/lib/python2.7/site-packages/dask/base.pyc in compute(self, **kwargs) 141 dask.base.compute 142 """ --&gt; 143 (result,) = compute(self, traverse=False, **kwargs) 144 return result 145 /home/avlach/virtualenvs/enorasys_sa_v2/local/lib/python2.7/site-packages/dask/base.pyc in compute(*args, **kwargs) 390 postcomputes = [a.__dask_postcompute__() if is_dask_collection(a) 391 else (None, a) for a in args] --&gt; 392 results = get(dsk, keys, **kwargs) 393 results_iter = iter(results) 394 return tuple(a if f is None else f(next(results_iter), *a) /home/avlach/virtualenvs/enorasys_sa_v2/local/lib/python2.7/site-packages/distributed/client.pyc in get(self, dsk, keys, restrictions, loose_restrictions, resources, sync, asynchronous, **kwargs) 2039 secede() 2040 try: -&gt; 2041 results = self.gather(packed, asynchronous=asynchronous) 2042 finally: 2043 for f in futures.values(): /home/avlach/virtualenvs/enorasys_sa_v2/local/lib/python2.7/site-packages/distributed/client.pyc in gather(self, futures, errors, maxsize, direct, asynchronous) 1476 return self.sync(self._gather, fut…
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/86443692
type: AnswerComment
score: 1
has text: This is so counter intuitive, but works I guess. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/49714943

django
tags question: http://stackoverflow.com/q/49628637
tags question: http://stackoverflow.com/q/49669909
tags question: http://stackoverflow.com/q/49718573
tags question: http://stackoverflow.com/q/49625464
tags question: http://stackoverflow.com/q/49709479
tags question: http://stackoverflow.com/q/49727082
tags question: http://stackoverflow.com/q/49710034
tags question: http://stackoverflow.com/q/49659648
tags question: http://stackoverflow.com/q/49649634
tags question: http://stackoverflow.com/q/49656297
tags question: http://stackoverflow.com/q/49621397
tags question: http://stackoverflow.com/q/49709502
tags question: http://stackoverflow.com/q/49745485
tags question: http://stackoverflow.com/q/49604076
tags question: http://stackoverflow.com/q/49744560
tags question: http://stackoverflow.com/q/49726089
tags question: http://stackoverflow.com/q/49744744
tags question: http://stackoverflow.com/q/49756389
tags question: http://stackoverflow.com/q/49605789
tags question: http://stackoverflow.com/q/49638471
tags question: http://stackoverflow.com/q/49732940
tags question: http://stackoverflow.com/q/49640460
tags question: http://stackoverflow.com/q/49701098
tags question: http://stackoverflow.com/q/49610120
tags question: http://stackoverflow.com/q/49644827
tags question: http://stackoverflow.com/q/49625820
tags question: http://stackoverflow.com/q/49665720
tags question: http://stackoverflow.com/q/49736688
tags question: http://stackoverflow.com/q/49735252
tags question: http://stackoverflow.com/q/49630802
tags question: http://stackoverflow.com/q/49751183
tags question: http://stackoverflow.com/q/49721089
tags question: http://stackoverflow.com/q/49712468
tags question: http://stackoverflow.com/q/49669303
tags question: http://stackoverflow.com/q/49664597
tags question: http://stackoverflow.com/q/49708166
tags question: http://stackoverflow.com/q/49620471
tags question: http://stackoverflow.com/q/49704754
tags question: http://stackoverflow.com/q/49703454
tags question: http://stackoverflow.com/q/49627003
tags question: http://stackoverflow.com/q/49610154
tags question: http://stackoverflow.com/q/49608540
tags question: http://stackoverflow.com/q/49737803
tags question: http://stackoverflow.com/q/49663398
tags question: http://stackoverflow.com/q/49644779
tags question: http://stackoverflow.com/q/49700123
tags question: http://stackoverflow.com/q/49657605
tags question: http://stackoverflow.com/q/49735665
tags question: http://stackoverflow.com/q/49652893
tags question: http://stackoverflow.com/q/49713826
tags question: http://stackoverflow.com/q/49645721
tags question: http://stackoverflow.com/q/49672902
tags question: http://stackoverflow.com/q/49712834
tags question: http://stackoverflow.com/q/49689863
tags question: http://stackoverflow.com/q/49722278
tags question: http://stackoverflow.com/q/49616684
tags question: http://stackoverflow.com/q/49640644
tags question: http://stackoverflow.com/q/49639075
tags question: http://stackoverflow.com/q/49701131
tags question: http://stackoverflow.com/q/49648383
tags question: http://stackoverflow.com/q/49661615
tags question: http://stackoverflow.com/q/49660110
tags question: http://stackoverflow.com/q/49661985
tags question: http://stackoverflow.com/q/49625592
tags question: http://stackoverflow.com/q/49725609
tags question: http://stackoverflow.com/q/49619531
tags question: http://stackoverflow.com/q/49739082
tags question: http://stackoverflow.com/q/49656326
tags question: http://stackoverflow.com/q/49747211
tags question: http://stackoverflow.com/q/49739795
tags question: http://stackoverflow.com/q/49652460
tags question: http://stackoverflow.com/q/49678805
tags question: http://stackoverflow.com/q/49736620
tags question: http://stackoverflow.com/q/49613851
tags question: http://stackoverflow.com/q/49743420
tags question: http://stackoverflow.com/q/49720400
tags question: http://stackoverflow.com/q/49742503
tags question: http://stackoverflow.com/q/49753225
tags question: http://stackoverflow.com/q/49716653
tags question: http://stackoverflow.com/q/49721410

http://stackoverflow.com/comment/86317673
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49625748
has text: I have uploaded some amended code, but although the script runs, it now does not write anything to file
type: Comment

http://stackoverflow.com/a/49738546
has comment: http://stackoverflow.com/comment/86492027
answers question: http://stackoverflow.com/q/49738396
has comment: http://stackoverflow.com/comment/86491848
type: Answer
has body: my_text="""start value1 as5q value3 dd9w type b value6 dp1p stop start value1 as value2 er type a stop start value1 as5 value2 er2 type c value4 dd1 stop""" blocks = re.findall("(?:start)(.*?)(?:stop)",my_text,re.DOTALL) this utilizes non-capturing groups, non-greedy match operator, and re.DOTALL flag in order to match newlines
accepted answer of: http://stackoverflow.com/q/49738396
score: -2
upvote count: 0
downvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86435653
has text: Possible duplicate of ['From/import' is not recognized as an internal or external command, operable program or batch file](https://stackoverflow.com/questions/37311877/from-import-is-not-recognized-as-an-internal-or-external-command-operable-pro)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49699587
score: 1

http://stackoverflow.com/comment/86455991
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49721143
has text: sorry i dont have much knowledge about it can u tell me how to do it

http://stackoverflow.com/a/49732546
score: 1
has comment: http://stackoverflow.com/comment/86479514
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86479111
answers question: http://stackoverflow.com/q/49731828
type: Answer
has body: try pip install --upgrade pip first and then pip install django-allauth==0.27.0
has comment: http://stackoverflow.com/comment/86479690

http://stackoverflow.com/comment/102006466
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49685031
has text: This wouldn't work when you want to specify a decimal separator in the read_csv function. It will cast these numbers as str with the wrong decimal separator and thereafter you will not be able to convert it to float directly.

http://stackoverflow.com/comment/86366343
score: 0
type: Comment
type: QuestionComment
has text: Never mind, **how many rows of `[Date, Temp, Humid, Change ]` data** do you have ready to use?
comment on: http://stackoverflow.com/q/49677173

http://stackoverflow.com/comment/86457523
comment on: http://stackoverflow.com/q/49718409
has text: What is `split`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86535303
comment on: http://stackoverflow.com/a/49724933
type: Comment
score: 0
type: AnswerComment
has text: Hi Paul, I am testing this algorithm, two questions, 1) if I have theater = 'Movie theater 2' and if movie name it same will this append movie details from Movie theater 2 for that movie? Example {"Movie 1": "Movie Theater 1 details, Movie Theater 2 details", "Movie 2": "Movie Theater 1 details, Movie Theater 2 details"} 2) I am getting '' empty elements in movie_details I would like to clean that up list(set) is not working any suggestions?

http://stackoverflow.com/comment/86500719
has text: Andriy Mukakha, there is one problem with the code that, when I read the file for Movie Theater 1 it populates the dictionary with values (for example showtimes), however, when the second time I run for Movie Theater 2 it populates the shows for Movies Theater 1 and Movies Theater 2. This way I have duplicate for Movie Theater 2 with Showtimes for Movies Theater 1. Any thoughts on making sure when you read the showtimes once skip that next time OR should I create clean up function to delete duplicate entries
comment on: http://stackoverflow.com/a/49725040
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49620462
possible better answer: http://stackoverflow.com/a/49620536
type: Question
answer count: 2
tagged with: file
has answer: http://stackoverflow.com/a/49620608
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/49620536
favorite count: 0
tagged with: text
type: AnsweredQuestion
score: 0
has title: How do you add characters to a line in python in an existing text file?
accepted answer: http://stackoverflow.com/a/49620608
has comment: http://stackoverflow.com/comment/86247835
has comment: http://stackoverflow.com/comment/86247803
has body: Suppose i have the text file: apple banana fruit how would i get that to : 1.apple 2.banana 3.fruit Is there a way to do this in python ? myfile=open("dates.txt","a") for i in range(14): myfile.write(i) myfile.write("\n")

http://stackoverflow.com/q/49745958
has comment: http://stackoverflow.com/comment/86506424
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I am trying to read a csv file which has some rows having Unicode character(â€) in it. Pandas is not able to handle those characters. When opening in MS excel, row looks like this Columns age;"job";"marital";"education";"default";"housing";"loan";"contact";"month";"day_of_week";"duration";"campaign";"pdays";"previous";"poutcome";"emp.var.rate";"cons.price.idx";"cons.conf.idx";"euribor3m";"nr.employed";"y" Row 41;"blue-collar";"divorcededâ€;â€basic.9y";"no";"yes";"no";"cellular";"may";"thu";102;1;999;0;"nonexistent";-1.8;92.893;-46.2;1.327;5099.1;"no" Pandas is reading it as age 41 job blue-collar marital divorceded”;”basic.9y education no default yes housing no loan cellular contact may month thu day_of_week 102 duration 1 campaign 999 pdays 0 previous nonexistent poutcome -1.8 emp.var.rate 92.893 cons.price.idx -46.2 cons.conf.idx 1.327 euribor3m 5099.1 nr.employed no y NaN Code df = pd.read_csv('Bank.csv', sep=';', skiprows = 1, names=["age", "job", "marital", "education", "default", "housing", "loan", "contact", "month", "day_of_week", "duration", "campaign", "pdays", "previous", "poutcome", "emp.var.rate", "cons.price.idx", "cons.conf.idx", "euribor3m", "nr.employed", "y"], encoding='utf-8-sig' ) Is there anyway around it?
has comment: http://stackoverflow.com/comment/86514132
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49746146
has comment: http://stackoverflow.com/comment/86506340
type: Question
has title: How to ignore Unicode Character(â€) while reading csv file using pandas

http://stackoverflow.com/a/49625150
accepted answer of: http://stackoverflow.com/q/49624840
has comment: http://stackoverflow.com/comment/86257265
has body: This has been fixed in March 2019. If you still see the warning consider updating your numpy. The warning is raised even for very small off-diagonal elements > 0. The default tolerance value does not seem to work well for 32 bit floats. As a workaround pass a higher tolerance to the function: np.random.multivariate_normal(mu, cov, tol=1e-6) Details np.random.multivariate_normal checks if the covariance is PSD by first decomposing it with (u, s, v) = svd(cov), and then checking if the reconstruction np.dot(v.T * s, v) is close enough to the original cov. With float32 the result of the reconstruction is further off than the default tolerance of 1e-8 allows, and the function raises a warning.
upvote count: 10
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/86257604
has comment: http://stackoverflow.com/comment/86257306
answers question: http://stackoverflow.com/q/49624840
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49706148
answers question: http://stackoverflow.com/q/49705758
has comment: http://stackoverflow.com/comment/86440341
score: 0
has comment: http://stackoverflow.com/comment/86430787
has comment: http://stackoverflow.com/comment/86427409
has comment: http://stackoverflow.com/comment/86669501
has comment: http://stackoverflow.com/comment/86426494
has comment: http://stackoverflow.com/comment/86426434
has body: First of all, you should really be using subprocess.Popen() so you can actually control your process without relying on flimsy external commands and the most basic way would be: import subprocess radio = None # a reference to hold our radio process def kill_radio(obj): if radio and radio.poll() is None: radio.kill() # use radio.terminate() for a milder version def tune_radio(obj, station): global radio if radio and radio.poll() is None: radio.kill() # use radio.terminate() for a milder version radio = subprocess.Popen(["radio", station]) Side note: I'd convert the whole .sh script to Python for considerably faster execution and easier control without the danger of orphaned processes. Now, the problem is that both subprocess.Popen() and subprocess.Popen.kill() are blocking methods so your functions wouldn't be returning until the process is started and terminated respectively. You can use fire-and-forget threads, as you've attempted, but you'll end up running a lot of threads waiting on their turn (plus you'd have to deal with queuing) so you need to decide what should happen when a user issues too much commands - disabling their controls until a process is started/terminated is probably the best as otherwise your app would be taking assumptions on behalf of the user. That purely depends on how you laid out your controls and app GUI, tho, so the only other option (apart from queuing the commands) that I would propose is to just ignore calls to the underlying radio, be it tune or kill, while it's already starting/being terminated. Something like: import subprocess import threading radio = None # a reference to radio radio_lock = threading.Lock() # a mutex for the radio control def control_radio(command, *args): global radio if radio_lock.acquire(False): # make sure other threads silently fail if radio and radio.poll() is None: # kill the radio process if running radio.kill() # use radio.terminate() for a milder version if command == "tune": # start the new radio proce…
has comment: http://stackoverflow.com/comment/86430420
type: Answer
has comment: http://stackoverflow.com/comment/86669518

http://stackoverflow.com/q/49688197
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/54970189
accepted answer: http://stackoverflow.com/a/49880647
has title: Getting error when exporting ipa in development method
upvote count: 3
has body: When I select IPA distribution method as development and try to export, I am getting this same error for all my projects, and I am not using python anywhere so why I am getting this error. Please help me to solve this error. I am using Xcode 9.2 ipatool failed with an exception:#&lt;RuntimeError: Couldn't locate python in /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/local/bin /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/libexec /Applications/Xcode.app/Contents/Developer/usr/bin /Applications/Xcode.app/Contents/Developer/usr/local/bin /Applications/Xcode.app/Contents/Developer/Tools /usr/bin /bin /usr/sbin /sbin&gt; /Applications/Xcode.app/Contents/Developer/usr/bin/ipatool:157:in `locate_tool' /Applications/Xcode.app/Contents/Developer/usr/bin/ipatool:137:in `unicode_equal?' /Applications/Xcode.app/Contents/Developer/usr/bin/ipatool:1703:in `block in MakeFileSystemNode' /Applications/Xcode.app/Contents/Developer/usr/bin/ipatool:1703:in `each' /Applications/Xcode.app/Contents/Developer/usr/bin/ipatool:1703:in `detect'
has answer: http://stackoverflow.com/a/49880647
tagged with: ipa
downvote count: 0
possible better answer: http://stackoverflow.com/a/49688247
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49688247
has answer: http://stackoverflow.com/a/63228982
tagged with: xcode
tagged with: ios
tagged with: python
answer count: 4
tagged with: export

http://stackoverflow.com/a/49687776
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49687402
has body: You can use this solution if number are distinct. def swap(a) : max_index=a.index(max(a)) min_index=a.index(min(a)) ma=max(a) mi=min(a) a[max_index]=mi a[min_index]=ma a=[3,4,5,2,1] swap(a) print(a)
score: 1
type: Answer

http://stackoverflow.com/q/49719584
answer count: 0
type: UnansweredQuestion
tagged with: error-handling
upvote count: 1
duplicate of: http://stackoverflow.com/q/23294658
downvote count: 1
has comment: http://stackoverflow.com/comment/86452155
has comment: http://stackoverflow.com/comment/86452122
has comment: http://stackoverflow.com/comment/86452165
score: 0
linked to: http://stackoverflow.com/q/23294658
has title: How to loop my try & except error code until the error is resolved (Negative Error)?
has body: So this is my code: print('How many cats do you have?') numCats = input() try: if int(numCats)&gt;=4: print('That is a lot of cats.') elif int(numCats)&lt;0: print('You can\'t have negative cats, dumbo') else: print('That is not that many cats') except ValueError: print('You did not enter a number') Currently, when I enter 'six', it outputs just the error message 'You did not enter a number' and the code ends there. I want the code to loop back to asking 'how many cats do I have' until I enter a non-error answer. Not sure how to do this. Would be great if anyone could offer this newbie some advice. Mainly, I would like to know how to except a Negative Error, instead of writing an elif statement for it.
tagged with: python
tagged with: loops
has comment: http://stackoverflow.com/comment/86452094
favorite count: 0
type: Question

http://stackoverflow.com/q/49738295
tagged with: machine-learning
tagged with: scikit-learn
tagged with: xgboost
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54667835
has body: I read the docs, import xgboost as xgb class xgboost.XGBClassifier(max_depth=3, learning_rate=0.1, n_estimators=100, silent=True, objective='binary:logistic', booster='gbtree', n_jobs=1,nthread=None, gamma=0, min_child_weight=1, max_delta_step=0, subsample=1, colsample_bytree=1, colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, random_state=0, seed=None, missing=None, **kwargs) Then I try to create my own instance following the API model_benchmark=xgb.XGBClassifier(booster ='linear',objective='binary:logistic') and I get: TypeError: __init__() got an unexpected keyword argument 'booster' Any suggestion on how to choose my desired booster?
tagged with: python
has title: setting booster in a XGBClassifier
possible better answer: http://stackoverflow.com/a/54667835
accepted answer: http://stackoverflow.com/a/49738490
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49738490

http://stackoverflow.com/q/49672621
type: Question
downvote count: 0
tagged with: pip
possible better answer: http://stackoverflow.com/a/74652148
favorite count: 0
has answer: http://stackoverflow.com/a/74652148
type: AnsweredQuestion
upvote count: 33
answer count: 3
has body: pip download has several flags that I would like to play with --platform, --abi, and --implementation. Where can I find the complete list of valid values for these flags?
accepted answer: http://stackoverflow.com/a/49673284
has title: What are the valid values for --platform, --abi, and --implementation for pip download?
has answer: http://stackoverflow.com/a/49673284
has answer: http://stackoverflow.com/a/72013604
tagged with: python
score: 33

http://stackoverflow.com/a/49681971
upvote count: 1
downvote count: 1
has body: You have named your variable str - same name as built-in function for conversion to string. You need to rename it, try this: import re class Solution: def rearrange(self, str_in): # Write your code here if str_in == "": return str_in sum = 0 letter = [] for i in range(len(str_in)): if re.search("([A-Z])", str_in[i]): letter.append(str_in[i]) else: sum += int(str_in[i]) letsort = sorted(letter) letstr = "".join(letsort) result = letstr + str(sum) return result
answers question: http://stackoverflow.com/q/49681941
type: Answer
score: 0

http://stackoverflow.com/comment/86212595
type: QuestionComment
comment on: http://stackoverflow.com/q/49601259
score: 0
has text: I wouldn't expect it to. How did you install the package?
type: Comment

http://stackoverflow.com/comment/86397997
score: 0
comment on: http://stackoverflow.com/q/49692440
type: Comment
type: QuestionComment
has text: Is the jupyter notebook and the packages like plotly installed in the same virtualenv?

http://stackoverflow.com/q/49647518
downvote count: 0
answer count: 3
tagged with: lookup-tables
has body: I have a numpy lookup table of xy coordinates, where columns 0=xa, 1=ya, 2=xb, 3=yb. I'm trying to use xa and ya (cols 0 &amp; 1) to act as the pair of elements that enable the looking up of xb and yb (cols 2 &amp; 3), which are the actual xy coordinates I want to use. lookup= [[0, 0, 0, 0] [2, 0, 1.98, -0.01] [4, 0, 3.99, -0.01] [6, 0, 6.03, -0.01] [8, 0, 8.02, -0.03] [10, 0, 9.98, -0.01] [12, 0, 11.99, 0] [14, 0, 13.99, 0] [0, 1, -0.03, 0.88] [2, 1, 1.95, 0.86] [4, 1, 3.97, 0.85] [6, 1, 5.97, 0.87] [8, 1, 7.96, 0.86] [10, 1, 9.95, 0.92] [12, 1, 11.95, 0.92] [14, 1, 13.97, 0.87]] I have a table with data that has x and y locations in the format xa ya, that I wish to to change to xb yb using the lookup table: gridloc= [[6, 0] [8, 0] [8, 0] [10, 0] [8, 1] [10, 1] [12, 1] [14, 1] So I want the result to be this: newloc= [[6.03, -0.01] [8.02, -0.03] [8.02, -0.03] [9.98, -0.01] [7.96, 0.86] [9.95, 0.92] [11.95, 0.92] [13.97, 0.87]] I've tried using this to try to create a dictionary, but I get an error: mapping = dict(zip(lookup[:,0:2], range(len(lookup)))) Traceback (most recent call last): File "&lt;ipython-input-12-528fb6616ce0&gt;", line 1, in &lt;module&gt; mapping = dict(zip(lookup[:,0:2], range(len(lookup)))) TypeError: unhashable type: 'numpy.ndarray' Does anyone have any advice, please? Should my tables be in numpy in the first place? Is dict the way to solve the problem?
has title: Lookup table using 2 columns to identify rows
accepted answer: http://stackoverflow.com/a/49648784
favorite count: 0
has answer: http://stackoverflow.com/a/49648784
tagged with: numpy
tagged with: python-3.x
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/49648258
tagged with: python
has answer: http://stackoverflow.com/a/49648258
linked to: http://stackoverflow.com/q/588004
tagged with: lookup
has answer: http://stackoverflow.com/a/49648089
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/86980887
score: 1
comment on: http://stackoverflow.com/a/49962590
has text: @reboot is the special specification for cron, instead of time/date fields. This ensures script is run when the instance starts/reboots. I have had success with above configuration using Amazon Linux AMIs
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86322054
has text: @RafaelC if you can you can test it :-) and feel free to edit the timing back :-)
comment on: http://stackoverflow.com/a/49656072
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86607300
score: 0
type: Comment
has text: sorry but i am not able to find mimetype from image data till.Because its not providing me binary data . So if you have idea how i can get mimetype from image data then please tell me . Thanks for your valuable time .Sir
type: AnswerComment
comment on: http://stackoverflow.com/a/49747985

http://stackoverflow.com/q/49696691
favorite count: 0
type: Question
tagged with: roc
has title: Python sklearn ROC-AUC curve with only one feature and various thresholds
tagged with: threshold
downvote count: 0
has comment: http://stackoverflow.com/comment/86423232
tagged with: python
accepted answer: http://stackoverflow.com/a/49715275
type: AnsweredQuestion
has body: I'm relatively new in this field and a bit confused right now... I'll explain: I've some elements in my data, each with a value between 0 and 1 and an associated label (1, 0). I need to test some thresholds, for example with a threshold = 0.4, all the values > 0.4 will be predicted as true (1) and all the values &lt; 0.4 will be predicted as false (0). I think I don't need a machine learning classifiers because, based on the threshold that I choose, I already know which label assign to each element. This is what I've done until now: prediction = [] for row in range(dfAggr.shape[0]): if dfAggr['value'].values[row] &gt;= threshold: prediction.append(1) else prediction.append(0) label = dfAggr['truth'].values.astype(int) #ROC CURVE fpr, tpr, thresholds = roc_curve(label, prediction) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC (area = %0.2f)' % (roc_auc)) plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.grid() plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic') plt.legend(loc="lower right") plt.savefig("rocauc.pdf", format="pdf") plt.show() And I obtain this plot: I think this plot is quite wrong, since I want a ROC curve build by testing each possible threshold between 0 and 1 to get the best possible value of cutoff. Is it conceptually wrong what I've done?
has answer: http://stackoverflow.com/a/49715275
answer count: 1
upvote count: 1
tagged with: scikit-learn
score: 1

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

http://stackoverflow.com/a/49668730
score: 0
has body: Using broadcasting might help here. For example, import numpy as np complete_list = np.random.randint(0, 2, (10000, 10)).astype(bool) binary_2 = np.random.randint(0, 2, 10).astype(bool) similarities = np.sum(complete_list &amp; binary_2, axis=1) idx = np.argsort(similarities) print("Seed", binary_2) print("Result", complete_list[idx[-1]]) print("Similarity", similarities[idx[-1]]) I couldn't get your example to run (maybe different python/library versions?) so haven't run any benchmarks comparing the two approaches. Of course, our machines will be different but the above takes about half a millisecond on mine. Note that I've used &amp; rather than | given your description of the intended logic.
answers question: http://stackoverflow.com/q/49668314
type: Answer

http://stackoverflow.com/q/49750354
tagged with: python
has answer: http://stackoverflow.com/a/49750460
has answer: http://stackoverflow.com/a/49768346
answer count: 3
downvote count: 0
has body: I have a usertable with a column 'routes' that has values like '[{"407": "410"}, {"410": "408"}]'. I need to select all rows that have values 408"}, so I'm using like keyword in MySQL to achieve this. The query looks as below select routes from usertable where routes like '%408"}%' This query works in MySQL Workbench, but when I take this to Python its not working, my query looks like below in Python (select routes from usertable where routes like'%{1}"}%').format(routes)` The error I see is as below: "Single '}' encountered in format string" I did try using escape characters i.e. \" and }} but still getting the same error. Please suggest how to fix this. Thanks, Seema
tagged with: mysql
has title: Single '}' encountered in format string
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/49750479
type: UnansweredQuestion
upvote count: 3

http://stackoverflow.com/q/49756246
has answer: http://stackoverflow.com/a/49756398
has answer: http://stackoverflow.com/a/49756536
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49756429
downvote count: 5
tagged with: python
has body: I have created this code but it is only storing one value how can i modify it to store as many std records as many user wants... while True: name=input('please provide name of a student') courses=[] stdrecord=() while True: course=input('please provide a course') courses.append(course) print(courses) ch_course=input('would you like to enter another course yes/no') if ch_course=='yes': continue else: stdrecord+=((name,courses)) break ch_name=input('would you like to enter another record yes/no') if ch_name=='no': print (stdrecord) break
score: -5
answer count: 3
has title: While loop for storing records with increasing tuples
upvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/49606931
score: 0
has body: You can try this: with open('RCSV.txt','r') as RCSV: for line in RCSV: if line.startswith(' THETA'): next_line = RCSV.readline() # or RCSV.next() print(next_line) Note that on your next iteration, line will be the line after next_line.
type: Answer
has comment: http://stackoverflow.com/comment/86220575
has comment: http://stackoverflow.com/comment/86220560
answers question: http://stackoverflow.com/q/49606909

http://stackoverflow.com/comment/86485786
type: QuestionComment
has text: When you say efficient/ python way, what exactly do mean... Memory efficient? Speed? Do you have a threshold to what efficient enough is? Basically, what's the context to this question?
score: 3
comment on: http://stackoverflow.com/q/49735841
type: Comment

http://stackoverflow.com/q/49743626
has body: I am writing a program in python using pytube, and I want to indicate progress when downloading a playlist. When downloading a single video I can do: YouTube(url, on_progress_callback=progressFunction) but that doesn't work when downloading a playlist: Playlist(url, on_progress_callback=progressFunction) I get the following error: TypeError: __init__() got an unexpected keyword argument 'on_progress_callback' Is there any way to get the progress when downloading a playlist?
has answer: http://stackoverflow.com/a/67029641
has answer: http://stackoverflow.com/a/53174660
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/106352189
possible better answer: http://stackoverflow.com/a/49743660
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49743660
has title: Python Pytube progress for playlist download
has answer: http://stackoverflow.com/a/73337434
score: 1
answer count: 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/53174660
tagged with: pytube

http://stackoverflow.com/comment/86313036
type: QuestionComment
score: 0
has text: Thanks, I tried adding details. Could you have a look? (:
comment on: http://stackoverflow.com/q/49641701
type: Comment

http://stackoverflow.com/comment/86387622
comment on: http://stackoverflow.com/q/49687537
type: Comment
has text: About the error, `len` returns an int which is not iterable (see the answer below for a solution). Then you'll have to to fix a `UnboundLocalError` exception by defining `coded` - or use the shorter version described in my previous comment.
score: 1
type: QuestionComment

http://stackoverflow.com/q/49653413
has body: I'm looking for a way to implement alternating SQL queries - i.e. a function that allows me to filter entries based on different columns. Take the following example: el=[["a","b",1],["a","b",3]] def save_sql(foo): with sqlite3.connect("fn.db") as db: cur=db.cursor() cur.execute("CREATE TABLE IF NOT EXISTS et" "(var1 VARCHAR, var2 VARCHAR, var3 INT)") cur.executemany("INSERT INTO et VALUES " "(?,?,?)", foo) db.commit() def load_sql(v1,v2,v3): with sqlite3.connect("fn.db") as db: cur=db.cursor() cur.execute("SELECT * FROM et WHERE var1=? AND var2=? AND var3=?", (v1,v2,v3)) return cur.fetchall() save_sql(el) Now if I were to use load_sql("a","b",1), it would work. But assume I want to only query for the first and third column, i.e. load_sql("a",None,1) (the None is just intended as a placeholder) or only the last column load_sql(None,None,5), this wouldn't work. This could of course be done with if statements checking which variables were supplied in the function call, but in tables with larger amounts of columns, this might get messy. Is there a good way to do this?
possible better answer: http://stackoverflow.com/a/49653827
answer count: 2
has title: Alternating SQL queries
has answer: http://stackoverflow.com/a/49653613
accepted answer: http://stackoverflow.com/a/49653613
score: 1
tagged with: sqlite
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49653827
tagged with: python
has comment: http://stackoverflow.com/comment/86315472
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49620140
has comment: http://stackoverflow.com/comment/86255753
has answer: http://stackoverflow.com/a/54423527
has comment: http://stackoverflow.com/comment/86259708
has title: Get hourly average for each month from a netcdf file
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86280357
linked to: http://stackoverflow.com/q/44520579
has comment: http://stackoverflow.com/comment/86374728
tagged with: python
has answer: http://stackoverflow.com/a/49625647
score: 11
has comment: http://stackoverflow.com/comment/86377016
upvote count: 13
has comment: http://stackoverflow.com/comment/86279134
tagged with: python-xarray
has comment: http://stackoverflow.com/comment/86377290
linked to: http://stackoverflow.com/q/38151013
has comment: http://stackoverflow.com/comment/86279171
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/49711216
has body: I have a netCDF file with the time dimension containing data by the hour for 2 years. I want to average it to get an hourly average for each hour of the day for each month. I tried this: import xarray as xr ds = xr.open_mfdataset('ecmwf_usa_2015.nc') ds.groupby(['time.month', 'time.hour']).mean('time') but I get this error: *** TypeError: `group` must be an xarray.DataArray or the name of an xarray variable or dimension How can I fix this? If I do this: ds.groupby('time.month', 'time.hour').mean('time') I do not get an error but the result has a time dimension of 12 (one value for each month), whereas I want an hourly average for each month i.e. 24 values for each of 12 months. Data is available here: https://www.dropbox.com/s/yqgg80wn8bjdksy/ecmwf_usa_2015.nc?dl=0
has answer: http://stackoverflow.com/a/58648628
downvote count: 2
has comment: http://stackoverflow.com/comment/86377063
tagged with: netcdf
has comment: http://stackoverflow.com/comment/86369792
linked to: http://stackoverflow.com/q/38792122
has comment: http://stackoverflow.com/comment/86286998
has comment: http://stackoverflow.com/comment/86369579
has comment: http://stackoverflow.com/comment/86366325
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49725639
linked to: http://stackoverflow.com/q/35898667
has comment: http://stackoverflow.com/comment/86371974

http://stackoverflow.com/comment/86255304
comment on: http://stackoverflow.com/q/49624173
type: QuestionComment
score: 5
type: Comment
has text: Did you read the documentation for the `random.randint()` function yet? The function does **not** accept a list of values, and your attempt to use it that way is rather non-sensical. Perhaps you were looking for `random.choice()` instead?

python-3.x
tags question: http://stackoverflow.com/q/49616658
tags question: http://stackoverflow.com/q/49732807
tags question: http://stackoverflow.com/q/49680299
tags question: http://stackoverflow.com/q/49639586
tags question: http://stackoverflow.com/q/49710186
tags question: http://stackoverflow.com/q/49742244
tags question: http://stackoverflow.com/q/49668102
tags question: http://stackoverflow.com/q/49643737
tags question: http://stackoverflow.com/q/49743234
tags question: http://stackoverflow.com/q/49727037
tags question: http://stackoverflow.com/q/49743718
tags question: http://stackoverflow.com/q/49601091
tags question: http://stackoverflow.com/q/49714068
tags question: http://stackoverflow.com/q/49691955
tags question: http://stackoverflow.com/q/49677311
tags question: http://stackoverflow.com/q/49640187
tags question: http://stackoverflow.com/q/49649102
tags question: http://stackoverflow.com/q/49654935
tags question: http://stackoverflow.com/q/49737648
tags question: http://stackoverflow.com/q/49725605
tags question: http://stackoverflow.com/q/49756646
tags question: http://stackoverflow.com/q/49687537
tags question: http://stackoverflow.com/q/49660249
tags question: http://stackoverflow.com/q/49656386
tags question: http://stackoverflow.com/q/49648180
tags question: http://stackoverflow.com/q/49638400
tags question: http://stackoverflow.com/q/49713568
tags question: http://stackoverflow.com/q/49741907
tags question: http://stackoverflow.com/q/49641087
tags question: http://stackoverflow.com/q/49620130
tags question: http://stackoverflow.com/q/49604001
tags question: http://stackoverflow.com/q/49752007
tags question: http://stackoverflow.com/q/49703946
tags question: http://stackoverflow.com/q/49722115
tags question: http://stackoverflow.com/q/49646796
tags question: http://stackoverflow.com/q/49690930
tags question: http://stackoverflow.com/q/49656317
tags question: http://stackoverflow.com/q/49738600
tags question: http://stackoverflow.com/q/49703947
tags question: http://stackoverflow.com/q/49751550
tags question: http://stackoverflow.com/q/49721621
tags question: http://stackoverflow.com/q/49713337
tags question: http://stackoverflow.com/q/49744164
tags question: http://stackoverflow.com/q/49743657
tags question: http://stackoverflow.com/q/49606375
tags question: http://stackoverflow.com/q/49672081
tags question: http://stackoverflow.com/q/49677790
tags question: http://stackoverflow.com/q/49658670
tags question: http://stackoverflow.com/q/49630410
tags question: http://stackoverflow.com/q/49651815
tags question: http://stackoverflow.com/q/49609262
tags question: http://stackoverflow.com/q/49619872
tags question: http://stackoverflow.com/q/49618016
tags question: http://stackoverflow.com/q/49673257
tags question: http://stackoverflow.com/q/49635871
tags question: http://stackoverflow.com/q/49653413
tags question: http://stackoverflow.com/q/49739560
tags question: http://stackoverflow.com/q/49683262
tags question: http://stackoverflow.com/q/49691342
tags question: http://stackoverflow.com/q/49717500
tags question: http://stackoverflow.com/q/49710109
tags question: http://stackoverflow.com/q/49675831
tags question: http://stackoverflow.com/q/49714254
tags question: http://stackoverflow.com/q/49604151
tags question: http://stackoverflow.com/q/49657838
tags question: http://stackoverflow.com/q/49691956
tags question: http://stackoverflow.com/q/49731478
tags question: http://stackoverflow.com/q/49738661
tags question: http://stackoverflow.com/q/49708476
tags question: http://stackoverflow.com/q/49682006
tags question: http://stackoverflow.com/q/49734080
tags question: http://stackoverflow.com/q/49669949
tags question: http://stackoverflow.com/q/49675587
tags question: http://stackoverflow.com/q/49701438
tags question: http://stackoverflow.com/q/49609028
tags question: http://stackoverflow.com/q/49734879
tags question: http://stackoverflow.com/q/49609473
tags question: http://stackoverflow.com/q/49712457
tags question: http://stackoverflow.com/q/49711512
tags question: http://stackoverflow.com/q/49702536

http://stackoverflow.com/q/49636987
score: 1
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49637237
type: AnsweredQuestion
has title: django read dynamic csv file error
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49637237
tagged with: python
favorite count: 0
has body: I wrote Django python csv reader but it's not working properly. I can see the file is uploaded to the system, but I can't read it and I'm getting the error below: Exception Type: AttributeError Exception Value: 'str' object has no attribute 'read' data = csv.reader(open('tmp/tmp.csv'), delimiter=";") When I am using as per above statically ,it's working but I need the dynamic one that I am receiving via file upload. I need your help because I am out of options to solve this. I know that decoded_file, io_string and data variables are not working correctly but can't fix them. def upload_csv(request): if request.method == 'POST' and request.FILES['csv_file']: myfile = request.FILES['csv_file'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) decoded_file = filename.read().decode('utf-8') io_string = io.StringIO(decoded_file) data = csv.reader(io_string, delimiter=';', quotechar='|') for row in data: if row[0] != 'FP_Item': post = FP() post.FP_Item = row[0] post.save() CSV File: Not much because still import trials, only 2 lines.There was ; at the end but I deleted and retried still the same 5.Item try Try
downvote count: 0
upvote count: 1
tagged with: django

http://stackoverflow.com/q/49641241
has comment: http://stackoverflow.com/comment/86290304
tagged with: python
has comment: http://stackoverflow.com/comment/86290272
has body: I'm having an issue which I believe is related to improper implementation of custom class __eq__/__hash__ functions. I created a custom Line class, where a line holds a slope and y intercept which are calculated from 2 Points. I'm running a test on equality between 2 lines, which is producing unexpected results as shown below. I'm looking for an explanation of why the first 2 lines in the test code I've included below are not equal, but the 2nd set of 2 lines are equal, despite both sets of lines having matching values for slope and y intercept? class Point: def __init__(self, x1, y1): self.x = x1 self.y = y1 def to_string(self): return '{},{}'.format(self.x, self.y) class Line: def __init__(self, pt1, pt2): self.m = (pt1.y - pt2.y)/(pt1.x - pt2.x) self.b = pt1.y - self.m * pt1.x def __eq__(self, other): if isinstance(other, self.__class__): return self.m == other.m and self.b == other.b else: return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.m, self.b)) def print_line(self): print('y = {} x + {}'.format(self.m, self.b)) test code: pt_a = Point(0.1, 1.0) pt_b = Point(1.1, 1.1) pt_c = Point(2.1, 1.2) line1 = Line(pt_a, pt_b) print('line1:') line1.print_line() line2 = Line(pt_b, pt_c) print('line2:') line2.print_line() if line1 == line2: print('lines equal') else: print('lines not equal') pt_x = Point(0.5, 1) pt_y = Point(1.5, 2) pt_z = Point(2.5, 3) line1 = Line(pt_x, pt_y) print('line1:') line1.print_line() line2 = Line(pt_y, pt_z) print('line2:') line2.print_line() if line1 == line2: print('lines equal') else: print('lines not equal') This test produces output: line1: y = 0.1 x + 0.99 line2: y = 0.1 x + 0.99 lines not equal line1: y = 1.0 x + 0.5 line2: y = 1.0 x + 0.5 lines equal
has answer: http://stackoverflow.com/a/49641370
has answer: http://stackoverflow.com/a/49641320
tagged with: python-2.7
answer count: 2
has title: Python 2.7 custom class __hash__ and __eq__ functions
has comment: http://stackoverflow.com/comment/86290214
type: UnansweredQuestion
tagged with: line
has comment: http://stackoverflow.com/comment/86290491
type: Question
score: 0
tagged with: hash
has comment: http://stackoverflow.com/comment/86290261

http://stackoverflow.com/q/49604330
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/86217646
tagged with: python
has comment: http://stackoverflow.com/comment/86217615
accepted answer: http://stackoverflow.com/a/49604566
has comment: http://stackoverflow.com/comment/86217629
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49604566
score: 0
has title: Cannot resolve conflicts with metaclasses of child classes
has body: I need to have a static instance of a class of the same class and one solution I thought was using metaclasses. I have the following word.py: from .token import Token from .tag import Tag class Token: def __init__(self, tag_id): self.tag = tag_id def __str__(self): return str(self.tag) class MetaWord(type): def __init__(cls, clsname, superclasses, attributedict): cls.and_ = cls('&amp;&amp;', Tag.AND) cls.or_ = cls("||", Tag.OR) cls.eq = cls("==", Tag.EQ) cls.ne = cls("!=", Tag.NE) class Word(Token, metaclass=MetaWord): def __init__(self, lexeme, tag): super(self.__class__, self).__init__(tag) self.lexeme = lexeme and another file type.py file, with a Type class that inherits from Word: from lexer.word import Word from lexer.tag import Tag class MetaType(type): def __init__(cls, clsname, superclasses, attributedict): cls.int_ = cls('int', Tag.BASIC, 4) cls.float_ = cls('float', Tag.BASIC, 8) cls.char_ = cls('char', Tag.BASIC, 1) cls.bool_ = cls('bool', Tag.BASIC, 1) class Type(Word, metaclass=MetaType): def __init__(self, word, tag_id, w): super(self.__class__, self).__init__(word, tag_id) self.width = w The problem I am having is that everytime I import Type it gives me the error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I have read some topics on this issue, but haven't figured out how to fix the conflict between the metaclasses
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/q/49643225
has answer: http://stackoverflow.com/a/54507446
possible better answer: http://stackoverflow.com/a/54507446
linked to: http://stackoverflow.com/q/26998223
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69637289
tagged with: python
linked to: http://stackoverflow.com/q/48915810
has answer: http://stackoverflow.com/a/49644300
accepted answer: http://stackoverflow.com/a/49644300
favorite count: 0
type: Question
upvote count: 266
has body: In numpy, we use ndarray.reshape() for reshaping an array. I noticed that in PyTorch, people use torch.view() for the same purpose, but at the same time, there is also a torch.reshape() existing. So I am wondering what the differences are between them and when I should use either of them?
score: 266
has answer: http://stackoverflow.com/a/55976519
downvote count: 0
tagged with: difference
tagged with: tensor
tagged with: pytorch
answer count: 5
has title: What's the difference between `reshape()` and `view()` in PyTorch?
has answer: http://stackoverflow.com/a/69676338
tagged with: reshape

http://stackoverflow.com/comment/86343062
score: 0
type: AnswerComment
has text: Glad I could help you. @OverLoop
comment on: http://stackoverflow.com/a/49653364
type: Comment

http://stackoverflow.com/comment/86371322
comment on: http://stackoverflow.com/a/49679415
has text: Thanks Raghav and Pig12. Now i understand
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86491024
type: QuestionComment
comment on: http://stackoverflow.com/q/49738220
type: Comment
has text: @Abhishakegupta I only the first letter of each name
score: 0

http://stackoverflow.com/q/49706880
answer count: 1
has comment: http://stackoverflow.com/comment/86427520
tagged with: django
has answer: http://stackoverflow.com/a/49714456
has comment: http://stackoverflow.com/comment/86427496
type: Question
tagged with: postgresql
has title: Django Postgres Make Migration Error
has comment: http://stackoverflow.com/comment/86427886
has comment: http://stackoverflow.com/comment/86426954
has comment: http://stackoverflow.com/comment/86429071
tagged with: python
has body: I have just deployed some code onto a production server from my local. I have set up a postgres database with a django app. The issue is when I run: $ python3 /usr/Apps/manage.py makemigrations I get the below error ################################################## Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "api_neli_report" does not exist LINE 1: ...ort"."price", "api_neli_report"."prediction" FROM "api_neli_ api_neli_report is a model I have set up that has not been migrated, as I can't migrate it without getting the error. Any idea how to fix this one? Also see model: from django.db import models # Create your models here. class SSALi_Report(models.Model): date = models.DateField() ticker = models.CharField(max_length=10,default='NA') market = models.CharField(max_length=250,default='NA') price = models.FloatField() prediction = models.FloatField() def __str__(self): return str(self.date) + " - " + str(self.ticker) class NELi_Report(models.Model): date = models.DateField() ticker = models.CharField(max_length=10,default='NA') market = models.CharField(max_length=250,default='NA') price = models.FloatField() prediction = models.FloatField() please note the model is working on my local Also see my resource model: # Logic/resources.py from tastypie.resources import ModelResource from api.models import SSALi_Report from api.models import NELi_Report from tastypie.authorization import Authorization class SSALi_Resource(ModelResource): class Meta: queryset = SSALi_Report.objects.all() print("#"*50) print(queryset) resource_name = 'SSALi_Report' authorization = Authorization() class NELi_Resource(ModelResource): class Meta: queryset = NELi_Report.objects.all() print("#"*50) print(queryset) resource_name = 'NELi_Report' table on my local Schema | Name | Type | Owner --------+-------------------------…
has comment: http://stackoverflow.com/comment/86427383
score: 0
has comment: http://stackoverflow.com/comment/86427174
has comment: http://stackoverflow.com/comment/86427136
has comment: http://stackoverflow.com/comment/86427251
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86427308
has comment: http://stackoverflow.com/comment/86429086

http://stackoverflow.com/comment/86262827
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49627957
type: QuestionComment
has text: The difference is the actual difference between opening a process, and forking it. Have a look at : https://stackoverflow.com/questions/2483041/what-is-the-difference-between-fork-and-thread

http://stackoverflow.com/comment/86336198
comment on: http://stackoverflow.com/a/49662938
score: 0
type: AnswerComment
has text: I could (Flatten), but the fact that I have a tensor of shape `(batch_size, samples, 1)` seems to indicate to me that the samples are not all getting processed by the conv net. Our conversation however has got me thinking and I think I have found the answer. I will write up an answer if it works. Thanks!
type: Comment

http://stackoverflow.com/comment/86492019
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49738715
has text: What do you mean by "get all values"? An OptionMenu is designed to provide a single value.
type: Comment

http://stackoverflow.com/a/49631114
accepted answer of: http://stackoverflow.com/q/49630410
answers question: http://stackoverflow.com/q/49630410
has body: Using angles is unnecessary, and there are problems in the way you do it. Using the atan will only give you angles between -pi/2 and pi/2, and you will get the same angle value for opposite directions. You should rather use Thales: import math a = (22732.23679147904, 6284399.7935522054) b = (20848.591367954294, 6281677.926560438) def extend_line(a, b, length): """ Returns the coordinates of point C at length beyond B in the direction of A-&gt;B""" ab = math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) coeff = (ab + length)/ab return (a[0] + coeff*(b[0]-a[0]), a[1] + coeff*(b[1]-a[1]) ) print(extend_line(a, b, 500)) # (20564.06031560228, 6281266.7792872535)
type: Answer
has comment: http://stackoverflow.com/comment/86271691
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86273063
upvote count: 1
has comment: http://stackoverflow.com/comment/86272373
type: AcceptedAnswer

http://stackoverflow.com/comment/86442768
type: QuestionComment
comment on: http://stackoverflow.com/q/49713433
score: 0
has text: The first read was to plot the all the shapes on map and second call was trying to color filing one of them. Is there a better way to approach it?
type: Comment

http://stackoverflow.com/q/49692459
has title: multiple model accuracy json result format using python
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49857935
type: AnsweredQuestion
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has comment: http://stackoverflow.com/comment/86397373
downvote count: 1
has body: I am building a multiple model and i am getting results with 7 models accuracy, i need those results with a proper json format. My multiple model building code will be like this seed = 7 "prepare models" models = [] models.append(('LogisticRegression', LogisticRegression())) models.append(('LinearDiscriminantAnalysis', LinearDiscriminantAnalysis())) models.append(('KNeighborsClassifier', KNeighborsClassifier())) models.append(('DecisionTreeClassifier', DecisionTreeClassifier())) models.append(('GaussianNB', GaussianNB())) models.append(('RandomForestClassifier',RandomForestClassifier())) models.append(('SVC', SVC())) "evaluate each model in turn" results = [] names = [] kfold_result = {} scoring = 'accuracy' # Kfold model selection for name, model in models: kfold = model_selection.KFold(n_splits=10, random_state=seed) cv_results = model_selection.cross_val_score(model, train[features_train],train["Churn"], cv=kfold, scoring=scoring) results.append(cv_results) names.append('"%s"' %name) # Appending result in new dictionary kfold_result[name] = cv_results.mean() model_results = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) #print(model_results) # For testing im just printing the dictionary values #print(kfold_result) #type(kfold_result) from collections import OrderedDict sorted_model = OrderedDict(sorted(kfold_result.items(), key = lambda x:x[1], reverse = True)) # print(sorted_model) # type(sorted_model) # make predictions on validation dataset for key in sorted_model.keys(): print(key) break # if condition if(key == "SVC"): prediction_model = SVC() elif(key == "RandomForestClassifier"): prediction_model = RandomForestClassifier() elif(key == "GaussianNB"): prediction_model = GaussianNB() elif(key == "DecisionTreeClassifier"): prediction_model = DecisionTreeClassifier() elif(key == "KNeighborsClassifier"): prediction_model = KNeighborsClassifier() elif(key == "LinearDiscriminantAnalysis"): prediction_model = LinearDiscriminantAnalysis() elif(key == "L…
favorite count: 0
accepted answer: http://stackoverflow.com/a/49857935
type: Question
tagged with: model

http://stackoverflow.com/a/49621605
score: 1
has comment: http://stackoverflow.com/comment/86250233
has body: You dont need to change anything in your dictionary. You just need to update attributes in both classes: # Declare your table class ItemTable(Table): City = Col('City') Unique_Id = Col('Unique_Id') FullName = Col('FullName') other_id = Col("other_id") area = Col("area") # Get some objects class Item(object): def __init__(self, City, Unique_Id,FullName,other_id,area): self.City = City self.Unique_Id = Unique_Id self.FullName = FullName self.other_id=other_id self.area = area and then simply as per from your reference URL: myTable = [{'City': 'Boston', 'Unique_Id': '123456-789', 'FullName': 'Smith, Joe', 'other_id': '0987654', 'area': 'Area 1'}, {'City': 'San Fransisco', 'Unique_Id': '654321-987', 'FullName': 'Brown, John', 'other_id': '7654321', 'area': 'Area 2'}, {'City': 'New York', 'Unique_Id': '7890123-456', 'FullName': 'Incomplete, Guy', 'other_id': None, 'area': None}] table = ItemTable(myTable) print(table.__html__()) The output is as below: City Unique_Id FullName other_id area Boston 123456-789 Smith, Joe 0987654 Area 1 San Fransisco 654321-987 Brown, John 7654321 Area 2 New York 7890123-456 Incomplete, Guy
accepted answer of: http://stackoverflow.com/q/49621478
has comment: http://stackoverflow.com/comment/86250097
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49621478

http://stackoverflow.com/comment/86377945
type: AnswerComment
comment on: http://stackoverflow.com/a/49683043
type: Comment
has text: That's a fair point. Unlike the example code above, my actual use-case would be within a class, so I'm not sure if `globals(`) would work on the class variables. Basically, I have a class representing a certain type of Selenium window, and about 2/3 of the functions in that class require the window to be in focus inside the Selenium browser for the function to work, so I have a decorator `focus_window()` which would focus the window before calling the function. If it's most pythonic, I can just put `@focus_window` before each function definition in the class. May have overthought this...
score: 0

http://stackoverflow.com/comment/86448023
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49716568
has text: I am still getting the 404 error
type: QuestionComment

http://stackoverflow.com/comment/86375302
has text: Wait, did you multiply all the time complexities together? That's not right; you're only doing O(n) base conversions and O(n) multiplications, so it should be O(n^3), dominated by base conversion. (In any case, you're going to hit the recursion limit long before runtime becomes a problem.)
type: Comment
comment on: http://stackoverflow.com/a/49679505
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86448451
score: 0
comment on: http://stackoverflow.com/q/49717695
has text: Yeah. Unless I am missing something conceptually. I'm trying to generate the keys for ElGamal encryption.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49687009
type: Question
tagged with: tf-idf
has body: I have a document that I tokenized, and then I take another document and I compare the two by calculating their cosine similarity. However, before I calculate their similarity, I want to increase the weight of one of the words beforehand. I'm thinking of doing this by doubling the count of that word, but I do not know how to do that. Suppose I have the following... text = [ "This is a test", "This is something else", "This is also a test" ] test = ["This is something"] Next I define the stop words and call CountVectorizer for both sets of documents. stopWords = set(stopwords.words('english')) vectorizer = CountVectorizer(stop_words=stopWords) trainVectorizerArray = vectorizer.fit_transform(text).toarray() testVectorizerArray = vectorizer.transform(test).toarray() In the next part I calculate the cosine similarity... cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3) for vector in trainVectorizerArray: print(vector) for testV in testVectorizerArray: print(testV) cosine = cosine_function(vector, testV) print(cosine) However, before I calculate the similarity, how can I increase the weight of one of the words. Suppose in this example I want to increase the weight of something, how can I do that? I think you do this by increasing the word count but I do not know how to increase that.
has title: How to increase weight of a word for CountVectorizer
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49687364
downvote count: 0
accepted answer: http://stackoverflow.com/a/49687364
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/86473925
has text: Try `df3=df.loc["Australia", df.columns[0:3]]`. The idea is you can select rows and columns by label simultaneously.
comment on: http://stackoverflow.com/q/49730107
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86522214
type: QuestionComment
has text: In case of pairs (+, -), do you want to always keep "+", "-" or you don't care?
comment on: http://stackoverflow.com/q/49753762
score: 0
type: Comment

http://stackoverflow.com/q/49612117
answer count: 1
type: Question
tagged with: raspbian
tagged with: cups
type: UnansweredQuestion
tagged with: python
has title: tea4Cups prehook sketch not running certain libraries
score: 0
has body: I am using tea4cups backend with the CUPS printing system. I'm writing a prehook in which I run a python script which turns on the printer via GPIO/relays and sets a cron task to turn it off after set time. I have narrowed down my problem to the point that I have identified I cannot use certain python libraries. Namely, crontab and logging. Whenever I import these libraries in the python script, the tea4cups prehook can't exit successfully. The job status shows this: completed at Mon 02 Apr 2018 12:59:44 UTC "Tea4CUPS v3.12_official (PID 22795) : Prehook prehook_new on printer Brother_HL_5470DW_Tea4Cups didn't exit successfully." Keep in mind my script runs flawlessly when I run it manually from the terminal. It's just that the tea4cups can't run it when I import these libraries into the script. Here is the python script: #!/usr/bin/python import RPi.GPIO as GPIO import Adafruit_DHT from sys import argv, exit import crontab import logging # Initialize temperature sensor sensor = Adafruit_DHT.DHT22 # Pin definitions DHTPin = 17 printPin = 27 heatPin = 22 # Pin Setup GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(heatPin, GPIO.OUT) GPIO.setup(printPin, GPIO.OUT) GPIO.output(heatPin, GPIO.HIGH) # Initialize variables temperature = 0 # Main Program print("final") Here is the tea4cups.conf file ending where I mention this prehook: prehook_new : python /home/pi/printserver/debug Here is the permissions for the python script: Can someone help me how should I proceed?
has answer: http://stackoverflow.com/a/51851094

http://stackoverflow.com/q/49633465
has comment: http://stackoverflow.com/comment/86275947
upvote count: 6
tagged with: grid-search
tagged with: python
has body: Is there a way to get access to the predicted values calculated within a GridSearchCV process? I'd like to be able to plot the predicted y values against their actual values (from the test/validation set). Once the grid search is complete, I can fit it against some other data using ypred = grid.predict(xv) but I'd like to be able to plot the values calculated during the grid search. Maybe there's a way of saving the points as a pandas dataframe? from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV, KFold, cross_val_score, train_test_split from sklearn.pipeline import Pipeline from sklearn.svm import SVR scaler = StandardScaler() svr_rbf = SVR(kernel='rbf') pipe = Pipeline(steps=[('scaler', scaler), ('svr_rbf', svr_rbf)]) grid = GridSearchCV(pipe, param_grid=parameters, cv=splits, refit=True, verbose=3, scoring=msescorer, n_jobs=4) grid.fit(xt, yt)
has answer: http://stackoverflow.com/a/68762679
possible better answer: http://stackoverflow.com/a/68762679
tagged with: svm
linked to: http://stackoverflow.com/q/46602518
type: AnsweredQuestion
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86312882
score: 6
tagged with: scikit-learn
favorite count: 0
type: Question
has title: GridSearchCV - access to predicted values across tests?
has answer: http://stackoverflow.com/a/49646065
accepted answer: http://stackoverflow.com/a/49646065

http://stackoverflow.com/q/49710192
tagged with: matplotlib
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: There are quite a few resources on the web for constructing a chart in Matplotlib with multiple y-axes. See: https://matplotlib.org/gallery/ticks_and_spines/multiple_yaxis_with_spines.html matplotlib: overlay plots with different scales? Constructing a chart with up to three y-axes is not difficult. However, a chart with four or five y_axes becomes more difficult to get the spacing of the placement of the y_axes nice looking. Is there a repeatable approach to get the spacing of the extra Y-axes to be non-overlapping? In particular, in the code below the calls to fig.subplots_adjust(right=...) and ax.spines["right"].set_position(("axes",...)) ought to be refined to account for the width of the preceding y-axis displays (in particular, the width of the numbers displayed in the y-axis display). I'm using Python 3.6.4, Matplotlib 2.1.2, and Qt5Agg as the Matplotlib backend on Windows 10. import matplotlib.pyplot as plt plt.ioff() def adjust_extra_yaxes(ax, pct_shift): ax.spines["right"].set_position(("axes", 1+pct_shift)) 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) fig, ax_0 = plt.subplots() ax_1 = ax_0.twinx() ax_2 = ax_0.twinx() ax_3 = ax_0.twinx() ax_4 = ax_0.twinx() num_extra_yaxes = 3 pct_width_per_yaxis = 0.1 fig_right_margin = 1.0 - pct_width_per_yaxis*num_extra_yaxes fig.subplots_adjust(right=fig_right_margin) i = 1 for ax in [ax_2, ax_3, ax_4]: adjust_extra_yaxes(ax, pct_width_per_yaxis*i) i+=1 l0, = ax_0.plot([0, 1, 2], [0, 1, 2], linestyle='-', label="Label Name 0", color='Blue') l1, = ax_1.plot([0, 1, 2], [0, 3000000, 2000000], linestyle='-', label="Label Name 1", color='Green') l2, = ax_2.plot([0, 1, 2], [5, 3, 1.5], linestyle='-', label="Label Name 2", color='Red') l3, = ax_3.plot([0, 1, 2], [800000, 200000, 150000], linestyle='-', label="Label Name 3", color='cyan') l4, = ax_4.plot([0, 1, 2], [50, 55, 200], linestyle='-', label="Label Name 4", color='black') ax_…
has title: Algorithm for Spacing Multiple (>3) Y-Axes in a Matplotlib Chart
score: 2
answer count: 0
linked to: http://stackoverflow.com/q/7733693

http://stackoverflow.com/a/49681140
has body: You can do it using set_index and unstack if you don't have multiple values for resulting rows and columns otherwise you'll have to use a aggregation method such as pivot_table or groupby: df_out = y.set_index(['col0','col1','col2']).unstack([1,2]) df_out.columns = df_out.columns.map('_'.join) df_out.reset_index() Output: col0 col3_a_x col3_b_x 0 1 12 13 1 2 14 15 Or with multiple values using groupby: df_out = y.groupby(['col0','col1','col2']).mean().unstack([1,2]) df_out.columns = df_out.columns.map('_'.join) df_out.reset_index()
answers question: http://stackoverflow.com/q/49680613
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/86253350
has text: its not the loop. its if/else block.
type: QuestionComment
comment on: http://stackoverflow.com/q/49623007
type: Comment
score: 0

http://stackoverflow.com/comment/86292617
score: 0
comment on: http://stackoverflow.com/q/49638900
type: Comment
type: QuestionComment
has text: @Foon error log: `[Wed Apr 04 01:32:20.532211 2018] [core:error] [pid 32180:tid 140546194487040] (13)Permission denied: [client 84.201.133.8:38686] AH00035: access to / denied (filesystem path '/root/enoticerepo1.2') because search permissions are missing on a component of the path `

http://stackoverflow.com/q/49750788
tagged with: pandas
linked to: http://stackoverflow.com/q/23668427
answer count: 1
downvote count: 0
has title: Merge three or more data frames with Pandas
favorite count: 0
type: Question
has body: In Pandas merge function you can merge two data frames, but I need to merge N, similar to an SQL statement where you combine N tables in a full outer join. For example, I need to merge the three data frames below by 'type_1', 'subject_id_1', 'type_2', 'subject_id_2' and 'type_3', 'subject_id_3'. Is this possible? import pandas as pd raw_data = { 'type_1': [1, 1, 0, 0, 1], 'subject_id_1': ['1', '2', '3', '4', '5'], 'first_name_1': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung']} df_a = pd.DataFrame(raw_data, columns = ['type_1', 'subject_id_1', 'first_name_1']) raw_datab = { 'type_2': [1, 1, 0, 0, 0], 'subject_id_2': ['4', '5', '6', '7', '8'], 'first_name_2': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty']} df_b = pd.DataFrame(raw_datab, columns = ['type_2', 'subject_id_2', 'first_name_2']) raw_datac = { 'type_3': [1, 1], 'subject_id_3': ['4', '5'], 'first_name_3': ['Joe', 'Paul']} df_c = pd.DataFrame(raw_datac, columns = ['type_3', 'subject_id_3', 'first_name_3']) ### need to include here the third data frame merged = pd.merge(df_a, df_b, left_on=['type_1','subject_id_1'], right_on = ['type_2','subject_id_2'], how='outer') print(merged) Note: The names of the fields to join are different in each data frame.
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49751512
has answer: http://stackoverflow.com/a/49751512
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/86290341
score: 0
has text: @Aran-Fey What I mean is variable declaration within the class like `abc=1`
type: QuestionComment
comment on: http://stackoverflow.com/q/49641319
type: Comment

http://stackoverflow.com/a/49678566
has comment: http://stackoverflow.com/comment/86369993
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86368928
has body: I remember this error occurring with older versions of Selenium. Please run this to update your Selenium and try to run your test again: pip install -U selenium If you need more help to update Selenium, use This to learn more about how to install packages. UPDATE Here is a working example of using WebDriverWait that should help: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait driver.get("https://www.supremenewyork.com/checkout") WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='order_billing_name']"))) nameField = driver.find_element_by_xpath("//*[@id='order_billing_name']") nameField.send_keys("Name") For more information on how WebDriverWait works, use: https://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
answers question: http://stackoverflow.com/q/49678015
type: Answer
has comment: http://stackoverflow.com/comment/86370407
accepted answer of: http://stackoverflow.com/q/49678015
score: 0

http://stackoverflow.com/q/49716186
accepted answer: http://stackoverflow.com/a/49716693
type: Question
has answer: http://stackoverflow.com/a/49716693
score: 0
has body: I have seen the doc, tf.train.ExponentialMovingAverage implement this formula: shadow_variable = decay * shadow_variable + (1 - decay) * variable I didn't find the formula of tf.train.MomentumOptimizer. But I think it may be: v = γ*v - learning_rate*dx θ = θ - v I think this two function have similar effect, so can they exchange each other?Or they have different application scenarios? Or I'm totally wrong? And does the shadow_variable is equivalent to θ? Thanks for any guidance.
answer count: 1
tagged with: machine-learning
tagged with: tensorflow
type: AnsweredQuestion
tagged with: python
has title: What's the difference between tf.train.ExponentialMovingAverage and tf.train.MomentumOptimizer?

http://stackoverflow.com/q/49716442
has body: My code, wat.txt contains a list of why I love her and This code isn't looping how I wanted. Originally I had.. Can someone direct me toward how I should fix this loop and keep getting sentences. I think its just the loops fault. I havn't programmed in a while, until today. :P thank you!(P.S. Its for my girlfriend) This is the Original loop while k: print("~ I love "+sen) wat=raw_input("") l.remove(sen) if wat=="Another" or "another" or "more": r=random.randint(1,n)-1 sen=l[r-1] print("~ I love "+sen) wat=input("") if n &lt;= 0: k=False else: k=False 2nd Attempt Not working Either #! /usr/bin/env python # -*- coding: utf-8 -*- l=[] output=open('C:/Users/David/Downloads/files/wat.txt','r') for line in output: l.append(line) import random n=len(l) r=random.randint(1,n)-1 sen=l[r-1] print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("Type 'Quit' To Leave or 'Another' to see another reason why I love you") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n\n") k=True while k: print("~ I love "+sen) wat=raw_input("") l.remove(sen) if wat=="Another" or "another" or "more": r=random.randint(1,n)-1 sen=l[r-1] if n &lt;= 0: k=False else: k=False
linked to: http://stackoverflow.com/q/15112125
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86445942
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python
has title: Cant seem to get Loop to work properly, or perhaps another issue; I havn't programmed in a while
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86445901

http://stackoverflow.com/a/49618232
accepted answer of: http://stackoverflow.com/q/49607625
score: 0
has comment: http://stackoverflow.com/comment/86244675
type: AcceptedAnswer
has body: With your whole code, the error is clear. You don't have the classic append error, but the same mistake: guessList = guessList.sort() sort sorts the list inplace and returns None.
answers question: http://stackoverflow.com/q/49607625
type: Answer

http://stackoverflow.com/comment/99247686
type: AnswerComment
comment on: http://stackoverflow.com/a/53350875
has text: Here for me the issue was that it does not load the annotations (like POS tags)
type: Comment
score: 0

http://stackoverflow.com/q/49735028
has answer: http://stackoverflow.com/a/49735295
possible better answer: http://stackoverflow.com/a/49735223
has body: I have several DataFrames (DataFrames have the same index and column structure). The problem is that there are NaN values in these dataframes. I want to replace these NaN values by mean value of other's DataFrames' corresponding values. For exapmle let's look at 3 dataframes. DataFrame1 with 1:M2 NaN : M1 M2 M3 0 1 1 2 1 8 NaN 9 2 4 2 7 3 9 6 3 DataFrame 2 with NaN value at 0:M3: M1 M2 M3 0 2 3 NaN 1 1 1 6 2 1 2 9 3 4 6 2 DataFrame3: M1 M2 M3 0 1 4 2 1 2 9 1 2 1 6 5 3 1 NaN 4 So we replace NaN in first DataFrame by 5 (9+1)/2. Second NaN should be replaced by 2 because (2+2)/2, third by 6 and so on. Is there any good and elegant way to do it?
tagged with: dataframe
tagged with: python
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49735295
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49735223
tagged with: nan
favorite count: 0
type: Question
tagged with: numpy
has title: Replace NaN values in entire dataframe with average of others

http://stackoverflow.com/comment/86491658
score: 2
comment on: http://stackoverflow.com/q/49738518
has text: Possible duplicate of [Access a function variable outside the function without using \`global\`](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49608737
downvote count: 0
answers question: http://stackoverflow.com/q/49608656
has comment: http://stackoverflow.com/comment/86225842
accepted answer of: http://stackoverflow.com/q/49608656
type: Answer
has comment: http://stackoverflow.com/comment/86224425
has comment: http://stackoverflow.com/comment/107191732
has comment: http://stackoverflow.com/comment/107193796
has comment: http://stackoverflow.com/comment/86224472
has body: It's all in the docs. You are interested in skipping the index column, so do: result.to_csv("output.csv", index=False) If you also want to skip the header add: result.to_csv("output.csv", index=False, header=False) I don't know how your input data looks like (it is a good idea to make it available in your question). But note that currently you can obtain the same results just by doing: import pandas as pd df = pd.DataFrame([0]*16) df.to_csv('results.csv', index=False, header=False)
score: 25
upvote count: 25
type: AcceptedAnswer

http://stackoverflow.com/comment/86491089
comment on: http://stackoverflow.com/q/49738260
type: Comment
has text: Why are you using two different functions (`std1` and `std2`) for the same thing? You should take a look at classes. They will be very helpful for your problem.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86498018
comment on: http://stackoverflow.com/a/49740663
score: 0
type: Comment
has text: @user2357112 Seems sensible, I didn't notice the comment in the docs there. Thanks!
type: AnswerComment

http://stackoverflow.com/a/49661183
has comment: http://stackoverflow.com/comment/94411820
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/94411596
has comment: http://stackoverflow.com/comment/86360940
downvote count: 0
type: AcceptedAnswer
has body: I dug into this a bit, so I'll share what I have. Whether or not it is a complete answer I'm not sure, but it may address some of your questions. Probably the best numba-based approach for this is to write your own "custom" CUDA kernel using numba CUDA (jit). An example of this is here for reduction or here for matrix multiply. To do this correctly would require learning something about CUDA programming. This didn't seem to be the direction you wanted to go in however. As an alternative your question is focusing on using numba vectorization to generate GPU code. numba vectorize decorator is used for functions which operate on scalar input and output, and the vectorization applies them to matrix input/matrix output. For functions that don't fit this, e.g. those that operate on a vector or a scalar but produce a vector, or those that operate on one or two vectors, and produce a vector or scalar output, numba provides the generalized guvectorize. Starting with your simplest example of what you want to do, we could realize this with guvectorize: What I tried so far is to write the function in a non-vectorized form (i.e. treat each entry of X separately), and pass the return array as an input: def foo_cuda(x,N,out): ''' :param x: Scalar :param N: Integer :rtype: 1D numpy array of length N ''' out[0] = x for i in range(1,N): out[i] = x**i+out[i-1] This intent, to take a scalar (per function call) and return a vector (per function call) falls within the capability of guvectorize (with some limitations/caveats - see notes at bottom). Here is a worked example, derived from the sample code here: # cat t2.py from __future__ import print_function import sys import numpy as np from numba import guvectorize, cuda if sys.version_info[0] == 2: range = xrange # function type: # - has void return type # # signature: (n)-&gt;(n) # - the function takes an array of n-element and output same. @guvectorize(['void(float32[:], float32[:])'], '(n) -&gt;(n)', target='cuda') def my_func(inp, o…
has comment: http://stackoverflow.com/comment/94381651
has comment: http://stackoverflow.com/comment/86343159
answers question: http://stackoverflow.com/q/49646182
has comment: http://stackoverflow.com/comment/94390258
type: Answer
accepted answer of: http://stackoverflow.com/q/49646182

http://stackoverflow.com/comment/86360240
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49669226
has text: maybe this post will help you: [How do I add a column to a nested struct in a pyspark dataframe](https://stackoverflow.com/questions/48777993/how-do-i-add-a-column-to-a-nested-struct-in-a-pyspark-dataframe/).
type: Comment

xgboost
tags question: http://stackoverflow.com/q/49738295
tags question: http://stackoverflow.com/q/49697514
tags question: http://stackoverflow.com/q/49744351
tags question: http://stackoverflow.com/q/49700672
tags question: http://stackoverflow.com/q/49628200
tag name: xgboost
tags question: http://stackoverflow.com/q/49756461
tags question: http://stackoverflow.com/q/49649675
type: Tag

http://stackoverflow.com/a/49612845
score: -1
upvote count: 0
has body: In your code I see x_train and x_test, so it looks like you've split your dataset a training/testing set correct? It's important that these two sets are independent of each other... i.e. the instances in each set are unique from each other. It's possible that you have a dataset with many repeating instances, if so... then your random split of the test set probably is just a subset of the training set and you are overtraining. One useful tool to debug is a plot of the learning curve. To do this, simply plot the accuracy of the training and test set after every training epoch. It can tell you a lot about the model: under-fitting, over-fitting, stagnant learning, etc.
downvote count: 1
answers question: http://stackoverflow.com/q/49612619
type: Answer

http://stackoverflow.com/q/49671691
tagged with: python
upvote count: 6
tagged with: lark-parser
type: Question
answer count: 2
score: 5
tagged with: grammar
has answer: http://stackoverflow.com/a/49673206
has comment: http://stackoverflow.com/comment/86354719
has body: I have a priority problem in my grammar, and I don't have any more idea to fix it. I'm using Lark Here is the thing (I have simplified the problem as much as I can): from lark import Lark parser = Lark(r""" start: set | set_mul set_mul: [nb] set set: [nb] "foo" nb: INT "x" %import common.INT %import common.WS %ignore WS """, start='start') input = "3xfoo" p = parser.parse(input) print(p.pretty()) The output is : start set_mul set nb 3 But what I want is : start set_mul nb 3 set I tried to put priority in my rules, but it's not working. Do you have any idea of what I would need to change to make it work ? Thanks
has title: Priority in grammar using Lark
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/49673206
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49675431
has answer: http://stackoverflow.com/a/49675431

http://stackoverflow.com/q/49652568
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49652909
tagged with: python
has body: I am using a trained model form keras. this model doesn't fit in to the GPU memory so I want to divide it into CPU and GPU and maybe on GPUs on different machines. 1) So, if I want to get all tf.variable on my CPU and the calculation on GPU how can I do this. Because some articles show that we can place the tf.variable on CPU and the calculation on a GPU. (I am talking about a pre-trained keras model). 2) If I want to separate the layers of the pre-trained model into different GPU on different machines. is it correct to use with tf.device and then add the layers to my sequence model like this. vgg16_model = keras.applications.vgg16.VGG16() cnnModel = Sequential() for layer in vgg16_model.layers[0:13]: cnnModel.add(layer) for layer in vgg16_model.layers[14:16]: cnnModel.add(layer) for layer in vgg16_model.layers[17:21]: cnnModel.add(layer) with tf.device(........): cnnModel.add(Dense(2048, name="compress_1")) cnnModel.add(Dense(1024, name="compress_2")) cnnModel.add(Dense(512, name="compress_3")) with tf.device(........): model = Sequential() model.add(keras.layers.TimeDistributed(cnnModel,input_shape=(10,224,224,3),name="CNN_Model")) with tf.device(........): model.add(keras.layers.LSTM(256,name="lstm1",return_sequences=True)) model.add(keras.layers.LSTM(128,name="lstm2",return_sequences=True)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(528)) model.add(keras.layers.Dense(64)) model.add(keras.layers.Dense(39,activation='sigmoid')) Thank you very much. Update I was thinking if I can access the attribute variable_device in the tensor variables of the model and set it by my self to the CPU. btw I am using the tf.keras implementation. Update2 I have tried some In the tensorboard I can see this: Does this mean that the calculation and the training is in the CPU and the data is in the GPU??
has title: keras trained model using different tf device
score: 2
upvote count: 2
answer count: 1
downvote count: 0
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/q/49625940
tagged with: python-3.x
score: 5
tagged with: turtle-graphics
has answer: http://stackoverflow.com/a/49634913
has title: Determine the window size turtle python setup
type: UnansweredQuestion
downvote count: 2
tagged with: python
upvote count: 7
answer count: 1
has body: In Python 3+, I am trying to run turtle.setup(400, 500) but it is not working. There is no reference named setup. How can I use the screen setup in Python 3?
favorite count: 0
type: Question

http://stackoverflow.com/comment/86459428
type: Comment
has text: Hey, thanks to your question/comment, i found out it wasn't able to find the element because i had to switch to frame. So it worked when i added the following before the code i used: driver.switch_to.frame('ptModFrame_0')
type: QuestionComment
comment on: http://stackoverflow.com/q/49722032
score: 0

http://stackoverflow.com/comment/86353178
comment on: http://stackoverflow.com/q/49671404
score: 3
type: Comment
type: QuestionComment
has text: Why are you trying to serialize the exception?

http://stackoverflow.com/comment/86351860
comment on: http://stackoverflow.com/q/49670868
type: Comment
type: QuestionComment
has text: First lists, now sets .... why? [YourOtherQuestion](https://stackoverflow.com/questions/49669856/how-to-repeat-an-operation-on-a-list)
score: 1

http://stackoverflow.com/a/49663942
upvote count: 1
answers question: http://stackoverflow.com/q/49663396
has comment: http://stackoverflow.com/comment/86338390
has comment: http://stackoverflow.com/comment/86338443
downvote count: 0
score: 1
has body: You could likely use a loop without much issue: files = [f for f in os.listdir('.') if os.path.isfile(f)] for f in files: with open(f, 'rb') as fh: last = fh.readlines()[-1].decode() print('file: {0}\n{1}\n'.format(f, last)) fh.close() Output: file.txt Hello, World! ... If your files are large then readlines() probably isn't the best option. Maybe go with tail instead: for f in files: print('file: {0}'.format(f)) subprocess.check_call(['tail', '-n', '1', f]) print('\n') The decode is optional, although for text "utf-8" usually works or if it's a combination of binary/text/etc then maybe something such as "iso-8859-1" usually should work.
type: Answer
has comment: http://stackoverflow.com/comment/86338092
has comment: http://stackoverflow.com/comment/86338471
has comment: http://stackoverflow.com/comment/86338465
has comment: http://stackoverflow.com/comment/86338346
has comment: http://stackoverflow.com/comment/86338132
has comment: http://stackoverflow.com/comment/86338067

http://stackoverflow.com/q/49699737
has comment: http://stackoverflow.com/comment/86412775
has comment: http://stackoverflow.com/comment/86412878
has comment: http://stackoverflow.com/comment/86412729
has comment: http://stackoverflow.com/comment/86412676
has comment: http://stackoverflow.com/comment/86412757
has comment: http://stackoverflow.com/comment/86412693
tagged with: python
linked to: http://stackoverflow.com/q/45121119
has body: I am using Python 3 and I want to simulate a card game with my Card class below: class Card: def __init__(self, name = "", stars = 0, attack = 0): self.name = name self.stars = stars self.attack = attack def setName(self, name): self.name = name def getName(self): return self.name def setStars(self, stars): self.stars = stars def getStars(self): return self.stars def setAttack(self, attack): self.attack = attack def getAttack(self): return self.attack def attack(self, enemyCard): print(self.name + "attacked" + enemyCard.getName() + "and did" + self.attack + "damage!") The following is my driver class: def main(): me = Card() me.setName("Good") me.setStars(99) me.setAttack(9000) you = Card() you.setName("EVIL") you.setStars(0) you.setAttack(-1) me.attack(you) &lt;-error here Everything works except at the very last line which is me.attack(you): TypeError: 'int' object is not callable I think it may have something to do with my attack method in Card but I don't quite understand why the variable you is seen as an int
tagged with: class
tagged with: python-3.x
answer count: 0
duplicate of: http://stackoverflow.com/q/45121119
score: 0
has comment: http://stackoverflow.com/comment/86413159
has comment: http://stackoverflow.com/comment/86413015
has title: Passing self as method parameter within class - Python
type: UnansweredQuestion
tagged with: parameter-passing
has comment: http://stackoverflow.com/comment/86412758
linked to: http://stackoverflow.com/q/2627002
type: Question
tagged with: parameters

http://stackoverflow.com/comment/86406772
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49660665
has text: Thanks for the answer, brvh. I'll look into numpy in the future.

http://stackoverflow.com/comment/86323928
has text: Use the hierarchy to stop when you've gone too deep.
type: Comment
comment on: http://stackoverflow.com/q/49656671
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86376898
type: Comment
score: 0
type: AnswerComment
has text: afaict, inverted commas usually refers to ' though, not "
comment on: http://stackoverflow.com/a/49682330

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

http://stackoverflow.com/comment/86337717
comment on: http://stackoverflow.com/a/49647120
score: 0
has text: It is working as intended, thank you..I have one more related query.I want to place the rectangle over a video. I tried to read the video and store the frames in a folder.Now I want to read the folder sequentially and one any particular frame draw the rectangle and the rest of the frames read should hold the rectangle. I am able to write the frames from a video but not able to read the using "os.listdi()". Can you help me with it.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49696821
tagged with: python-3.x
answer count: 2
upvote count: 0
score: -3
has comment: http://stackoverflow.com/comment/86406578
tagged with: python
has answer: http://stackoverflow.com/a/49697002
accepted answer: http://stackoverflow.com/a/49697236
has comment: http://stackoverflow.com/comment/86414707
has comment: http://stackoverflow.com/comment/86406521
has body: I have the following code to print the (distinct numbers), but I'm trying to check the inputs before the process, should be ten digits numbers only with only one space. I tried while and try but still can't figure out: def main(): list1 = input("Enter ten numbers: ").split() set1 = set(list1) print(set1) list2 = list(set1) string = string.join(list2) print("The distinct numbers are: " + str(string)) main()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49697236
possible better answer: http://stackoverflow.com/a/49697002
downvote count: 3
favorite count: 0
has title: Print distinct numbers in python 3
type: Question

http://stackoverflow.com/comment/86222976
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49608130
has text: @KlausD. it seems to be that way..
type: Comment

http://stackoverflow.com/a/49613338
score: 0
type: Answer
has body: Test it on a smaller data-set. The performance would be the same given you do not test using extremely small sets of data.
answers question: http://stackoverflow.com/q/49613287

http://stackoverflow.com/q/49661426
has answer: http://stackoverflow.com/a/50161286
answer count: 2
has comment: http://stackoverflow.com/comment/86332784
tagged with: screenshot
tagged with: directory
tagged with: macos
has comment: http://stackoverflow.com/comment/86332902
type: Question
type: UnansweredQuestion
tagged with: python
has title: Find out default screenshot path in MacOS from within Python to monitor screenshots
has body: I have a program that monitors for new screenshots but however, I had to change the default screenshot directory to /screenshots instead of the in com.apple.screencapture How can I obtain the directory set within com.apple.screencapture from within Python so that the program can run on any MacOS computer without having to manually change the screenshot directory location first. Example code (currently after changing dir): path = os.path.join(os.path.curdir, 'screenshots') observer = Observer() event_handler = ScreenshotEventHandler() # Create a watchdog to watch &lt;current_dir&gt;/screenshots directory observer.schedule(event_handler, path) observer.start()
has answer: http://stackoverflow.com/a/50048594
score: 0

http://stackoverflow.com/q/49694832
has comment: http://stackoverflow.com/comment/86404226
has answer: http://stackoverflow.com/a/72525657
type: Question
tagged with: ctypes
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: pickle
has comment: http://stackoverflow.com/comment/86408210
has comment: http://stackoverflow.com/comment/86403895
favorite count: 0
score: 2
linked to: http://stackoverflow.com/q/1555944
has comment: http://stackoverflow.com/comment/86405018
has body: I have the following classes of a ctypes Structure. import ctypes as ct class my_array(ct.Structure): _fields_ = [("_data", ct.POINTER(ct.c_uint32)), ("_size", ct.c_size_t)] def __init__(self, data): self._data = (ct.c_uint32 * len(data))() for i in range(0, len(data)): self._data[i] = data[i] self._size = len(data) def __reduce__(self): data = [None]*self._size for j in xrange(0, self._size): data[j] = self._data[j] return (my_array, (data,)) class my_struct(ct.Structure): _fields_ = [("numbs", my_array)] However, when I pickle the second object import cPickle a = my_array([1, 2, 10]) b = my_struct(a) with open('myfile', 'wb') as f: cPickle.dump(a, f) # This succeeds cPickle.dump(b, f) # This fails I get the exception Traceback (most recent call last): File "tmp.py", line 30, in &lt;module&gt; cPickle.dump(a, f) # This fails ValueError: ctypes objects containing pointers cannot be pickled I don't understand why this is happening since I implemented __reduce__ in my_array? Implementing __getstate__ did not work either. I know I can overload __reduce__ again in my_struct but this seems overly complicated for me since then I have to keep overloading __reduce__ everytime I include my_array in a structure.
has comment: http://stackoverflow.com/comment/86404955
has comment: http://stackoverflow.com/comment/86405486
tagged with: python
has comment: http://stackoverflow.com/comment/86408255
has comment: http://stackoverflow.com/comment/86408123
has title: Pickling a ctypes.Structure with ct.Pointer

http://stackoverflow.com/q/49750276
has comment: http://stackoverflow.com/comment/86545991
type: UnansweredQuestion
tagged with: azure
tagged with: python
has title: Azure Speech To Text WebSocket [Python]
has body: I am facing a issue of sending the speech.config header in on_open event listener, it shows the error that i have captured below, it seems the web socket cannot be built successfully. I am following the official guide from Micrsoft And it it possible to send the header after the connection is established? Thanks a lot for any help ! Here is my code: import speech_recognition as sr import json import requests import ssl import urllib3 import xmltodict import time import websocket import thread import uuid from googletrans import Translator from urllib import urlencode from auth import AzureAuthClient import datetime import struct import pyaudio import sys import StringIO import platform import os def get_wave_header(frame_rate): """ Generate WAV header that precedes actual audio data sent to the speech translation service. :param frame_rate: Sampling frequency (8000 for 8kHz or 16000 for 16kHz). :return: binary string """ if frame_rate not in [8000, 16000]: raise ValueError("Sampling frequency, frame_rate, should be 8000 or 16000.") nchannels = 1 bytes_per_sample = 2 output = StringIO.StringIO() output.write('RIFF') output.write(struct.pack('&lt;L', 0)) output.write('WAVE') output.write('fmt ') output.write(struct.pack('&lt;L', 18)) output.write(struct.pack('&lt;H', 0x0001)) output.write(struct.pack('&lt;H', nchannels)) output.write(struct.pack('&lt;L', frame_rate)) output.write(struct.pack('&lt;L', frame_rate * nchannels * bytes_per_sample)) output.write(struct.pack('&lt;H', nchannels * bytes_per_sample)) output.write(struct.pack('&lt;H', bytes_per_sample * 8)) output.write(struct.pack('&lt;H', 0)) output.write('data') output.write(struct.pack('&lt;L', 0)) data = output.getvalue() output.close() return data def get_wave_empty(): output = StringIO.StringIO() # for num in range(1, 801): for num in range(1, 41): output.write(struct.pack('&lt;L', 0)) data = output.getvalue() output.close() return data def on_open(ws): timestap = datetime.datetime.utcnow().isoformat()+'Z…
answer count: 0
score: 1
downvote count: 0
tagged with: websocket
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49612444
type: Answer
downvote count: 0
has body: I would implement it this way: is_found = False with open("file.csv", "r") as file: reader = csv.reader(file) for item in reader: if toFind == item is_found = True break # No need to keep on searching so we stop here if not is_found: print "Cannot be Found" Using a boolean that is pre-set to False I would be sure that printing the boolean value at the end of the loop it will contain True only if toFind was found in the CSV.
answers question: http://stackoverflow.com/q/49612375
upvote count: 1
score: 1

selenium
tags question: http://stackoverflow.com/q/49623986
tags question: http://stackoverflow.com/q/49727716
tags question: http://stackoverflow.com/q/49734915
tags question: http://stackoverflow.com/q/49721211
tags question: http://stackoverflow.com/q/49627458
tags question: http://stackoverflow.com/q/49750037
tags question: http://stackoverflow.com/q/49679287
tags question: http://stackoverflow.com/q/49612510
tags question: http://stackoverflow.com/q/49634265
tags question: http://stackoverflow.com/q/49722032
tags question: http://stackoverflow.com/q/49699973
tags question: http://stackoverflow.com/q/49738777
tags question: http://stackoverflow.com/q/49747034
tags question: http://stackoverflow.com/q/49678384
tags question: http://stackoverflow.com/q/49755907
tags question: http://stackoverflow.com/q/49751425
tags question: http://stackoverflow.com/q/49674105
tags question: http://stackoverflow.com/q/49649070
tags question: http://stackoverflow.com/q/49714285
tags question: http://stackoverflow.com/q/49651116
tags question: http://stackoverflow.com/q/49713502
tags question: http://stackoverflow.com/q/49636099
tags question: http://stackoverflow.com/q/49658100
tags question: http://stackoverflow.com/q/49675286
tags question: http://stackoverflow.com/q/49746928
tags question: http://stackoverflow.com/q/49647205
tags question: http://stackoverflow.com/q/49703521
tags question: http://stackoverflow.com/q/49751433
tags question: http://stackoverflow.com/q/49757073
tags question: http://stackoverflow.com/q/49640060
tags question: http://stackoverflow.com/q/49640106
tags question: http://stackoverflow.com/q/49748736
tags question: http://stackoverflow.com/q/49642896
tags question: http://stackoverflow.com/q/49719015
tags question: http://stackoverflow.com/q/49603312
tags question: http://stackoverflow.com/q/49676174
tags question: http://stackoverflow.com/q/49665316
tags question: http://stackoverflow.com/q/49623423
tags question: http://stackoverflow.com/q/49631464
tags question: http://stackoverflow.com/q/49751398
tags question: http://stackoverflow.com/q/49657833
tags question: http://stackoverflow.com/q/49673465
tags question: http://stackoverflow.com/q/49682846
tags question: http://stackoverflow.com/q/49671968
tags question: http://stackoverflow.com/q/49757013
tags question: http://stackoverflow.com/q/49603294
tags question: http://stackoverflow.com/q/49626707
tags question: http://stackoverflow.com/q/49698691
tags question: http://stackoverflow.com/q/49699061
type: Tag
tags question: http://stackoverflow.com/q/49618287
tags question: http://stackoverflow.com/q/49622197
tags question: http://stackoverflow.com/q/49678015
tags question: http://stackoverflow.com/q/49658070
tags question: http://stackoverflow.com/q/49616151
tags question: http://stackoverflow.com/q/49734806
tags question: http://stackoverflow.com/q/49648208
tags question: http://stackoverflow.com/q/49627314
tags question: http://stackoverflow.com/q/49705523
tags question: http://stackoverflow.com/q/49601677
tags question: http://stackoverflow.com/q/49620853
tags question: http://stackoverflow.com/q/49641855
tag name: selenium
tags question: http://stackoverflow.com/q/49715966
tags question: http://stackoverflow.com/q/49623250
tags question: http://stackoverflow.com/q/49700854
tags question: http://stackoverflow.com/q/49681470
tags question: http://stackoverflow.com/q/49680943
tags question: http://stackoverflow.com/q/49653105
tags question: http://stackoverflow.com/q/49653274
tags question: http://stackoverflow.com/q/49617485
tags question: http://stackoverflow.com/q/49614879
tags question: http://stackoverflow.com/q/49734903
tags question: http://stackoverflow.com/q/49702760
tags question: http://stackoverflow.com/q/49705203
tags question: http://stackoverflow.com/q/49675683
tags question: http://stackoverflow.com/q/49719930
tags question: http://stackoverflow.com/q/49670686
tags question: http://stackoverflow.com/q/49698207

http://stackoverflow.com/comment/118275703
type: Comment
has text: Note that while the "Requirements parsing" link doesn't explicitly say, it does appear to handle comments in the requirements.txt file.
type: AnswerComment
comment on: http://stackoverflow.com/a/59971236
score: 1

http://stackoverflow.com/comment/86257611
comment on: http://stackoverflow.com/q/49620585
type: Comment
type: QuestionComment
score: 0
has text: I'm also suffering because of this today - Firefox gets further than Chrome presumably because there's no preflight check, but still fails at the response stage. None of the solutions at https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask work for me...

http://stackoverflow.com/a/49707565
answers question: http://stackoverflow.com/q/49707491
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86428681
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49707491
type: Answer
has body: I have tested your example and got totally different result. First, I copied your given json string. And use len(json_str), get its length as 205. And I save it as a text file json_str.json, and get its size as 205B. That makes sense. Second, I use sys.getsizeof(json_str) to get its memory size and get 254, that also makes sense as an empty sting in python3 has 49 size. Add 205 and equal to 254. So I really cannot understand the results you given in question.
has comment: http://stackoverflow.com/comment/86428912

http://stackoverflow.com/q/49734251
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49734344
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49734405
score: 0
has title: How python objects are releasing resources?
has body: I have a python class ReportGenerator which needs temporary directory to store intermediate files. Once object of ReportGenerator is destroyed my code is required to delete temporary folder. Where to place directory removal code to make sure that once object is not referenced, the temp folder will be deleted. In C++ it is obvious to delete folder in destructor of class. In python there is a __del__ but as I understand from other posts it is not recommended to use it in such situation. So in general what is a right way in python so one object can own a resource and release once it destroyed?
type: Question

http://stackoverflow.com/a/49741587
has comment: http://stackoverflow.com/comment/86532066
has body: As mentioned in @Trap's answer, you need to return the results from the SearchHarddisk() method instead of trying to append them to the self.allfiles in fullThreadSearch(). This is because each invocation of SearchHarddisk() runs in its own address space, so there's effectively a different self.allfiles list object in each one. Here's something with those changes made that seems to work on my Windows machine. Note that I based it on the sample code shown in the ProcessPoolExecutor Example section of the documentation which uses the ProcessPoolExecutor.map() method instead of calling ProcessPoolExecutor.submit() repeatedly. import concurrent.futures as futures import os import time import win32api class SearchThreader(): def __init__(self): self.allfiles = [] self.harddisks = win32api.GetLogicalDriveStrings().split('\000')[:-1] #skip the folders that shouldn't have files with this extension self.exlude = { "$SysReset", "AMD", "inetpub", "NVIDIA", "PerfLogs", "Windows.old", "Windows", "ProgrammData", "Programm Files (x86)", "Programm Files", "Doc", "Fotos", "Lib", "lib", "libs" "Scripts", "Tools", "bin", "Config", "Logs", "log", "mods", "win" } self.fullThreadSearch() def SearchHarddisk(self, hd): allfiles = [] # Local variable. for root, dirs, files in os.walk(hd, topdown=True): dirs[:] = [d for d in dirs if d not in self.exlude] for f_name in files: file_path = os.path.join(root, f_name) if file_path.endswith(".mp3"): allfiles.append(file_path) # Append to local list. print(file_path) return allfiles # Return all found on this harddisk. def fullThreadSearch(self): with futures.ProcessPoolExecutor() as executor: for harddisk, matching_files in zip( self.harddisks, executor.map(self.SearchHarddisk, self.harddisks)): print('harddisk: {}, matching_files: {}'.format(harddisk, matching_files)) self.allfiles.extend(matching_files) if __name__ == "__main__": starttime = time.time() ST = SearchThreader() print(ST.allfiles) print(time.time() - starttime)
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86531246
answers question: http://stackoverflow.com/q/49740521
type: Answer
accepted answer of: http://stackoverflow.com/q/49740521

http://stackoverflow.com/comment/86512148
type: Comment
has text: It's a pity. I thought C# value tuples were inspired by Python so the functionality is similar.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49748514

http://stackoverflow.com/q/49705941
accepted answer: http://stackoverflow.com/a/49709180
answer count: 1
has body: I need to compute a convolution product using the convolution theorem. However, I do not understand why I neeed to apply fftshift on the inverse fourier transform to get the correct result. Otherwise, the result is swapped (well, I know that is what fftshift is made for, but I don't understand why I obtain a swapped result from the inverse fft). Here is a minimal example with two functions that decrease quickly so that I do not add to bother with padding. The result is checked against scipy.signal.convolve: import numpy as np import scipy.signal as sig Nx = 400 xp = np.arange(Nx) - Nx/2. Lg = 20 Lb = 25 ff = np.exp(-(xp/Lg)**2) * xp/Lg # function (two bumps of opposite signs) gg = np.zeros(Nx) # convolution kernel (just a box) gg[abs(xp)&lt;Lb] = 1 conv_pure = sig.convolve(ff, gg, mode="same") # that is the correct one tff = np.fft.rfft(ff) # DFT of the function tfg = np.fft.rfft(gg) # DFT of the kernel conv_dfts = np.fft.irfft(tff*tfg).real # should be the convolution product conv_dftshift = np.fft.fftshift(conv_dfts) And here is how it looks like So, why is conv_dftsswapped ?
tagged with: scipy
favorite count: 0
tagged with: fft
type: Question
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86425396
has title: Why do I need to "fftshift" the product of DFTs to recover the convolution product
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49709180
upvote count: 1

http://stackoverflow.com/q/49724962
tagged with: python
accepted answer: http://stackoverflow.com/a/49725068
possible better answer: http://stackoverflow.com/a/49725157
has answer: http://stackoverflow.com/a/49725068
has title: Compare values in different columns
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49725157
has body: I have a df like this: Name Salary Age Cars Avg Salary Avg Age Avg Cars John 50000 35 1 60000 38 1 Tom 65000 45 3 60000 38 1 Some columns are better when the values are higher, whereas other columns are vice versa. So I created two lists higher_better = ['Salary', 'Cars'] lower_better = ['Age'] I want to compare them and return a score for them, so I define a new function like this: def compare_higher(a, b): return 1 if a &gt; b else 0 if a == b else -1 compare_higher(higher_better, lower_better) def compare_lower(b, a): return 1 if a &gt; b else 0 if a == b else -1 compare_lower(higher_better, lower_better) I want to create new columns for the comparison results, then I can add their score together. Ideal output as below: Name Salary Age Cars Avg Salary Avg Age Avg Cars Comp Salary Comp Age Comp Cars Score John 50000 35 1 60000 38 1 -1 1 0 0 Tom 65000 45 3 60000 38 1 1 -1 1 1 I have the pieces but don't know how to combine them. How do you compare the values in the columns and return them in new columns? Thank you for your help.
answer count: 2
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: dataframe

http://stackoverflow.com/comment/86242910
has text: Why ***two*** searches?
type: Comment
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49617782

http://stackoverflow.com/comment/86530719
type: Comment
type: AnswerComment
has text: @Kassandstorm if you want to put in the beginning then I would use 0, just for clarity.
comment on: http://stackoverflow.com/a/49757531
score: 0

http://stackoverflow.com/q/49752344
upvote count: 1
has comment: http://stackoverflow.com/comment/86519725
has comment: http://stackoverflow.com/comment/86521253
favorite count: 0
accepted answer: http://stackoverflow.com/a/49753369
has comment: http://stackoverflow.com/comment/86520719
type: AnsweredQuestion
has title: regex to match a line but don't include the string in output
has comment: http://stackoverflow.com/comment/86519245
score: 1
tagged with: python
has body: I am trying to parse SQL query join condition . I need to extract the line line which contains (+) and also group it based on extract . I am using python 3.6 Below are my test strings : 1. a.deptno = b.dept_no(+) 2. c.deptno(+)=b.dept_no 3. a.deptno(+)= 900 First : I need to extract lines which has (+) second : Need to extract the alias for example 1. a , b 2. c , b 3. a Till now I have tried regex Using ([\w_]+).*?([\w_]+)\(\+\) I am able to extract first group but second group seems to have some issue . Any advice will be really helpful
tagged with: regex
possible better answer: http://stackoverflow.com/a/49752906
has answer: http://stackoverflow.com/a/49753369
type: Question
has answer: http://stackoverflow.com/a/49752906
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/127608398
type: Comment
has text: This doesn't seem to work in my case. Also coming from R Studio. I removed the ALT + SHIFT + E option and replaced it with CTRL + enter, but doesn't behave as expected.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/58305322

http://stackoverflow.com/comment/86233276
comment on: http://stackoverflow.com/q/49611608
has text: @SzabolcsDombi I understand that so i also put the method inside use_model.py.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86400126
comment on: http://stackoverflow.com/q/49693803
score: 0
type: Comment
type: QuestionComment
has text: What is the possible content of your string? Is username always the part after the last slash?

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

http://stackoverflow.com/comment/86315765
score: 0
has text: I am already able to count the number of objects using cv2.findContours but I can't use this information to calculate the area and perimeter of each object.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49653146

http://stackoverflow.com/q/49739478
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86494824
has comment: http://stackoverflow.com/comment/86514852
type: UnansweredQuestion
tagged with: standards
linked to: http://stackoverflow.com/q/11130156
downvote count: 0
tagged with: python
tagged with: standard-library
has comment: http://stackoverflow.com/comment/86495226
has comment: http://stackoverflow.com/comment/86494410
has comment: http://stackoverflow.com/comment/86493962
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/11130156
answer count: 0
has title: Standard write-only dummy file-like Python object
score: 1
has comment: http://stackoverflow.com/comment/86493550
has comment: http://stackoverflow.com/comment/86494337
has comment: http://stackoverflow.com/comment/86493783
has comment: http://stackoverflow.com/comment/86511616
has comment: http://stackoverflow.com/comment/86494677
upvote count: 1
has comment: http://stackoverflow.com/comment/86494626
has body: [EDIT] It is not important why I do want to have a dummy of writeable file-like object, but I would like to avoid unnecessary possibility of a memory leak io.StringIO. Is there any standard (preferably stl, but any widely accepted by the community will do) implementation of such object? According to Does the same answer imply that the questions should be closed as duplicate? the question is not a duplicate of Suppress stdout / stderr print from Python functions as it is about a standard dummy object, not about the suppression of stderr. Such object may be useful also for mocking etc. Indeed, one of the answers there (linking to NullDevice) is compatible with my present solution.

http://stackoverflow.com/comment/86427389
type: AnswerComment
has text: @user40 - Do you think year with month? like `2016-01` ? Or `month`s only without `year`s only?
type: Comment
comment on: http://stackoverflow.com/a/49706980
score: 0

http://stackoverflow.com/comment/86470745
type: AnswerComment
comment on: http://stackoverflow.com/a/49728252
type: Comment
has text: Thank you for your answer. However, I have several more unicodes. \u20132, \u20136, \u00e4 etc. Should I parse every \u things to read it? Thanks.
score: 0

http://stackoverflow.com/q/49601479
tagged with: python-3.x
has title: proper exec command formatting
accepted answer: http://stackoverflow.com/a/49603793
has body: I've got this program to test the behaviour of a exec() function before putting it in My program. I was expecting that in the end I will receive a number represented by b="last_trade_id"(13621701 in the case shown bellow) but all I get is None or ost_tranzakcja { "last_trade_id": 13621701, "product_id": "BTC-EUR", "sequence": 3542855617, "time": "2018-04-01T18:38:32.455000Z", "type": "heartbeat" } printed [a] before exec: ost_tranzakcja printed [a] after exec: ost_tranzakcja printed [a] after modified exec: None printed [a] after local exec: None printed [a] after modified local exec: None printed [a]without and after exec: : None Heres the program I've used for testing: import time import json from websocket import create_connection ws=create_connection("wss://ws-feed.gdax.com") ws.send(json.dumps({"type": "subscribe", "channels": [{"name": "heartbeat", "product_ids": ["BTC-EUR"],}]})) def KonektorWebsocket(): dane=ws.recv() dane=json.loads(dane) print(json.dumps(dane, indent=4, sort_keys=True)) a='ost_tranzakcja' b="last_trade_id" exec("print('printed [a] before exec:', a)") exec("a=dane.get('"+ b +"', None)") exec("print('printed [a] after exec:', a)") a=exec("dane.get('"+ b +"', None)") exec("print('printed [a] after modified exec:', a)") exec("a=dane.get('"+ b +"', None)",locals()) exec("print('printed [a] after local exec:', a)") a=exec("dane.get('"+ b +"', None)",locals()) exec("print('printed [a] after modified local exec:', a)") print("printed [a]without and after exec: ", a) while True: KonektorWebsocket() time.sleep(0.15)
has answer: http://stackoverflow.com/a/49603793
tagged with: python
has answer: http://stackoverflow.com/a/49612423
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49612423
type: Question

http://stackoverflow.com/a/49704292
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49704283
downvote count: 0
has comment: http://stackoverflow.com/comment/86423884
has comment: http://stackoverflow.com/comment/86423721
score: 3
has comment: http://stackoverflow.com/comment/86424479
type: Answer
has body: You need filter first by between: ageDataFrame = (data[data.Date.dt.year.between(2010, 2015)] .groupby(['Region', data.Date.dt.year]) .agg(ageAverage)) Also in last version of pandas 0.22.0 get: SpecificationError: cannot perform renaming for age with a nested dictionary Correct solution is specify column in list after groupby and aggregate by tuple - first value is new column name and second aggregate function: np.random.seed(123) rng = pd.date_range('2009-04-03', periods=10, freq='13M') data = pd.DataFrame({'Date': rng, 'Region':['reg1'] * 3 + ['reg2'] * 7, 'average age': np.random.randint(20, size=10)}) print (data) Date Region average age 0 2009-04-30 reg1 13 1 2010-05-31 reg1 2 2 2011-06-30 reg1 2 3 2012-07-31 reg2 6 4 2013-08-31 reg2 17 5 2014-09-30 reg2 19 6 2015-10-31 reg2 10 7 2016-11-30 reg2 1 8 2017-12-31 reg2 0 9 2019-01-31 reg2 17 ageAverage = {('age','mean')} #groupby and apply functions ageDataFrame = (data[data.Date.dt.year.between(2010, 2015)] .groupby(['Region', data.Date.dt.year])['average age'] .agg(ageAverage)) print (ageDataFrame) age Region Date reg1 2010 2 2011 2 reg2 2012 6 2013 17 2014 19 2015 10
has comment: http://stackoverflow.com/comment/86421904
accepted answer of: http://stackoverflow.com/q/49704283
has comment: http://stackoverflow.com/comment/86424484

http://stackoverflow.com/a/49713166
type: Answer
answers question: http://stackoverflow.com/q/49713058
has body: In Python string literals, the backslash character has special meaning and is called the escape character. It is used to prefix what is called an 'escape sequence'. For example, \n is an escape sequence that inserts a newline character into your string. You can find out more about these sequences here: string-and-bytes-literals. Sometimes like in your case, you want your string literal to include the actual backslash character. To do that you have to escape the backslash with another backslash like this: "\\". This results in a string containing a single backslash character, which is what you're observing. If you don't want to have to insert double backslashes into all of your file paths, you can do what @138 suggested and use a raw string literal (prefixed with r: r'Raw string'). Raw string literals ignore anything that looks like an escape sequence, and treat each character as its literal value.
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/49737737
has comment: http://stackoverflow.com/comment/86489920
has comment: http://stackoverflow.com/comment/86489898
has body: As mentioned, you can use pd.melt combined with pd.merge. Just remember to reset_index to promote your index to a column, and then to align column names. df1 = pd.melt(df.reset_index(), id_vars=df.index.name)\ .rename(columns={'variable': 'Date'}) res = pd.merge(df2, df1, how='left') # PN Date value # 0 90020 2017-11-01 105.0 # 1 90020 2017-11-02 105.0 # 2 90061 2017-11-01 -3.0 # 3 90065 2017-11-02 30.0 # 4 94008 2017-11-03 NaN To maintain df2 index: res = df2.reset_index()\ .merge(df1, how='left')\ .set_index('index') # PN Date value # index # 4 90020 2017-11-01 105.0 # 9 90020 2017-11-02 105.0 # 12 90061 2017-11-01 -3.0 # 13 90065 2017-11-02 30.0 # 17 94008 2017-11-03 NaN
accepted answer of: http://stackoverflow.com/q/49737588
type: Answer
answers question: http://stackoverflow.com/q/49737588
score: 4
upvote count: 4
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49638005
has comment: http://stackoverflow.com/comment/86284499
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49638648
tagged with: cnc
tagged with: python
has body: Here's a summary of my setup: 3 axis CNC, controllable via a python script running on raspberry pi Windows PC can connect to the pi can run a script The end goal is for a UI made in C# to initiate an automated test cycle for the CNC to run in. In the python program there is a Cnc object that stores the devices current position and contains methods to position it to a certain place. The problem is if i run a new script every time i want to move the CNC, I have to re initialize the Cnc instance and it will forget it's position. So I'm wondering if I can have one master program running that contains the one and only Cnc instance, then when the remote machine wants to tell the CNC to move it can run a different script with argz for the new position python action.py x y z. This script could then communicate to the master program to call the move method to the appropriate location without ever having to re-construct a new Cnc object. Then ideally the master program would indicate when the motion is completed and send back a message to the "action" script, that script would output something to tell the remote system that the action is completed, then it would exit, ready to be called again with new argz. In the end the remote system is highly abstracted from any of the working and just needs to start running the master, then run the move script with argz any time it wants to perform a motion. Note: My other idea was to just save a text file with the current position then always re initialize the instance with the info in the file. EDIT: SOLVED... sort of handler.py The handler will continuously read from a text file named input.txt looking for a new integer. If received it will update a text file named output.txt to read '0', then do some action with the input (i.e move a cnc) then write the value '1' to output.txt. from time import sleep cur_pos=0 while True: with open("input.txt","r") as f: pos=f.readline() try: if pos=='': pass else: pos=int(pos) except: print pos print…
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86285473
tagged with: ssh
has answer: http://stackoverflow.com/a/49638153
has answer: http://stackoverflow.com/a/49680315
has title: Communicating between multiple python programs running in parallel
has comment: http://stackoverflow.com/comment/86283839
has comment: http://stackoverflow.com/comment/86288879
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/q/49727453
has title: Celery Flask Database Connection Error
type: Question
has comment: http://stackoverflow.com/comment/86468803
answer count: 0
has body: I want to access my postgresql database from my celery worker. Since I'm using factory pattern, I used https://github.com/mattupstate/overholt/blob/master/overholt/factory.py this link to create my celery worker. I'm using celery -A xyz.jobs worker command to start my celery worker. jobs.py file: from xyz.models.user import User from xyz.app import create_celery_app celery = create_celery_app() @celery.task() def do_some_stuff(): print(User.get_all()) When I call this task from one of my endpoints, I get the following error: [2018-04-09 10:21:39,530: ERROR/ForkPoolWorker-8] Task xyz.jobs.do_some_stuff[b3a71e41-2335-470f-89b8-f4844c6eba1c] raised unexpected: AttributeError("'NoneType' object has no attribute 'drivername'",) Traceback (most recent call last): File "/Users/user/Documents/celeryTest/xyz_backend/venv/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 999, in __call__ return self.registry[key] KeyError: 4320768832 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/user/Documents/celeryTest/xyz_backend/venv/lib/python3.6/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/Users/user/Documents/celeryTest/xyz_backend/xyz/app.py", line 30, in __call__ return TaskBase.__call__(self, *args, **kwargs) File "/Users/user/Documents/celeryTest/xyz_backend/venv/lib/python3.6/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/Users/user/Documents/celeryTest/xyz_backend/xyz/jobs.py", line 10, in do_some_stuff print(User.get_all()) File "/Users/user/Documents/celeryTest/xyz_backend/xyz/models/__init__.py", line 47, in get_all return db.session.query(cls).filter_by(**kwargs).all() File "/Users/user/Documents/celeryTest/xyz_backend/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 153, in do return getattr(self.registry(), name)(*args, **kwargs) File "/Users/user/Documents…
has comment: http://stackoverflow.com/comment/86468911
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86468675
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86469071
has comment: http://stackoverflow.com/comment/86469057
tagged with: flask
tagged with: flask-sqlalchemy
tagged with: celery
favorite count: 0
has comment: http://stackoverflow.com/comment/86469224
has comment: http://stackoverflow.com/comment/86469086
has comment: http://stackoverflow.com/comment/86469182
score: 1
tagged with: sqlalchemy

ajax
tags question: http://stackoverflow.com/q/49746131
tags question: http://stackoverflow.com/q/49668987
type: Tag
tags question: http://stackoverflow.com/q/49710766
tags question: http://stackoverflow.com/q/49751784
tags question: http://stackoverflow.com/q/49718302
tags question: http://stackoverflow.com/q/49738321
tag name: ajax
tags question: http://stackoverflow.com/q/49635819

http://stackoverflow.com/a/49626304
has body: A (not very elegant) solution is to give all categorical datas to sns.swarmplot import seaborn as sns import numpy as np y = np.random.randint(5,size = 40) time = np.repeat([1,2,3,100],10) # now add more categorical datas time_all = np.append(time, np.arange(1,101)) y_all = np.append(y, np.nan*np.arange(100)) sns.swarmplot(time_all,y_all) # hide all the ticks that are not wanted plt.x_ticks([1,2,3,100],[1,2,3,100])
type: Answer
answers question: http://stackoverflow.com/q/49626091
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86273047
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49632641
has text: @xg.plt.py Yeah they start with #
type: QuestionComment

http://stackoverflow.com/a/62651115
answers question: http://stackoverflow.com/q/49643793
score: 0
has body: I also like to take advantage of the fact that you do not have to compile Python source and use plain Python files for configuration. But in the real world you may have multiple environments, each requires a different configuration, and you may also want to read some (mostly sensitive) information from env vars or files that are not in source control (to prevent committing those by mistake). That's why I wrote this library: https://github.com/davidohana/kofiko, which let you use plain Python files for configuration, but is also able to override those config settings from .ini or env-vars, and also support customization for different environments. Blog post about it: https://medium.com/swlh/code-first-configuration-approach-for-python-f975469433b9
type: Answer

http://stackoverflow.com/a/49679723
downvote count: 0
has comment: http://stackoverflow.com/comment/86374643
has comment: http://stackoverflow.com/comment/86403777
score: 3
accepted answer of: http://stackoverflow.com/q/49679643
type: Answer
answers question: http://stackoverflow.com/q/49679643
has body: &gt;&gt;&gt; di = {'key1': [1,200], 'key2':[1,100]} &gt;&gt;&gt; di {'key1': [1, 200], 'key2': [1, 100]} &gt;&gt;&gt; di['key1'][0] += 1 &gt;&gt;&gt; di['key1'][1] += 150 &gt;&gt;&gt; di {'key1': [1, 300], 'key2': [1, 100]} &gt;&gt;&gt; So looking at the above example you can see that it is first accessing the key then the index in the array and setting it to a new value. di['key1'][0] += 1 is incrementing it by 1 di['key1'][1] += 150 is adding the new value
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/86400884
type: Comment
type: QuestionComment
score: 0
has text: Are those lists of strings? or one big string that has brackets on the ends?
comment on: http://stackoverflow.com/q/49693758

http://stackoverflow.com/q/49723594
tagged with: python
has answer: http://stackoverflow.com/a/49724618
type: Question
has body: A noob question (revised): I read in a .csv file and I tried to specify dtypes as in the following: import csv import pandas as pd cdc = pd.read_csv('myFile.csv', dtype = { 'Phenotype': str, 'State': str, 'EventType': str, 'EventYear': str, 'AgeCategory': str, 'NumberTested' : str, 'NumberResistant': str, 'PercentResistant': str }) But after reading the df file, I get: df.dtypes Phenotype object State object EventType object EventYear object AgeCategory object NumberResistant object PercentResistant object dtype: object I thought instead I'd get dtypes of string for each column. I'd like each column to be read as a string because some columns have a mixture of numbers and strings as you'll see below in the .csv example file. Once the file is read in I can start manipulating the gosh darn thing! Bottom line: I want to clean up the data rows and replace "None Tested" and "Not Defined" with NaNs or zeroes. I can't do that with 'objects,' that I can figure out, anyway. FYI, I've read in the .csv as a df with no 'dtype' parameter but I get the same problem. After reading the file with no dtypes specfied, I tried creating a new column of integers from existing columns, but the 'object' dtype seems to get in the way of that, too. I'm stuck. I've looked around and I can't seem to figure this out myself. Sample input .csv file here: (there are no extra lines between rows, I just tried to make the rows more readable) Phenotype,State,EventType,EventYear,AgeCategory,NumberTested,NumberResistant,PercentResistant Acinetobacter,AK,All HAIs,2011, 1-18,2,1,0.5 Acinetobacter,AK,CAUTI,2011, 1-18,0,None Tested,Not Defined Acinetobacter,AK,CLABSI,2011, 1-18,0,None Tested,Not Defined Acinetobacter,AK,SSI,2011, 1-18,0,None Tested,Not Defined Acinetobacter,AK,All HAIs,2011,&lt;1,2,2,1.0 Acinetobacter,AK,CAUTI,2011,&lt;1,0,None Tested,Not Defined Acinetobacter,AK,CLABSI,2011,&lt;1,0,None Tested,Not Defined Acinetobacter,AK,SSI,2011,&lt;1,0,None Tested,Not Defined Acinetobacter,AK,All HAIs,2…
has comment: http://stackoverflow.com/comment/86461297
linked to: http://stackoverflow.com/q/43992806
has comment: http://stackoverflow.com/comment/86461441
upvote count: 2
score: 2
linked to: http://stackoverflow.com/q/33957720
tagged with: pandas
has comment: http://stackoverflow.com/comment/86464374
has title: I can't seem to specify column dtypes when reading in a .csv file
has comment: http://stackoverflow.com/comment/86462642
duplicate of: http://stackoverflow.com/q/33957720
has comment: http://stackoverflow.com/comment/86460885
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86462675
favorite count: 0
has comment: http://stackoverflow.com/comment/86464121
has comment: http://stackoverflow.com/comment/86464398
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/41143969
has comment: http://stackoverflow.com/comment/86462632
has comment: http://stackoverflow.com/comment/86461255

http://stackoverflow.com/q/49749000
accepted answer: http://stackoverflow.com/a/49749168
tagged with: python
tagged with: stock
has answer: http://stackoverflow.com/a/49749168
has title: How to change the domain of the Many2one field by inheritance?
score: -1
tagged with: odoo-11
type: AnsweredQuestion
downvote count: 2
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: What I mean is that; Model with name "stock.return.picking" has "location_id" field. When I click on the return button , I want to see all the location_id. But location_id has domain: location_id = fields.Many2one( comodel_name='stock.location', string='Return Location', domain="['|', ('id', '=', original_location_id),'&amp;', ('return_location', '=', True), ('id', 'child_of', parent_location_id)]" ) How can I change this domain?
type: Question
tagged with: odoo

http://stackoverflow.com/a/49712379
has comment: http://stackoverflow.com/comment/86440179
answers question: http://stackoverflow.com/q/49710734
score: 0
has body: I fixed that by making my own function which compares each pixel before subtracting it to prevent any overflow from occuring. def custom_sub(i2,i1): x = len(i1) y = len(i1[0]) o = deepcopy(i1) for ix in range(x): for iy in range(y): if i1[ix][iy] &gt; i2[ix][iy]: o[ix][iy] = 0 else: o[ix][iy] = i2[ix][iy]-i1[ix][iy] return o This is the output, bright regions now only where the spark flash is occurring. This question is similiar to mine. Subtraction in my case was performed with uint8 type, this can be converted to int16. Resulting picture can then be iterated over and any negative number removed.
type: Answer

http://stackoverflow.com/comment/86525515
has text: Are the negative signs always preceded and followed by a +. What if you have (+---+++) Do you want remove all pairs leave (+) or just remove those - next to a positive leaving (-++)? I think you need a more extensive testing set and expected outputs.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49753762

http://stackoverflow.com/comment/86342200
has text: @RehanAzher This might be what I'm looking for, I'll have to study it thanks
score: 0
comment on: http://stackoverflow.com/q/49666050
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86496869
type: Comment
comment on: http://stackoverflow.com/q/49740628
score: 0
type: QuestionComment
has text: i had point to 3.5 in bashrc

http://stackoverflow.com/q/49639586
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86317838
linked to: http://stackoverflow.com/q/43117659
type: UnansweredQuestion
has title: pass arguments to __init__ for pipelines in scrapy
has comment: http://stackoverflow.com/comment/86321348
has comment: http://stackoverflow.com/comment/86317467
tagged with: python
has comment: http://stackoverflow.com/comment/86287312
has comment: http://stackoverflow.com/comment/86320039
has comment: http://stackoverflow.com/comment/86317148
score: 0
has comment: http://stackoverflow.com/comment/86317604
has body: I know there is a way to do this using the following example, taken from this question (also based on the documentation): class MongoPipeline(object): collection_name = 'scrapy_items' def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') ) However as far as I know, this takes those values from a settings file. In my case, I must use it as an argument, since it is an arbitrary string provided by the user, so it won't be in any file. This situation is similar to this question. Nevertheless I also need to use the argument during the __init__ method since my pipeline is inheriting from another arbitrary class which needs this parameter, so the workaround provided for this second question (which was just to pass arguments inside the spider), but this won't work for me (since I need it in the __init__). To clarify, my situation is the following: class Foo(): # this class is not a pipelines, # it is just an arbitrary class which manages the connections with the databases def __init__(self, foo: str): self.foo=foo class MyPipieline(Foo): def __init__(self, foo: str): Foo.__init__(foo) Where foo is a string provided by the user, so it can't be read from a file. Is there a way to achieve this? EDIT Just to clarify: the foo parameter is provided by the user at the invocation of the script, so my main is something like that: parser = argparse.ArgumentParser(description='My main script') # Add arguments parser.add_argument('-f', '--foo', type=str, required=True) args = parser.parse_args() foo = args.foo # Here I have the foo value I want to use in pipeline's __init__ process = CrawlerProcess(get_project_settings()) process.crawl(MySpider) process.start()
upvote count: 1
has answer: http://stackoverflow.com/a/49650183
linked to: http://stackoverflow.com/q/27513707
answer count: 1
tagged with: scrapy
downvote count: 1
has comment: http://stackoverflow.com/comment/86321915
favorite count: 0
type: Question

http://stackoverflow.com/comment/86258437
type: Comment
score: 0
type: AnswerComment
has text: I see. [Click here for more info on speedup on non-gpu setups](https://stackoverflow.com/questions/43143003/how-can-i-speed-up-deep-learning-on-a-non-nvidia-setup)
comment on: http://stackoverflow.com/a/49624210

masking
tag name: masking
tags question: http://stackoverflow.com/q/49670832
type: Tag

http://stackoverflow.com/comment/86386434
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49652707
has text: The error message says it: "can't multiply sequence by non-int of type 'float'", hence this multiplication doesn't do what you think.
type: Comment

http://stackoverflow.com/q/49673723
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86358357
tagged with: python
has comment: http://stackoverflow.com/comment/86358797
has comment: http://stackoverflow.com/comment/86358413
has comment: http://stackoverflow.com/comment/86359392
has comment: http://stackoverflow.com/comment/86358866
has comment: http://stackoverflow.com/comment/86358680
has comment: http://stackoverflow.com/comment/86359587
has answer: http://stackoverflow.com/a/49673987
has comment: http://stackoverflow.com/comment/86359474
has comment: http://stackoverflow.com/comment/86358547
has title: Making imported modules or imported methods in single file module private
has comment: http://stackoverflow.com/comment/86358432
score: 2
has comment: http://stackoverflow.com/comment/86359027
downvote count: 0
answer count: 1
has body: When I have a single file module relying on a 3rd party module or method from a 3rd party module which is imported in the single file module, then I have access to the 3rd party module or method when I import the single file module. I want to prevent that, my suggestion was to import the 3rd party module or method and renaming them with an underscore in front. Would that be a good idea, what other options do I have. Example 1: # this is a single file module called DemoModule.py import numpy as np def calculate_something(): x = np.cos(0) return x Now when I import DemoModule I do not only have access to calculate_something, but I also have access to everything numpy has to offer as well. Would this be a good way to avoid that situation: # this is a single file module called DemoModule.py import numpy as _np def calculate_something(): x = _np.cos(0) return x Example 2: # this is a single file module called DemoModule.py from numpy import cos def calculate_something(): x = cos(0) return x Now when I import DemoModule I do not only have access to calculate_something, but I also have access to cos. Would this be a good way to avoid that situation: # this is a single file module called DemoModule.py from numpy import cos as _cos def calculate_something(): x = _cos(0) return x Edit: A run from the command line In[2]: import DemoModule In[3]: DemoModule.np.cos(1) Out[3]: 0.54030230586813977
has comment: http://stackoverflow.com/comment/86361077
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86359175
has comment: http://stackoverflow.com/comment/86358307
linked to: http://stackoverflow.com/q/28766414
has comment: http://stackoverflow.com/comment/86358380

http://stackoverflow.com/comment/86239566
has text: df.groupby('id').max()
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49616277
score: 3

http://stackoverflow.com/comment/86462632
score: 0
comment on: http://stackoverflow.com/q/49723594
type: QuestionComment
has text: "...strings will be stored as objects as strings do not have a fixed length" That's helpful, I'll keep looking along those lines, but i've had no love trying to cast an 'object' to an 'int'. It seems to work in-line, but once I get out of that code block, the value is back to an object!
type: Comment

http://stackoverflow.com/a/49645385
answers question: http://stackoverflow.com/q/49645296
upvote count: 3
downvote count: 0
score: 3
type: Answer
has body: Use pd.DataFrame.assign unpacking the dictionary into keyword arguments. df1.assign(**my_dict) c1 c2 c3 c4 c5 0 1 2 3 4 5

http://stackoverflow.com/q/49644114
type: Question
has title: Remove duplicate of dict list
accepted answer: http://stackoverflow.com/a/49644227
has comment: http://stackoverflow.com/comment/86295901
has comment: http://stackoverflow.com/comment/86295952
has body: How can I remove duplicates from the dict list below, while summing up the corresponding values thanks {'VIC': [['City West ', 10.0], ['City West ', 30.0], ['Thornbury ', 0.0]], 'NSW': [['Queanbeyan ', 5.0],['Queanbeyan ', 20.0]], 'ACT': [['Civic ', 8.0], ['Civic ', 60.0], ['Civic ', 1.0]]} Desired output {'VIC': [['City West ', 40.0], ['Thornbury ', 0.0]], 'NSW': 'Queanbeyan ', 25.0, 'ACT': 'Civic ', 69.0}
has answer: http://stackoverflow.com/a/49644227
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86295900
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49644407
answer count: 3
score: 0
possible better answer: http://stackoverflow.com/a/49644318
has answer: http://stackoverflow.com/a/49644318

http://stackoverflow.com/a/49716495
has body: Ok, found the problem! The settings are correct, the problem was that for some reason I was using a custom storage for my FileField! All I had to do was removing the storage=...: file = models.FileField(upload_to=some_path, storage=CustomStorage()) to file = models.FileField(upload_to=some_path)
accepted answer of: http://stackoverflow.com/q/49715802
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/121449567
answers question: http://stackoverflow.com/q/49715802
score: 2

http://stackoverflow.com/a/49601633
score: 0
has comment: http://stackoverflow.com/comment/86210803
has comment: http://stackoverflow.com/comment/86210744
answers question: http://stackoverflow.com/q/49601575
type: Answer
has comment: http://stackoverflow.com/comment/86210884
has body: You can try django debug toolbar. There are many option to track requests. Pretty sure you will find something.

http://stackoverflow.com/comment/86221729
comment on: http://stackoverflow.com/a/49607280
score: 0
type: Comment
type: AnswerComment
has text: Yes I use this sorted = df.sort_values(['Id1', 'Id2', 'Id3', 'Id4'], ascending=False), but values don't sorting correct. For ex. here is true (Ip)10.10.8.30 (id1)10782 (id2)18156 (id3)NaN (id)NaN, because id1 < id2, but here )ip)10.10.12.48 (id1)18171 (id)10724 (id3)NaN (id4)NaN, sort does not work, because id1 is not < id2

http://stackoverflow.com/comment/86295127
type: QuestionComment
has text: What do you mean by "print the variable names"? Can you give a [mcve], including simple `argparse` code , and a sample command line, and what you'd like to print out for that command line?
score: 2
comment on: http://stackoverflow.com/q/49643749
type: Comment

http://stackoverflow.com/comment/86301089
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49646424
has text: I have edited these out but they are still in the history.

http://stackoverflow.com/a/49643916
answers question: http://stackoverflow.com/q/49643676
has body: Even if the to find elements are not the maxima but for example randomly chosen, we can still use argmax on a==b. Example: # generate random data &gt;&gt;&gt; n = 10 &gt;&gt;&gt; a = np.round(np.random.random((n, n)), 1) &gt;&gt;&gt; a array([[0.3, 0.2, 0.2, 0.4, 0.1, 0.6, 0.8, 0.9, 0.8, 0.1], [0.7, 1. , 0.1, 0.1, 0.4, 1. , 0.7, 0.8, 0.6, 0.5], [0.1, 0.5, 1. , 0.4, 0.6, 0.8, 0.9, 0.3, 0.2, 0.4], [0.2, 0.6, 0.2, 0. , 0.7, 0.8, 0.9, 0.6, 0. , 0.1], [0.4, 0. , 0.8, 0.2, 0.1, 0.8, 0.2, 0.6, 0.1, 0. ], [0.1, 0.2, 0.4, 0.4, 0. , 0.6, 0.6, 0.9, 0.6, 0.3], [0.9, 1. , 0.8, 0.8, 0.3, 0.5, 0.5, 0.2, 0.4, 0.7], [0.5, 0.5, 0.2, 0.8, 0.8, 0.1, 0.7, 0.5, 0.9, 0.5], [0. , 0.4, 0.5, 0.5, 0.6, 0.2, 0.5, 0.9, 0.6, 0.9], [0.8, 0.5, 0.1, 0.9, 0.7, 0.1, 0.8, 0. , 0.9, 0.8]]) # randomly pick an index each column &gt;&gt;&gt; choice = np.random.randint(0, n, (n,)) &gt;&gt;&gt; # retrieve values at chosen locations &gt;&gt;&gt; b = a[choice, range(n)] &gt;&gt;&gt; b array([0.4, 0.2, 0.8, 0.4, 0.6, 0.6, 0.8, 0.9, 0.6, 0.5]) &gt;&gt;&gt; # now recover `choice`, or if the same as the chosen value occurs # earlier in that column return the index of the first occurrence. &gt;&gt;&gt; recover = np.argmax(a==b, axis=0) &gt;&gt;&gt; recover array([4, 0, 4, 0, 2, 0, 0, 0, 1, 1]) &gt;&gt;&gt; # check result: &gt;&gt;&gt; recover &lt;= choice array([ True, True, True, True, True, True, True, True, True, True]) &gt;&gt;&gt; a[recover, range(n)] == b array([ True, True, True, True, True, True, True, True, True, True]) As a nice little bonus this takes advantage of the fact that max/argmax short-ciruits on booleans (a==b is, however, still evaluated everywhere): &gt;&gt;&gt; timeit('np.argmax(x)', globals={'np': np, 'x': np.ones(1000000, bool)}, number=100000) 0.10291801800121902 &gt;&gt;&gt; timeit('np.argmax(x)', globals={'np': np, 'x': np.zeros(1000000, bool)}, number=100000) 4.172021539001435
type: Answer
score: 0

http://stackoverflow.com/q/49670832
tagged with: masking
tagged with: lstm
has comment: http://stackoverflow.com/comment/137907567
has title: Keras lstm with masking layer for variable-length inputs
answer count: 1
downvote count: 0
tagged with: keras
accepted answer: http://stackoverflow.com/a/49679189
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86386038
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49679189
has body: I know this is a subject with a lot of questions but I couldn't find any solution to my problem. I am training a LSTM network on variable-length inputs using a masking layer but it seems that it doesn't have any effect. Input shape (100, 362, 24) with 362 being the maximum sequence lenght, 24 the number of features and 100 the number of samples (divided 75 train / 25 valid). Output shape (100, 362, 1) transformed later to (100, 362 - N, 1). Here is the code for my network: from keras import Sequential from keras.layers import Embedding, Masking, LSTM, Lambda import keras.backend as K # O O O # example for N:3 | | | # O O O O O O # | | | | | | # O O O O O O N = 5 y= y[:,N:,:] x_train = x[:75] x_test = x[75:] y_train = y[:75] y_test = y[75:] model = Sequential() model.add(Masking(mask_value=0., input_shape=(timesteps, features))) model.add(LSTM(128, return_sequences=True)) model.add(LSTM(64, return_sequences=True)) model.add(LSTM(1, return_sequences=True)) model.add(Lambda(lambda x: x[:, N:, :])) model.compile('adam', 'mae') print(model.summary()) history = model.fit(x_train, y_train, epochs=3, batch_size=15, validation_data=[x_test, y_test]) my data is padded at the end. example: &gt;&gt; x_test[10,350] array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32) The problem is that the mask layer seems to have no effect. I can see it with the loss value being printed during training which is equal to the one without mask I calculate after: Layer (type) Output Shape Param # ================================================================= masking_1 (Masking) (None, 362, 24) 0 _________________________________________________________________ lstm_1 (LSTM) (None, 362, 128) 78336 _________________________________________________________________ lstm_2 (LSTM) (None, 362, 64) 49408 _________________________________________________________________ lstm_3 (LSTM) (None, 362, 1) 264 ____________________________________…
has comment: http://stackoverflow.com/comment/86370204
score: 18
tagged with: python
has comment: http://stackoverflow.com/comment/86364837
has comment: http://stackoverflow.com/comment/109789175
upvote count: 18

http://stackoverflow.com/a/58466827
has body: Hello Everyone Let me show you how to Write State of the art descriptors using Python Meta class, How to Perform Validation on them. and How to define your Own Datatype with Metaclass __Author__ = "Soumil Nitin SHah " __Version__ = "0.0.1" __Email__ = ['soushah@my.bridgeport.edu',"shahsoumil519@gmail.com"] __Github__ = "https://github.com/soumilshah1995" Credits = """ Special Thanks to David Beazley for his Tutorials """ from inspect import Parameter, Signature import datetime class Descriptor(object): def __init__(self, name): self.name = name def __get__(self, instance, owner): print(" __get__ ") return instance.__dict__[self.name] # This will return Value # if instance is not None: # return self # else: # return instance.__dict__[self.name] def __set__(self, instance, value): print(" __set__ ") instance.__dict__[self.name] = value def __delete__(self, instance): print(" __delete__ ") del instance.__dict__[self.name] def __repr__(self): return "Object Descriptor : {}".format(self.name) class Typed(Descriptor): ty = object def __set__(self, instance, value): if not isinstance(value, self.ty): raise TypeError('Expected %s' % self.ty) super().__set__(instance, value) class PositiveInterger(Descriptor): def __set__(self, instance, value): if value &lt; 0: raise ValueError ("Value cannot be less than 0") class Sized(Descriptor): def __init__(self, *args, maxlen, **kwargs): self.maxlen = maxlen super().__init__(*args, **kwargs) def __set__(self, instance, value): if len(value) &gt; self.maxlen: raise ValueError('Too big') super().__set__(instance, value) def make_signature(names): return Signature( Parameter(name, Parameter.POSITIONAL_OR_KEYWORD) for name in names) class Integer(Typed): ty = int class Float(Typed): ty = float class String(Typed): ty = str class StructMeta(type): def __new__(cls, clsname, base, clsdict): clsobj = super().__new__(cls, clsname, base, clsdict) sig = make_signature(clsobj._fields) # print("Sig", sig) setattr(clsobj, '__signature__', sig) ret…
answers question: http://stackoverflow.com/q/49705827
score: 0
type: Answer

http://stackoverflow.com/comment/86310656
comment on: http://stackoverflow.com/q/49651170
type: Comment
type: QuestionComment
has text: @jpp Median values!
score: 1

http://stackoverflow.com/comment/86488996
type: Comment
has text: @meowgoesthedog, I trimmed down the code as much as I could. Would you please, now let me find some help?
type: QuestionComment
comment on: http://stackoverflow.com/q/49724370
score: 0

http://stackoverflow.com/comment/86325151
type: AnswerComment
has text: For instance, when I was inspecting the source code for this question, I saw this: `href="/users/4343502/touch-my-boom-boom"`. This link on it's own isn't a website, but if you add `https://www.stackoverflow.com` to the front it becomes valid.
type: Comment
comment on: http://stackoverflow.com/a/49654858
score: 0

http://stackoverflow.com/comment/86403905
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49695477
has text: What do you mean by "specific characters"?

http://stackoverflow.com/comment/86456569
has text: Sample sizes? Have you tried with different train/val/test splits? What is your task and data like?
type: Comment
comment on: http://stackoverflow.com/q/49721691
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86307758
comment on: http://stackoverflow.com/q/49646879
score: 0
type: Comment
type: QuestionComment
has text: You can guess R0/R from the maximum value and L*C from its position. From the slope at small frequencies you get L/R0 etc.

http://stackoverflow.com/comment/86343373
comment on: http://stackoverflow.com/a/49666485
type: Comment
score: 0
type: AnswerComment
has text: @Vinny Yes, and I'm pretty sure it's _deliberate_ that this looks wrong. Python is forcing you to highlight to the reader that you're doing something weird by making it look weird. (Compare to Tcl, where this would be perfectly idiomatic, and… that's part of the reason we're using Python right now instead of Tcl.)

http://stackoverflow.com/a/49613345
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86242658
downvote count: 1
has comment: http://stackoverflow.com/comment/86236453
answers question: http://stackoverflow.com/q/49612908
type: Answer
has body: Unless this metric is already implemented in CNTK, implement your own custom "metric" function in whatever format CNTK requires, and have it pass the inputs on to scikit-learn's metric function.
has comment: http://stackoverflow.com/comment/86235993

http://stackoverflow.com/q/49741733
has comment: http://stackoverflow.com/comment/86498057
has comment: http://stackoverflow.com/comment/86498182
has comment: http://stackoverflow.com/comment/86498136
score: 0
has title: Detecting codes within a certain alphabetical sequence
has body: I work with language codes, especially with the ISO 639-3 standard, which uses three letter codes to represent languages (eng for English, jpn for Japanese, etc). However, codes in the range of qaa–qtz are not proper language codes but are just empty ones that the user has to define.So, qaa, qab...qaz, qba, and so on. I was wondering how to write code that would be able to detect if a code is part of this series? In these codes, the last letter goes all the way through a-z, then starts at a new sequence in the second letter. Kind of like a three digit number, except instead of 0-9 digits, it's a-z letters.
has comment: http://stackoverflow.com/comment/86505305
has comment: http://stackoverflow.com/comment/86503900
answer count: 1
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49741816
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49699969
type: UnansweredQuestion
tagged with: amazon-ec2
answer count: 1
downvote count: 0
has title: Datadog: ERROR:ddtrace.writer:cannot send services to localhost:8126: [Errno 111] Connection refused
tagged with: python
has answer: http://stackoverflow.com/a/49706349
tagged with: docker
score: 3
has body: My application is running in the docker container and it is not able to communicate with dd-trace agent running on host which is ec2 I've done all the configurations and still facing ERROR:ddtrace.writer:cannot send spans to localhost:8126: [Errno 111] Connection refused Any idea how to fix this?
upvote count: 3
favorite count: 0
type: Question
tagged with: datadog

http://stackoverflow.com/q/49665623
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
has body: Currently, I am working on mining software repository in github. I use the git log command to get the commit logs. But when I only need to find the commit logs contain a specific word, some unexpected logs also have shown. For example, I need the commit log contains word HBASE-792. I used command git log --grep='HBASE-792' --oneline. But these logs have shown: HBASE-7921. TestHFileBlock.testGzipCompression should ignore the block checksum HBASE-7923 force unassign can confirm region online on any RS to get rid of double assignments HBASE-7928 Scanning .META. with startRow and/or stopRow is not giving proper results; REVERT. NEEDS SOME MORE WORK Fix overlogging; part of HBASE-792 patch Patches to alleviate HBASE-790 and HBASE-792 What I need are only the last 2 commit logs which exactly contain HBASE-792. What pattern should I write in grep?
tagged with: github
downvote count: 1
tagged with: git
favorite count: 0
tagged with: git-log
type: Question
has title: Regex for grepping exact phrase in git log
tagged with: grep
possible better answer: http://stackoverflow.com/a/49665665
tagged with: python
accepted answer: http://stackoverflow.com/a/49665737
has answer: http://stackoverflow.com/a/49665665
has answer: http://stackoverflow.com/a/49665737

http://stackoverflow.com/comment/86279019
has text: yes same error as before
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49635129
type: QuestionComment

http://stackoverflow.com/q/49748278
tagged with: python
upvote count: 7
has comment: http://stackoverflow.com/comment/86511565
has comment: http://stackoverflow.com/comment/86511341
downvote count: 1
has comment: http://stackoverflow.com/comment/86511088
favorite count: 0
has comment: http://stackoverflow.com/comment/86514052
has comment: http://stackoverflow.com/comment/86511823
has comment: http://stackoverflow.com/comment/86513262
has comment: http://stackoverflow.com/comment/86511413
has comment: http://stackoverflow.com/comment/86511131
has answer: http://stackoverflow.com/a/49749361
has comment: http://stackoverflow.com/comment/86512966
has comment: http://stackoverflow.com/comment/86511530
has comment: http://stackoverflow.com/comment/86512058
has comment: http://stackoverflow.com/comment/86511939
has body: I've been looking over many answers here on stackoverflow. I've tried absolutely everything. I have this at the top of my AddressConversion.py python script. #!/usr/bin/env python import argparse The objective is to run this as a command utility, meaning I could type AddressConversion [options][address] As of now I would settle for being able to type ./AddressConversion [options][address] I have done the chmod so the file is executable I've ran dos2unix on the file to eliminate any random windows characters(which wouldn't seem possible because the file has only been used on Ubuntu. I've checked the python install with which python with the results /usr/bin/python I've also checked which env and get a similar path The script will work fine when I use the traditional python command. It also works fine when I type: usr/bin/env python It will open up the python interpreter. These steps seem to be the solutions suggested anytime someone asks this question. I am getting this error: ./AddressConversion.py: line 1: import: command not found ./AddressConversion.py: line 3: syntax error near unexpected token `(' ./AddressConversion.py: line 3: `def init_parser():' which seems like it is trying to run it as a shell script or something. Any suggestions?
has comment: http://stackoverflow.com/comment/86511208
tagged with: shebang
has comment: http://stackoverflow.com/comment/86511560
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86511463
has title: shebang not working for python script
has answer: http://stackoverflow.com/a/62420363
type: UnansweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/139613497

http://stackoverflow.com/a/49667427
has comment: http://stackoverflow.com/comment/86345033
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49667299
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86367117
has comment: http://stackoverflow.com/comment/86345366
answers question: http://stackoverflow.com/q/49667299
has body: The button is moved, but then it's immediately added to the QStackedWidget, which will change the parenting and undo the move. Plus, with a QStackedWidget, the child widgets size and position are controlled by the size and position of the QStackedWidget
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86367102

http://stackoverflow.com/q/49714322
tagged with: anaconda
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86458848
tagged with: python
has comment: http://stackoverflow.com/comment/86459307
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/86446235
has comment: http://stackoverflow.com/comment/86458800
tagged with: pycharm
answer count: 0
has title: Errors with importing TensorFlow
has comment: http://stackoverflow.com/comment/86459395
has comment: http://stackoverflow.com/comment/86458933
has comment: http://stackoverflow.com/comment/86442206
score: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: Supposedly I had installed correctly TensorFlow through Anaconda, and I activated TensorFlow successfully by typing (in Anaconda prompt): C:&gt; activate tensorflow But when I try to validate it (also, in Anaconda prompt) by import tensorflow as tf I get two errors: **ImportError: DLL load failed with the error code -1073741795** and **ImportError: No module named '_pywrap_tensorflow_internal'** finally, it adds: Failed to load the native Tensorflow runtime Also, in the tutorial are specified (for validating the installation) the next steps: Start a terminal. If you installed through Anaconda, activate your Anaconda environment. Invoke python from your shell as follows: $ python ... So, I've considered that I could have missed the "activate Anaconda environment", since I simply made the next: C:\Users\username&gt; activate tensorflow (tensorflow) C:\Users\username&gt;python &gt;&gt;&gt; import tensorflow as tf But then, what does it mean to activate Anaconda environment? What could I have missed? Edit: I've tried to see if I get any more information of the error by trying to run the next .py file in Pycharm (being the interpreter C:\Users\username\Anaconda3\envs\tensorflow\python.exe) from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() tf.global_variables_initializer().run() for _ in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean…
has comment: http://stackoverflow.com/comment/86453964

http://stackoverflow.com/q/49678246
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49682967
type: UnansweredQuestion
answer count: 1
tagged with: scikit-learn
type: Question
has body: I am facing a problem with the sci kit neural network (sknn) module. The code: from sknn.mlp import Regressor, Layer capasinicio = TodasEstaciones.loc['2015-01-12':'2015-03-31'].as_matrix()[:,[0,2]] capasalida = TodasEstaciones.loc['2015-01-12':'2015-03-31'].as_matrix()[:,1] neurones = 1000 tasaaprendizaje = 0.00001 numiteraciones = 9000 #Definition of the training for the neural network redneural = Regressor( layers=[ Layer("ExpLin", units=neurones), Layer("ExpLin", units=neurones), Layer("Linear")], learning_rate=tasaaprendizaje, n_iter=numiteraciones) redneural.fit(capasinicio, capasalida) #Get the prediction for the train set valortest = ([]) for i in range(capasinicio.shape[0]): prediccion = redneural.predict(np.array([capasinicio[i,:].tolist()])) valortest.append(prediccion[0][0]) The error message: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-7-e1e3c4d6d246&gt; in &lt;module&gt;() ----&gt; 1 from sknn.mlp import Regressor, Layer 2 3 capasinicio = TodasEstaciones.loc['2015-01-12':'2015-03-31'].as_matrix()[:,[0,2]] 4 capasalida = TodasEstaciones.loc['2015-01-12':'2015-03-31'].as_matrix()[:,1] 5 neurones = 1000 ModuleNotFoundError: No module named 'sknn' It appears that installing the module through pip pip install scikit-neuralnetwork does not solve the problem any help would be appreciated :)
has title: No module named 'sknn'
tagged with: anaconda

http://stackoverflow.com/q/49696933
answer count: 0
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I'm hoping someone can provide some insight or advice on this as I'm truly puzzled. As part of my machine learning journey, I have created my own image set and am attempting to build a Keras/TensorFlow CNN from the ground up (I've already tried using existing models; this is the next step) A best-practice seems to be to mean-center and unit-variance the input training data and to apply that same scaling to the validation/test data. I can calculate the mean and std of my entire training set. What I don't understand is how to pass these metrics to the validation step. Since this sounds like something everyone would have to do I'm surprised that this isn't baked into Keras. Or if it is and I'm missing it, please feel free to enlighten me. Examples I've seen are on very small data sets (cifar10) that can be entirely loaded into memory (or maybe I don't understand them) That's not possible with my data. I've considered using Keras pre-processing functionality, but that only takes as input a single numpy array. I would have to hard-code the channel means/stds, which obviously not desirable. And the important bits of my code/model are: train_datagen = ImageDataGenerator( rotation_range = 30, width_shift_range = 0.3, height_shift_range = 0.3, zoom_range = 0.25, horizontal_flip=True, vertical_flip=True, featurewise_center=True, featurewise_std_normalization=True, ) train_generator = train_datagen.flow_from_directory( training_dir, target_size=(image_width, image_height), batch_size=batch_size, class_mode='categorical', follow_links=True ) validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(image_width, image_height), batch_size=batch_size, class_mode='categorical', follow_links=True ) If anyone thinks it's useful I can also post my code to calculate the mean and standard deviation using 'flow_from_directory' I thank all of you who take the time to read and/or respond.
tagged with: machine-learning
tagged with: python
tagged with: keras
has title: How to Pass Training Mean and Standard Deviation to Validation Step in Keras/TensorFlow
linked to: http://stackoverflow.com/q/40449522
upvote count: 2
score: 2
linked to: http://stackoverflow.com/q/41855512
has comment: http://stackoverflow.com/comment/88401924

http://stackoverflow.com/q/49709197
tagged with: google-api
downvote count: 0
tagged with: refresh-token
upvote count: 1
score: 1
has body: I made a personal use app that just queries my gmail for a certain type of email. The app is successfully running on a pi night and day making requests to the Gmail service every thirty seconds. However every week or so I get this error: messages = gmail.users().messages().list(userId='me').execute() # q='is:unread' File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- packages\oauth2client\_helpers.py", line 133, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- packages\googleapiclient\http.py", line 839, in execute method=str(self.method), body=self.body, headers=self.headers) File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- packages\googleapiclient\http.py", line 166, in _retry_request resp, content = http.request(uri, method, *args, **kwargs) File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- packages\oauth2client\transport.py", line 186, in new_request credentials._refresh(orig_request_method) File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- packages\oauth2client\client.py", line 761, in _refresh self._do_refresh_request(http) File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- packages\oauth2client\client.py", line 819, in _do_refresh_request raise HttpAccessTokenRefreshError(error_msg, status=resp.status) oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Token has been expired or revoked. Which forces me to go back in, delete my old credentials and rerun the authorization. I've tried to do the other fixes online like setting flow.authorization_url(access_type = 'offline', approval_prompt='force') But the 'OAuth2WebServerFlow' object has no attribute 'authorization_url'. Here is my full authorization code: def authenticate(CLIENT_SECRET_FILE, APPLICATION_NAME, SCOPE, credential_name): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.jo…
has comment: http://stackoverflow.com/comment/91018097
tagged with: facesservlet
tagged with: python
favorite count: 0
type: Question
has title: Using Google API Refresh Token in Python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49746757
type: UnansweredQuestion
has body: I want to create a dynamic plot using holoviewS of amount given and balance remaining. Ideally a line or bar chart and I can select based on category The data(df) is as below ID Amount_Given Balance Interest Date_issues category Amount_Given_Band 1 200 0 15 20180102 A 0-200 2 700 500 25 20180203 B 500-1000 3 1500 705.50 45 20170603 A 1001-5000 4 20000 20000 200 20171231 C 10000-20000 Below is the code %%opts Curve [width=600 height=400 show_grid=True ] (color='indianred', alpha=0.5, line_width=1) ds = hv.Dataset(df).sort(['Date_issues']) ds.to(hv.Curve, 'Date_issues' ,'Amount_Given_Band', 'category') but i get the error IOPub data rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--NotebookApp.iopub_data_rate_limit`. i am using bokeh extension
tagged with: data-visualization
tagged with: holoviews
tagged with: python
tagged with: bokeh
linked to: http://stackoverflow.com/q/43288550
score: 0
has title: Dynamic plots in holoviews
answer count: 0
has comment: http://stackoverflow.com/comment/86595600
type: Question
has comment: http://stackoverflow.com/comment/86587816

http://stackoverflow.com/comment/104677085
type: QuestionComment
has text: It's relaxing to see someone has done your job by asking what you exactly needed to. Still, it's a bit cranky to know you are far away from the problems which ppl have faced years ago!
comment on: http://stackoverflow.com/q/49718346
score: 0
type: Comment

http://stackoverflow.com/comment/86534948
type: Comment
comment on: http://stackoverflow.com/q/49756461
score: 4
has text: People have been wondering for some time now about this; it is strange indeed that one cannot use the CV folds for this purpose https://stackoverflow.com/questions/43866284/grid-search-and-early-stopping-using-cross-validation-with-xgboost-in-scikit-lea
type: QuestionComment

cisco
type: Tag
tags question: http://stackoverflow.com/q/49716220
tag name: cisco
tags question: http://stackoverflow.com/q/49699030

http://stackoverflow.com/q/49704679
favorite count: 0
has comment: http://stackoverflow.com/comment/86422787
has comment: http://stackoverflow.com/comment/86424427
has body: I'm having a trouble when accessing google api. I use python and python modlue Googlemaps. I was going to get the routing information with the code below. directions_result = gmaps.directions(IN,OUT,mode="driving", departure_time="2018-04-05 09:00:00", traffic_model='pessimistic',alternatives=False,language="ja") http error 400 hits me when I try to make it work. It works actually without "depature_time"...so something might be wrong with it, FYI. Any advice will be appreciated.
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49707351
type: Question
has comment: http://stackoverflow.com/comment/86424409
has comment: http://stackoverflow.com/comment/86422653
has comment: http://stackoverflow.com/comment/86426612
tagged with: google-maps
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86424719
answer count: 1
has title: Error on getting google maps info
has comment: http://stackoverflow.com/comment/86422914
has comment: http://stackoverflow.com/comment/86422833
downvote count: 1

http://stackoverflow.com/q/49694649
tagged with: scrapy
has title: Scraping links with Scrapy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49781334
score: 1
tagged with: python
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/86405265
tagged with: python-3.x
upvote count: 1
type: UnansweredQuestion
has body: I am trying to scrape a swedish real estate website www.booli.se . However, i can't figure out how to follow links for each house and extract for example price, rooms, age etc. I only know how to scrape one page and i can't seem to wrap my head around this. I am looking to do something like: for link in website: follow link attribute1 = item.css('cssobject::text').extract()[1] attribute2 = item.ss('cssobject::text').extract()[2] yield{'Attribute 1': attribute1, 'Attribute 2': attribute2} So that i can scrape the data and output it to an excel-file. My code for scraping a simple page without following links is as follows: import scrapy class BooliSpider(scrapy.Spider): name = "boolidata" start_urls = [ 'https://www.booli.se/slutpriser/lund/116978/' ] '''def parse(self, response): for link in response.css('.nav-list a::attr(href)').extract(): yield scrapy.Request(url=response.urljoin(link), callback=self.collect_data)''' def parse(self, response): for item in response.css('li.search-list__item'): size = item.css('span.search-list__row::text').extract()[1] price = item.css('span.search-list__row::text').extract()[3] m2price = item.css('span.search-list__row::text').extract()[4] yield {'Size': size, 'Price': price, 'M2price': m2price} Thankful for any help. Really having trouble getting it all together and outputting specific link contents to a cohesive output-file (excel).
answer count: 1
downvote count: 0
tagged with: web-scraping

http://stackoverflow.com/q/49751151
upvote count: 1
has comment: http://stackoverflow.com/comment/86524081
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86516720
type: Question
has comment: http://stackoverflow.com/comment/86517008
has title: Use python module on command line
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86524010
has comment: http://stackoverflow.com/comment/86520540
tagged with: python
has comment: http://stackoverflow.com/comment/86524059
answer count: 0
score: 0
has body: I want to use python re on the command line, like $ python3 -m antigravity which open [xkcd: Python](https://xkcd.com/353/) Then I tried re import -m re re.findall("\w+") &lt; foo.md -bash: syntax error near unexpected token `(' Is it possible to employ modules on the command line as -m antigravity

http://stackoverflow.com/q/49698836
score: 0
has comment: http://stackoverflow.com/comment/86410824
has answer: http://stackoverflow.com/a/50169815
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86410825
type: UnansweredQuestion
has title: Use plasTeX on short strings
has comment: http://stackoverflow.com/comment/86410826
answer count: 1
has body: I'm trying to find a python package which will convert short strings like A closed-form solution of $\textbf{R}\textbf{R}_1=\textbf{R}_2\textbf{R}$ w.r.t $\textbf{R}$ to a reasonable HTML representation, like A closed-form solution of RR1 = R2 R w.r.t R No LaTeX packages or document layout commands (\section etc.) will be involved; just the subset of TeX allowed in stackexchange postings. While Mathjax does handle this beautifully, unfortunately Javascript options are off the table, as this is for an email digest--it has to be static HTML output. Inline CSS is fine. I know there's a Node.js version of Mathjax that can approximate its output in static form (with a buhc of caveats about how the result won't be browser-responsive and other things I don't care about), but I want Python. The best option I've found seems to be plasTeX, but all the documentation there seems to be about converting whole .tex files to .html, or, for some reason, .xml files, which is much more than I want to do. I suppose, if need be, I could generate temporary .html files and then use BeautifulSoup to parse out only the part I'm interested in, but this seems a bit silly. Since I'm talking about doing this maybe 50 times per script invocation, this would certainly be doable. Is there a simple way to use plasTeX or any other python package to get html equivalents of short latex snippets?
has comment: http://stackoverflow.com/comment/86410823

http://stackoverflow.com/comment/86523755
score: 0
has text: @PearlySpencer edited qstn pls check
comment on: http://stackoverflow.com/q/49754398
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86458608
has text: @J.Taylor why do you want to run process by separate batches? What stops you from running fetching process for all urls and limiting simultaneous amount using `Semaphore`? It'll be more efficient than waiting for one batch before starting another.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49717630

http://stackoverflow.com/comment/86725131
type: AnswerComment
has text: Thank you @bruno desthuilliers. I'm not clear on the `if we_have_enough(response)` part though. Could I ask if you can briefly explain what it is and what do I define the `we_have_enough` variable as?
type: Comment
comment on: http://stackoverflow.com/a/49653832
score: 0

dictionary
tags question: http://stackoverflow.com/q/49752007
tags question: http://stackoverflow.com/q/49687742
tags question: http://stackoverflow.com/q/49672708
tags question: http://stackoverflow.com/q/49699779
tags question: http://stackoverflow.com/q/49688094
tags question: http://stackoverflow.com/q/49701438
tags question: http://stackoverflow.com/q/49721950
tags question: http://stackoverflow.com/q/49661380
tags question: http://stackoverflow.com/q/49618250
tags question: http://stackoverflow.com/q/49698314
tags question: http://stackoverflow.com/q/49622962
tags question: http://stackoverflow.com/q/49749928
tags question: http://stackoverflow.com/q/49682701
tags question: http://stackoverflow.com/q/49701267
tags question: http://stackoverflow.com/q/49645763
tags question: http://stackoverflow.com/q/49732476
tags question: http://stackoverflow.com/q/49735841
tags question: http://stackoverflow.com/q/49720579
tags question: http://stackoverflow.com/q/49665752
tags question: http://stackoverflow.com/q/49713452
tags question: http://stackoverflow.com/q/49628611
tags question: http://stackoverflow.com/q/49600700
tags question: http://stackoverflow.com/q/49641382
tags question: http://stackoverflow.com/q/49692917
tags question: http://stackoverflow.com/q/49651595
tags question: http://stackoverflow.com/q/49609445
tags question: http://stackoverflow.com/q/49621478
tags question: http://stackoverflow.com/q/49639242
tags question: http://stackoverflow.com/q/49744175
tags question: http://stackoverflow.com/q/49752669
tags question: http://stackoverflow.com/q/49645296
tags question: http://stackoverflow.com/q/49724471
tags question: http://stackoverflow.com/q/49739102
tags question: http://stackoverflow.com/q/49654261
tags question: http://stackoverflow.com/q/49659027
tags question: http://stackoverflow.com/q/49599981
tags question: http://stackoverflow.com/q/49603867
tags question: http://stackoverflow.com/q/49638617
tags question: http://stackoverflow.com/q/49677047
tags question: http://stackoverflow.com/q/49709395
tags question: http://stackoverflow.com/q/49711793
tags question: http://stackoverflow.com/q/49724113
tags question: http://stackoverflow.com/q/49739651
tags question: http://stackoverflow.com/q/49671404
tags question: http://stackoverflow.com/q/49684082
tags question: http://stackoverflow.com/q/49681843
tags question: http://stackoverflow.com/q/49648180
tags question: http://stackoverflow.com/q/49646583
tags question: http://stackoverflow.com/q/49757979
tags question: http://stackoverflow.com/q/49602329
tags question: http://stackoverflow.com/q/49657263
tags question: http://stackoverflow.com/q/49704700
tags question: http://stackoverflow.com/q/49686322
tags question: http://stackoverflow.com/q/49627714
tags question: http://stackoverflow.com/q/49714625
tags question: http://stackoverflow.com/q/49640298
tags question: http://stackoverflow.com/q/49743622
tags question: http://stackoverflow.com/q/49708847
type: Tag
tags question: http://stackoverflow.com/q/49744416
tags question: http://stackoverflow.com/q/49662970
tags question: http://stackoverflow.com/q/49654198
tags question: http://stackoverflow.com/q/49606012
tags question: http://stackoverflow.com/q/49739639
tags question: http://stackoverflow.com/q/49625954
tags question: http://stackoverflow.com/q/49716307
tags question: http://stackoverflow.com/q/49671985
tags question: http://stackoverflow.com/q/49724324
tags question: http://stackoverflow.com/q/49600272
tags question: http://stackoverflow.com/q/49634965
tags question: http://stackoverflow.com/q/49718388
tags question: http://stackoverflow.com/q/49751826
tags question: http://stackoverflow.com/q/49687078
tags question: http://stackoverflow.com/q/49665672
tags question: http://stackoverflow.com/q/49676893
tags question: http://stackoverflow.com/q/49731099
tags question: http://stackoverflow.com/q/49603112
tags question: http://stackoverflow.com/q/49646795
tags question: http://stackoverflow.com/q/49612553
tags question: http://stackoverflow.com/q/49610449

http://stackoverflow.com/comment/86409148
has text: @MazelTov is right, better practice is to append the celery output to some logfile (best practice to make this logfile persistence on the host)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49693247

http://stackoverflow.com/comment/86294313
has text: By the way, what's the point of `if context_manager is None:`? Why would you ever use `@context_manager_to_decorator(None)` in your code?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49643012
type: QuestionComment

http://stackoverflow.com/comment/86289838
has text: Do you have any suggestion if I cannot execute the SQL and still want to code?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49641005
type: Comment

http://stackoverflow.com/a/49662961
score: 2
upvote count: 2
downvote count: 0
has body: You can use zip() and a list comprehension like: Code: desired = [[a, b] for a, b in zip(A, A[1:])] Test Code: A = [1, 2, 3, 4] desired = [[a, b] for a, b in zip(A, A[1:])] print(desired) Result: [[1, 2], [2, 3], [3, 4]]
type: Answer
answers question: http://stackoverflow.com/q/49662932

http://stackoverflow.com/comment/86211718
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49602228
has text: "I am a blind person" - as in literally blind? Your code formatting is off, but I'm not sure how you'd be able to tell if you can't see it. I don't know how screen readers interact with code formatting.

http://stackoverflow.com/comment/86223347
type: QuestionComment
has text: The import is fine, but you have to use `PyQt4.QtGui` instead of just `QtGui` to reference it.
score: 0
comment on: http://stackoverflow.com/q/49608401
type: Comment

http://stackoverflow.com/comment/86295268
type: Comment
has text: @Ali - Is possible use `df = df.groupby('Job Title')['Qualification Name'].apply(lambda x: ','.join(x.dropna().unique())).reset_index()` or `df = df.groupby('Job Title')['Qualification Name'].apply(lambda x: ','.join(set(x.dropna()))).reset_index()`? If there is no `NaN` but empty string in last value?
comment on: http://stackoverflow.com/q/49642062
type: QuestionComment
score: 1

http://stackoverflow.com/a/49719969
accepted answer of: http://stackoverflow.com/q/49713472
type: Answer
has body: I managed to solve this as follows: In my responsible model i added the following lines: def clean(self): if self.user == self.patient.user: raise ValidationError(_("A patient can not be responsible for himself")) So now it is no longer possible for a patient to be responsible for himself.
answers question: http://stackoverflow.com/q/49713472
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49625375
has body: Here is a sample code how you can change the attributes of Fruit_type: Sample Code import xml.etree.ElementTree as ET parent = ET.parse("d:\\untitled\\note.xml") root = parent.getroot() for nodes in root.getchildren() : for subNodes in nodes.getchildren() : for mynode in subNodes.getchildren(): print("##### Before Change of attributes ########### \n") print(ET.tostring(mynode)) print("\n ##### After Change of attributes ###########\n") mynode.set('fruit_type', '0234') mynode.set('colour', '999') mynode.set('weight', '45') print(ET.tostring(mynode)) Output ##### Before Change of attributes ########### b'&lt;fruit_type colour="000" fruit_type="0x" weight="32"&gt;\n &lt;/fruit_type&gt;\n ' ##### After Change of attributes ########### b'&lt;fruit_type colour="999" fruit_type="0234" weight="45"&gt;\n &lt;/fruit_type&gt;\n ' hope this helps
has comment: http://stackoverflow.com/comment/86259659
answers question: http://stackoverflow.com/q/49624797
has comment: http://stackoverflow.com/comment/86291362
has comment: http://stackoverflow.com/comment/86291213
type: Answer
has comment: http://stackoverflow.com/comment/86297380
score: 0

http://stackoverflow.com/a/49662237
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49650962
has body: Implemented Ratah's recommendation to 8.923 about 5 seconds improvement, by reading file to single string double duration; std::clock_t start; ifstream testfile("testfile.txt", ios_base::in); unsigned int line_idx = 0; bool found = false; string line; regex ptrn("^(\\d*)\\s(care)$"); std::smatch matches; start = std::clock(); /* Debug time */ std::string test_str((std::istreambuf_iterator&lt;char&gt;(testfile)), std::istreambuf_iterator&lt;char&gt;()); if(regex_search(test_str, matches, ptrn)) { found = true; } testfile.close(); duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout &lt;&lt; "Found? " &lt;&lt; (found ? "yes" : "no") &lt;&lt; std::endl; std::cout &lt;&lt; " Total time: " &lt;&lt; duration &lt;&lt; std::endl; After UKMonkey's note, reconfigured project to release which also includes \O2 and brought it down to 0.086 seconds Thanks to Jean-Francois Fabre, Ratah, UKMonkey
score: 0
answers question: http://stackoverflow.com/q/49650962

http://stackoverflow.com/comment/86442260
comment on: http://stackoverflow.com/q/49714510
score: 2
type: Comment
has text: http://www.mathpath.org/Algor/cuberoot/cube.root.newton.htm or ask Math SE
type: QuestionComment

http://stackoverflow.com/comment/86454993
has text: How do you deal with repeated numbers? Should we assume input numbers are unique?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49720942
score: 0

http://stackoverflow.com/a/49734119
answers question: http://stackoverflow.com/q/49732826
score: 4
has comment: http://stackoverflow.com/comment/86482448
has comment: http://stackoverflow.com/comment/86482454
upvote count: 5
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/86540330
has comment: http://stackoverflow.com/comment/86482489
has comment: http://stackoverflow.com/comment/86482414
has body: Editing files in-place is a task riddled with gotchas (much like modifying an iterable while iterating over it) and usually not worth the trouble. In most cases, writing to a temporary file (or working memory, in dependence of what you have more - storage space or RAM) then deleting the source file and replacing the source file with the temporary file will be equally performant as attempting to do the same thing in-place. But, if you insist, here's a generalized solution: import os def remove_line(path, comp): with open(path, "r+b") as f: # open the file in rw mode mod_lines = 0 # hold the overwrite offset while True: last_pos = f.tell() # keep the last line position line = f.readline() # read the next line if not line: # EOF break if mod_lines: # we've already encountered what we search for f.seek(last_pos - mod_lines) # move back to the beginning of the gap f.write(line) # fill the gap with the current line f.seek(mod_lines, os.SEEK_CUR) # move forward til the next line start elif comp(line): # search for our data mod_lines = len(line) # store the offset when found to create a gap f.seek(last_pos - mod_lines) # seek back the extra removed characters f.truncate() # truncate the rest This will remove only the line matching the provided comparison function and then iterate over the rest of the file shifting the data over the 'removed' line. You won't need to load the rest of the file into your working memory, either. To test it, with test.csv containing: fname,lname,age,sex John,Doe,28,m Sarah,Smith,27,f Xavier,Moore,19,m You can run it as: remove_line("test.csv", lambda x: x.startswith(b"Sarah")) And you'll get test.csv with the in-place removed Sarah line: fname,lname,age,sex John,Doe,28,m Xavier,Moore,19,m Keep in mind that we're passing a bytes comparison function as the file is opened in binary mode to keep consistent line breaks while truncating/overwriting. UPDATE: I was interested in the actual performance of various techniques presented here but I didn't hav…

http://stackoverflow.com/comment/86286845
type: Comment
comment on: http://stackoverflow.com/a/49639485
has text: @WarrenWeckesser. For reference, I asked on the list: https://mail.python.org/pipermail/numpy-discussion/2018-April/077901.html
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86422897
comment on: http://stackoverflow.com/a/49704588
score: 0
type: AnswerComment
has text: Yes absolutely!
type: Comment

http://stackoverflow.com/comment/86390435
comment on: http://stackoverflow.com/a/49689386
type: Comment
score: 0
has text: Having thought about this, I don't think it would work. The people in my field save things as all kinds of nonsensical file extensions that they like to use (but usually they are just disguised np arrays)
type: AnswerComment

http://stackoverflow.com/a/49741531
has body: You could also create a new dictionary class to instead pass the key if it's missing. class SmartDict(dict): def __missing__(self, key): return key df.col_1.map(SmartDict(value2fixed)) #0 dada #1 mel #2 hoodie #Name: col_1, dtype: object
type: Answer
has comment: http://stackoverflow.com/comment/86497780
has comment: http://stackoverflow.com/comment/86553914
score: 3
has comment: http://stackoverflow.com/comment/86497920
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49740814

http://stackoverflow.com/a/49621851
answers question: http://stackoverflow.com/q/49621727
type: Answer
has body: Here's one way - no guarantees about speed or elegance: # Rename column to match desired output df.columns = [1] # Build a series with index=group_number, value=group_name num2name = df[df[1].str.startswith('group')].reset_index(drop=True) # Add column that indicates the group membership of each row, starting at 0 df[0] = df[1].str.startswith('group').cumsum() - 1 # Convert group numbers (0 onward) to group names ('groupN' starting from 1) df[0].replace(group_rows, inplace=True) df.sort_index(axis=1) df 0 1 0 group1 group1 1 group1 john 2 group1 mike 3 group1 marry 4 group2 group2 5 group2 dan 6 group2 ann 7 group2 jacob 8 group2 susan
score: 0

http://stackoverflow.com/comment/86430095
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49707924
score: 0
has text: @KyleJ. I tried csv.DictReader but didn't work as expected. However, I am not sure this is what you had in mind. Any feedback is highly appreciated.

http://stackoverflow.com/a/49660344
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49659474
downvote count: 0
has body: Issue : Problem you are facing is that there are embedded javascript in htmls due to which you will see data missing in html page. so here([requests_html]) is a very nice library designed to request htmls by kennethreitz Sample Code : from requests_html import * sessions = Session() r = sessions.get('https://www.usstoragecenters.com/storage-units/fl/north-miami-beach/15555-w-dixie-hwy') for lines in r.iter_lines() : print(lines) Sample output Due to the comment size limtation i cannot post the full html , here is the piece of HTML printed with above print b' ' b' ' b' ' b' ' b' Self Storage Units at 15555 West Dixie Highway, North Miami Beach, FL 33162 | US Storage Centers ' b' ' b' ' b' ' b' ' b' ' b' ' b' ' b' ' b' ' b' ' b' ' b' {' b' "@context": "http://schema.org",' b' "@type": "WebPage"' b' ,"breadcrumb": {' b' "@context": "http://schema.org",' b' "@type": "BreadcrumbList",' b' "itemListElement": [{' b' "@type": "ListItem",' b' "name": "US Storage Centers",' b' "url": "https://www.usstoragecenters.com/",' b' "position": 0' b' }, {' b' "@type": "ListItem",' b' "name": "Storage Units",' b' "url": "https://www.usstoragecenters.com/storage-units",' b' "position": 1' b' }, {' b' "@type": "ListItem",' b' "name": "FL",' b' "url": "https://www.usstoragecenters.com/storage-units/fl",' b' "position": 2' b' }, {' **...... truncated .....**
upvote count: 1
has comment: http://stackoverflow.com/comment/86407292

http://stackoverflow.com/comment/115326372
score: 0
comment on: http://stackoverflow.com/a/49737705
type: Comment
has text: @Netwave My solution does not need to make it a set.
type: AnswerComment

http://stackoverflow.com/a/49710402
downvote count: 2
upvote count: 1
has body: \ is the escape character in Python. If you end your string with \, it will escape the close quote, so the string is no longer terminated properly. You should use a raw string by prefixing the open quote with r: os.listdir(r'C:/Users/Tatheer Hussain/Desktop//ChatBot/chatterbot-corpus-master/chatterbot_corpus/data///english/')
type: Answer
score: -1
accepted answer of: http://stackoverflow.com/q/49710301
answers question: http://stackoverflow.com/q/49710301
has comment: http://stackoverflow.com/comment/86434309
type: AcceptedAnswer

http://stackoverflow.com/a/49664506
has comment: http://stackoverflow.com/comment/86340608
downvote count: 0
has comment: http://stackoverflow.com/comment/86340453
type: Answer
accepted answer of: http://stackoverflow.com/q/49664210
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86340562
answers question: http://stackoverflow.com/q/49664210
has body: There is nothing wrong with your code except your indentation. Correct is: def create(pos=[0,0]): def player(dir_x,dir_y,step): new_x = pos[0] + dir_x*step new_y = pos[1] + dir_y*step pos[0] = new_x pos[1] = new_y return pos return player if __name__ == '__main__': player = create() print player(1,0,10) print player(0,1,20) print player(-1,0,10) which prints: [10, 0] [10, 20] [0, 20]

http://stackoverflow.com/comment/86268957
comment on: http://stackoverflow.com/q/49630802
has text: If you would like to know how querys perform, check out the django debug toolbar, beside the raw sql queries and how often these queries were made, you also see the time it took to execute
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/comment/86378953
type: Comment
has text: Sorry but -- when I run the first two lines: unexpected EOF while parsing error occurs.. Is it cos this is Python 2.7?
type: AnswerComment
comment on: http://stackoverflow.com/a/49683375
score: 0

http://stackoverflow.com/comment/86436238
type: Comment
comment on: http://stackoverflow.com/q/49711149
score: 0
has text: Perhaps you should add a method to the objects, that links them both ways?
type: QuestionComment

http://stackoverflow.com/q/49711343
linked to: http://stackoverflow.com/q/47034888
has title: Sigmoid in logistic regression (Tom Hope's Guide to Building Deep Learning Systems)
has body: I am following Tom Hope's book to learn Tensorflow and I arrived upon this Logistic Regression Example: import tensorflow as tf import numpy as np N = 20000 def sigmoid(x): return 1 / (1 + np.exp(-x)) # === Create data and simulate results ===== x_data = np.random.randn(N,3) w_real = [0.3,0.5,0.1] b_real = -0.2 wxb = np.matmul(w_real,x_data.T) + b_real y_data_pre_noise = sigmoid(wxb) y_data = np.random.binomial(1,y_data_pre_noise) NUM_STEPS = 50 g1 = tf.Graph() wb_ = [] with g1.as_default(): x = tf.placeholder(tf.float32,shape=[None,3]) y_true = tf.placeholder(tf.float32,shape=None) with tf.name_scope('inference') as scope: w = tf.Variable([[0,0,0]],dtype=tf.float32,name='weights') b = tf.Variable(0,dtype=tf.float32,name='bias') y_pred = tf.matmul(w,tf.transpose(x)) + b with tf.name_scope('loss') as scope: loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true,logits=y_pred)) with tf.name_scope('train') as scope: learning_rate = 0.5 optimizer = tf.train.GradientDescentOptimizer(learning_rate) train = optimizer.minimize(loss) # Before starting, initialize the variables. We will 'run' this first. init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(NUM_STEPS): sess.run(train,{x: x_data, y_true: y_data}) if (step % 5 == 0): print(step, sess.run([w,b])) wb_.append(sess.run([w,b])) print(50, sess.run([w,b])) The example runs as described in the book, however, there is one thing I do not understand, why has the author not used tf.sigmoid() for the inference? with tf.name_scope('inference') as scope: w = tf.Variable([[0,0,0]],dtype=tf.float32,name='weights') b = tf.Variable(0,dtype=tf.float32,name='bias') ***y_pred = tf.sigmoid(tf.matmul(w,tf.transpose(x)) + b)*** Is there something obvious that I have overlooked? Also the results look largely similar with and without the said modification.
favorite count: 0
upvote count: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/49813612
accepted answer: http://stackoverflow.com/a/49813612
downvote count: 0
answer count: 1
tagged with: machine-learning
linked to: http://stackoverflow.com/q/48138475
tagged with: tensorflow
tagged with: logistic-regression
type: Question
score: 2
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/q/49742684
has body: So say I want to loop through a List of tuples and extract two mins each time, merge them, then insert them back into the list until I ended up with one giant tuple. This would in turn be a tuple of tuples. So it would look something like this. for currentValue in range(len(tupleList) - 1): t1 = ExtractMin(tupleList) #buildHeap(tupleList) t2 = ExtractMin(tupleList) #buildHeap(tupleList) #need to merge but i'm not sure how to go about it mergedTuple = t1 + t2 tupleList.append(tuple(mergedTuple)) Is there a best practice in python to merge tuples for a situation like this?
has comment: http://stackoverflow.com/comment/86500093
type: Question
has comment: http://stackoverflow.com/comment/86500042
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86500002
has comment: http://stackoverflow.com/comment/86500479
score: 0
has comment: http://stackoverflow.com/comment/86500256
tagged with: python
has title: merging tuples in python to create a tuple of tuples

http://stackoverflow.com/q/49699802
tagged with: canvas
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: Understanding tkinter tag_bind
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49700214
has answer: http://stackoverflow.com/a/49700214
has comment: http://stackoverflow.com/comment/86413423
tagged with: python
has body: I cannot figure out how to use the tag_bind method associated with a canvas. I created an oval and expected to be able to generate an event by clicking on it. When I do this, nothing happens. What is the correct use of tag_bind? import tkinter as tk class Window(): def __init__(self, master): self.master = master self.create_widgets() def create_widgets(self): self.c = tk.Canvas(self.master, bg='white', height=200, width=300) self.c.pack() b = tk.Button(self.master, text='Draw', command=self.draw) b.pack() def draw(self): self.c.delete('all') self.oval = self.c.create_oval([30,50], [130,80]) self.rect = self.c.create_rectangle([180,10], [280,80]) self.c.tag_bind(self.oval, '&lt;Button-1&gt;', self.oval_func) def oval_func(self, event): self.c.delete(self.rect) self.c.create_text(150, 150, text='Hello, world!', anchor='w') if __name__ == '__main__': root = tk.Tk() app = Window(root) root.mainloop()
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86413723

http://stackoverflow.com/comment/86390095
comment on: http://stackoverflow.com/a/49688707
score: 0
type: Comment
type: AnswerComment
has text: Ok, so after `df = df.set_index('datetime')` what is `print (df.index)` ?

autoencoder
tags question: http://stackoverflow.com/q/49699242
tags question: http://stackoverflow.com/q/49708945
tags question: http://stackoverflow.com/q/49672249
tags question: http://stackoverflow.com/q/49744112
tags question: http://stackoverflow.com/q/49642414
type: Tag
tags question: http://stackoverflow.com/q/49606482
tags question: http://stackoverflow.com/q/49716558
tag name: autoencoder
tags question: http://stackoverflow.com/q/49690066

http://stackoverflow.com/comment/86314450
score: 0
type: AnswerComment
has text: oh! thank you very much, I've re-read it a bunch of times and haven't seen it.
type: Comment
comment on: http://stackoverflow.com/a/49652947

http://stackoverflow.com/a/49719795
has comment: http://stackoverflow.com/comment/86454816
has body: Assuming you have a file 'scrabble_letters.txt' which contains the scores for each letter, then below code defines a method scrabble_score() which takes a word as an argument and prints the score of the word. f = open('scrabble_letters.txt') scores = {} # make a map of letter to its score. Important: note the type casting to integer. for line in f: temp = line.strip() # line.split() takes a line eg. "1 K" and returns an array ['1', 'K'] i.e. splits by spaces. temp = line.split() scores[temp[1]] = int(temp[0]) def scrabble_score(word): total = 0 for letter in word: total += scores[letter] print (total, "points") For a sample text file: 1 E 1 A 1 I 1 N 1 O 5 K 6 W Running the method as scrabble_score('KIWI') prints the output 13 points P.S: The scoring version (as you mentioned french in the question) is purely dependent on contents of scrabble_letters.txt. You have an option of opening the desired file depending on condition using if-else block
downvote count: 0
has comment: http://stackoverflow.com/comment/86485306
answers question: http://stackoverflow.com/q/49719535
has comment: http://stackoverflow.com/comment/86453830
has comment: http://stackoverflow.com/comment/86485090
type: Answer
has comment: http://stackoverflow.com/comment/86485191
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86458355

http://stackoverflow.com/comment/86531239
has text: Could be related to the recent pip TLS deprecation. See [this](https://stackoverflow.com/a/49748494/1526703) answer
comment on: http://stackoverflow.com/q/49745105
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86397895
score: 0
has text: Which library are you using? Perhaps pickle isn't the right tool for the job.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49692436

http://stackoverflow.com/q/49685419
answer count: 3
has comment: http://stackoverflow.com/comment/86382270
tagged with: pandas
has answer: http://stackoverflow.com/a/49685798
possible better answer: http://stackoverflow.com/a/49685671
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86382335
has comment: http://stackoverflow.com/comment/86382352
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49687347
has answer: http://stackoverflow.com/a/49687347
has body: I have created a pandas dataframe and have stored my information in the given frame as DF when i print df i get the output as Number changes Id 300 ['Body Weight', 'Color'] 12345 400 32145 500 45698 600 74125 700 Body Weight 96325 800 Body Weight 44444 900 ['band Voltage Rating', 'Body Weight'] 963258 1000 666666 In some places for column changes There are "[" and "]" . Please let me know how can I remove those brackets?
has title: How to remove the square bracket from the python dataframe
has answer: http://stackoverflow.com/a/49685671
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86382366

http://stackoverflow.com/q/49633303
score: 0
has body: Following problem: I am working with python and I have two texts in different languages (texta and textb) which have both a lot of sentences. The aim is to align each sentence in texta with a sentence of textb. The overall length is roughly equal, but the number of the sentences is not. It is somewhere about 1:1.3, so at times one sentence of texta might get two sentences of textb. The order of the sentences in both texts needs to be preserved. Now I have a CNN that outputs a matrix of all the sentences and a propability score of them being a translation of each other. This might in a simplified way look like this: [0.5,0.2,.0.0] [0.1,0.6,0.4] [0.2,0.3,0.8] The accuracy of these predictions is about 50%. So when I just select the best result of each row I get a precision of 50%. Now one would expect the ideal path to be more or less diagonal, since both texts will contain more or less the same information at the same place. However in reality this is not always the case. A sentence can be short, a sentence can be long, sometimes a paragraph is missing (translation mistake). So I wonder what is a nice approach to solve this problem. My first idea is to just measure the distance to the diagonal center and give a penalty that reduces the propability score as further as an element is away from that center. However this approach is weak in the case that a paragraph is missing and thus a longer sequence of sentences lies further away from the center. So I am looking for a kind of optimization technique, but I do not know where to start yet.
answer count: 1
accepted answer: http://stackoverflow.com/a/49635243
upvote count: 1
tagged with: nlp
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86274507
has title: Finding path in a matrix for sentence alignment
tagged with: python
has answer: http://stackoverflow.com/a/49635243
type: AnsweredQuestion
tagged with: deep-learning
tagged with: matrix

http://stackoverflow.com/comment/86577102
type: AnswerComment
score: 0
type: Comment
has text: This works but as a consequence, I can no longer move cells by dragging them. Is there any there any way to still allow for drag and drop reordering?
comment on: http://stackoverflow.com/a/49725697

http://stackoverflow.com/q/49661963
type: Question
tagged with: struct
has comment: http://stackoverflow.com/comment/86365809
score: 3
has answer: http://stackoverflow.com/a/49662124
upvote count: 5
has comment: http://stackoverflow.com/comment/86365967
tagged with: python
has comment: http://stackoverflow.com/comment/86334015
has title: unpack_from requires a buffer of at least 1164 bytes
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86364474
has comment: http://stackoverflow.com/comment/86355922
has comment: http://stackoverflow.com/comment/86363259
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86333991
has body: I'm using struct to parse fixed width strings. However, I'm having some trouble with dealing fixed width strings larger than 1000 bytes. For example, when I execute the following code: import struct fmt = '2s25s16s1s40s2s1s1s2s9s1s6s10s25s2s2s9s8s2s2s4x8s2x2s2s2s2s2s1x13s6s2s2s2s2s1x3s4s6s4s12x1s2s1x7s1s2s2s2s2s2s1x3s6x2s2x2s2x2s2x2s2x2s2x2s6s2x1s4x4s2s2s2s2s2s2s2s8x3s3s3s3s3s3s3s3s3s2s2s2s2s2s2s8s2x2s2s2s2s2s150s50s4x1s2s8s15x30s30s10s15s15s10s10s10s10s12s3s3s3s3s1s3s3s1x15s2s3s8s2s2s2s2s2s16s2s3s2x2s3s2x1s1s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s10x2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s2s2s3s3s42s6s21s3s3s3s3s3s3s3s3s3s3s3s3s7s' parse = struct.Struct(fmt).unpack_from line = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ123456' parse(line.encode()) I get the following error: Traceback (most recent call last): File "so.py", line 6, in &lt;module&gt; parse(line.encode()) struct.error: unpack_from requires a buffer of at least 1164 bytes …
has comment: http://stackoverflow.com/comment/86365765
favorite count: 0
accepted answer: http://stackoverflow.com/a/49662124

http://stackoverflow.com/q/49659796
type: AnsweredQuestion
score: 2
upvote count: 3
tagged with: environment-variables
has comment: http://stackoverflow.com/comment/86329258
has title: Python: os.environ KeyError after export
answer count: 1
has body: Why python can't get evironment variable after export? How to fix this? λ: export AUTOTEST=/home/anton/eltx/scripts/gitlab/ ~ λ: python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.environ['AUTOTEST'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'AUTOTEST' &gt;&gt;&gt; &gt;&gt;&gt; os.environ.get('AUTOTEST', 'none_value') 'none_value' &gt;&gt;&gt;
accepted answer: http://stackoverflow.com/a/49666773
downvote count: 1
has comment: http://stackoverflow.com/comment/86329818
favorite count: 0
type: Question
tagged with: keyerror
has answer: http://stackoverflow.com/a/49666773
has comment: http://stackoverflow.com/comment/86329157
has comment: http://stackoverflow.com/comment/86335144
tagged with: python

http://stackoverflow.com/q/49707518
duplicate of: http://stackoverflow.com/q/11205254
score: 1
favorite count: 0
has title: Python: method chaining not working as expected - creating and sorting a list
type: Question
tagged with: python-3.x
has body: I am trying to create a list and sort it. If I am splitting the steps in separate statements, it works like I expect: mylist = [4, 1, 2, 6, 0, 9] mylist.sort() gives me the expected result: [0, 1, 2, 4, 6, 9] while mylist = [4, 1, 2, 6, 0, 9].sort() results in None I don't understand why. I would expect, that in the second example, the list would be sorted and assigned to mylist
has comment: http://stackoverflow.com/comment/86428321
answer count: 0
linked to: http://stackoverflow.com/q/22442378
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86428439
linked to: http://stackoverflow.com/q/7301110

qscrollarea
tags question: http://stackoverflow.com/q/49677073
type: Tag
tag name: qscrollarea

http://stackoverflow.com/comment/86310084
has text: other difference: you're performing only 1 call to regex in python because you're reading all the file at once. With C++ code you're calling it once per line.
type: QuestionComment
comment on: http://stackoverflow.com/q/49650962
score: 7
type: Comment

http://stackoverflow.com/q/49722029
has answer: http://stackoverflow.com/a/49789123
accepted answer: http://stackoverflow.com/a/49789123
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
upvote count: 1
tagged with: fuzzing
favorite count: 0
type: Question
has body: I'm attempting to learn the intricacies of fuzzing unknown protocols to locate vulnerabilities in applications. I'm using a publicly known vulnerable app, Disk Savvy Enterprise 10.4.18, which has a known SEH Buffer Overflow in it. I currently have a boofuzz script that I'm trying to utilize the process_monitor.py script with, and am unable to restart the service that is crashing. I have process_monitor.py running on my target machine, and am connecting to it successfully from my fuzzing machine. My problem is the error in the question title-- when the application crashes, it 'attempts' to restart the process, but I get the error PED-RPC&gt; remote method restart_target cannot be found The relevant bits of my python script are: session = sessions.Session( crash_threshold="10000", # Arbitrary, high crash threshold check_data_received_each_request=0, # Don't check data after every request (slow) restart_sleep_time=0.1, sleep_time=0.1, ) # Define target target = sessions.Target( connection = SocketConnection(dst, dport, proto='tcp') ) # Define procmon options target.procmon = pedrpc.Client(dst, 26002) target.procmon_options = { "proc_name" : "disksvs.exe", "stop_commands" : ['net stop "Disk Savvy Enterprise"'], "start_commands" : ['net start "Disk Savvy Enterprise"'] } I'm starting process_monitor.py on my destination machine with the following line: python process_monitor.py --port 26002 --crash_bin diskSaavy_Crashes.txt Here's the resulting output once started, and after it crashes: Couldn't import dot_parser, loading of dot files will not be possible. [03:11.00] Process Monitor PED-RPC server initialized: [03:11.00] crash file: C:\Python27\Lib\site-packages\boofuzz\diskSaavy_Crashes.txt [03:11.00] # records: 3 [03:11.00] proc name: None [03:11.00] log level: 1 [03:11.00] awaiting requests... [03:23.29] updating target process name to 'disksvs.exe' [03:23.30] updating stop commands to: ['net stop "Disk Savvy Enterprise"'] [03:23.30] updating start commands to: ['net s…
has title: boofuzz: 'PED-RPC> remote method restart_target cannot be found'
tagged with: python

http://stackoverflow.com/q/49741391
has title: how to set a text as a label when button is clicked?
has answer: http://stackoverflow.com/a/66441905
possible better answer: http://stackoverflow.com/a/66441905
tagged with: python
has answer: http://stackoverflow.com/a/49741556
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
tagged with: pyqt
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/49741556
has body: I want to set text as label when button is clicked. self.labl.setText does work normally, but it doesn't work when it is in button function. I have read all the similar questions here, but still didn't solve the problem :( import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel from PyQt5.QtCore import pyqtSlot class App(QWidget): def __init__(self): super().__init__() self.title = 'title' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.labl = QLabel(self) self.labl.setText('abc') button = QPushButton('button', self) button.move(170,300) button.clicked.connect(self.on_click) self.show() @pyqtSlot() def on_click(self): self.labl = QLabel(self) self.labl.setText('abc') if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
favorite count: 0
type: Question
tagged with: qlabel
answer count: 2

http://stackoverflow.com/q/49715235
tagged with: imshow
tagged with: python
has title: Imshow in large arrays
answer count: 0
has comment: http://stackoverflow.com/comment/86443684
score: 0
has comment: http://stackoverflow.com/comment/86443499
has comment: http://stackoverflow.com/comment/86443676
has body: I'm trying to use Imshow to make a plot from arrays of ~97000 elements each. I've read the info on the webpage of numpy and also read some examples, I've tried them and it works, but when I try to use my large arrays I have a problem related to the memory that the function uses. Does anyone have an idea on what can be going wrong? Cheers.
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/86498136
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49741733
has text: This seems trivial, even without knowing anything about regex: `code[0] == 'q' and 'a' <= code[1] < 'u'`, or, if you're already converting from codes to numbers, something like `num in range(code_to_num('qaa'), code_to_num('qua'))`. Is there some reason the obvious possibilities don't work for you?

http://stackoverflow.com/q/49719429
tagged with: keras
has title: tensorflow nonmaxsuppresion usage
has answer: http://stackoverflow.com/a/49724991
answer count: 1
tagged with: python
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/49719685
type: UnansweredQuestion
score: 0
has body: I am trying to use nonmax suppresion on my output of CNN. I am using box = tf.image.non_max_suppression( prediction[0], [], 15, iou_threshold=0.5, name=None ) where prediction[0] is 2d array , output of model.predict However printing it outputs Tensor("non_max_suppression/NonMaxSuppressionV2:0", shape=(?,), dtype=int32) How to retrieve the coordinations of boxes from the output of non_max_suppresion?

http://stackoverflow.com/q/49624167
has body: output_tensor = layers.Dense(10, activation='softmax')(x) Here are some codes in keras. I don't understand what (x) means in context of the invoked method. Can anyone help me?
answer count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49630749
tagged with: python
tagged with: keras
favorite count: 0
score: -7
has comment: http://stackoverflow.com/comment/86258740
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/86255543
has title: Here is some Keras code. I don't understand what "(x)" means
downvote count: 7
tagged with: tensorflow
type: Question
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86401895
score: 0
type: Comment
type: AnswerComment
has text: gives the same error, `feed_dict` won't receive tensors; `y_pred` is one. thanks anyway!
comment on: http://stackoverflow.com/a/49688441

http://stackoverflow.com/comment/86383372
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49682298
type: AnswerComment
has text: Yes. Your question was pretty clear to me. First, the code appends one table to the other, and then it groups rows that have the same date together, summing up all other columns for each row that contains that date.

http://stackoverflow.com/comment/86511413
comment on: http://stackoverflow.com/q/49748278
has text: @khelwood I just ran a test script and it worked wit ./test.py and yes /user/bin/env python opens the python interpreter.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86401767
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49694340
score: 0
has text: "These letters are vowels in English: A, E, I, O, U, and sometimes Y." I wrongly assumed that it always is. Oops. However in my native language it is always a vowel :D

http://stackoverflow.com/comment/86344283
type: Comment
has text: Also, why is this tagged both python-3.x and python-2.7? Which one are you using?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49667195

http://stackoverflow.com/q/49627281
has comment: http://stackoverflow.com/comment/86261702
has body: so i started learning python yesterday (0 programming background) and i cant figure out why my code doesnt keep track of the score import random def main(score): choice = int(input("put your number here \n")) number = random.randint(0,5) if (choice &lt; number): print("sorry you missed, guess was too low") elif choice &gt; number: print("sorry you missed guess was too high") elif choice == number: print("congratz u won\n") score += 1 global score score = 0 while True: main(score) print("your score is " + str(score)) player_input = input("wanna continue? press ""enter"" else type ""exit"" \n") if player_input == "exit": exit() else: continue
has comment: http://stackoverflow.com/comment/86261819
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86262321
tagged with: python
has comment: http://stackoverflow.com/comment/86263625
downvote count: 4
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/86261751
answer count: 1
has answer: http://stackoverflow.com/a/49627424
has title: why it doesnt keep track of the score
favorite count: 0
type: Question

http://stackoverflow.com/comment/127091760
type: AnswerComment
has text: btw, they are not perfectly equivalent, and cupy works well only with cuda, it's not guarantee anything on other GPUs
type: Comment
comment on: http://stackoverflow.com/a/65960802
score: 0

http://stackoverflow.com/a/49692429
score: 14
upvote count: 14
downvote count: 0
has body: Notice that running pip3 install psycopg2 doesn't respect the requirements.txt file. To upgrade this package you need to use -U option: pip3 install -U psycopg2 which is a shorthand for: pip3 install --upgrade psycopg2 After that, you can update your requirements.txt with the following command: pip freeze &gt; requirements.txt If you're looking for a solution to automatically update the requirements.txt file after you upgrade package/packages, you can use pip-upgrader. Installation: pip install pip-upgrader Usage: pip-upgrade The above command auto-discovers the requirements file and prompts for selecting upgrades. You can also specify a path to the requirements file or/and specify a package to upgrade: pip-upgrade /path/to/requirements.txt -p psycopg2
type: Answer
answers question: http://stackoverflow.com/q/49692192

http://stackoverflow.com/a/49600109
type: Answer
has body: Why not store your tuples in a numpy array? import numpy as np s = np.array([[1,2], [1,4], [2,6]]) s[np.where(s[:,0] == 1)] gives you array([[1,2], [1,4]])
score: 0
answers question: http://stackoverflow.com/q/49599865

http://stackoverflow.com/comment/86458472
has text: @MaríaVictoria it looks as though there an example using waitress - https://github.com/cloudfoundry/python-buildpack/tree/db6474a50b99348da6c5256bb2133e03745ffd52/fixtures/django_python_3 - maybe try waitress instead?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49715279
type: Comment

http://stackoverflow.com/comment/86305805
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49648258
has text: @jdehesa What do you mean by woth nothing exactly? worth for what? can you please elaborate? I assume that you mean in terms of memory usage, if it's so that's what you have to give up in exchange of gaining performance in runtime, in most cases though. And since the momory usage is not a critical issue here I didn't propose a generator-based approach which is terribly slower than such a vectorized approach.
score: 0

http://stackoverflow.com/comment/86290200
score: 0
type: Comment
type: AnswerComment
has text: I get around this by using Dropbox link instead.
comment on: http://stackoverflow.com/a/49641057

http://stackoverflow.com/comment/86418515
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49702214
type: QuestionComment
has text: Hold on a sec—you're sending `"accept-encoding": "gzip, deflate, br"`. Is it returning [brotli](https://github.com/google/brotli)-compressed data? Test just removing `br` from that line.

http://stackoverflow.com/q/49756488
favorite count: 0
has body: I would like to define different strengths for bottom-borders with xlsxwriter. My question is: How can I prevent the thick-bottom-HEADER-border from being overwritten in the example below? I would like to note, that if I start one row later with the conditional format, I get one row without bottom borders. import numpy as np import pandas as pd dates = pd.DataFrame(pd.date_range('2000-01-01', periods = 15), columns = ['date']) d = pd.DataFrame(np.random.randint(1, 5, (15, 3)), columns = list('abc')) d = pd.concat([dates, d], axis = 1) writer = pd.ExcelWriter('dates_border.xlsx', #OR: 'c:\\users\\USER_NAME\\desktop\\dates_border.xlsx', datetime_format='yyyy.mm') d.to_excel(writer, 'Sheet1', index = False) worksheet = writer.sheets['Sheet1'] workbook = writer.book # header: I LOSE THE THICK BOTTOM BORDER OF THE HEADER header_format = workbook.add_format({'bottom': 2, 'bg_color': '#F9DA04'}) for col_num, value in enumerate(d.columns.values): worksheet.write(0, col_num, value, header_format) # data with bottom borders format1 = workbook.add_format() format1.set_bottom(7) worksheet.conditional_format(1, 0, d.shape[0], d.shape[1] -1, {'type': 'cell', 'criteria': '&lt;&gt;', 'value': '""', 'format': format1}) writer.save() Thx &amp; kind regards
type: Question
accepted answer: http://stackoverflow.com/a/49763660
upvote count: 2
has title: Defining different pandas xlsxwriter border types
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49763660
tagged with: xlsxwriter
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49676240
answer count: 2
has answer: http://stackoverflow.com/a/49689287
downvote count: 0
tagged with: nested
has answer: http://stackoverflow.com/a/49676680
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49689287
possible better answer: http://stackoverflow.com/a/49676680
tagged with: python
tagged with: dictionary
score: 4
upvote count: 4
has title: Python 3.6 nested dictionary dynamic update
type: AnsweredQuestion
has body: I have a file like the following: HP;1&lt;br/&gt; MN;stringval&lt;br/&gt; IS/VD1;32.00&lt;br/&gt; IS/HD1;1.34&lt;br/&gt; IS/E/ID;362.0000000&lt;br/&gt; IS/OLVD;0.0000000&lt;br/&gt; ISN/I/HFD;3283.8999023&lt;br/&gt; D1/I/MF;7.3059464&lt;br/&gt; D1/I/P;32.0388412&lt;br/&gt; D1/E/E;2778.4829102&lt;br/&gt; D1/S1/SB/I/P;32.0388412&lt;br/&gt; EN;5145&lt;br/&gt; After the ";" there is the value I want to put in a dictionary. Every word followed by / is a key. My final goal is to have the following dictionary: {"HP":1.0,"MN":'stringval',"IS":{"VD1":32.00,"HD1":1.34,"E":{"ID":362.0000000},"OLVD":0.0000000},"ISN":{"I":{"HFD":3283.8999023}},"D1":{"I":{"MF":7.3059464,"P":32.03884},"E":{"E":2778.4829102},"S1":{"SB":{"I":{"P":32.0388412}}}},"EN":5145} I do not know the maximum number of levels of the final dictionary. I tried the following code: fid = open(myfile,mode='r') content=fid.readlines() content = [x.replace(' ','').strip() for x in content] outdata = dict() for i in content: dict_struct = i.split(';')[0] val = i.split(';')[-1] n_lev = dict_struct.count('/') test2 = '{"' + dict_struct.replace('/', '":{"') + '":' + val + '}' * (n_lev + 1) try: outdata.update(eval(test2)) print(test2) except: test2 = '{"' + dict_struct.replace('/', '":{"') + '":"' + val + '"' + '}' * (n_lev + 1) print(test2) outdata.update(eval(test2)) This code is not working because update() actually overwrites some of the inputs; this is the output: {"HP": 1, "MN": "stringval", "IS": {"OLVD": 0.0}, "ISN": {"I": {"HFD": 3283.8999023}}, "D1": {"S1": {"SB": {"I": {"P": 32.0388412}}}}, "EN": 5145} Could you give me some hints?

http://stackoverflow.com/comment/86466836
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49726373
has text: @TheZadok42 First, check https://stackoverflow.com/a/40312117/6309 for more details. Second, do in command line from any folder: git ls-remote /url/of/remote/repo: if it requires authentication, it will query for your username/password and cache them. Then you can proceed with your python program.

http://stackoverflow.com/q/49730325
score: 0
has comment: http://stackoverflow.com/comment/86474589
tagged with: python
tagged with: image-processing
has body: I am trying to capture frame from video stream to do some processing on, however I could not take the stream into python or control it using python, thus I captured it and saved it then I am trying to extract a frame from it but I can't find a way. Can anyone help me pleas.
has answer: http://stackoverflow.com/a/49730985
has title: How to extract a frame from a video using python?
type: UnansweredQuestion
answer count: 1
type: Question
tagged with: video-streaming
tagged with: video

http://stackoverflow.com/comment/86209016
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49600931
has text: try running `pip3 install pillow`

http://stackoverflow.com/comment/86248317
type: Comment
comment on: http://stackoverflow.com/a/49620265
has text: Hi jpp, I thought about using dict but it can just store 1 detail per key, right? In this case, I need to store somewhat around 3 info about each subject to display my data correctly. I just edited and added some example input and output to the post. See if it becomes clearer. Thanks btw
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86319774
type: Comment
type: QuestionComment
has text: @Kos my Python script is spawned by a parent process and the parent exits after a while so the child becomes a daemon. I use `subrpocess.Popen` to create the child. How can I turn the child into a sudo without me having to type my password every time I start my script?
score: 0
comment on: http://stackoverflow.com/q/49654856

http://stackoverflow.com/comment/86502546
comment on: http://stackoverflow.com/q/49741836
score: 0
has text: In general you cannot detect system integrity issues from within that same system. It is a common pattern in malicious software to sabotage such measures, but the details would be something for [security.SE](https://security.stackexchange.com/).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86500546
score: 0
has text: @ASGM Copy the dataframe, then update the rows specified by `selector` with new values specified by `update`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49742196

http://stackoverflow.com/q/49619662
possible better answer: http://stackoverflow.com/a/49619687
has answer: http://stackoverflow.com/a/49619769
has body: Here's the list: alist = ([1,2,3],[4,5,6],[7,8,9],[10,11,12]) I need to print the list like this: list1 list2 list3 list4 1 4 7 10 2 5 8 11 3 6 9 12 Here is my code so far: for item in alist: print("{:&gt;8.2f} {:&gt;8.2f} {:&gt;8.2f} {:&gt;8.2f}".format(the meat and potato goes here))
score: 0
has answer: http://stackoverflow.com/a/49620257
has answer: http://stackoverflow.com/a/49619687
tagged with: nested
has comment: http://stackoverflow.com/comment/86246381
has comment: http://stackoverflow.com/comment/86246374
type: Question
tagged with: http://stackoverflow.com/tag/zip
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86246336
has title: How do you print lists from within a list in rows?
has comment: http://stackoverflow.com/comment/86246388
tagged with: python
has comment: http://stackoverflow.com/comment/86246598
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49619769
tagged with: list
answer count: 3

tensorflow
tags question: http://stackoverflow.com/q/49658802
tags question: http://stackoverflow.com/q/49686860
tags question: http://stackoverflow.com/q/49641098
tags question: http://stackoverflow.com/q/49649116
tags question: http://stackoverflow.com/q/49738702
tags question: http://stackoverflow.com/q/49661708
type: Tag
tags question: http://stackoverflow.com/q/49672457
tags question: http://stackoverflow.com/q/49691315
tags question: http://stackoverflow.com/q/49730923
tags question: http://stackoverflow.com/q/49757077
tags question: http://stackoverflow.com/q/49617670
tags question: http://stackoverflow.com/q/49649836
tags question: http://stackoverflow.com/q/49749706
tags question: http://stackoverflow.com/q/49682839
tags question: http://stackoverflow.com/q/49643622
tags question: http://stackoverflow.com/q/49756909
tags question: http://stackoverflow.com/q/49627073
tags question: http://stackoverflow.com/q/49706909
tags question: http://stackoverflow.com/q/49620294
tags question: http://stackoverflow.com/q/49753793
tags question: http://stackoverflow.com/q/49692842
tags question: http://stackoverflow.com/q/49750705
tags question: http://stackoverflow.com/q/49732130
tags question: http://stackoverflow.com/q/49646304
tags question: http://stackoverflow.com/q/49721407
tags question: http://stackoverflow.com/q/49702795
tags question: http://stackoverflow.com/q/49746950
tags question: http://stackoverflow.com/q/49605958
tags question: http://stackoverflow.com/q/49651354
tags question: http://stackoverflow.com/q/49699488
tags question: http://stackoverflow.com/q/49620638
tags question: http://stackoverflow.com/q/49680440
tags question: http://stackoverflow.com/q/49620049
tags question: http://stackoverflow.com/q/49620057
tags question: http://stackoverflow.com/q/49600415
tags question: http://stackoverflow.com/q/49662266
tags question: http://stackoverflow.com/q/49679602
tags question: http://stackoverflow.com/q/49662207
tags question: http://stackoverflow.com/q/49714839
tags question: http://stackoverflow.com/q/49714322
tags question: http://stackoverflow.com/q/49654187
tags question: http://stackoverflow.com/q/49735217
tags question: http://stackoverflow.com/q/49674965
tags question: http://stackoverflow.com/q/49729362
tags question: http://stackoverflow.com/q/49740247
tags question: http://stackoverflow.com/q/49716324
tags question: http://stackoverflow.com/q/49713848
tags question: http://stackoverflow.com/q/49711343
tags question: http://stackoverflow.com/q/49621599
tags question: http://stackoverflow.com/q/49599876
tags question: http://stackoverflow.com/q/49755610
tags question: http://stackoverflow.com/q/49750367
tags question: http://stackoverflow.com/q/49729522
tags question: http://stackoverflow.com/q/49604812
tags question: http://stackoverflow.com/q/49665247
tags question: http://stackoverflow.com/q/49673602
tags question: http://stackoverflow.com/q/49688134
tags question: http://stackoverflow.com/q/49664523
tags question: http://stackoverflow.com/q/49609247
tags question: http://stackoverflow.com/q/49735127
tags question: http://stackoverflow.com/q/49630178
tags question: http://stackoverflow.com/q/49728381
tags question: http://stackoverflow.com/q/49733073
tags question: http://stackoverflow.com/q/49676466
tags question: http://stackoverflow.com/q/49701918
tags question: http://stackoverflow.com/q/49619628
tags question: http://stackoverflow.com/q/49635269
tags question: http://stackoverflow.com/q/49757054
tags question: http://stackoverflow.com/q/49609092
tags question: http://stackoverflow.com/q/49659536
tags question: http://stackoverflow.com/q/49659892
tags question: http://stackoverflow.com/q/49732469
tags question: http://stackoverflow.com/q/49649291
tags question: http://stackoverflow.com/q/49688680
tags question: http://stackoverflow.com/q/49712104
tags question: http://stackoverflow.com/q/49603937
tags question: http://stackoverflow.com/q/49738758
tags question: http://stackoverflow.com/q/49649186
tags question: http://stackoverflow.com/q/49654008

http://stackoverflow.com/q/49684260
has answer: http://stackoverflow.com/a/49684602
type: AnsweredQuestion
score: 3
has body: In the snippet below I have a segment of code that is currently acting as I want it to: def weave_iterable(*iters): return ''.join('{}'.format('{}'*len(chars)).format(*chars) for chars in zip(*iters)) &gt;&gt;&gt; string1 = 'aeim' &gt;&gt;&gt; string2 = 'bfjn' &gt;&gt;&gt; string3 = 'cgko' &gt;&gt;&gt; string4 = 'dhlp' &gt;&gt;&gt; string5 = '----' &gt;&gt;&gt; iterable_args = (string1, string2, string3, string4, string5) &gt;&gt;&gt; weave_iterable(*iterable_args) 'abcd-efgh-ijkl-mnop-' However, I am wondering if there is a more efficient and/or more Pythonic way of formatting text that is being returned by my weave_iterable function? Specifically, I'm wondering if there is any way I can avoid using .format() twice, due to the unknown number of arguments passed into this function. I am developing in Python 2.7, but would be happy with an answer in Python 3.x
answer count: 3
possible better answer: http://stackoverflow.com/a/49684297
has comment: http://stackoverflow.com/comment/86380089
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/49684297
has title: Weaving N iterable arguments of equal length
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49684327
has comment: http://stackoverflow.com/comment/86380133
has answer: http://stackoverflow.com/a/49684327
upvote count: 3
downvote count: 0
tagged with: string

http://stackoverflow.com/q/49630683
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/86268280
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: formatting
has body: I have a code "if x &gt; 18:\n\tif y &gt; 500000:\n\t\tprint('switch_credit_type')\n\telif y &lt; 50000:\n\t\tif z &gt; 2:\n\t\t\tprint('success')\n\t\telse:\n\t\t\tprint('get_more_info')\n\telse:\n\t\tprint('get_more_info')\nelse:\n\tprint('fail')\n" Is any way to format it and print in jupyter cell like a "if x &gt; 18: if y &gt; 500000: print('switch_credit_type') elif y &lt; 50000: if z &gt; 2: print('success') else: print('get_more_info') else: print('get_more_info') else: print('fail')"
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Print formated code in Jupyter
tagged with: python
has comment: http://stackoverflow.com/comment/86268349

http://stackoverflow.com/a/64831597
has body: A good way to do this is following the recommendations in Pytest docs, combined with the third way given in this answer here. This implies: Creating a simple config.py for your project. Make sure to configure packages and package_dir correctly. Read more here. Install an "editable" it using pip install -e . This will create .egg.info in your project folder and also install it. Test it using pytest. Delete that "editable" package using pip uninstall name_of_package and then removing the egg with rm -r $(find . -name '*.egg-info') I know it seems more complex than the simple hacks that simply change sys.path but it is a more clean approach. One thing that was hard for me to understand at the beginning was that using this method you are effectively installing the package to do testing. I hadn't done that with other languages. The reason: you can think of it as a way to also test the installer itself. Without this step, it's completely possible to have a passing test suite and yet have a broken installer (and you end up to accidentally publish a broken package) (from the discussion of this answer here)
has comment: http://stackoverflow.com/comment/134853346
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49605830

http://stackoverflow.com/q/49650191
has comment: http://stackoverflow.com/comment/86309699
has comment: http://stackoverflow.com/comment/86309530
has comment: http://stackoverflow.com/comment/86309656
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86310310
has comment: http://stackoverflow.com/comment/86310034
score: 4
favorite count: 0
type: Question
has title: Writing back the updated dataframe to csv file in python/pandas
has comment: http://stackoverflow.com/comment/86309547
tagged with: pandas
has comment: http://stackoverflow.com/comment/86310827
has comment: http://stackoverflow.com/comment/86310584
linked to: http://stackoverflow.com/q/125703
linked to: http://stackoverflow.com/q/41574037
tagged with: python
has body: I have a csv loaded using pandas as a dataframe. I make a update to only one record of the dataframe and write back to the original csv file. I know that in order to write back we have to write the whole dataframe back to csv. like this: df1.to_csv(file_name) However, is there any where we can write back the updated values alone to the csv instead of writing the whole file? Please advise
has comment: http://stackoverflow.com/comment/86310072
upvote count: 4
has comment: http://stackoverflow.com/comment/86309640
answer count: 0

http://stackoverflow.com/comment/86252222
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49622646
has text: Sorry, indentation was a typo. I also thought about that, but when I debugged the code. The was no call stack in vs code. Moreover, it printed the value for the person taking the tutorial.
type: Comment

http://stackoverflow.com/comment/86326837
comment on: http://stackoverflow.com/q/49658760
score: 0
type: Comment
has text: Can you share a sample of corpus.json?
type: QuestionComment

http://stackoverflow.com/q/49643751
accepted answer: http://stackoverflow.com/a/49644217
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49644217
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86295582
upvote count: 1
tagged with: python
has body: I have series object 'master' sample data print (master.head(2).to_dict()) {4: 0, 5: array([['ANDAMAN &amp; NICOBAR ISLANDS', 4, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['ANDHRA PRADESH', 13161, 107, 0.008130081300813009, 0, datetime.date(2016, 11, 1)], ['ARUNACHAL PRADESH', 8, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['ASSAM', 1317, 6, 0.004555808656036446, 0, datetime.date(2016, 11, 1)], ['Army Postal Service', 10, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['BIHAR', 440, 4, 0.00909090909090909, 0, datetime.date(2016, 11, 1)], ['CHANDIGARH', 416, 9, 0.021634615384615384, 1, datetime.date(2016, 11, 1)], ['CHATTISGARH', 629, 5, 0.00794912559618442, 0, datetime.date(2016, 11, 1)], ['DAMAN &amp; DIU', 19, 1, 0.05263157894736842, 1, datetime.date(2016, 11, 1)], ['DELHI', 6777, 60, 0.008853474988933156, 0, datetime.date(2016, 11, 1)], ['Delhi', 1, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['GOA', 1546, 17, 0.010996119016817595, 1, datetime.date(2016, 11, 1)], ['GUJARAT', 8428, 102, 0.01210251542477456, 1, datetime.date(2016, 11, 1)], ['Gujarat', 190, 1, 0.005263157894736842, 0, datetime.date(2016, 11, 1)], ['HARYANA', 3741, 42, 0.011226944667201283, 1, datetime.date(2016, 11, 1)], ['HIMACHAL PRADESH', 801, 7, 0.008739076154806492, 0, datetime.date(2016, 11, 1)], ['JAMMU &amp; KASHMIR', 852, 11, 0.012910798122065728, 1, datetime.date(2016, 11, 1)], ['JHARKHAND', 457, 2, 0.00437636761487965, 0, datetime.date(2016, 11, 1)], ['KARNATAKA', 22947, 210, 0.009151523074911754, 0, datetime.date(2016, 11, 1)], ['KERALA', 5868, 77, 0.013122017723244717, 1, datetime.date(2016, 11, 1)], ['Karnataka', 49, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['LAKSHADWEEP', 13, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['MADHYA PRADESH', 3031, 29, 0.009567799406136588, 0, datetime.date(2016, 11, 1)], ['MAHARASHTRA', 15027, 153, 0.010181672988620483, 1, datetime.date(2016, 11, 1)], ['MANIPUR', 16, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['MEGHALAYA', 12, 0, 0.0, 0, datetime.date(2016, 11, 1)], ['MIZORAM', 4…
has comment: http://stackoverflow.com/comment/86295470
has comment: http://stackoverflow.com/comment/86295100
has title: How to convert a series object in to a single DataFrame?
type: AnsweredQuestion
tagged with: pandas
score: 1

http://stackoverflow.com/a/49694764
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49693770
score: 1
type: Answer
has body: This is one way using a generator expression with slicing: w = np.array([True,False,True,True,False,False,False]) n = 2 val = False res = next((i for i, j in enumerate(w[k:k+n] for k in range(len(w)-n+1)) \ if np.all(j==val)), None) # 4

http://stackoverflow.com/comment/86361602
type: Comment
comment on: http://stackoverflow.com/a/49673613
score: 0
type: AnswerComment
has text: Thanks for the explantation and yet another example.

http://stackoverflow.com/q/49700647
tagged with: python
tagged with: regex
score: 2
has body: i have data frame that looks like this value 0 A067-M4FL-CAA-020 1 MRF2-050A-TFC,60 ,R-12,HT 2 moreinfo 3 MZF8-050Z-AAB 4 GoCats 5 MZA2-0580-TFD,60 ,R-669,LT i want to be able to strip ,60 ,R-12,HT using regex and also deletes the moreinfo and GoCats rows from the df. My expected Results: value 0 A067-M4FL-CAA-020 1 MRF2-050A-TFC 2 MZF8-050Z-AAB 3 MZA2-0580-TFD I first removed the strings del = ['hello', 'moreinfo'] for i in del: df = df[value!= i] Can somebody suggest a way to use regex to match and delete all case that do match A067-M4FL-CAA-020 or MZF8-050Z-AAB pattern so i don't have to create a list for all possible cases? I was able to strip a single line like this but i want to be able to strip all matching cases in the dataframe pattern = r',\w+ \,\w+-\w+\,\w+ *' line = 'MRF2-050A-TFC,60 ,R-12,HT' for i in re.findall(pattern, line): line = line.replace(i,'') &gt;&gt;&gt; MRF2-050A-TFC I tried adjusting my code but it prints out the same output for each row pattern = r',\w+ \,\w+-\w+\,\w+ *' for d in df: for i in re.findall(pattern, d): d = d.replace(i,'') Any suggestions will be greatly appreciated. Thanks
tagged with: strip
answer count: 3
has title: Using Reg Ex to Match Strings in a Data Frame and Replace - python
tagged with: pandas
has answer: http://stackoverflow.com/a/49707312
downvote count: 0
has comment: http://stackoverflow.com/comment/86416170
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/49703623
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49700817

http://stackoverflow.com/comment/86437769
type: QuestionComment
comment on: http://stackoverflow.com/q/49712037
has text: I'm no expert, but a good starting point might be Facebook Research's open-source tool called Prophet: https://facebook.github.io/prophet/docs/quick_start.html#python-api
score: 0
type: Comment

http://stackoverflow.com/comment/86258664
type: Comment
type: QuestionComment
score: 0
has text: Honestly, that's some nutty extractor =)
comment on: http://stackoverflow.com/q/49600319

http://stackoverflow.com/q/49701425
has body: I am experimenting to see if I can get pixel values out of an image. But the image values I'm getting out aren't what I expected them to be. (Specifically, the green channel for the green triangle gives me a weird value) To break this down, I'm running 2 small experiments. 1) I plot 2 triangles: pink alongside red. I get the pixel values I'd expect. 2) I plot 2 triangles: pink alongside green. I don't get values I expect. So for the first scenario, I know that beforehand, I'd expect to get these pixel values back: So using this simple function, I will plot these triangles: def get_pixel_vals(to_plot): im = Image.new("RGB", (140,125)) for a_vertice in to_plot: ImageDraw.Draw(im).polygon(a_vertice[1], outline=a_vertice[0], fill=None) pix = np.array(im) for channel_num, color_channel in enumerate(['red', 'green', 'blue']): channel_list = [] channel_array = pix[..., channel_num] # gets you the R, G, or B channel of the numpy array print '********* \n', color_channel, 'channel, min:', channel_array.min() channel_list.append(channel_array.flatten().tolist()) channel_flat = [item for alist in channel_list for item in alist] print color_channel, 'num unique values:', len(set(channel_flat)) print color_channel, 'values:', list(set(channel_flat)) imshow(im) to_plot_pink_red = [ ['pink', [(25,25), (25,100), (50,100), ]] , ['red', [(100,25), (100,100), (125, 100)]] ] get_pixel_vals(to_plot_pink_red) And I get: ********* red channel, min: 0 red num unique values: 2 red values: [0, 255] ********* green channel, min: 0 green num unique values: 2 green values: [0, 192] ********* blue channel, min: 0 blue num unique values: 2 blue values: [0, 203] Perfect! Exactly what I'd expect! So what about if I plot a pink triangle alongside a green triangle? I'd expect and I almost get it...but not quite! to_plot_pink_green = [ ['pink', [(25,25), (25,100), (50,100), ]] , ['green', [(100,25), (100,100), (125, 100)]] ] get_pixel_vals(to_plot_pink_green) ********* red channel, min: 0 red num uniq…
tagged with: python
tagged with: rgb
has title: Pixel values in green channel aren't as expected when using PIL in python
has answer: http://stackoverflow.com/a/49701991
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49701991
type: AnsweredQuestion
score: 0
tagged with: colors
tagged with: python-imaging-library
answer count: 1

http://stackoverflow.com/comment/86350943
type: QuestionComment
has text: you have a syntax error, remove coma: `dataframe.set_index('Year'),['AUD'].plot()` --> `dataframe.set_index('Year')['AUD'].plot()`
score: 0
comment on: http://stackoverflow.com/q/49670376
type: Comment

http://stackoverflow.com/comment/86374447
comment on: http://stackoverflow.com/q/49681262
has text: I don't know what "insert" means in this context. Do you mean the user enters a file name? That could be done with the `input` function. This is basic enough that you would be well served running through some tutorials before going forward.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49782268
upvote count: 1
has body: Your self.pdfQueue.get() is blocking the rest of the method in your DataParser instance. See https://docs.python.org/2/library/queue.html#Queue.Queue.get
answers question: http://stackoverflow.com/q/49743631
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/q/49625798
score: 0
tagged with: url
has comment: http://stackoverflow.com/comment/86258774
tagged with: python-requests
answer count: 1
tagged with: fancyurlopener
accepted answer: http://stackoverflow.com/a/49640977
tagged with: urllib
has answer: http://stackoverflow.com/a/49640977
has comment: http://stackoverflow.com/comment/86258968
type: Question
has body: Sometimes it's necessary to change the version attribute when retrieving a request using FancyURLopener, e.g. from urllib.request import FancyURLopener class NewOpener(FancyURLopener): version = 'Some fancy thing' url = 'www.google.com' opener = NewOpener.retrieve(url, 'google.html') Is there an equivalence in the requests library when using requests.get()?
has title: FancyURLopener.version equivalence in requests
tagged with: python
has comment: http://stackoverflow.com/comment/86258866
type: AnsweredQuestion

http://stackoverflow.com/comment/86358225
has text: Could you elaborate what you were actually expecting?
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/49673677

http://stackoverflow.com/q/49743765
accepted answer: http://stackoverflow.com/a/49743796
tagged with: python
score: -1
has body: import operator class Student: def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age studi1=Student('john', 'A', 15) studi2=Student('dave', 'B', 10) studi3=Student('jane', 'B', 12) student_Dict = {} student_Dict[studi1.name]=studi1 student_Dict[studi2.name]=studi2 student_Dict[studi3.name]=studi3 for key in (sorted(student_Dict.values(), key=operator.attrgetter('age'))): print(key) I want to sort it first by grade and then by age. I wanted help regarding the lambda notation.
tagged with: lambda
has answer: http://stackoverflow.com/a/49743796
has comment: http://stackoverflow.com/comment/86502454
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86502448
has title: How to sort a dictionary with two attributes in succession?
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/86502545
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49655402
has answer: http://stackoverflow.com/a/49694584
downvote count: 0
tagged with: authentication
upvote count: 1
favorite count: 0
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/73257271
has body: I installed django-allauth and set it up to use it for the internet registration and authentication backend in order to have an email confirmation at registration and sign up the users using their email instead of their username. What is happening is that the registration works perfectly, the authentication using the email doesn't work whereas it's working with the username. I got the following error: The e-mail address and/or password you specified are not correct. Here my current configuration: Django-allauth: 0.35.0 Django: 1.11 Python: 3.6.4 mysql: 15.1 # settings.py SITE_ID = 1 DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', ] AUTHENTIFICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] LOGIN_REDIRECT_URL = 'main:home' LOGOUT_REDIRECT_URL = 'main:home' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(APPS_DIR, 'templates'), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.media', 'django.template.context_processors.i18n', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True # url.py urlpatterns = [ # Django admin url(settings.ADMIN_URL, admin.s…
type: AnsweredQuestion
answer count: 2
has title: email authentification doesn't work using django-allauth
tagged with: django-allauth
accepted answer: http://stackoverflow.com/a/49694584
score: 1
possible better answer: http://stackoverflow.com/a/73257271

http://stackoverflow.com/a/49654858
answers question: http://stackoverflow.com/q/49654499
has comment: http://stackoverflow.com/comment/86319415
type: Answer
has comment: http://stackoverflow.com/comment/86318951
has comment: http://stackoverflow.com/comment/86325065
has comment: http://stackoverflow.com/comment/86318893
has comment: http://stackoverflow.com/comment/86325151
has body: Something like this would suffice: import re def get_urls(message): ## message is a string (1) Use a regex to find all substrings beginning with 'http' and ending in whitespace (2) Return these. This may contain more strings than you want, so you will need to manually inspect them. If you post an attempt at solving the solution, I csan post more specific code. This is enough to get you started on your own implementation.
has comment: http://stackoverflow.com/comment/86318784
has comment: http://stackoverflow.com/comment/86319213
score: 0

http://stackoverflow.com/comment/86311311
has text: hi @wildplasser sorry it's my bad lol, there is no hardcode Yes, the query works fine on my side i am trying to implement that to my dataset thanks !
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49651217
type: Comment

http://stackoverflow.com/q/49630427
accepted answer: http://stackoverflow.com/a/49710996
has title: How to plot normal distribution with percentage of data as label in each band/bin?
tagged with: plotly
has answer: http://stackoverflow.com/a/49710996
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/65275628
type: Question
answer count: 2
score: 6
has body: While plotting normal distribution graph of data, how can we put labels like in image below for percentage of data in each bin where each band has a width of 1 standard deviation using matplotlib/seaborn or plotly ? Currently, im plotting like this: hmean = np.mean(data) hstd = np.std(data) pdf = stats.norm.pdf(data, hmean, hstd) plt.plot(data, pdf)
has comment: http://stackoverflow.com/comment/86270636
tagged with: python
upvote count: 7
has answer: http://stackoverflow.com/a/65275628
downvote count: 1
linked to: http://stackoverflow.com/q/43360414
favorite count: 0
tagged with: statistics
tagged with: normal-distribution
type: AnsweredQuestion

http://stackoverflow.com/a/49616788
accepted answer of: http://stackoverflow.com/q/49616737
downvote count: 1
has body: If the warning is matter . df=df.assign(prob_win=prob_win)
type: Answer
has comment: http://stackoverflow.com/comment/86241721
answers question: http://stackoverflow.com/q/49616737
score: 2
has comment: http://stackoverflow.com/comment/86241778
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49656859
accepted answer: http://stackoverflow.com/a/49658433
tagged with: django-file-upload
has answer: http://stackoverflow.com/a/49658433
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm building a django app that will let people upload CSVs that will be stored in S3 (based on django-storages) then processed by celery tasks which will then ingest them into the database. These CSVs can be any size, from a few rows (where Django would store it as a InMemoryUploadedFile) to hundreds of megabytes (where django would use aTemporaryUploadedFile.) I'm using a simple ModelForm on a generic CreateView, but I want to add a way to check the first row in the file (the header) to validate that the CSV has all the columns I need. This would be pretty simple if I knew the path of the file. I'd just use python's standard file and csv handling functionality to read the first line into the csv module and check the fields. But how do I do that using an uploaded file where it may be in memory or it may be a temporary file, inside the modelform?
answer count: 1
has title: Get header of CSV file in Django ModelForm
tagged with: django-forms
type: Question

http://stackoverflow.com/comment/86399692
comment on: http://stackoverflow.com/q/49693485
type: QuestionComment
has text: If your `dates` column are dates in your df, you can just do `df['year'] = df['dates'].dt.year`. Otherwise, you might first have to do `df['dates'] = pd.to_datetime(df['dates'])`.
score: 1
type: Comment

http://stackoverflow.com/q/49692297
tagged with: python
has body: I am trying to remove the \n characters from the output of a nslookup. While this seems like a simple task and there are many posts about filtering \n they do not seem to work for me. Code works perfectly in Python 2.7 however it does not in 3.6 mx = str(subprocess.check_output(('nslookup -type=mx ' + "test.nl"), shell=True)) clean = re.sub(r"\n", " ", mx) clean2 = mx.replace("\n", " ") print(clean) print(clean2) Output \nNon-authoritative answer:\ntest.nl\tmail exchanger Wanted result Non-authoritative answer: test.nl\tmail exchanger Neither of these work, however when I remove the '\' it filters the 'n' perfectly. Can anyone tell me what I am doing wrong? Or how I can achieve the wanted result? ps: Well aware this could be a duplicate and I'm just making a dumb mistake, However the solutions given in similar posts do not work for me.
tagged with: nslookup
accepted answer: http://stackoverflow.com/a/49692446
tagged with: replace
type: AnsweredQuestion
score: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/86396630
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86396538
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/86396566
type: Question
has title: Remove \n from string python 3.6
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86396674
has answer: http://stackoverflow.com/a/49692446
has comment: http://stackoverflow.com/comment/86396587
has comment: http://stackoverflow.com/comment/86396798

http://stackoverflow.com/comment/86293991
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49643100
has text: This means "match a digit only if there is not a non-whitespace character before it, and there is not a non-whitespace character after it".

http://stackoverflow.com/a/49708597
type: Answer
answers question: http://stackoverflow.com/q/49708543
has comment: http://stackoverflow.com/comment/86431116
has comment: http://stackoverflow.com/comment/86430748
has comment: http://stackoverflow.com/comment/86430998
has comment: http://stackoverflow.com/comment/86431118
accepted answer of: http://stackoverflow.com/q/49708543
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: read lines from file lines = [] with open(file_name, 'r') as f: for line in f: lines.append(line) with open(file_name, 'w+') as f: flag = True for line in lines: f.write(line) if line.startswith("example string") and flag: f.write("what ever\n") flag = False input file 123456 example string&lt;random&gt; asdfg zxc example string&lt;random&gt; output file 123456 example string&lt;random&gt; what ever asdfg zxc example string&lt;random&gt;
has comment: http://stackoverflow.com/comment/86430916
score: 1

http://stackoverflow.com/q/49655375
type: Question
has comment: http://stackoverflow.com/comment/86322243
has answer: http://stackoverflow.com/a/49655683
downvote count: 0
accepted answer: http://stackoverflow.com/a/49655513
has title: Python: Else statement with 2 for loops
tagged with: python
has answer: http://stackoverflow.com/a/49655513
possible better answer: http://stackoverflow.com/a/49655903
has comment: http://stackoverflow.com/comment/86320757
linked to: http://stackoverflow.com/q/9542738
has answer: http://stackoverflow.com/a/49655903
has comment: http://stackoverflow.com/comment/86320588
has comment: http://stackoverflow.com/comment/86320918
has comment: http://stackoverflow.com/comment/86321534
tagged with: if-statement
has comment: http://stackoverflow.com/comment/86321716
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86321769
has comment: http://stackoverflow.com/comment/86321038
favorite count: 0
has body: I am searching for the pythonic way to do the following: I have a list of keys and a list of objects. For any key, something should be done with the first object that fits to that key. If no object fits to no key, so nothing has be done at all, something different should be done instead. I implemented this as follows and it is working properly: didSomething = False for key in keys: for obj in objects: if &lt;obj fits to key&gt;: doSomething(obj, key) didSomething = True break if not didSomething: doSomethingDifferent() But normally, if there is only one for-loop, you don't need such a temporary boolean to check whether something has been done or not. You can use a for-else statement instead. But this does not work with 2 for-loops, did it? I have the feeling that there should be some better way to do this but i don't get it. Do you have any ideas or is there no improvement? Thank you :)
has comment: http://stackoverflow.com/comment/86321009
has comment: http://stackoverflow.com/comment/86319860
answer count: 4
tagged with: for-loop
has answer: http://stackoverflow.com/a/49655620

virtualenv
tags question: http://stackoverflow.com/q/49659099
tags question: http://stackoverflow.com/q/49738173
tag name: virtualenv
tags question: http://stackoverflow.com/q/49737459
tags question: http://stackoverflow.com/q/49756084
tags question: http://stackoverflow.com/q/49694833
tags question: http://stackoverflow.com/q/49738702
tags question: http://stackoverflow.com/q/49616104
tags question: http://stackoverflow.com/q/49750356
tags question: http://stackoverflow.com/q/49746499
tags question: http://stackoverflow.com/q/49741754
tags question: http://stackoverflow.com/q/49722911
tags question: http://stackoverflow.com/q/49750550
tags question: http://stackoverflow.com/q/49679283
tags question: http://stackoverflow.com/q/49639644
tags question: http://stackoverflow.com/q/49636986
tags question: http://stackoverflow.com/q/49616399
tags question: http://stackoverflow.com/q/49745105
type: Tag
tags question: http://stackoverflow.com/q/49647452
tags question: http://stackoverflow.com/q/49657055
tags question: http://stackoverflow.com/q/49659422

http://stackoverflow.com/comment/86430746
has text: shouldn't [2, B] have Chris & Rob?
comment on: http://stackoverflow.com/q/49706818
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49716089
answers question: http://stackoverflow.com/q/49711763
has comment: http://stackoverflow.com/comment/86504332
has comment: http://stackoverflow.com/comment/86590357
has body: Without numpy, you can zip the lists together and add them up: [sum(i) for i in zip(lst1,lst2)] It is easier to use a list comprehension rather than map For formatting the numbers it is natural to use str.format(). As you don't know the widths of the numbers in advance, you first create a format string, and the easiest way to do that is to use format # maxlen returns the length of the longest element def maxlen(l): return max([len(str(i)) for i in l]) # sumtable returns a formatted multiline string containing the sums # written in a human readable form. def sumtable(l1,l2): #sums contains the answers, and table is the full table numbers in #the calculations as a list of tuples sums = [sum(i) for i in zip(l1,l2)] table = list(zip(l1,l2,sums)) width1 = maxlen(l1) width2 = maxlen(l2) widthsum = maxlen(sums) # formatstring has a form like "{:3d} + {:5d} = {:5d}\n" formatstring = "{{:{}d}} + {{:{}d}} = {{:{}d}}\n".format(width1,width2,widthsum) # unpack the values from the table into the format string and return. return (formatstring.format(*table[0]) + formatstring.format(*table[1]) + formatstring.format(*table[2])) print(sumtable([3,54,-30],[65,8,800])) # 3 + 65 = 68 # 54 + 8 = 62 # -30 + 800 = 770
has comment: http://stackoverflow.com/comment/86464576
has comment: http://stackoverflow.com/comment/86471248
type: Answer
has comment: http://stackoverflow.com/comment/86464641
has comment: http://stackoverflow.com/comment/86590294
has comment: http://stackoverflow.com/comment/86464372
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86364128
type: AnswerComment
has text: Say, that is a really snazzy way to find initial parameter estimates for this problem - my complements on the excellent results.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49676284

http://stackoverflow.com/comment/86492324
type: Comment
type: QuestionComment
score: 0
has text: It sounds like the site may be serving dynamic content (which means that some of the HTML is created/modified only when a web browser is using it). This has the effect of having a "hole" in the HTML where you see data on your dev tools but not in the scrapy scraped page. Does this [q/a](https://stackoverflow.com/q/8550114/3491991) sound like your problem?
comment on: http://stackoverflow.com/q/49738811

http://stackoverflow.com/comment/86387487
score: 0
comment on: http://stackoverflow.com/q/49681973
has text: Can you post your buildozer.spec?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49600619
score: 0
answers question: http://stackoverflow.com/q/49600496
has body: Try it like this - I do not speak french nor do I play domino, but this code works somewhat: class Partie: def __init__(self, plateau, donnes): self.plateau = plateau self.donnes = donnes self.tour = None self.passe = 0 self.gagnant = None self.nombre_joueurs = 3 # added @staticmethod def show_instructions(somePartie): instructions = """ Game Instructions : """ print(instructions) somePartie.afficher_etat_donnes() # changed, needs instance of partie to call # non static method on the instance.... def afficher_etat_donnes(self): for joueur in range(self.nombre_joueurs): # fixed missing self. print(f"The player {joueur} has {len(self.donnes[joueur])} dominos in hand.") # make a Partie p = Partie("",[[1,1,1,1],[2,2,2,2,2,2],[2,2,2]]) # call static method, give it instance of partie to enable calling other method Partie.show_instructions(p) Output: Game Instructions : The player 0 has 4 dominos in hand. The player 1 has 6 dominos in hand. The player 2 has 3 dominos in hand.
type: Answer

http://stackoverflow.com/q/49610908
has body: I need to export some rows from a table in a PostgreSQL database to a .csv file using a Python script: #!/usr/bin/python # -*- coding: utf-8 -*- import sys, psycopg2 ... conn = psycopg2.connect("dbname=dbname user=user password=password") cur = conn.cursor() sql = "\copy (SELECT * FROM table WHERE month=6) TO '/mnt/results/month/table.csv' WITH CSV DELIMITER ';';" cur.execute(sql) cur.close() ... But when I run the script I get this: Syntax error at or near «\» LINE 1: \copy (SELECT * FROM TABLE WHERE month=6) TO '... Does anyone know what can be wrong or give me a tip about?
tagged with: postgresql
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49612480
score: 21
has answer: http://stackoverflow.com/a/71264723
tagged with: sql
has answer: http://stackoverflow.com/a/49612480
accepted answer: http://stackoverflow.com/a/49612587
upvote count: 21
has answer: http://stackoverflow.com/a/49612587
has answer: http://stackoverflow.com/a/68616731
has comment: http://stackoverflow.com/comment/86228742
favorite count: 0
type: Question
tagged with: export-to-csv
linked to: http://stackoverflow.com/q/12316953
has comment: http://stackoverflow.com/comment/86228715
linked to: http://stackoverflow.com/q/49000890
downvote count: 0
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/86228493
has title: Exporting a PostgreSQL query to a csv file using Python
answer count: 4

http://stackoverflow.com/q/49626182
has comment: http://stackoverflow.com/comment/86321519
accepted answer: http://stackoverflow.com/a/49657997
has comment: http://stackoverflow.com/comment/86259859
tagged with: excel
has comment: http://stackoverflow.com/comment/86285709
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49641095
has comment: http://stackoverflow.com/comment/86321394
score: 2
linked to: http://stackoverflow.com/q/7618121
has comment: http://stackoverflow.com/comment/86325611
downvote count: 2
tagged with: openpyxl
has answer: http://stackoverflow.com/a/49641095
has comment: http://stackoverflow.com/comment/86266013
has comment: http://stackoverflow.com/comment/86261261
favorite count: 0
has comment: http://stackoverflow.com/comment/86259649
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/8429014
has answer: http://stackoverflow.com/a/49657997
has body: I would like to print out an Excel Sheet, in which I'll have a column with a lot of text. Inside of this text I would like to highlight some specific words in bold? ['B1'] = text text text text text text text text bold text text text text Till now I just found ways to change the hole cell 'B1' to another format. Does anybody have an idea how to highlight a single word in another way? e.g. another color, italic or line breaks? Thank you! :)
linked to: http://stackoverflow.com/q/28774757
linked to: http://stackoverflow.com/q/14149748
has title: Is there a way with openpyxl to print a single word **bold**?
tagged with: python
has comment: http://stackoverflow.com/comment/86324332

http://stackoverflow.com/comment/86427737
comment on: http://stackoverflow.com/q/49706655
has text: Have you tried `extract_first()`? If you are using pycharm, why not put a debug point before `return item`, here is how. https://stackoverflow.com/questions/21788939/how-to-use-pycharm-to-debug-scrapy-projects
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49626398
answers question: http://stackoverflow.com/q/49626230
has comment: http://stackoverflow.com/comment/86259797
has body: import sys while True : with open('tmp.txt', 'ab') as f : f.write('this is a test\n')
has comment: http://stackoverflow.com/comment/86290631
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/86290737
upvote count: 1
type: Answer

http://stackoverflow.com/a/49630281
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49630204
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86351646
score: 4
has body: Try this : import collections, numpy collections.Counter(arr) Or unique, counts = numpy.unique(arr, return_counts=True) dict(zip(unique, counts))
answers question: http://stackoverflow.com/q/49630204
type: Answer

http://stackoverflow.com/q/49639619
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49639690
tagged with: dataframe
tagged with: python
tagged with: sorting
has body: If I have created a predefined list, say top 3 stocks in the order of ["CAT","AI", "BOC"], how can I get this new dataframe by working from the original dataframe below that will essentially sort_value the ticker column by the order for which the above predefined list is shown? (still chronological order also) Thanks date price ticker volume 0 2018-01-01 1.323 AI 2000 1 2018-01-02 1.525 AI 1500 2 2018-01-03 1.045 AI 500 3 2018-01-01 2.110 BOC 3201 4 2018-01-02 2.150 BOC 5200 5 2018-01-03 2.810 BOC 1980 6 2018-01-01 5.199 CAT 2000 7 2018-01-02 4.980 CAT 450 8 2018-01-03 4.990 CAT 3000
has comment: http://stackoverflow.com/comment/86287027
has title: Sort value by predefined list
score: 0
duplicate of: http://stackoverflow.com/q/13838405
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/13838405

http://stackoverflow.com/q/49654291
tagged with: eclipse
has body: I have written a Robot test case which takes input list from command line. I ran the test case from command line and it executed successfully. All the issue comes when i run the same script from Eclipse, the test case fails and gives a console message - 'List variable '@{list_of_vars}' has no item in index 0.' Below is my code - [Tags] TestCLI @{list_of_vars} Split String ${my_vars} Log @{list_of_vars}[0] Log @{list_of_vars}[1] Syntax used for executing test case from command line: python -m robot -v my_vars:one,two -E space:, -t "TestCLI" C:\Users\user1\eclipse-workspace\RobotTests\robot\firstTest.robot I understood that @{list_of_vars} is looking for input elements when running the test case from eclipse. I have used Run and Start Process keywords to start the command line and couldn't succeed. Is there any way to resolve the error and run the same script from eclipse. Additional details - Robot framework version - 3.0.2, Eclipse oxygen, Python version 3.6.4, RED Editor 0.8.3.2018xxx
tagged with: robotframework
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86327360
has answer: http://stackoverflow.com/a/49658504
has comment: http://stackoverflow.com/comment/86327134
favorite count: 0
has title: How to execute Robot testcase from eclipse which takes command line list arguments as input?
type: Question
has comment: http://stackoverflow.com/comment/86324601
score: 1
tagged with: python

http://stackoverflow.com/comment/86234142
type: QuestionComment
comment on: http://stackoverflow.com/q/49602691
score: 0
has text: thanks @abarnert. Last time I didn't give enough code and it seems I've vomited code this time, hopefully I'll get the hand of this soon.
type: Comment

http://stackoverflow.com/a/49673754
has body: Yeah reduce down to minimal complexity then optimize as @jpp commented. Take a look at this also, great way to get things like this done at speed with Python. http://chriskiehl.com/article/parallelism-in-one-line/
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49673005

http://stackoverflow.com/q/49663127
has body: I am attempting to write a django custom tag to replace more than 3 occurrences of a line break (\n) with 2 line breaks. For example, I would like to replace the following \n\n\n\n\n\n\n\n\n or \n\n\n\n\n or \n\n\n with \n\n Here is my custom tag so far: @register.filter(name='replace_three_linebr') def replace_three_linebr(value): """Replaces all occurrences of GT 2 adjoined line breaks with 2 line breaks from the given string.""" return value.replace("\n\n\n", "\n\n")
accepted answer: http://stackoverflow.com/a/49663199
has answer: http://stackoverflow.com/a/49663199
tagged with: django
has comment: http://stackoverflow.com/comment/86336269
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: django-templates
answer count: 1
has title: Django Custom Tag - Replace more than 3 line breaks with two line breaks
type: Question

http://stackoverflow.com/comment/86320379
score: 0
comment on: http://stackoverflow.com/q/49655566
has text: The metaclass’s instance check is being called both times, but in 3.x, the metaclass isn’t `MyMeta`, it’s `type`. So that’s why the docs on `__instancecheck__` don’t explain the difference—because the difference is somewhere else, in how you specify a metaclass.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86409086
type: Comment
comment on: http://stackoverflow.com/a/49683145
type: AnswerComment
has text: I liked a lot your suggestion. How do I accept it? Sorry, I am newbie to SO.
score: 0

http://stackoverflow.com/comment/88604559
has text: Worked for me on Mac.
comment on: http://stackoverflow.com/a/49758204
score: 5
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86238127
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49615674
has text: You can use [`runpy.run_path`](https://docs.python.org/3/library/runpy.html#runpy.run_path) instead of that exec thing.
score: 0

http://stackoverflow.com/a/49658811
has comment: http://stackoverflow.com/comment/86327818
answers question: http://stackoverflow.com/q/49658698
has comment: http://stackoverflow.com/comment/86328020
type: Answer
score: 3
upvote count: 3
has body: Try: def join_hyphens(text): while "-\n\n" in text: text = text.replace("-\n\n", "-\n") return text.replace("-\n", "") This will still create multiple strings, but less then your method as it creates one copy of the string per max occurence of -\n\n + 1 to remove all -\n from it.
downvote count: 0

http://stackoverflow.com/a/49712361
has comment: http://stackoverflow.com/comment/86438404
upvote count: 1
score: 1
type: Answer
has body: Yes but you need to create some extra tensors, something like this: # creates 'both inactive' ground truth flag tensor both_inactive_gt = tf.cast( 1.0 - tf.reduce_sum( labels, 1 ), tf.bool ) threshold = 0.5 # whatever threshold you want to use # two steps to create prediction flag tensor # First: -2, -1, 0, 1, or 2 : only -2 is interesting for us both_inactive_pred_0 = tf.reduce_sum( tf.sign( prediction_op - threshold ), 1 ) # Second: True for 'both inactive' and False otherwise both_inactive_pred = tf.cast( - tf.sign( both_inactive_pred_0 + 1.5 ), tf.bool ) # now tie it all together result = tf.logical_or( tf.logical_and( both_inactive_gt, both_inactive_pred ), tf.logical_and( tf.logical_not( both_inactive_gt ), tf.equal(tf.argmax(labels, 1), tf.argmax(prediction_op, 1 ) ) ) Hope this helps!
has comment: http://stackoverflow.com/comment/86438298
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49712104
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49712104

http://stackoverflow.com/q/49605886
type: Question
type: UnansweredQuestion
has title: 'NoneType' object is not iterable - Emotion Detection Error
has comment: http://stackoverflow.com/comment/86219152
tagged with: python
has comment: http://stackoverflow.com/comment/86219362
has body: I am trying to achieve emotion detection using opencv2. However when I run the python script it would have this error: In 1: runfile('C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master/EmoDetect.py', wdir='C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master') usage: EmoDetect.py [-h] [-i I [I ...]] optional arguments: -h, --help show this help message and exit -i I [I ...] Enter the filenames with extention of an Image Initializing Dlib face Detector.. Loading landmark identification data... Unable to find trained facial shape predictor. You can download a trained facial shape predictor from: http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2 Loading trained data..... Unable to load trained data. Make sure that traindata.pkl and pcadata.pkl are in the current directory Traceback (most recent call last): File "", line 1, in runfile('C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master/EmoDetect.py', wdir='C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master') File "C:\Users\Belay Mendez\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\Users\Belay Mendez\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master/EmoDetect.py", line 105, in for filename in arg.i: TypeError: 'NoneType' object is not iterable TypeError: 'NoneType' object is not iterable It would then crash the kernel and is unable to start it and then leads to this: libpng warning: Image width is zero in IHDR libpng warning: Image height is zero in IHDR libpng error: Invalid IHDR data libpng warning: Image width is zero in IHDR libpng warning: Image height is zero in IHDR libpng error: Invalid IHDR data I don't know what is wrong,…
has comment: http://stackoverflow.com/comment/86219082
has comment: http://stackoverflow.com/comment/86218701
has comment: http://stackoverflow.com/comment/86218633
tagged with: opencv
score: 0
tagged with: face-detection
has comment: http://stackoverflow.com/comment/86218799
answer count: 0
has comment: http://stackoverflow.com/comment/86219088
has comment: http://stackoverflow.com/comment/86218698

http://stackoverflow.com/comment/86418584
comment on: http://stackoverflow.com/q/49698258
type: Comment
has text: You can use Gstreamer https://gist.github.com/tetkuz/0c038321d05586841897 or FFMPEG https://www.alkannoide.com/2013/07/04/play-with-ffserver-a-quick-overview/. OpenCV supports both of these. FFMPEG requires an instance of ffserver to be running, which is unfortunate because ffserver is deprecated and soon will be removed. So I recommend looking into Gstreamer.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/137305502
score: 0
has text: A flaw in that solution is that if you get some poor matchings you may extract a component that cycle back to one of the image, ex: edges `edges = [(img1_feat_i, img2_feat_j), (img2_feat_j, img3_feat_k), (img3_feat_k, img1_feat_l), ...]` you will get a component `[img1_feat_i, img2_feat_j, img3_feat_k, img1_feat_l, img2_feat_m, ...]`
comment on: http://stackoverflow.com/a/49634456
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86672695
type: QuestionComment
comment on: http://stackoverflow.com/q/49731828
has text: Possible duplicate of [pip install fails for every package ("Could not find a version that satisfies the requirement")](https://stackoverflow.com/questions/49748063/pip-install-fails-for-every-package-could-not-find-a-version-that-satisfies-th)
type: Comment
score: 0

http://stackoverflow.com/comment/86510436
has text: @Aquarius_Girl Do you want a menubar or a ToolBar?
type: Comment
comment on: http://stackoverflow.com/a/49747956
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86418060
score: 0
has text: Your question is very confusing. Are you using the words "string" and "list" interchangeably or is that just my imagination? Anyway, if I understand correctly, I think `' '.join(Items)` solves your problem?
type: QuestionComment
comment on: http://stackoverflow.com/q/49702173
type: Comment

http://stackoverflow.com/q/49672081
has comment: http://stackoverflow.com/comment/86355381
has comment: http://stackoverflow.com/comment/86356231
downvote count: 0
upvote count: 1
has title: Pandas Series aggregating by time results in duplicates
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86363622
type: UnansweredQuestion
has body: I'm fighting with a pandas problem I just don't get my head around. So I have a datetime indexed pandas Series my_series: Time 2017-04-25 15:10:44 8 2017-04-25 15:17:20 27 2017-04-25 16:23:51 31 2017-04-25 17:49:47 15 2017-04-25 17:53:00 4 2017-04-25 17:55:15 3 2017-04-25 18:53:37 7 2017-04-25 18:54:00 4 2017-04-25 19:00:36 5 2017-04-25 22:34:19 18 2017-04-25 23:08:52 6 2017-04-26 07:47:46 10 2017-04-26 07:59:54 9 2017-04-26 08:05:18 8 2017-04-26 08:12:40 8 2017-04-26 09:24:30 19 2017-04-26 09:49:12 5 2017-04-26 09:52:26 5 2017-04-26 11:35:09 4 2017-04-26 12:34:00 8 .. Name: Duration, dtype: int64 Now I try to group this data on a weekly basis: my_series.groupby(pd.TimeGrouper("W")).apply(print) or my_series.resample("W").apply(print) Where both ways lead to the same result: Time 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 2017-04-25 15:10:44 8 .. So for some reason it duplicates the values like crazy. Can someone explain to me why it behaves like that and how I could change that to what I would expect, namely that I receive the actual array consisting of the data of a certain week.
tagged with: python
tagged with: pandas-groupby
answer count: 0
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86363547

http://stackoverflow.com/comment/86366962
has text: It's not lots of strings the same but the same string as value for different keys. `CAT_TO_NAME = {cat:name for name, cat in [('Error', [1, 2, 3]), ('Incorrect', [4, 5, 6]), ('Warning', [7,8])]}`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49674759
type: AnswerComment

baduk
type: Tag
tags question: http://stackoverflow.com/q/49754713
tag name: baduk

http://stackoverflow.com/a/49996654
type: Answer
answers question: http://stackoverflow.com/q/49661414
score: 0
has body: Just replace Adj close column with close column because in morningstar use close column as adj close df['100mma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean() replace with df['100mma'] = df['Close'].rolling(window=100, min_periods=0).mean()

http://stackoverflow.com/comment/86367243
type: QuestionComment
has text: @SalA. You can always check if a pair is "newly generated" or not: u, v belong to two different components, and (u, v) is not an existing edge of weight 0. Could you try to count (or estimate) the number of newly generated pairs? If this number is too large, it's not reasonable at all to create all of them.
comment on: http://stackoverflow.com/q/49669112
score: 0
type: Comment

http://stackoverflow.com/a/49690928
has body: There are more problems in this code, but to solve that one, add the line: self.controller=controller To the newUser classes __init__ function.
has comment: http://stackoverflow.com/comment/86397418
score: 0
has comment: http://stackoverflow.com/comment/86393810
has comment: http://stackoverflow.com/comment/86393930
has comment: http://stackoverflow.com/comment/86394367
answers question: http://stackoverflow.com/q/49688826
type: Answer

http://stackoverflow.com/q/49724629
type: Question
tagged with: python
tagged with: sparse-matrix
accepted answer: http://stackoverflow.com/a/49736558
has comment: http://stackoverflow.com/comment/86470026
has answer: http://stackoverflow.com/a/49736558
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86485160
downvote count: 0
has comment: http://stackoverflow.com/comment/86463246
upvote count: 1
score: 1
has title: Performance of loading and storing sparse data with numpy
answer count: 1
tagged with: storage
favorite count: 0
tagged with: numpy
has body: I thought about a custom sparse data format. It's meant for space efficient storage and loading, not to do computations on it. The essence is to store the indices and values of nonzero entries. I was wondering if there are some tweaks that could improve the performance. The need emerged from handling data like this: N "images" (32x32) with four channels each. The images contain on average ~5% nonzero values. As N grows very large, storing all the images in RAM is inefficient. So only the number of nonzero entries, their indices and values as well as the original shape is stored. Here's a example how this can be implemented: import numpy as np def disassemble_data(data): # get some dense data and make it sparse lengths = np.count_nonzero(data, axis=(1, 2, 3)) idxs = np.flatnonzero(data) vals = data.ravel()[idxs] return lengths, idxs, vals, data.shape def assemble_data(lengths, idxs, vals, shape): # get some sparse data and make it dense data = np.zeros(shape) lower_idx = 0 for length in lengths: upper_idx = lower_idx + length data.ravel()[idxs[lower_idx:upper_idx]] = vals[lower_idx:upper_idx] lower_idx = upper_idx return data # Create some dummy data my_data = np.random.uniform(0, 1, (10, 4, 32, 32)) my_data[my_data &gt; 0.05] = 0 # make data sparse and then dense again my_new_data = assemble_data(*disassemble_data(my_data)) # assert that this actually works assert np.allclose(my_data, my_new_data) Now, we can directly see the advantage: The data is densified image by image. This allows us to load the whole dataset into RAM and generate dense images on demand via a generator: def image_generator(lengths, idxs, vals, shape): idxs %= np.prod(shape[1:]) lower_idx = 0 for length in lengths: upper_idx = lower_idx + length data = np.zeros(shape[1:]) data.ravel()[idxs[lower_idx:upper_idx]] = vals[lower_idx:upper_idx] lower_idx = upper_idx yield data Further it is also possible to generate batches of images: def image_batch_generator(lengths, idxs, vals, shape, batch_size): …
tagged with: performance
linked to: http://stackoverflow.com/q/48672130

http://stackoverflow.com/a/49643116
has comment: http://stackoverflow.com/comment/93469417
score: 0
answers question: http://stackoverflow.com/q/49628202
has body: You are talking about plist files in the JSON format. Your example is not JSON. Let's start with this sample plist in XML <?xml version="1.0" encoding="UTF-8"?> Author William Shakespeare Lines It is a tale told by an idiot, Full of sound and fury, signifying nothing. Birthdate 1564 And convert it to JSON format: plutil -convert json sample.plist {"Author":"William Shakespeare","Birthdate":1564,"Lines":["It is a tale told by an idiot,","Full of sound and fury, signifying nothing."]} Now you can read this using the JSON library. import json plist_text = '{"Author":"William Shakespeare","Birthdate":1564,"Lines":["It is a tale told by an idiot,","Full of sound and fury, signifying nothing."]}' plist = json.loads(plist_text) print('The author is ' + plist['Author']) Output: $ python3 plist.py $ The author is William Shakespeare
type: AcceptedAnswer
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49628202
has comment: http://stackoverflow.com/comment/93468726
has comment: http://stackoverflow.com/comment/93468644
type: Answer
has comment: http://stackoverflow.com/comment/86395717
has comment: http://stackoverflow.com/comment/93468340

http://stackoverflow.com/comment/86456102
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49714155
has text: Ok when i run it from the cli in a .py file it animates the curve fine but in jupyter notebook it doesnt work. Why this could happen?
type: AnswerComment

http://stackoverflow.com/a/49723297
has body: Are you looking for something as simple as this? import numpy as np x = [[1,6,5,4],[1,6,9,8],[6,5,1,4]] rate = 0.2 out = [np.npv(rate, i) for i in ars]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49721598

http://stackoverflow.com/q/49755841
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49757907
has comment: http://stackoverflow.com/comment/86527220
answer count: 1
has answer: http://stackoverflow.com/a/49757907
has body: I've aggregated some data and i'd like to get the aggregation values back into another dataframe. I've aggregated the data like this bycluster_type = df.groupby(['cluster', 'Type']) tCount = bycluster_type['Type'].agg([len]) Edit: From this point i made some mistakes which i've corrected now and added a few new thoughts. tCount is now a DataFrame with a MultiIndex. What i'd lke to do now is to get the cluster, type and the corresponding value to put it together with some other data in another dataframe. For example: &gt;&gt;&gt; tCount len cluster Type 1.0 M 1 2.0 M 7 4.0 M 2 So the next step is to get the index and the row: index, row = next(tCount.index.values) So what i'd do next is to unzip the index tuple into cluster and type and get the len value from the row. cluster, type = index val = row['len'] Is there a more efficent or elegant way of achieving my goal? Edit: Some example data cluster, Type, foo 1, M, f 1, T, o 1, S, o 2, M, f 2, M, o 3, T, o
has comment: http://stackoverflow.com/comment/86531787
has comment: http://stackoverflow.com/comment/86528681
tagged with: series
has title: Python pandas series multiindex iteration
type: Question
has comment: http://stackoverflow.com/comment/86527300
tagged with: python
has comment: http://stackoverflow.com/comment/86526675
has comment: http://stackoverflow.com/comment/86526604
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49603077
has body: It's as simple as: x=[['Saks, Lord &amp; Taylor data breach may affect 5 million customers', (u'By Mike Murphy', u'April 1, 2018, 5:24 p.m. EST')],['Why The China Hustle is a finance documentary all U.S. investors need to see', (u'By MarketWatch', u'NewsWatch')],['Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets', (u'By Mike Murphy', u'April 1, 2018, 4:49 p.m. EST')]] import csv with open('bla.csv','w') as fd: writer=csv.writer(open('bla.csv','w')) writer.writerows(x) Note "Why The China ..." is not quoted in the csv as it does not contain any commas. If you want it quoted you can use quoting=QUOTE_ALL in the writer constructor.
score: 2
answers question: http://stackoverflow.com/q/49603012
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49603012
has comment: http://stackoverflow.com/comment/86213543
has comment: http://stackoverflow.com/comment/86213522

http://stackoverflow.com/q/49635269
score: 4
has comment: http://stackoverflow.com/comment/86280425
linked to: http://stackoverflow.com/q/37091899
has comment: http://stackoverflow.com/comment/86278664
linked to: http://stackoverflow.com/q/49525056
has answer: http://stackoverflow.com/a/59167488
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 4
has title: How to load batches of CSV files using tf.data and map
has comment: http://stackoverflow.com/comment/86278936
answer count: 2
has body: I have been searching for an answer as to how I should go about this for quite some time and can't seem to find anything that works. I am following a tutorial on using the tf.data API found here. My scenario is very similar to the one in this tutorial (i.e. I have 3 directories containing all the training/validation/test files), however, they are not images, they're spectrograms saved as CSVs. I have found a couple solutions for reading lines of a CSV where each line is a training instance (e.g., How to *actually* read CSV data in TensorFlow?). But my issue with this implementation is the required record_defaults parameter as the CSVs are 500x200. Here is what I was thinking: import tensorflow as tf import pandas as pd def load_data(path, label): # This obviously doesn't work because path and label # are Tensors, but this is what I had in mind... data = pd.read_csv(path, index_col=0).values() return data, label X_train = tf.constant(training_files) # training_files is a list of the file names Y_train = tf.constant(training_labels # training_labels is a list of labels for each file train_data = tf.data.Dataset.from_tensor_slices((X_train, Y_train)) # Here is where I thought I would do the mapping of 'load_data' over each batch train_data = train_data.batch(64).map(load_data) iterator = tf.data.Iterator.from_structure(train_data.output_types, \ train_data.output_shapes) next_batch = iterator.get_next() train_op = iterator.make_initializer(train_data) I have only used Tensorflows feed_dict in the past, but I need a different approach now that my data has gotten to the size that it can no longer fit in memory. Any thoughts? Thanks.
has answer: http://stackoverflow.com/a/49676348
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86335309

http://stackoverflow.com/a/49776128
accepted answer of: http://stackoverflow.com/q/49615818
score: 2
answers question: http://stackoverflow.com/q/49615818
type: AcceptedAnswer
downvote count: 0
has body: @app.route def index(): class someObj: def someFunc(someArg): return 10 + someArg return render_template("template.html", obj=someObj(), arg=25) ------------- &lt;div&gt; {{ obj.someFunc(someArg=arg) }} &lt;/div&gt; The above will display '35' in the HTML. In general when inside the curly brackets you do no need to rewite them again. I.e. don't do this: {{ obj.someFunc(someArg={{ arg }}) }} Your error is because jinja 2 thought the value you passed to the value argument was "{{row[" and after that it expected a comma separator but instead received item_url. {{ form.item_url_field(value="{{row["item_url"]}}" ) }} should be {{ form.item_url_field(value=row['item_url']) }} (if indeed row is a dict that has been injected into the template scope)
upvote count: 2
type: Answer

http://stackoverflow.com/comment/86326227
comment on: http://stackoverflow.com/q/49657455
type: Comment
has text: Could you print the shapes and the `dtype` of the ndarrays? Do they have any non-float values (nan, inf, etc)?
type: QuestionComment
score: 0

http://stackoverflow.com/q/49666331
answer count: 1
has body: want to write a code that calculate bills for the phone user out of string. the string format is as following: "00:05:01,444-555-701, 00:06:03,111-222-333, 00:01:20,444-555-701" first "hh:mm:ss,ddd-ddd-ddd" hours:minutes:seconds, phone number with the following conditions: 1- if the call duration is less than five minutes, every started second is for 5 cents. 2- if the call is more than or equal to five minutes, every started minute is for 150 cents. 3-the longest call for a phone number is for free, in the example 444-555-701 is for free since total calls duration is 00:06:23 is the longest call
has title: calculate the phone bills for user out of string
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49668592
accepted answer: http://stackoverflow.com/a/49668592
tagged with: python
type: AnsweredQuestion
downvote count: 4
upvote count: 0
score: -4

http://stackoverflow.com/q/49730803
score: 0
tagged with: bash
accepted answer: http://stackoverflow.com/a/49731585
has comment: http://stackoverflow.com/comment/86479198
has answer: http://stackoverflow.com/a/49731585
has comment: http://stackoverflow.com/comment/86475153
has comment: http://stackoverflow.com/comment/86475083
has comment: http://stackoverflow.com/comment/86475121
has body: Is there a more elegant way of comparing these two files? Right now I am getting the following error message: syntax error near unexpected token (... diff &lt;( tr -d ' '. result = Popen("diff &lt;( tr -d ' \n' &lt;" + file1 + ") &lt;( tr -d ' \n' &lt;" + file2 + ") | wc =l", shell=True, stdout=PIPE).stdout.read() Python seems to read "\n" as a literal character.
has comment: http://stackoverflow.com/comment/86475184
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49730843
has comment: http://stackoverflow.com/comment/86475079
has comment: http://stackoverflow.com/comment/86475340
tagged with: python
has comment: http://stackoverflow.com/comment/86475106
has comment: http://stackoverflow.com/comment/86475098
has title: Comparing two files and removing all whitespaces
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49730843

http://stackoverflow.com/a/49719136
has comment: http://stackoverflow.com/comment/86451510
has comment: http://stackoverflow.com/comment/86451134
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You can loop through each row of your txt column like this: import pandas as pd from langdetect import detect import re df = pd.read_csv("annotation_sample.csv") def try_detect(cell): try: detected_lang = detect(cell) except: detected_lang = None return detected_lang # this took 13 mins to run on my machine df['lang'] = df.txt.apply(try_detect) df['lang'].value_counts(dropna=False) en 54641 es 5857 NaN 5665 pt 5279 de 4218 zh-cn 2971 fr 2730 it 2286 ko 2010 ja 1324 ca 1280 nl 1065 da 968 id 811 ro 775 no 608 vi 546 tr 511 af 497 pl 487 cy 451 tl 445 sv 434 fa 417 et 369 he 348 fi 343 so 289 ru 270 sl 224 hr 210 cs 204 hu 203 ar 190 lt 182 sw 181 sk 160 lv 153 el 143 sq 104 zh-tw 37 th 35 bg 26 uk 21 mk 15 ur 13 ta 1 ml 1 bn 1 hi 1 Name: lang, dtype: int64
has comment: http://stackoverflow.com/comment/86451535
has comment: http://stackoverflow.com/comment/86451251
answers question: http://stackoverflow.com/q/49719013
has comment: http://stackoverflow.com/comment/86451340
has comment: http://stackoverflow.com/comment/86451610
has comment: http://stackoverflow.com/comment/86451419
type: Answer
has comment: http://stackoverflow.com/comment/86451583
has comment: http://stackoverflow.com/comment/86451625
accepted answer of: http://stackoverflow.com/q/49719013
has comment: http://stackoverflow.com/comment/86451488

http://stackoverflow.com/q/49622511
has comment: http://stackoverflow.com/comment/86252502
type: Question
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49628678
has answer: http://stackoverflow.com/a/49628678
score: 2
type: AnsweredQuestion
has body: I am trying this username1 = "admin" password = "password" host = "localhost" prefix = 'mongodb://' + username1 + ':' suffix = '@' + host + ':27017/' connString = prefix + urllib.quote(password) + suffix db = MongoClient(connString) fs = gridfs.GridFS(db)//getting error at this line And the error is database must be an instance of database pymongo. I am following this Your help will be highly appreciated.
answer count: 1
tagged with: pymongo
downvote count: 0
has title: database must be an instance of database pymongo
has comment: http://stackoverflow.com/comment/86252016
favorite count: 0

http://stackoverflow.com/a/49756882
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49755973
has body: The problem is that you call window.after(10, move) from within your move function without ever cancelling it again. This generates a never ending loop of calls to move for every &lt;KeyPress&gt; event. What you could do is to save the after call to a variable. With this you can make sure that move isn't called again from outside this loop, plus you can use it to cancel the after call on the key's release: from tkinter import * window = Tk() canvas = Canvas(window, width = 300, height = 300, bg ='white') canvas.focus_set() speedx = 0 speedy = 0 speed = 1 # Make variable to store after call object after_obj = None x1=40 y1=40 oval=canvas.create_oval(x1-10,y1-10,x1+10,y1+10,width=2,fill='orange') def key_press(event): global x1, y1 global speedx, speedy, speed global after_obj button = event.keysym if button == 'Up': speedx = 0 speedy = -speed elif button == 'Down': speedx = 0 speedy = speed elif button == 'Right': speedx = speed speedy = 0 elif button == 'Left': speedx = -speed speedy = 0 # Only call move from here if there is no after scheduled if after_obj is None: move() def move(): global x1,y1 global oval global speedx, speedy global after_obj x1 += speedx y1 += speedy canvas.delete(oval) oval = canvas.create_oval(x1+10,y1-10,x1-10,y1+10,width=2,fill='orange') # Save the after call object after_obj = window.after(10, move) def key_release(event): global speedx, speedy global after_obj # When pressing multiple buttons at the same time you can get a key release without an after_obj, so check if it exists then cancel it if after_obj: window.after_cancel(after_obj) # Reset after_obj to None so move can be called from key_press again after_obj = None speedx = 0 speedy = 0 canvas.bind('&lt;KeyPress&gt;', key_press) canvas.bind("&lt;KeyRelease&gt;", key_release) canvas.pack(padx =5, pady =5) window.mainloop()
has comment: http://stackoverflow.com/comment/86529003
accepted answer of: http://stackoverflow.com/q/49755973
type: AcceptedAnswer

http://stackoverflow.com/q/49696146
has comment: http://stackoverflow.com/comment/86444113
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/47534715
tagged with: pandas
has answer: http://stackoverflow.com/a/49696656
accepted answer: http://stackoverflow.com/a/49696656
has comment: http://stackoverflow.com/comment/86405159
tagged with: dataframe
has title: How to sort value of each row of data frame and return the sorted columns name
type: Question
has body: I have 2 data frames with different rows, dF1=(1098 x 2 column ) and df2=(1331 x2) for example: df1 lat-2 long-2 R1 10.612811 46.265142 R2 10.604078 45.896510 R3 10.610205 45.727291 R4 10.606051 45.772968 R5 10.596646 46.517013 df2 lat-1 long-1 G1 10.604065 45.896533 G2 10.612811 46.265142 G3 10.606051 45.772968 G4 10.610205 45.727291 G5 10.606747 44.772287 G6 10.619976 45.847164 G7 10.607682 45.477258 G8 10.784809 44.769609 with the help of Get Nearest Point from each other in pandas dataframe I calculate the Euclidian distance between each Row of df1 and all Rows of df2, so new_df has (1089 x 1331). new_df G1 G2 G3 G4 G5 G6 G7 G8 R1 0.368713 0.000000 0.492220 0.537857 1.492867 0.418039 0.787901 1.505391 R2 0.000026 0.368735 0.123558 0.169330 1.124226 0.051844 0.419267 1.141302 R3 0.169353 0.537857 0.045865 0.000000 0.955010 0.120271 0.250046 0.973469 R4 0.123581 0.492220 0.000000 0.045865 1.000681 0.075491 0.295714 1.019158 R5 0.620524 0.252389 0.744104 0.789838 1.744755 0.670255 1.039814 1.757506 I want the result like this: close R1 [G2,G1,G6,G3,G5,G4,G7,G8] R2 [G1, G6, ,,......] R3 [G4,...] R4 [G3,....] R5 [G2,G5,...] R6 [G2,G3,...] R7 [G4,...] in other words, I want for each row of new_df to sort value of columns in ascending order , finally return result like I want. I could not use codes of Get Nearest Point from each other in pandas dataframe I try to write like this: def Closest(df): d=defaultdict(list) for x in (df.index): y=df.loc[str(x)].copy() M=y.tolist() Q=M.sort_val(ascending=True) p=Q.index d[x].appand(p) return (d) my idea was like: h=new_df.loc["R1"].copy() h: G1 0.368713 G2 0.000000 G3 0.492220 G4 0.537857 G5 1.492867 G6 0.418039 G7 0.787901 G8 1.505391 Name: R3, dtype: float64 k=h.sort_values(ascending=True) k.index d={} d['R']=k.index so I wanted to create a dictionary which contains index R as key and list of ordered G as value.finally, I can make a data frame from this dictionary. but when I write this function is sending ("'float' object ha…
answer count: 1
tagged with: python

http://stackoverflow.com/comment/86571133
type: Comment
type: QuestionComment
has text: you are using anaconda so you should try to first update pip from conda : `conda install pip` then install watson-developer-cloud again
score: 0
comment on: http://stackoverflow.com/q/49750577

http://stackoverflow.com/a/49603579
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49603557
type: Answer
has body: Here is one way using a list comprehension and str.strip. Note it does not appear you require regex for this task. channels = 'KMP, PRIME' lst = [i.strip() for i in channels.split(',')] # ['KMP', 'PRIME'] res = ','.join(lst) # KMP,PRIME
accepted answer of: http://stackoverflow.com/q/49603557
score: 3

http://stackoverflow.com/a/49658762
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49658383
has comment: http://stackoverflow.com/comment/86327328
upvote count: 2
type: AcceptedAnswer
has body: Split your trigrams to select first 2 and also last two words (just in case you want to analyze. Then you may do comparisons and at high level you may try String Fuzzy Matching for 100% match. Preferred data structure I would say List. Make list of all above two list of lists having 2 words from trigrams and then perform matching operation. For example: li = ['spam eggs blabla'] li[0].split()[0:2] output &gt;&gt; ['spam', 'eggs'] Now you may want to convert to string li1 = li[0].split()[0:2] str1 = ' '.join(li1) Now you do similarly for bigrams and try comparisons. For reference String Fuzzy Match Here
downvote count: 0
answers question: http://stackoverflow.com/q/49658383
has comment: http://stackoverflow.com/comment/86326926

http://stackoverflow.com/comment/86323483
comment on: http://stackoverflow.com/q/49657011
type: Comment
has text: @Mick there is some dead time between messages. I thought `sock.recv` would return an error if it attempts to read data and there is nothing to read?
type: QuestionComment
score: 0

http://stackoverflow.com/a/49731631
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49731550
has body: You can only split likes with likes - if you want to split with \n while still keeping graph_text as bytes, define the split as a bytes sequence, too: graph_lines = graph_text.split(b'\n') Otherwise, if you know the codec your graph_text data was encoded with, first decode it into a str with: graph_text.decode("&lt;codec&gt;") and then continue treating it as a str.

http://stackoverflow.com/comment/92764900
type: AnswerComment
has text: Hey, I'm facing the same problem. Did you do something with my_op other than that line?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49687674

http://stackoverflow.com/a/49610397
score: 0
answers question: http://stackoverflow.com/q/49610175
has body: JulioCamPlaz has already provided a decent enough solution, but if you want to maintain the date format, you can use regex for this: import re x = time.ctime(os.path.getmtime("/home/sulata/Documents/source/")) print(re.sub(r':\d{1,2}\s', ' ', x)) What this does is that it removes the final two digits (seconds) of the time which are followed by a space, and replaces it with a space. Although this may be an over-complicated method, it is short, and gives you the exact same date format without the seconds, and without altering it in any way.
type: Answer

http://stackoverflow.com/comment/86332465
type: AnswerComment
comment on: http://stackoverflow.com/a/49661353
has text: It doesn't have to start with a number, he said it can be `a.1` or `a.a`.
score: 1
type: Comment

http://stackoverflow.com/q/49602973
has title: LibreOffice python macro gives error while same command from python console works fine
favorite count: 0
has comment: http://stackoverflow.com/comment/86237234
has body: We are trying to write a string from a cell in a LO Calc sheet to Blue Tooth serial. The BT connection works. After using: "sudo rfcomm bind 7 1" we can send strings using cutecom. From the python command line this also works: f1 = open("/dev/rfcomm7", "a") f1.write("noot") f1.flush() f1.close() "noot" is received fine by the HC-05 BT unit on the arduino and shown on the display. However running the below macro from LibreOffice Calc raises the an error: com.sun.star.uno.RuntimeExceptionError during invoking function writetofile in module file:///home/###/.config/libreoffice/4/user/Scripts/python/writeToSer.py (: [Errno 29] Illegal seek /home/###/.config/libreoffice/4/user/Scripts/python/writeToSer.py:17 in function writetofile() [f = open("/dev/rfcomm7", "a")] /usr/lib/libreoffice/program/pythonscript.py:870 in function invoke() [ret = self.func( *args )] ) Macro in Calc: import uno def writetofile(*args): oDoc = XSCRIPTCONTEXT.getDocument() oSheet = oDoc.CurrentController.ActiveSheet oCell1 = oSheet.getCellByPosition(2, 80) shNumber = oCell1.String f2 = open("/home/###/pythonoefeningen/test.txt", "a") f2.write(shNumber) f2.write("\n") f2.flush() f2.close() f = open("/dev/rfcomm7", "a") f.write("piet") # shNumber) f.flush() f.close() The f2 part was added to confirm the upper part fetching the value from the spreadsheet works and the output to a file works. (it does). The error occurs on the line: f = open("/dev/rfcomm7", "a") Who can explain the difference in behavior between the command line and the macro. And of course suggest a solution. Os: linux mint 18 Cheers,
has comment: http://stackoverflow.com/comment/86230389
tagged with: python
tagged with: bluetooth
type: Question
answer count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: libreoffice-calc
tagged with: arduino
downvote count: 0

http://stackoverflow.com/q/49749227
has comment: http://stackoverflow.com/comment/87171350
possible better answer: http://stackoverflow.com/a/49749544
tagged with: python
tagged with: lambda
accepted answer: http://stackoverflow.com/a/50076269
type: AnsweredQuestion
score: -2
answer count: 2
has title: AWS S3 access control
downvote count: 2
has answer: http://stackoverflow.com/a/49749544
tagged with: amazon-web-services
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86597741
has answer: http://stackoverflow.com/a/50076269
has body: I need to build an authorization system on AWS. There are some customer records stored in DynamoDB. The customer may have different permission for the S3 resources. So, how can I implement this? I am trying to use API gateway to proxy S3 and use Lambda authorizer to check the record and control the access, is this the right way? Struggling, Struggling...
has comment: http://stackoverflow.com/comment/87162594
upvote count: 0

http://stackoverflow.com/a/49719695
upvote count: 3
has comment: http://stackoverflow.com/comment/86462967
downvote count: 0
has comment: http://stackoverflow.com/comment/86455309
score: 3
type: Answer
has body: Button and Label sizes can be set using several different approaches: Use Kivy Metrics. You can set sizes using dp (for example dp(100)), this is a Density-independent Pixel size. There is also a sp (used similarly) that is Scale-independent Pixels (normally used for font sizes) Use self.texture_size. You can set sizes using this as size: self.texture_size. This will make your Button and Label widgets just large enough to fit the text in it. You can add some padding by using something like: width: self.texture_size[0] + dp(10) height: self.texture_size[1] + dp(10) Use size_hint. This will ensure that the Button and Label widgets take up the same percentage of your display, regardless of the device. Don't forget to set size_hint to None, None for the first two above to work.
answers question: http://stackoverflow.com/q/49713682

raspberry-pi3
tags question: http://stackoverflow.com/q/49659112
tags question: http://stackoverflow.com/q/49708190
tag name: raspberry-pi3
tags question: http://stackoverflow.com/q/49687583
type: Tag
tags question: http://stackoverflow.com/q/49621613
tags question: http://stackoverflow.com/q/49619685
tags question: http://stackoverflow.com/q/49691739
tags question: http://stackoverflow.com/q/49612632
tags question: http://stackoverflow.com/q/49627214
tags question: http://stackoverflow.com/q/49720037
tags question: http://stackoverflow.com/q/49659035
tags question: http://stackoverflow.com/q/49628421
tags question: http://stackoverflow.com/q/49749648
tags question: http://stackoverflow.com/q/49733271
tags question: http://stackoverflow.com/q/49638857
tags question: http://stackoverflow.com/q/49746240
tags question: http://stackoverflow.com/q/49611180
tags question: http://stackoverflow.com/q/49677674
tags question: http://stackoverflow.com/q/49707262

http://stackoverflow.com/a/49614559
type: Answer
has body: Here's a basic version that does what you described, improving it is left as an exercise to the reader: input = [1, 2, 3, 0, 4] output = [] for i, item in enumerate(input): current = input[:] current[i] = item - 1 if item &gt; 0 else item output.append(current) Edit: If the whole operation should be skipped if the current element is less than 1 as implied by the comments, the solution would become: input = [1, 2, 3, 0, 4] output = [] for i, item in enumerate(input): if item &gt; 0: current = input[:] current[i] -= 1 output.append(current)
has comment: http://stackoverflow.com/comment/86235777
has comment: http://stackoverflow.com/comment/86235853
answers question: http://stackoverflow.com/q/49614329
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86236385

http://stackoverflow.com/comment/86301643
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49646270
type: QuestionComment
has text: even if i call a draw function after "self.point_info[:] = [self.list_x[self.i],self.list_y[self.i]]" , it still works the same.

http://stackoverflow.com/a/49707472
downvote count: 0
answers question: http://stackoverflow.com/q/49707401
has comment: http://stackoverflow.com/comment/86428449
type: Answer
has comment: http://stackoverflow.com/comment/86428599
score: 2
upvote count: 2
has body: The solution: [0] + [i for i in mylist if i] looks good enough, except if 0 is not in mylist, in which case you're wrongly adding 0. Besides, adding 2 lists like this isn't very good performance wise. I'd do: newlist = [i for i in mylist if i] if len(newlist) != len(mylist): # 0 was removed, add it back newlist.append(0) (or using filter newlist = list(filter(None,mylist)) which could be slightly faster because there are no native python loops) Appending to a list at the last position is very efficient (list object uses pre-allocation and most of the time no memory is copied). The length test trick is O(1) and allows to avoid to test 0 in mylist

http://stackoverflow.com/comment/86282661
type: QuestionComment
comment on: http://stackoverflow.com/q/49617067
has text: Looks like it is because you can write the file specifically do the directory you need to create a placeholder file then drop it in. I got it to work by doing file = open("Destination_directory" + x, "a+")
score: 0
type: Comment

amazon-web-services
tags question: http://stackoverflow.com/q/49730389
tags question: http://stackoverflow.com/q/49612548
tags question: http://stackoverflow.com/q/49670491
tags question: http://stackoverflow.com/q/49750173
tags question: http://stackoverflow.com/q/49646236
tags question: http://stackoverflow.com/q/49755781
tags question: http://stackoverflow.com/q/49749227
tags question: http://stackoverflow.com/q/49633643
tags question: http://stackoverflow.com/q/49618760
tags question: http://stackoverflow.com/q/49706693
tags question: http://stackoverflow.com/q/49607286
tags question: http://stackoverflow.com/q/49665155
tags question: http://stackoverflow.com/q/49603710
tags question: http://stackoverflow.com/q/49635508
tags question: http://stackoverflow.com/q/49634637
tags question: http://stackoverflow.com/q/49620386
tags question: http://stackoverflow.com/q/49742393
tags question: http://stackoverflow.com/q/49619986
type: Tag
tags question: http://stackoverflow.com/q/49724939
tags question: http://stackoverflow.com/q/49640452
tags question: http://stackoverflow.com/q/49695050
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/49682311
tags question: http://stackoverflow.com/q/49615914
tags question: http://stackoverflow.com/q/49652460
tags question: http://stackoverflow.com/q/49713393
tags question: http://stackoverflow.com/q/49734744
tags question: http://stackoverflow.com/q/49720662
tags question: http://stackoverflow.com/q/49622575
tags question: http://stackoverflow.com/q/49609243

http://stackoverflow.com/a/49741516
has comment: http://stackoverflow.com/comment/86540821
has comment: http://stackoverflow.com/comment/86540942
type: Answer
has comment: http://stackoverflow.com/comment/86540916
accepted answer of: http://stackoverflow.com/q/49741255
has comment: http://stackoverflow.com/comment/86540976
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86540784
answers question: http://stackoverflow.com/q/49741255
has comment: http://stackoverflow.com/comment/86540931
has comment: http://stackoverflow.com/comment/86540946
has comment: http://stackoverflow.com/comment/86541534
type: AcceptedAnswer
has body: The issue is with the following piece of code : with open (fname +'.txt', 'w') as outfile: outfile.write(cln +"\n") fname contains "\n" which cannot be a valid file name to open. All you need to do is just change it to this with open (fname.rstrip() +'.txt', 'w') as outfile: outfile.write(cln +"\n") Full Code fix included: import os import sys import requests import bs4 from bs4 import BeautifulSoup import re import html5lib def clean_me(htmldoc): soup = BeautifulSoup(htmldoc.text.encode('UTF-8'), 'html5lib') for s in soup(['script', 'style']): s.decompose() return ' '.join(soup.stripped_strings) with open('urloutshort.txt', 'r') as filein: for url in filein: if "http" in url: page = requests.get(url.strip()) fname = (url.replace('http://', '')) fname = fname.replace('/', ' ') print(fname) cln = clean_me(page) with open(fname.rstrip() + '.txt', 'w') as outfile: outfile.write(cln + "\n") Hope this helps
has comment: http://stackoverflow.com/comment/86541020
has comment: http://stackoverflow.com/comment/86582259
downvote count: 0

http://stackoverflow.com/q/49716403
has comment: http://stackoverflow.com/comment/86445991
tagged with: permutation
has comment: http://stackoverflow.com/comment/86445879
has comment: http://stackoverflow.com/comment/86446327
has title: Python: Produce all possible sequence combination from a list with character limit
favorite count: 0
type: Question
tagged with: combinations
upvote count: 5
score: 5
possible better answer: http://stackoverflow.com/a/49719208
tagged with: python
has answer: http://stackoverflow.com/a/49719208
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49717795
answer count: 2
has body: My question is exactly the same as this question. I have the array (list) of characters. I would like to get all possible sequence combinations from that list but with the limit of characters (for example: 2 characters as maximum). Further, no single character can be repeated in a permutation line: chars = ['a', 'b', 'c', 'd'] # output output = [['a', 'b', 'c', 'd'], ['ab', 'c', 'd'], ['a', 'bc', 'd'], ['a', 'b', 'cd'], ['ab', 'cd'], ['abc', 'd'], # this one will be exempted ['a', 'bcd'], # this one will be exempted ['abcd']] # this one will be exempted I know I can check the condition to omit the over-limit characters combinations while generating and building the sequence. But it will add the run time. My purpose is to reduce the existing execution time. Without the character count limitation, the combinations will be generated like 2^(N-1). If the list is over 15 characters, it will take too long to execute the program. Therefore I would like to reduce the combinations count by character limit. The priority is performance. I already research and tried for two days without any success.
has answer: http://stackoverflow.com/a/49717795
linked to: http://stackoverflow.com/q/27263155
downvote count: 0
has comment: http://stackoverflow.com/comment/86445832

http://stackoverflow.com/q/49739465
upvote count: 0
has answer: http://stackoverflow.com/a/49740117
has title: tar file with combination of directory name and original timestamp
tagged with: http://stackoverflow.com/tag/tar
tagged with: shell
has comment: http://stackoverflow.com/comment/86494276
downvote count: 1
favorite count: 0
score: -1
type: Question
has body: I want to create the tar file which contains the combination directory name and original timestamp. There are so many files which needs to convert in above format. For the directory below, I expect the new tar file name would be rs_jul_29_2016.tar drwxr-xr-x 3 root root 4096 Jul 29 2016 rs
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86494951
tagged with: python
tagged with: sh
has comment: http://stackoverflow.com/comment/86494856
has comment: http://stackoverflow.com/comment/86494801
answer count: 2
has answer: http://stackoverflow.com/a/49739930

http://stackoverflow.com/q/49642875
has body: I like to run,start or stop a container in docker that is running in another system. I like to know how to do it. My use case is I like to create docker container dynamically for each request. If the container is created for a particular request I like to use the same container. Could it be accessed using api requests? if so what port should i connect to? I need to do this from java
type: Question
has answer: http://stackoverflow.com/a/49644113
tagged with: python
score: -1
has title: Need to access docker engine that is running in one system from another system
tagged with: docker
accepted answer: http://stackoverflow.com/a/49644113
type: AnsweredQuestion
upvote count: 0
tagged with: java
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86297667
favorite count: 0

http://stackoverflow.com/q/49645900
has title: Error accessing an attribute of a class instance
has comment: http://stackoverflow.com/comment/86300066
answer count: 2
tagged with: oop
has body: class chainlist: def ___init__(self): self.chain = [6 ,7] self.create_block(proof=1) blockchain = chainlist() print(chainlist.chain) error: Traceback (most recent call last): File "main.py", line 11, in &lt;module&gt; print(chainlist.chain) AttributeError: class chainlist has no attribute 'chain'
score: 0
has comment: http://stackoverflow.com/comment/86299970
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86300077
has answer: http://stackoverflow.com/a/49645982
has comment: http://stackoverflow.com/comment/86300419
has answer: http://stackoverflow.com/a/49645986
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/49732791
type: Answer
has comment: http://stackoverflow.com/comment/86479818
has body: What about using **kwargs as parameter, so parameter names are not set on function definition but can be retrieved from dict kwargs? Btw, you should provide an example, because I don't clearly get the point of a function that could not rely on the name of its parameter to work ;)
has comment: http://stackoverflow.com/comment/86479726
has comment: http://stackoverflow.com/comment/86479892
score: 0
answers question: http://stackoverflow.com/q/49732428
has comment: http://stackoverflow.com/comment/86480098
has comment: http://stackoverflow.com/comment/86480163

http://stackoverflow.com/q/49649014
tagged with: scrapy
type: Question
has body: I got this code in this website NTP Soundbooster Filtro attuale Catalogo: Aliant Marca e Modello: Mazda - 3 Versione: (3th gen) 2013-now (Petrol) And I am trying to extract the element "Mazda - 3" and I am unable to get it, it return blank. In the code, the "Mazda - 3" part is in brand value. I get the name and the version value. This is how I implemented: for ntp in response.css('div.content-1col-nobox'): name = ntp.xpath('normalize-space(//h5/text())').extract_first() brand = ntp.xpath('normalize-space(//blockquote/p//text()[4])').extract_first() version = ntp.xpath('normalize-space(//div/blockquote[1]/p//text()[6])').extract_first() result = ("{} {} - {}".format(name, brand, version)) This post is related to this one, it work there, but I realized that I get only part of the data. See here: Scrapy add.xpath or join xpath Can anybody help me please. Thank you in advance.
has answer: http://stackoverflow.com/a/49655113
tagged with: python
linked to: http://stackoverflow.com/q/49630374
tagged with: xpath
type: AnsweredQuestion
has title: Scrapy unable to get xpath
score: 0
accepted answer: http://stackoverflow.com/a/49655113
answer count: 1

http://stackoverflow.com/q/49733119
answer count: 1
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
tagged with: python
has title: Calculate mean reciprocal rank
has body: I'm trying to find a way for calculating a MRR fro search engine. I know that reciprocal rank is calculated like : RR= 1/position of first relevant result But this works when I know which is my query word(I mean "question")! In my case I have only results: . . . I have following format of data available: Correct result for query n.1: GT=[doc1, doc2, doc3] Result of my search engine for query n.1: SE=[doc2,doc7,doc1] How I should calculate the RR in this case? Till now i'm doing it in following way: all_rr=[] for i in queries: for j in queries_results: pos=j.index(i[0])+1 RR=1/pos all_rr.append(RR) MRR=np.mean(all_rr) Is this a right approach? (p.s. queries is my GT's dataframe and queries_result is my SE results dataframe)
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51658241

http://stackoverflow.com/a/49739500
type: Answer
has comment: http://stackoverflow.com/comment/86495055
has comment: http://stackoverflow.com/comment/86493806
answers question: http://stackoverflow.com/q/49739231
score: 0
has body: The error says that your object users of type Users has no cursor attribute. Based on the piece of code, there's indeed no cursor attribute on that object/class, so it is expected that cls.cursor.execute(...) throws an exception.
has comment: http://stackoverflow.com/comment/86494745
has comment: http://stackoverflow.com/comment/86493906

http://stackoverflow.com/q/49687914
tagged with: python
has comment: http://stackoverflow.com/comment/86387037
tagged with: regex
has comment: http://stackoverflow.com/comment/86387067
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49688132
has comment: http://stackoverflow.com/comment/86386984
has answer: http://stackoverflow.com/a/49688132
possible better answer: http://stackoverflow.com/a/49688041
upvote count: 1
has answer: http://stackoverflow.com/a/49688041
has comment: http://stackoverflow.com/comment/86387135
linked to: http://stackoverflow.com/q/7409780
downvote count: 1
has title: Regular expression python 4 integers followed by a space
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86387689
has comment: http://stackoverflow.com/comment/86387575
has body: I am trying to split a file each time that there are exactly 4 integers followed by a space on a line in ht efile. I think I am almost there (looking at all questions and examples). Think I need a last push. Could anyone help me out. The script splits all lines that start with 4 integers. It needs to only split when its just 4 integers and not more then 4. import re file = open('test.txt', 'r') Try 1 for x in file.read().split(re.match(r"[0-9]{4}\s", file.readline())): print (x) Try 2 for x in file.read().split(re.match(r"[0-9][0-9][0-9][0-9]\s", file.readline())): print (x) try 3 for x in re.split(r"[0-9]{4}\s", file.read()): print (x) Sample input 1020 200123242151111231 bla bla bla 200123331231231441 bla bla bla 1030 200123242151111231 bla bla bla 200123331231231441 bla bla bla Wished for output is the above content split in: 200123242151111231 bla bla bla 200123331231231441 bla bla bla and 200123242151111231 bla bla bla 200123331231231441 bla bla bla
has comment: http://stackoverflow.com/comment/86387066

http://stackoverflow.com/comment/86491015
type: QuestionComment
comment on: http://stackoverflow.com/q/49736999
has text: Since `wait_closed` is a coroutine, you need to either `await` it or use `run_until_complete` to let it run its course.
type: Comment
score: 1

http://stackoverflow.com/a/49696356
has comment: http://stackoverflow.com/comment/86450297
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49668165
has comment: http://stackoverflow.com/comment/86405440
has body: You have two options. First, the version of Python installed by Visual Studio 2017 is just regular Python. So from a command prompt you can type py.exe -m pip install -e . (optionally including a version number as py.exe -3.6 -m pip ...) to run any commands with it as you normally would. (But note that Visual Studio installs Python for all users, which means you may need to use an administrator command prompt or a virtual environment.) Second, if you're in Visual Studio, you can use the regular "Install package" dialog. When searching for a package, the first item in the list is going to execute exactly what you type. You'll need to use the full path rather than ., but otherwise you can type -e &lt;path&gt; in there and click the first result:
accepted answer of: http://stackoverflow.com/q/49668165
type: Answer
has comment: http://stackoverflow.com/comment/86406581

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/49658725
tags question: http://stackoverflow.com/q/49752547
tags question: http://stackoverflow.com/q/49716294
tags question: http://stackoverflow.com/q/49736006
tags question: http://stackoverflow.com/q/49727313
tags question: http://stackoverflow.com/q/49609718
tags question: http://stackoverflow.com/q/49684133
tags question: http://stackoverflow.com/q/49697876
tags question: http://stackoverflow.com/q/49643793
tags question: http://stackoverflow.com/q/49753012
tags question: http://stackoverflow.com/q/49625918
tags question: http://stackoverflow.com/q/49631072
tags question: http://stackoverflow.com/q/49608967
tags question: http://stackoverflow.com/q/49600385
tags question: http://stackoverflow.com/q/49606856
tags question: http://stackoverflow.com/q/49614493
tags question: http://stackoverflow.com/q/49747632
tags question: http://stackoverflow.com/q/49661771
tags question: http://stackoverflow.com/q/49665969
tags question: http://stackoverflow.com/q/49626788
tags question: http://stackoverflow.com/q/49687742
tags question: http://stackoverflow.com/q/49658760
tags question: http://stackoverflow.com/q/49671693
tags question: http://stackoverflow.com/q/49615349
tag name: json
tags question: http://stackoverflow.com/q/49707491
tags question: http://stackoverflow.com/q/49702531
tags question: http://stackoverflow.com/q/49684700
tags question: http://stackoverflow.com/q/49712385
tags question: http://stackoverflow.com/q/49740849
tags question: http://stackoverflow.com/q/49624055
tags question: http://stackoverflow.com/q/49627871
tags question: http://stackoverflow.com/q/49748899
tags question: http://stackoverflow.com/q/49627084
tags question: http://stackoverflow.com/q/49708847
tags question: http://stackoverflow.com/q/49728723
tags question: http://stackoverflow.com/q/49629782
tags question: http://stackoverflow.com/q/49620498
tags question: http://stackoverflow.com/q/49653836
tags question: http://stackoverflow.com/q/49671523
tags question: http://stackoverflow.com/q/49690138
tags question: http://stackoverflow.com/q/49617605
tags question: http://stackoverflow.com/q/49757889
tags question: http://stackoverflow.com/q/49619865
tags question: http://stackoverflow.com/q/49604819
tags question: http://stackoverflow.com/q/49691704
tags question: http://stackoverflow.com/q/49635819
tags question: http://stackoverflow.com/q/49702861
tags question: http://stackoverflow.com/q/49600631
tags question: http://stackoverflow.com/q/49612815
tags question: http://stackoverflow.com/q/49680588
tags question: http://stackoverflow.com/q/49643760
tags question: http://stackoverflow.com/q/49635722
tags question: http://stackoverflow.com/q/49674363
tags question: http://stackoverflow.com/q/49639152
tags question: http://stackoverflow.com/q/49654377
tags question: http://stackoverflow.com/q/49688476
tags question: http://stackoverflow.com/q/49653637
tags question: http://stackoverflow.com/q/49742707
tags question: http://stackoverflow.com/q/49692459
tags question: http://stackoverflow.com/q/49736688
tags question: http://stackoverflow.com/q/49728033
tags question: http://stackoverflow.com/q/49620677
tags question: http://stackoverflow.com/q/49682906
type: Tag
tags question: http://stackoverflow.com/q/49680411
tags question: http://stackoverflow.com/q/49660272
tags question: http://stackoverflow.com/q/49689863
tags question: http://stackoverflow.com/q/49614725
tags question: http://stackoverflow.com/q/49662560
tags question: http://stackoverflow.com/q/49682024
tags question: http://stackoverflow.com/q/49616250
tags question: http://stackoverflow.com/q/49607176
tags question: http://stackoverflow.com/q/49706693
tags question: http://stackoverflow.com/q/49673596
tags question: http://stackoverflow.com/q/49642153
tags question: http://stackoverflow.com/q/49606012
tags question: http://stackoverflow.com/q/49665749
tags question: http://stackoverflow.com/q/49695836
tags question: http://stackoverflow.com/q/49617178

http://stackoverflow.com/a/49738078
downvote count: 1
has comment: http://stackoverflow.com/comment/124765029
upvote count: 8
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/124764872
has body: here is alpha blending in python import numpy as np import cv2 alpha = 0.4 img1 = cv2.imread('Desert.jpg') img2 = cv2.imread('Penguins.jpg') #r,c,z = img1.shape out_img = np.zeros(img1.shape,dtype=img1.dtype) out_img[:,:,:] = (alpha * img1[:,:,:]) + ((1-alpha) * img2[:,:,:]) ''' # if want to loop over the whole image for y in range(r): for x in range(c): out_img[y,x,0] = (alpha * img1[y,x,0]) + ((1-alpha) * img2[y,x,0]) out_img[y,x,1] = (alpha * img1[y,x,1]) + ((1-alpha) * img2[y,x,1]) out_img[y,x,2] = (alpha * img1[y,x,2]) + ((1-alpha) * img2[y,x,2]) ''' cv2.imshow('Output',out_img) cv2.waitKey(0)
has comment: http://stackoverflow.com/comment/124764339
has comment: http://stackoverflow.com/comment/124764838
answers question: http://stackoverflow.com/q/49737541
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/124764716
accepted answer of: http://stackoverflow.com/q/49737541

http://stackoverflow.com/comment/86342768
score: 0
has text: I updated the code. Believe or not still getting a black screen.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49656343

pydrive
tags question: http://stackoverflow.com/q/49680145
tag name: pydrive
type: Tag

http://stackoverflow.com/q/49635215
tagged with: python-3.x
has body: I need to read a *.inp file into a data frame. the file looks like this B*** BASE 321 Emit 200.000 /mrpo :B311 :200. Emit, 200.000 CG, 1,UFNQ, 123.56 CG, 2,UFNQ, 143.76 CG, 33,UFNQ, 123.56 CG, 223,UFNQ, 143.76 B*** qwqwndqq is iellai ai 200.000 67 B*** qwqwndqq is iellai ai 5050.000 63 /mrpo B*** END 321 Emit 200.000 /EOF I want read it as dataframe and access and change the second number in all rows ( expect in first 5 and last 3 lines ) and rewrite a new *.inp file This is the code I am using df=pandas.read_csv(file_name, sep =',',header = None, engine ='python') output:Expected 1 fields in line 7 saw 2 df=pandas.read_csv(file_name, sep ='s',header = None, engine ='python') output:all in one column df=pandas.read_csv(file_name, sep ='delimiter',header = None, engine ='python') output:all in one column I want new file like this B*** BASE 321 Emit 200.000 /mrpo :B311 :200. Emit, 200.000 CG, 10001,UFNQ, 123.56 CG, 10002,UFNQ, 143.76 CG, 10033,UFNQ, 123.56 CG, 10223,UFNQ, 143.76 B*** qwqwndqq is iellai ai 200.000 67 B*** qwqwndqq is iellai ai 5050.000 63 /mrpo B*** END 321 Emit 200.000 /EOF please suggest if there is any other way in python
has comment: http://stackoverflow.com/comment/86278293
type: UnansweredQuestion
tagged with: python
tagged with: pandas
score: 2
has comment: http://stackoverflow.com/comment/86282306
upvote count: 2
has answer: http://stackoverflow.com/a/49635794
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86278140
has comment: http://stackoverflow.com/comment/86278587
has comment: http://stackoverflow.com/comment/86277786
favorite count: 0
type: Question
has title: python read_csv with sep parameters is giving all in one column or says expected 2 fileds in line 6 but saw 4

http://stackoverflow.com/comment/86308001
type: Comment
type: QuestionComment
has text: 20:30:02.533, as you can see in 2018-01-25T20:30:02.533+0000 , time is 20:30:02.533 only.
comment on: http://stackoverflow.com/q/49649917
score: 0

http://stackoverflow.com/a/49722059
score: 0
upvote count: 1
downvote count: 1
has body: You can use the built-in functions from pyspark.sql.functions to parse into a date and then extract the year: from pyspark.sql.functions import to_date, year &gt;&gt;&gt; df = sqlContext.createDataFrame([("12/12/1980",1,2)], ("Date","Num", "#")) &gt;&gt;&gt; df2 = df.withColumn("Year", year(to_date(df.Date, "dd/MM/yyyy"))) &gt;&gt;&gt; df2.show() +----------+---+---+----+ | Date|Num| #|Year| +----------+---+---+----+ |12/12/1980| 1| 2|1980| +----------+---+---+----+
answers question: http://stackoverflow.com/q/49721738
type: Answer

http://stackoverflow.com/comment/86529516
score: 0
has text: Take a look at this- [How to reshape a multidimensional array to a 2D image?](https://stackoverflow.com/questions/43441230/how-to-reshape-a-multidimensional-array-to-a-2d-image)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49756995

http://stackoverflow.com/q/49702560
accepted answer: http://stackoverflow.com/a/49702588
linked to: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/86419150
has answer: http://stackoverflow.com/a/49702588
type: Question
has comment: http://stackoverflow.com/comment/86418985
answer count: 1
has comment: http://stackoverflow.com/comment/86418869
has body: Here is my current code: row1 = ["","",""] row2 = ["","",""] row3 = ["","",""] def gameTime () print ( row1[0], row1[1], row1[2] ) print ( row2[0], row2[1], row2[2] ) print ( row3[0], row3[1], row3[2] ) while True: player1Row = input ( "Select a row: " ) player1Column = input ( "Select a column: " ) if player1Row == 1 and player1Column == 1: if row1[0] !="X" and row1[0] !="O": row1 [0] = "X" gameTime () I have attempted a few different strategies to replace the list index item [0] using .append() or even .remove() then .append() similarly to no avail. I feel like I am missing something because it works if I place value to the list items as 0,1,2 rather than "" but I wish to do it the way I have right now in order to complete the game. Any suggestions are appreciated. Thank you for your time!
has comment: http://stackoverflow.com/comment/86419050
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86418849
has title: Issues replacing list value for a game of Tic Tac Toe
tagged with: python

http://stackoverflow.com/q/49659112
tagged with: systemd
has comment: http://stackoverflow.com/comment/86328651
has comment: http://stackoverflow.com/comment/86327640
type: AnsweredQuestion
score: 0
has body: I have this code snippet running on a raspberry pi. It basically take pictures of people coming in and out of my room. import RPi.GPIO as GP import os import socket def opencallback(channel): print(GP.input(channel)) if GP.input(channel): global closeEvent closeEvent = 1 else: global openEvent openEvent = 1 def transmit(message): s = socket.create_connection((host, port)) s.send(message) s.close() def capture(cam, gpiolist, quick): GP.output(cam1, gpiolist[0]) GP.output(cam2, gpiolist[1]) GP.output(cam3, gpiolist[2]) if quick: cmd = "raspistill -o capture_%d.jpg -t 2" % cam else: cmd = "raspistill -o capture_%d.jpg" % cam os.system(cmd) # init GP.setwarnings(False) GP.setmode(GP.BOARD) cam1 = 7 cam2 = 11 cam3 = 12 doorIn = 40 ledOut = 38 GP.setup(cam1, GP.OUT) # camera Mux1 GP.setup(cam2, GP.OUT) # camera Mux2 GP.setup(cam3, GP.OUT) # camera Mux3 GP.setup(ledOut, GP.OUT) # LED OUT GPIO 20 GP.setup(doorIn, GP.IN) # Door detector in GPIO 21 GP.add_event_detect(doorIn, GP.BOTH, callback=opencallback) GP.output(ledOut, False) openEvent = 0 closeEvent = 0 host = '192.168.1.111' port = 13579 # main while True: if openEvent == 1: transmit("2-01") capture(2, (False, True, False), True) # front cam transmit("2-03") openEvent = 0 else: pass if closeEvent == 1: transmit("2-02") GP.output(ledOut, True) capture(3, (False, False, True), False) GP.output(ledOut, False) transmit("2-04") closeEvent = 0 else: pass Usually, I run it simply by using a standard call through command line and it doesn't load out the system. However, I recently converted it to a service using systemd/ systemctl because I wanted to load that script in the background when I boot the pi. Now, this script is gulping a whole processor core by itself (as reported by htop). I didn't change anything to the code itself during the transition and when I run it the old way, it is still working okay. Most of the time, it is simply running the while loop doing nothing and waiting for a callback from GPIO and then execut…
has answer: http://stackoverflow.com/a/49659546
has comment: http://stackoverflow.com/comment/86329055
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/86327780
has comment: http://stackoverflow.com/comment/86328067
linked to: http://stackoverflow.com/q/510348
type: Question
has comment: http://stackoverflow.com/comment/86328372
has title: Script uses too many cpu power when run as a service on a Raspberry pi
has comment: http://stackoverflow.com/comment/86327646
answer count: 2
has comment: http://stackoverflow.com/comment/86328154
possible better answer: http://stackoverflow.com/a/49659581
linked to: http://stackoverflow.com/q/17075788
has comment: http://stackoverflow.com/comment/86328350
accepted answer: http://stackoverflow.com/a/49659546
has answer: http://stackoverflow.com/a/49659581
has comment: http://stackoverflow.com/comment/86327990
has comment: http://stackoverflow.com/comment/86328076
has comment: http://stackoverflow.com/comment/86328088
tagged with: python
has comment: http://stackoverflow.com/comment/86328404
has comment: http://stackoverflow.com/comment/86328243

http://stackoverflow.com/comment/86489507
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49737596
has text: It looks like you use some Label() widgets already - why not just use that technique for lat/lon/response ?
type: Comment

http://stackoverflow.com/a/49679829
score: 1
type: Answer
has body: the problem isn't the global variable but the row name being reassigned in the loop: row = ['.' for elem in row] that creates a new reference of row, unknown to matrix. You could improve &amp; fix by using slice assignment for instance &amp; more efficient code: for row in matrix: if not '.' in row: # no need to count, just check if a dot is there row[:] = ['.'] * len(row) this works but creates &amp; copies a lot of data. A list comprehension instead of the loop would probably be better: matrix = [row if '.' in row else ['.'] * len(row) for row in matrix] (it works because matrix is global). Also matrix init could be simplified to: matrix=[['.']*WIDTH for _ in range(HEIGHT)] Since strings are immutable you can use multiplication to create the rows (but not for the outer loop!)
has comment: http://stackoverflow.com/comment/86371489
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49679716
accepted answer of: http://stackoverflow.com/q/49679716

http://stackoverflow.com/q/49616424
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49616518
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49616682
downvote count: 0
has title: Check equality of float columns in python
has answer: http://stackoverflow.com/a/49616473
possible better answer: http://stackoverflow.com/a/49616473
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49616518
answer count: 3
has body: I have a dataframe with 2 columns containing floats. I first excluded rows where columns contain zeros and then wanted to check for each row, if the elements of the columns are equal. I tried: df.loc[(df['col1'] != 0.0) &amp; (df['col2'] != 0.0), 'Error'] = np.where(assert_almost_equal(df['col1'], df['col2']), 'Not equal', '') result was: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). and also tried: np.where(df['col1'] == df['col2'], 'Not equal', '') and np.where(df.col1.eq(df.col2), 'Not equal', '') and result was: ValueError: shape mismatch: value array of shape (24788,) could not be broadcast to indexing result of shape (9576,) and also tried apply-function. How can I compare the floats within two columns row by row? I do really want need equality, not isclose or something similar. Thank you, MaMo
linked to: http://stackoverflow.com/q/24870953
tagged with: pandas
tagged with: compare
tagged with: python

http://stackoverflow.com/a/49733617
has body: Based on what you whant to do with you'r data. Try to use mongoDB aggregation. But if you need only query, and do nothing with data, i don't think you will be able to avoid saving all the data in variable.
answers question: http://stackoverflow.com/q/49731562
score: 0
type: Answer

http://stackoverflow.com/comment/86241852
score: 0
type: QuestionComment
has text: https://stackoverflow.com/a/44797397/7919597
type: Comment
comment on: http://stackoverflow.com/q/49617180

http://stackoverflow.com/comment/86268040
type: QuestionComment
has text: *"There should be one and preferably only one obvious way to do it."* - If `sum` was interchangeable with `str.join` there'd be *two* ways to do it…
comment on: http://stackoverflow.com/q/49630581
score: 1
type: Comment

http://stackoverflow.com/q/49617947
has body: I'm working on a programm that uses data from .txt-files and does stuff with said data. The data contains mostly latin characters, but sometimes there are also Japanese characters. That's what I want to do: # -- coding: UTF-8 -- import numpy as np test=open("test.txt", "r") test2=open("list.txt", "w") test2.write("# ") for line in test: line2=line.replace('""', "(None)") line3=line2.replace('"', "") line4=line3.replace(" ", "_") line5=line4.replace(",", " ") test2.write(line5) It works perfectyl fine but there are some Japanese characters that cause problems. Funny thing is, characters like ゲ, ノ, セ, ト or ク are no big deal, but these characters are:い が か. As soon as one of them hides somewhere in test.txt, the follwoing error-message occurs: UnicodeDecodeError Traceback (most recent call last) C:\Users\syhon\Documents\DV-Liste\ListeV2.0\ListeV2.py in &lt;module&gt;() 196 197 test2.write("# ") --&gt; 198 for line in test: 199 line2=line.replace('""', "(None)") 200 line3=line2.replace('"', "") C:\Users\syhon\Anaconda3\lib\encodings\cp1252.py in decode(self, input, final) 21 class IncrementalDecoder(codecs.IncrementalDecoder): 22 def decode(self, input, final=False): ---&gt; 23 return codecs.charmap_decode(input,self.errors,decoding_table)[0] 24 25 class StreamWriter(Codec,codecs.StreamWriter): UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6281: character maps to &lt;undefined&gt; However, I was able to find out that I can print said characters without problem in python 2, but not in python 3. So, is it possible to get these characters decoded in python 3?
tagged with: python
type: Question
tagged with: cjk
accepted answer: http://stackoverflow.com/a/49618253
tagged with: genfromtxt
has answer: http://stackoverflow.com/a/49618253
answer count: 1
has title: python 3 japanese letters from genfromtxt
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86359578
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49667486
has text: Please use the [tag:python-3.x] tag only for version specific questions; always do use the [tag:python] tag together with it (as described in that tag).

http://stackoverflow.com/comment/86462921
comment on: http://stackoverflow.com/q/49724128
score: 0
has text: You have to log it yourself
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49616277
has comment: http://stackoverflow.com/comment/86239435
linked to: http://stackoverflow.com/q/15705630
has comment: http://stackoverflow.com/comment/86240446
has comment: http://stackoverflow.com/comment/86315006
has title: How to iterate over rows of a single column based on value of another column?
has comment: http://stackoverflow.com/comment/86315102
has body: This is the dataset I am working on right now. I want to find the maximum value of the cycle column for a single value of the id column. For ex, I want to find out the max cycle value for id-1, id-2 and so on but I can't really figure out the loop logic. How do I get the code to ouptut maximum cycle value for particular id? My dataset has id values from 1-100 so the code should give me a 100 max cycle values.
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/15705630
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86239566
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49617487

http://stackoverflow.com/q/49628308
possible better answer: http://stackoverflow.com/a/49628378
has answer: http://stackoverflow.com/a/49628378
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49628640
accepted answer: http://stackoverflow.com/a/49628640
has body: I'm exploring the REPL and I noticed the __builtins__ module. I entered &gt;&gt;&gt; __builtins__. and hit Tab, then Python REPL showed me a list of builtin identifiers, including abs, len, zip and True, False, None etc. The first test passed without doubt: &gt;&gt;&gt; __builtins__.zip is zip True But the second one didn't: &gt;&gt;&gt; __builtins__.None is None File "&lt;stdin&gt;", line 1 __builtins__.None is None ^ SyntaxError: invalid syntax Why?
tagged with: python
linked to: http://stackoverflow.com/q/13401563
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/18050815
has title: Python 3: __builtins__.None: Invalid syntax?

http://stackoverflow.com/comment/86330081
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49660203
has text: Do you have to be using multiple while statements? There's still one in here?
type: Comment

http://stackoverflow.com/q/49661746
has body: Okay so, something's odd and I can't figure it out. Suppose I've got some categories, each with some items, all fitted into a dictionary. import wx nyoom = {} nyoom['spiders'] = ['Yellow Sac', 'Orbweaver', 'Garden'] nyoom['cats']= ['Bombay','Angora'] nyoom['cambrian'] = ['Wiwaxia','Hallucigenia','Pikaia','Alomancaris'] Then I want to display each category as a button which collapses or displays all of that category's contents as buttons as well. class SeqFrame(wx.Frame): def __init__(self): wx.Frame.__init__( self, None, wx.ID_ANY, "GUI Woes", size=(400,400)) self.panel = wx.Panel(self, wx.ID_ANY) sizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) #sizer for the window numActsTxtBox = wx.TextCtrl( self.panel, -1, "1", size=(40, -1)) numActsTxtTxt = wx.CheckBox( self.panel, -1, "Number of Times") sizer.Add( numActsTxtTxt, 0, wx.ALL ) sizer.Add( numActsTxtBox, 0, wx.ALL ) for categories in nyoom.keys(): self.categPanes=[] self.categPanes.append(wx.CollapsiblePane(self.panel, -1, label=categories)) self.buildPanes(self.categPanes[-1], sizer) thisPanel = self.categPanes[-1].GetPane() panelSizer = wx.BoxSizer( wx.VERTICAL ) #sizer for the panel contents sortedCategory = nyoom[categories] sortedCategory.sort() for i in range(0,len(nyoom[categories])): thisSeq = wx.Button( thisPanel, label=sortedCategory[i], name=sortedCategory[i]) panelSizer.Add( thisSeq, 0, wx.GROW | wx.ALL ,0 ) thisPanel.SetSizer(panelSizer) panelSizer.SetSizeHints(thisPanel) self.panel.SetSizerAndFit(sizer) self.Fit() def buildPanes(self, categPane, sizer): categPane.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged) sizer.Add(categPane, 0, wx.GROW | wx.ALL, 0) def OnPaneChanged(self, evt): self.panel.GetSizer().Layout() self.panel.Fit() self.Fit() if __name__ == '__main__': app = wx.App() frame = SeqFrame() frame.Show(True) app.MainLoop() (That's my entire sample app.) I can't figure out why, but everything works fine for the last category in the dictionary: But the previous categories can only di…
has title: wxpython collapsible panes inconsistent sizing response
has answer: http://stackoverflow.com/a/49662328
tagged with: sizer
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: wxpython
upvote count: 1
tagged with: python
tagged with: wxgrid
accepted answer: http://stackoverflow.com/a/49662328
type: AnsweredQuestion
tagged with: wxwidgets

http://stackoverflow.com/q/49686867
upvote count: 2
downvote count: 2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49687101
has title: Getting "JSONDecodeError" while loading a json in Python
has body: I have gone through various suggestions in various Stackoverflow posts, but none of the suggestions worked so far. Below is my code: with open("entvpndeviceusage.json","r") as f: data = f.read() d = json.loads(data) &amp; even if i do d = json.load(f).decode('utf-8'), it fails with the same below error. File "C:\Users\611840750\AppData\Local\Continuum\anaconda3\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting value You can see the file here: https://files.fm/u/3maf9dp9 Partial File content #Datasource :entvpndeviceusage [ { "timestamp": "2018-04-04T11:45:06.620Z", "result": { "dimensions": [ "SOURCENSG_DN", "DOMAIN", "APPID", "QUERY", "ENTERPRISENAME", "DOMAIN_SPECID", "ENT_SPECID", "SOURCENSG", "DOMAIN_DN" ], "metrics": [ "INGRESSMB", "TOTALMB", "EGRESSMB" ], "events": [ { "segmentId": "entvpndeviceusage_2018-04-04T11:00:00.000Z_2018-04-04T12:00:00.000Z_2018-04-04T10:00:00.368Z_26", "offset": 0, "event": { "timestamp": "2018-04-04T11:45:06.620Z", "DOMAIN": "AC_PHILIPS ELECTRONICS NEDERLAND B_V__0001_31798", "APPID": "904ac61a-fd4b-4a16-bf4a-4cf0671fd6e4", "ENTERPRISENAME": "PHILIPS ELECTRONICS NEDERLAND B_V_", "ENT_SPECID": "bdbd9597-77a6-403a-bcce-a7b6cb78c862", "QUERY": "/ENT_DEVICE_USAGE.txt", "DOMAIN_SPECID": "f3d73d15-c50c-4ed8-80bd-510424d88ad1", "SOURCENSG": null, "DOMAIN_DN": "Philips Office", "SOURCENSG_DN": null, "INGRESSMB": 0, "TOTALMB": 2924.72998046875, "EGRESSMB": 2924.72998046875 } }, { "segmentId": "entvpndeviceusage_2018-04-04T11:00:00.000Z_2018-04-04T12:00:00.000Z_2018-04-04T10:00:00.368Z_28", "offset": 0, "event": { "timestamp": "2018-04-04T11:45:07.870Z", "DOMAIN": "AC_PHILIPS ELECTRONICS NEDERLAND B_V__0001_31798", "APPID": "b13cb67e-2b79-4fdd-8331-d58c87791df0", "ENTERPRISENAME": "PHILIPS ELECTRONICS NEDERLAND B_V_", "ENT_SPECID": "bdbd9597-77a6-403a-bcce-a7b6cb78c862", "QUERY": "/ENT_DEVICE_USAGE.txt", "DOMAIN_SPECID": "f3d73d15-c50c-4ed8-80bd-510424d88a…
has answer: http://stackoverflow.com/a/49687165
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86384970
tagged with: python
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86384952
has comment: http://stackoverflow.com/comment/86385575

http://stackoverflow.com/comment/86379714
type: QuestionComment
comment on: http://stackoverflow.com/q/49677780
type: Comment
has text: Hi Ernest, Please see above. I have supplemented more details
score: 0

http://stackoverflow.com/comment/86521557
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49742558
has text: Thanks for the reply, attempted this with both 3.4 and 3.5 to be sure and still getting the same error. Any other advice?

http://stackoverflow.com/q/49609445
has title: Python - Removing duplicate nested lists from a dictionary after first element
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49609864
has comment: http://stackoverflow.com/comment/86225720
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86225997
has comment: http://stackoverflow.com/comment/86225827
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86225798
has body: I am using the code beneath to scan through a dictionary and remove duplicate lists. nduplicates = {k:[list(y) for y in {tuple(x[1:]) for x in v}] for k,v in resulsts.items()} The dictionary results is in this format: {'example': [['london','5.123', '-3.123'],['bham','5.123', '-3.123'],['manc','51.23', '-3.453']], [etc..]} Applying the list comprehension works and removes the duplicate nested lists, exclusing the first element; leaving the dictionary like this: {'example': [['london','5.123', '-3.123'],['manc','51.23', '-3.453']]} I was wondering if there is a different way to go about removing the duplicates opposed to the already working solution. I have also tried, but this isn't fully working anyway: print({k: [y for x, y in enumerate(v) \ if y not in v[1:x]] for k, v in results.items()}) Thanks for any help! Any other work arounds for the list comprehension/remove duplicate code would be appreciated!
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49609864

http://stackoverflow.com/q/49742227
tagged with: python
type: AnsweredQuestion
score: 0
has title: Tkinter update label with variable from inside function
has body: I'm using Tkinter to create a window with an entry field and a button. When the button is pressed and a certain condition is not met, I need my_label2 to show a specific text, in this case 'Not Valid'. Otherwise, I need the my_label2 to be blank. I have the variable label_text inside a function that is called by the button press, but I get an error saying that label_text is not defined. Can someone help me out with this? root = tk.Tk() def my_function(): valid = #this variable is either true or false if valid : label_text = '' else : label_text = 'Not Valid' my_label = tk.Label(root, text = "Enter text: ") my_label.grid(row = 0, column = 0) my_entry = tk.Entry(root) my_entry.grid(row = 0, column = 1) my_button = tk.Button(root, text = "Submit", command = my_function) my_button.grid(row = 1, column = 1) my_label2 = tk.Label(root, textvariable = label_text) my_label2.grid(row = 2, column = 1) root.mainloop()
accepted answer: http://stackoverflow.com/a/49742306
answer count: 1
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/49742306

http://stackoverflow.com/comment/86307120
comment on: http://stackoverflow.com/q/49648981
score: 0
has text: Problem with this one is that it will still give me all `b` related to `a`. I want to get rows of `B` which matched with that condition. `D.objects.prefetch_related('a__b').filter(a__b__name=F('name'))` - This will return all D and also all `b` related to `a` because prefetch is not filtered (Correct me if i am wrong). I have edited my question for better understanding of my problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49756084
score: 3
accepted answer: http://stackoverflow.com/a/49756257
type: Question
has answer: http://stackoverflow.com/a/49758139
possible better answer: http://stackoverflow.com/a/49758139
has title: Docker Virtualenv
answer count: 2
upvote count: 3
has body: With containerized applications such as Docker, is it possible to use virtualenv such that the environment stays running from the build process, to when the image is finally run? It seems that creating a virtualenv via pip and running the environment never seems to work. For example: RUN pip3 install virtualenv RUN virtualenv venv RUN source venv/bin/activate Would never seem to render a true virtual environment whereas following pip installs would be installed under the environment. The reason I need, or believe I need this setup, is that specific directories use dependencies that are different versions of neighboring directories: Folder B uses numpy version X, whereas Folder C uses numpy version Y. With Docker, is there a tool or feature that I am forgetting that would allow me to use pip installs like a virtual environment, with different versions of the same dependency in different directories?
downvote count: 0
tagged with: pip
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/49756257
favorite count: 0
tagged with: docker
type: AnsweredQuestion

http://stackoverflow.com/a/49741683
has body: I could fix the Problem finally. But I have to put the Step size to h=0.001 so that it doesnt become an error. This takes the programm to 3 hours of computing... can I pimp the while loop to make it a bit faster?
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49733535

http://stackoverflow.com/q/49697699
tagged with: date
has answer: http://stackoverflow.com/a/49698739
has body: I have a csv-File (Columns: Date, Price, x, y, z), frow which I would like to read only the rows that fall into a certain time period. I tried this: ... abc1 = pandas.read_csv(filesource1, parse_dates=['Date']) abc2 = abc1.price startDate = datetime(2014,8,1) endDate = datetime(2018,3,1) daterange = pandas.date_range(startDate,endDate) abc3 = abc2[daterange] print (abc3.head()) This gives me a list, where only the date is included and price is 'NaN'. How would this be done right?
tagged with: pandas
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86409064
has comment: http://stackoverflow.com/comment/86409174
has comment: http://stackoverflow.com/comment/86409117
has comment: http://stackoverflow.com/comment/86408738
has title: select rows by date with Pandas read_csv
type: Question
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/86343199
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49666668
has text: Split is a `str` method, that's why is not working. The information repeated that you mention, what is repeated? Words, full lines? If you provide this (you don't have to provide the actual info), maybe we can provide a better answer.

http://stackoverflow.com/comment/86277786
score: 0
comment on: http://stackoverflow.com/q/49635215
type: QuestionComment
has text: Text file is like this:
type: Comment

http://stackoverflow.com/comment/91364724
type: AnswerComment
has text: Specifically I'm trying to install `python-apns` which is compatible both with Python 2.7 and Python 3. My source is Python 2.7 and I'm working in a Python virtual environment. I tried `python2.7 -m pip install python-apns` and `python3 -m pip install python-apns` both inside the virtualenv and outside and all 4 tries result the same `(from versions: )` so something is brain dead. Do you think it can be Linux distribution related or rather some clashes of Python versions?
type: Comment
comment on: http://stackoverflow.com/a/49748494
score: 0

http://stackoverflow.com/comment/86209455
comment on: http://stackoverflow.com/a/49601116
type: AnswerComment
has text: If you're using `strptime` to parse the dates, what is the point of using `daterangeparser` at all?
score: 0
type: Comment

http://stackoverflow.com/comment/86396976
type: AnswerComment
comment on: http://stackoverflow.com/a/49691586
type: Comment
has text: https://stackoverflow.com/questions/49692459/multiple-model-accuracy-json-result-format-using-python
score: 0

http://stackoverflow.com/a/49698216
has body: I think I've found the solution. As it says in this link: https://www.quora.com/How-do-I-load-images-efficiently-for-training-a-deep-neural-network-CNNs-My-images-are-too-big-to-load-all-of-them-into-memory I can save in a list, the name of all the photos, suffle them, and then load only the photos I need for training. The variable I've mentioned (imageTrain) will be a list of Strings, where each string is the path of each image. Hope is clear!
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49698127

http://stackoverflow.com/comment/86504018
score: 0
has text: `File "<ipython-input-101-9da8a1cd8f0d>", line 2, in <module> A = df.a[i] File "C:\Users\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py", line 642, in __getitem__ return self._get_with(key) File "C:\Users\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py", line 655, in _get_with return self._get_values_tuple(key) File "C:\Users\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py", line 700, in _get_values_tuple raise ValueError('Can only tuple-index with a MultiIndex') ValueError: Can only tuple-index with a MultiIndex`
type: Comment
comment on: http://stackoverflow.com/q/49744674
type: QuestionComment

http://stackoverflow.com/comment/86397180
has text: Well I edited my question to show you where I am stuck. Isn't there any possibility to have a 'pointer' to the matched object so that I can work with it in the later part of the program. In C++ you could do that but isn't there any Pythonic way?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49669620

http://stackoverflow.com/q/49724663
answer count: 2
tagged with: functional-programming
has comment: http://stackoverflow.com/comment/86463865
upvote count: 3
score: 3
has title: Python: Can I partially apply reduce with an initializer?
has comment: http://stackoverflow.com/comment/86463344
downvote count: 0
has comment: http://stackoverflow.com/comment/86463646
favorite count: 0
type: Question
has body: The initializer comes after the iterable. This causes problems for partial application. Consider these (trivial) examples: In [1]: from functools import reduce, partial In [2]: f = partial(reduce, lambda a,b: a+b, 100) In [3]: f([1,2,3]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-3-816cce84b257&gt; in &lt;module&gt;() ----&gt; 1 f([1,2,3]) TypeError: reduce() arg 2 must support iteration In [4]: f = partial(reduce, lambda a,b: a+b, initializer=100) In [5]: f([1,2,3]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-5-816cce84b257&gt; in &lt;module&gt;() ----&gt; 1 f([1,2,3]) TypeError: reduce() takes no keyword arguments Is there some trick to get around this?
has comment: http://stackoverflow.com/comment/86463500
has answer: http://stackoverflow.com/a/49724741
tagged with: functools
has comment: http://stackoverflow.com/comment/86463562
has comment: http://stackoverflow.com/comment/86463282
has comment: http://stackoverflow.com/comment/86463371
has answer: http://stackoverflow.com/a/49724729
has comment: http://stackoverflow.com/comment/86463510
tagged with: python
tagged with: partial-application
possible better answer: http://stackoverflow.com/a/49724741
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86463592
accepted answer: http://stackoverflow.com/a/49724729
tagged with: reduce

http://stackoverflow.com/comment/86334661
score: 0
type: Comment
type: AnswerComment
has text: @HUAN5235 Then you have to come up with some unambiguous rule. If you never have hash marks as part of the comments, the rule could just be to match from the _last_ hash mark, like `re.sub(r'#[^#]*$', '', s, flags=re.MULTILINE)`. If both comments and text can have hash marks… you'll have to think something up, but whatever you come up with can probably be implemented.
comment on: http://stackoverflow.com/a/49662257

http://stackoverflow.com/a/49614980
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49614798
upvote count: 2
has comment: http://stackoverflow.com/comment/86237540
type: Answer
has body: Even without using any libraries, this is fairly easy with the csv you're using. First open the file (I'm going to assume you have the path saved in the variable filename), then read the file with the readlines() function, and then filter out according to the condition you give. with open(filename, 'r') as csv: # Open the file for reading rows = [line.split(',') for line in csv.readlines()] # Read each the file in lines, and split on commas filter = [line[0] for line in rows if abs(float(line[1])) &lt; 1] # Filter out all lines where the second value is not equal to 1 This is now the accepted answer, so I'm adding a disclaimer. There are numerous reasons why this code should not be applied to other CSVs without thought. It reads the entire CSV in memory It does not account for e.g. quoting It is acceptable for very simple CSVs but the other answers here are better if you cannot be certain that the CSV won't break this code.
has comment: http://stackoverflow.com/comment/86236601
has comment: http://stackoverflow.com/comment/86237055
has comment: http://stackoverflow.com/comment/86236468
answers question: http://stackoverflow.com/q/49614798
score: 2
has comment: http://stackoverflow.com/comment/86236606

http://stackoverflow.com/comment/86484481
comment on: http://stackoverflow.com/q/49733311
score: 0
has text: @Zorgan but your requirement doesn't seem to make sense. If you can't pass it, how can your view depend on it? It needs to come from somewhere.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86283809
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49637965
type: QuestionComment
has text: Make sure that you can run this code yourself to get the expected error.

http://stackoverflow.com/q/49702026
downvote count: 1
tagged with: tensorflow
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/86418246
type: Question
accepted answer: http://stackoverflow.com/a/49702387
tagged with: scikit-learn
tagged with: python
tagged with: keras
answer count: 1
has body: I want to train a CNN with Keras. I understand that x_train contains the data features and y_trainthe labels. I tried test_train_split(x_train,test_size=0.2,train_size=0.8). How do I create y_train?
tagged with: deep-learning
type: AnsweredQuestion
has title: How to create a data-set for deep learning?
upvote count: 0
has answer: http://stackoverflow.com/a/49702387

http://stackoverflow.com/a/49715127
accepted answer of: http://stackoverflow.com/q/49715043
type: AcceptedAnswer
has body: You need to break out of the while loop, this has to be done at 2 places: After reading the file (when it is a correct file) After the Enter key is pressed. because we want to end. Also you need to prompt the question inside the loop so the question is asked again at every iteration and the inputFile value is updated with the latest user input One last thing, I think your else clause can be removed as it is never accessed, the if and elif catch all the possibilities (ie, inputFile has a value or not). def getFiles(cryptSelection): while True: inputFile = input("\nEnter the file to %s. Press Enter alone to abort:" % cryptSelection) if inputFile != '': try: fileText = open(inputFile, "r") fileText.close() # break out of the loop as we have a correct file break except IOError: print("Error - that file does not exist. Try again.") else: # This is the Enter key pressed event break return inputFile
score: 0
answers question: http://stackoverflow.com/q/49715043
type: Answer

http://stackoverflow.com/comment/100623936
comment on: http://stackoverflow.com/q/49642896
score: 0
type: Comment
has text: For me, `driver.execute_script('window.print();')` just closes the window, nothing downloaded.
type: QuestionComment

http://stackoverflow.com/a/49712757
type: Answer
has comment: http://stackoverflow.com/comment/86438983
has body: Look into Python classes. Example class Customer: #constructor, self == this def __init__(self, data): self.data = data def ReadCustomerRecord (cust_id): ## get from db cust = Customer(data) return cust customer = ReadCustomerRecord(1234) Python is a dynamically typed-language meaning that type-checking is done during the runtime of the program. All types are implicit, in fact methods can return varying types based on the condition. def func(is_list): if is_list: return [1,2,3] else: return 1
upvote count: 2
has comment: http://stackoverflow.com/comment/86439055
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86439012
has comment: http://stackoverflow.com/comment/86439116
answers question: http://stackoverflow.com/q/49712729

http://stackoverflow.com/q/49723682
tagged with: time-series
has comment: http://stackoverflow.com/comment/86461053
has comment: http://stackoverflow.com/comment/86461097
has comment: http://stackoverflow.com/comment/86461082
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86461126
tagged with: python
linked to: http://stackoverflow.com/q/42137529
has comment: http://stackoverflow.com/comment/86461305
score: 0
has answer: http://stackoverflow.com/a/49724049
has answer: http://stackoverflow.com/a/49723744
answer count: 2
tagged with: pandas
has title: python time series lag by shift(1), how to fillna for the created NaN
has comment: http://stackoverflow.com/comment/86461145
has body: I have a a very large dataset containing id and data points of time series (with some missing values). The following is just an example. I will need to create a lag variable for both group which of course will create NaN for the first observation for each group. I would like to assign the next available value to the created NaN specifically but leave other missing value untouched for later manipulation. id time value lag_value A 2000 10 NaN # I want this to be 10, the next available value A 2001 11 10 A 2002 NaN 11 A 2003 14 NaN A 2004 10 14 Edit: I think it would be cleaner to use first_valid_index to assign the next available value, see Pandas - find first non-null value in column
type: Question

http://stackoverflow.com/comment/86522403
comment on: http://stackoverflow.com/q/49753830
score: 0
type: Comment
type: QuestionComment
has text: # filename = wget.download(url.strip()) print (url.strip()) , one url per line .

http://stackoverflow.com/q/49621699
tagged with: python
has comment: http://stackoverflow.com/comment/86250409
has body: I don't understand why I have this error in my code."UnboundLocalError: local variable 'state' referenced before assignment" My understanding is that the variable "state" is a local variable, and I didn't use it beyond the function. def get_list_of_university_towns(): with open("university_towns.txt") as townfile: unitowns=townfile.readlines() town_list=[] for line in unitowns: line.rstrip() if line[-6:]=="[edit]": state = line[:-6] elif ' (' in line: town = line[:line.index("(")-1] town_list.append([state,town]) else: town = line town_list.append([state,town]) unitown_pd=pd.DataFrame(town_list, columns=["State","RegionName"]) return unitown_pd get_list_of_university_towns()
has comment: http://stackoverflow.com/comment/86250234
type: Question
has comment: http://stackoverflow.com/comment/86250471
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has title: local variable 'state' referenced before assignment
has comment: http://stackoverflow.com/comment/86250349
favorite count: 0
has answer: http://stackoverflow.com/a/49638008
tagged with: pandas
has comment: http://stackoverflow.com/comment/86250337
has comment: http://stackoverflow.com/comment/86250298

http://stackoverflow.com/a/49713781
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49681973
has body: I have arrived at an answer to this problem and I'd like to thank @Jatmir for sending my down the right path in the comments to the question. The issue is that the base-Ubuntu-image I used does not include any locales by default. In order to add them to the image I was building, I added the following commands to my Dockerfile: RUN apt-get install -y locales RUN locale-gen en_US.UTF-8 RUN update-locale en_US.UTF-8 Then, I just ran these commands in the container and committed it: export LC_ALL=$(locale -a | grep en_US) export LANG=$(locale -a | grep en_US) Alternatively, you could add these variables to either the Dockerfile, or declare them in run the command. Any of said approaches should work.

http://stackoverflow.com/q/49756646
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49757481
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49757752
tagged with: python-internals
type: Question
has answer: http://stackoverflow.com/a/49758859
has answer: http://stackoverflow.com/a/49757211
tagged with: python
type: UnansweredQuestion
score: 34
upvote count: 34
has title: When is a function in a standard library module called a built-in function?
answer count: 4
has body: I am confused about the term "built-in" function. I thought it meant only those functions built into the interpreter and documented in - 2. Built-in Functions But it appears that functions defined in standard library modules are also built-in functions (in some cases). For example - &gt;&gt;&gt; import os &gt;&gt;&gt; os.chdir &lt;built-in function chdir&gt; &gt;&gt;&gt; import warnings &gt;&gt;&gt; warnings.warn &lt;built-in function warn&gt; &gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps &lt;function dumps at 0x7f3643a240d0&gt; # not built-in &gt;&gt;&gt; dir &lt;built-in function dir&gt; &gt;&gt;&gt; So when is a function in a standard library module called a built-in function and when is it not?
has comment: http://stackoverflow.com/comment/86529267

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/49654550

http://stackoverflow.com/q/49614553
accepted answer: http://stackoverflow.com/a/49614797
has answer: http://stackoverflow.com/a/49614797
tagged with: python
has answer: http://stackoverflow.com/a/49614911
has body: I'm reading Python 2.3 MRO article, where the following class hierarchy is given: &gt;&gt;&gt; O = object &gt;&gt;&gt; class F(O): pass &gt;&gt;&gt; class E(O): pass &gt;&gt;&gt; class D(O): pass &gt;&gt;&gt; class C(D,F): pass &gt;&gt;&gt; class B(E,D): pass &gt;&gt;&gt; class A(B,C): pass 6 --- Level 3 | O | / --- \ / | \ / | \ / | \ --- --- --- Level 2 2 | E | 4 | D | | F | 5 --- --- --- \ / \ / \ / \ / \ / \ / --- --- Level 1 1 | B | | C | 3 --- --- \ / \ / --- Level 0 0 | A | --- On the paragraph following it, the following quote left me confused: A lazy programmer can obtain the MRO directly from Python 2.2, since in this case it coincides with the Python 2.3 linearization. &gt;&gt;&gt; A.mro() (&lt;class '__main__.A'&gt;, &lt;class '__main__.B'&gt;, &lt;class '__main__.E'&gt;, &lt;class '__main__.C'&gt;, &lt;class '__main__.D'&gt;, &lt;class '__main__.F'&gt;, &lt;type 'object'&gt;) The reason I'm confused is that earlier on the article it's stated: Classic classes maintain their old method resolution order, depth first and then left to right. Question: If the old-style MRO is depth-first, left to right, then the old-style MRO of the aforementioned class hierarchy should be different, i.e ABEODOCDOFO. Therefore, the "lazy programmer" cannot obtain its MRO directly from Python 2.2. Is that right? For example, on the following snippet (Don't run it on Python 3.x): class O: x = 'o' class F(O): pass class E(O): pass class D(O): pass class C(D,F): x = 'c' class B(E,D): pass class A(B,C): pass print A.x If the old-style MRO was the same as the new-style MRO (i.e., ABEC etc.), I'd expect it to print c. However, it prints o (i.e., it's ABEO etc.). Or here: class O: pass class F(O): pass class E(O): pass class D(O): x = 'd' class C(D,F): x = 'c' class B(E,D): pass class A(B,C): pass print A.x If the old-style MRO was the same as the new-style MRO (i.e., ABEC etc.), I'd expect it to print c. However, it prints d (i.e., it's ABEOD etc.). I'm new to Python, so I guess I m…
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49614802
answer count: 3
upvote count: 2
possible better answer: http://stackoverflow.com/a/49614911
downvote count: 0
tagged with: method-resolution-order
tagged with: multiple-inheritance
favorite count: 0
type: Question
has title: Does the MRO of this class hierarchy is the same for old-style and new-style?

http://stackoverflow.com/a/49757139
has comment: http://stackoverflow.com/comment/86533596
upvote count: 0
type: AcceptedAnswer
downvote count: 1
has body: You can simply use clf.predict_proba(). For example: clf.predict_proba([[8,8]]) will return you a vector of float that represents the probability of the data being each of the unique value in column "a".
has comment: http://stackoverflow.com/comment/86531791
has comment: http://stackoverflow.com/comment/86530730
has comment: http://stackoverflow.com/comment/86532364
answers question: http://stackoverflow.com/q/49756175
type: Answer
accepted answer of: http://stackoverflow.com/q/49756175
score: -1

http://stackoverflow.com/q/49602329
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
type: Question
has body: I need to select the row previous to when discharge_location is Readmit within a group. Then set the ID and Discharge_location to a dictionary. sample df ID admit discharge discharge_location first 20 3-4-2018 3-6-2018 Home 1 20 2-2-2018 2-6-2018 Home 0 20 2-5-2018 2-23-2018 Readmit 0 30 1-2-2018 2-3-2018 Rehab 1 30 1-15-2018 1-18-2018 Readmit 0 30 1-20-2018 1-24-2018 Home 0 40 1-20-2018 1-24-2018 Home 0 40 1-20-2018 1-24-2018 Home 0 40 1-20-2018 1-24-2018 Home 0 final result ID Discharge_location 20 Home 30 Rehab
tagged with: python
tagged with: dictionary
has title: How to select the previous row in a group with pandas?
has answer: http://stackoverflow.com/a/49602357
score: 2
accepted answer: http://stackoverflow.com/a/49602357
upvote count: 2
type: AnsweredQuestion
tagged with: pandas-groupby

trace
tag name: trace
tags question: http://stackoverflow.com/q/49650704
type: Tag

http://stackoverflow.com/a/49697872
upvote count: 1
has body: You can create a column that is uniquely assigned to each change in sign event. Some sample data df = pd.DataFrame({'Image':list('xxxxxxxxxxxxxxx'),'Sign':[1,1,-1,-1,1,1,-1,-1,-1,1,1,1,-1,-1,-1]}) Image Sign 0 x 1 1 x 1 2 x -1 3 x -1 4 x 1 5 x 1 6 x -1 7 x -1 8 x -1 9 x 1 10 x 1 11 x 1 12 x -1 13 x -1 14 x -1 Now use cumsum() and shift to find locations of a sign changes and assign this value back to the dataframe df['groups'] = (df.Sign != df.Sign.shift(1)).cumsum() Now we can groupby the column [groups], and store the slices of the original dataframe in a list frames = [frame for _,frame in df.groupby('groups')] frames[0] Image Sign groups 0 x 1 1 1 x 1 1
type: Answer
answers question: http://stackoverflow.com/q/49697289
score: 1
downvote count: 0

http://stackoverflow.com/a/56690750
score: 0
has body: Here is another technique I found useful when you have control over the format of the YAML output. Instead of having the data be a single structure, you can split it up into separate YAML documents by using the "---" separator. For example, instead of - foo: 1 bar: 2 - foo: 2 bar: 10 You can write this as: foo: 1 bar: 2 --- foo: 2 bar: 10 and then use the following python code to parse it: with open("really_big_file.yaml") as f: for item in yaml.load_all(f): print(item)
type: Answer
answers question: http://stackoverflow.com/q/49723620

http://stackoverflow.com/a/50871168
score: 1
has body: Installed vc-redist.x64 (Visual C++ Redistributable for Visual Studio 2015) from microsoft site and Python 3.6.5 32-bit (on Windows 7 64-bit) from https://www.python.org/downloads/ and the above error (api-ms-win-crt-runtime-l1-1-0.dll is missing) is gone.
answers question: http://stackoverflow.com/q/49703836
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49650772
tagged with: hough-transform
has comment: http://stackoverflow.com/comment/86309978
has title: Detecting silver and reflecting balls with OpenCV
answer count: 1
has body: I am trying to detect silver balls reflecting the environment with OpenCV: With black balls, I successfully did it by detecting circles: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray,(5,5),0); gray = cv2.medianBlur(gray,5) gray = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,3.5) kernel = np.ones((3,3),np.uint8) gray = cv2.erode(gray,kernel,iterations = 1) gray = cv2.dilate(gray,kernel,iterations = 1) circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT, 1, 260, \ param1=30, param2=65, minRadius=0, maxRadius=0) But when using the program with silver balls, we don't get any result. When looking at the edges calculated by the program, the edges of the ball are quite sharp. But the Code is not recognizing any ball. How do I improve the detection rate of the silver ball? I think of two ways doing that: - Improving edge calculation - Make the circle detection accept an image with unclear edges Is that possible? What is the best way of doing so? Help is very appreciated.
favorite count: 0
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/49651752
linked to: http://stackoverflow.com/q/33544411
downvote count: 0
tagged with: python
score: 4
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86309817
has answer: http://stackoverflow.com/a/49651752

http://stackoverflow.com/a/49726484
score: 6
downvote count: 0
type: Answer
upvote count: 6
has body: eval is for expressions. assert is a statement. You seem to think it's a function, but it's not. You could exec an assert, if you wanted to for some reason. this = silly = [] exec('assert this is silly')
answers question: http://stackoverflow.com/q/49726442
has comment: http://stackoverflow.com/comment/86467627
has comment: http://stackoverflow.com/comment/86467092

http://stackoverflow.com/comment/86292826
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
type: QuestionComment
comment on: http://stackoverflow.com/q/49642627
score: 1
type: Comment

http://stackoverflow.com/comment/86503455
comment on: http://stackoverflow.com/q/49707063
type: QuestionComment
score: 0
has text: Can you please confirm?
type: Comment

http://stackoverflow.com/a/49669987
has body: Try this out import random aList = ['A','B','C','D'] for i in range(5): aList.append(''.join(random.sample(aList, num))) print(aList)
answers question: http://stackoverflow.com/q/49669856
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/86281135
has text: I need to remove both the duplicate and the original value if a duplicate is found. Both "Most pythonic way to remove tuples from a list if first element is a duplicate" and "Removing duplicates from list of lists in Python" keep one of the duplicate values.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49636085

http://stackoverflow.com/a/49676541
answers question: http://stackoverflow.com/q/49676174
type: Answer
has body: PyCharm is using a VirtualEnviroment. You may have installed the libraries in a manual installation of python through PIP. Read the documentation to install packages with PyCharm. https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html I think the documentation will help you.
has comment: http://stackoverflow.com/comment/86366496
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49658802
upvote count: 14
accepted answer: http://stackoverflow.com/a/49659358
has answer: http://stackoverflow.com/a/60601644
possible better answer: http://stackoverflow.com/a/60601644
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has title: How can I use tf.data Datasets in eager execution mode?
tagged with: python
has body: In the tf.data talk at the TensorFlow Dev Summit 2018, Derek Murray presented a way to combine the tf.data API with TensorFlow's eager execution mode (at 10:54). I tried out a simplified version of the code shown there: import tensorflow as tf tf.enable_eager_execution() dataset = tf.data.Dataset.from_tensor_slices(tf.random_uniform([50, 10])) dataset = dataset.batch(5) for batch in dataset: print(batch) causing TypeError: 'BatchDataset' object is not iterable I also tried using dataset.make_one_shot_iterator() and dataset.make_initializable_iterator() to iterate over the dataset, but they result in RuntimeError: dataset.make_one_shot_iterator is not supported when eager execution is enabled. and RuntimeError: dataset.make_initializable_iterator is not supported when eager execution is enabled. TensorFlow version: 1.7.0, Python version: 3.6 How can you use the tf.data API with eager execution?
score: 14
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49659358
answer count: 2

http://stackoverflow.com/comment/86527379
has text: There's nothing failing in the code I provided. I just miss the two last steps i circled in red in the picture that I do not know how to do. The code provided are the steps to do before the two last steps i dont know how to do.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49756110
type: Comment

http://stackoverflow.com/comment/86492249
type: Comment
score: 0
type: AnswerComment
has text: @Marcelo, Yes, you don't have enough rep yet to upvote, but I believe you can accept an answer still by checking on the mark next to the correct answer, refer to this: https://stackoverflow.com/help/someone-answers
comment on: http://stackoverflow.com/a/49683145

http://stackoverflow.com/comment/86407577
score: 0
has text: I am not sure if I understand the question correctly, your question comes after you have the indexes (i.e. `[16, 53, 84]`) in order to use that in a loop? Can the `df1`, `df2`... be elements of a list?
type: QuestionComment
comment on: http://stackoverflow.com/q/49697289
type: Comment

http://stackoverflow.com/comment/86327442
type: Comment
has text: @Chrispresso Tried dot product method as well, but it doesn't work for terms in numerator.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49658872

http://stackoverflow.com/comment/127040914
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49735873
type: Comment
has text: Might need to wrap `sobel` in a `np.float64()`, that fixed a very similar problem for me

http://stackoverflow.com/comment/86824750
type: QuestionComment
has text: I see, thanks for your feedback
score: 0
comment on: http://stackoverflow.com/q/49742061
type: Comment

http://stackoverflow.com/q/49687991
has body: How the logical operators i.e;(or, and) works on the strings or numbers? Example: print(2 or 3)--&gt; o/p: 2 print('two' or 'three')--&gt; o/p: 'two' I want to know how internally it works and reason behind the output's
answer count: 1
has comment: http://stackoverflow.com/comment/86387502
score: -1
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has title: About or & and operator
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86388440
duplicate of: http://stackoverflow.com/q/44612144
has answer: http://stackoverflow.com/a/49688320
downvote count: 3

http://stackoverflow.com/comment/86291597
score: 2
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49641953
has text: "using `hasattr(i, '__iter__')` is not sufficient to check if `i` is iterable" - true, but `isinstance(x, Iterable)` fails for many of the same cases. The most reliable check is to just call `iter`.

constraints
type: Tag
tags question: http://stackoverflow.com/q/49655875
tag name: constraints
tags question: http://stackoverflow.com/q/49645410

http://stackoverflow.com/q/49662932
has answer: http://stackoverflow.com/a/49662962
downvote count: 1
has body: I have a thousand numbers in a list like this: A=[1,2,3,4] I want to covert this in the following format: desired_A=[[1,2],[2,3],[3,4]] How can I do this?
linked to: http://stackoverflow.com/q/21303224
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/49662961
has title: Python: Convert list [a,b,c,d] to [ [a,b],[b,c],[c,d] ]
duplicate of: http://stackoverflow.com/q/21303224
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
upvote count: 1
tagged with: python

performance
tags question: http://stackoverflow.com/q/49691346
tags question: http://stackoverflow.com/q/49719627
tags question: http://stackoverflow.com/q/49735639
tags question: http://stackoverflow.com/q/49732807
tags question: http://stackoverflow.com/q/49708476
tags question: http://stackoverflow.com/q/49724629
tags question: http://stackoverflow.com/q/49603221
tags question: http://stackoverflow.com/q/49697477
tags question: http://stackoverflow.com/q/49602682
tags question: http://stackoverflow.com/q/49622894
tag name: performance
tags question: http://stackoverflow.com/q/49664523
tags question: http://stackoverflow.com/q/49629849
tags question: http://stackoverflow.com/q/49646954
tags question: http://stackoverflow.com/q/49711793
type: Tag
tags question: http://stackoverflow.com/q/49701143
tags question: http://stackoverflow.com/q/49742975
tags question: http://stackoverflow.com/q/49671985
tags question: http://stackoverflow.com/q/49631008

http://stackoverflow.com/q/49700167
has comment: http://stackoverflow.com/comment/86413690
has comment: http://stackoverflow.com/comment/86413726
tagged with: latitude-longitude
has comment: http://stackoverflow.com/comment/86413602
has comment: http://stackoverflow.com/comment/86413656
type: Question
has comment: http://stackoverflow.com/comment/86413988
has body: I have a rectangle of size 900 * 600. I know top left and bottom right GPS Coordinates in Lat/Long. In Pixel top left is 0,0 bottom right is 900.600. How can i find x,y coordinate for all GPS coordinates within rectangle?
answer count: 0
has comment: http://stackoverflow.com/comment/86413558
has comment: http://stackoverflow.com/comment/86413698
has comment: http://stackoverflow.com/comment/86443751
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/15285940
has comment: http://stackoverflow.com/comment/86413849
tagged with: gps
has comment: http://stackoverflow.com/comment/86413662
has comment: http://stackoverflow.com/comment/86413791
has title: Map GPS Coordinate to x,y coordinate in rectangle
score: 0
tagged with: math

http://stackoverflow.com/a/49628756
score: -1
accepted answer of: http://stackoverflow.com/q/49626983
downvote count: 2
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/49626983
has body: Try this, import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy() ssh.connect('hostname', username='test', password='123') sftp = ssh.open_sftp() with open('path.txt') as fp: for line in fp: print line for filename in sftp.listdir(line): if filename.endswith('.txt') or filename.endswith('.file') or filename.endswith('.xml'): check_1 = filename stdin, stdout, stderr = ssh.exec_command('hostname') result1 = stdout.read().decode().splitlines() std1in, std1out, std1err = ssh.exec_command('python -V') result2 = std1out.read().decode().splitlines() output_check = '{0:&gt;25} {1:&gt;45} {2:&gt;30}'.format(filename,result1,result2) print output_check file = open("check.txt","a") file.write(output_check,'\n') file.close()
has comment: http://stackoverflow.com/comment/86264488
type: Answer

http://stackoverflow.com/comment/86378642
comment on: http://stackoverflow.com/q/49681811
has text: You can accept the answer now. Glad I could help :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49635654
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49637457
has answer: http://stackoverflow.com/a/49635711
answer count: 2
has comment: http://stackoverflow.com/comment/86280343
has title: Django-Rest-Framework 'str' object has no attribute 'id'
has answer: http://stackoverflow.com/a/49637457
has body: I am creating a call in DRF to POST to the site. I am a bit confused why I get this error. I do not understand why this expects it to be a str. I know there are similiar posts but they still elude be to the solution. Error AttributeError: 'str' object has no attribute 'id' [03/Apr/2018 10:55:12] "POST /api/user/UserProfile/1/ HTTP/1.1" 500 83982 serializer.py looks like and if I remove instance.id i get the same error but just for the next line. from rest_framework import serializers from api.models import UserProfile from django.contrib.auth.models import User class UserProfileSerializer(serializers.Serializer): # id = serializers.UUIDField() class Meta: model = UserProfile def create(self, validated_data): return UserProfile.objects.create(**validated_data) def update(self, instance, validated_data): instance.id = validated_data.get('profile_id', str(instance.id)) instance.user_id = validated_data.get('user_id', instance.user_id) instance.save() return instance View @csrf_exempt def user_profile_list(request, user_id): try: userid = user_id except userid.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': uprofile = UserProfile.objects.all().values() list2 = list(uprofile) return JsonResponse(list2, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = UserProfileSerializer(userid, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) urls.py url(r'^api/user/UserProfile/(?P&lt;user_id&gt;[0-9]+)/$', userprofile.user_profile_list),
downvote count: 0
tagged with: django
tagged with: python
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/49635711
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86282777
has comment: http://stackoverflow.com/comment/86278747
favorite count: 0

http://stackoverflow.com/q/49605102
has comment: http://stackoverflow.com/comment/86217429
has comment: http://stackoverflow.com/comment/86217420
has body: Consider the following simple Python code: from operator import itemgetter def main(): my_list = [ ('Bob', 'RnD', 10), ('John', 'RnD', 11), ('Mary', 'Sales', 10), ('Linda', 'Sales', 11), ] # I saw a lot of examples tell people to do multi-fields sorting like this, but # PyCharm inspector warns it print(sorted(my_list, key=itemgetter(1, 2), reverse=True)) # I read some articles and found that the following code works, too, without warning. print(sorted(my_list, key=(lambda x: (x[1], x[2])), reverse=True)) if __name__ == '__main__': main() For the line "print(sorted(my_list, key=itemgetter(1, 2), reverse=True))", PyCharm shows the following warning: Expected type '(Tuple[str, str, int]) -> Any' (matched generic type '(_T) -> Any'), got 'itemgetter' instead more... (Ctrl+F1) When I click 'more', it shows: Expected type '(Tuple[str, str, int]) -> Any' (matched generic type '(_T) -> Any'), got 'itemgetter' instead less... (Ctrl+F1) This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations. Both code (both itemgetter and lambda) work well, just code inspection warning. So my questions are: Why PyCharm inspector warns me with this? Is it worth to be fixed? and how to fix it with itemgetter? Shall I suppress such warning for all my projects? Shall I always use the next line (with lambda statement) for such sorting?
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86217379
has title: Why PyCharm inspector shows type warning when I use operator.itemgetter with sorted function?
favorite count: 0
type: Question
score: 5
answer count: 0
tagged with: pycharm
has comment: http://stackoverflow.com/comment/98494011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86217432
downvote count: 0

http://stackoverflow.com/comment/86548212
has text: Anybody who can help me? I am in desperate need of help. Thanks a lot!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49713817
score: 0

http://stackoverflow.com/a/49732993
answers question: http://stackoverflow.com/q/49732897
score: 1
downvote count: 0
upvote count: 1
has body: __init__() is short for "initialize" and is the python way of dealing with something called Constructors in object oriented programming. I think it's best to use examples. Let's say you're creating a program called dog simulator. # Notice that animals are a CLASS of objects. class Animal: # Before we do anything, we have to create an instance of an object. # If we want to do something to a file, we have to first create one, aka (initialize one) # __init__ means "initialize", the two underscores in pythong mean it's # a special function. def __init__(self): print("initializing a new animal...") # One thing that animals do is they eat. It's a "function" of animals. def eat(self): print("mmmm... delicious") # Notice that dogs are a CLASS of animals. class Dog(Animal): # one function of a dog is we have to create a new instance of it def __init__(self): print("initializing a new dog...") # another function is that they bar. def bark(self): print("woof!") # This is our main program. Notice it's checking if the name of # this process is called "main". if __name__ == "__main__": doggo = Dog() # Lets create a new dog, we'll name him doggo doggo.eat() # Since dogs are a "class" of animals, they can do everything animals do. doggo.bark() # They can also do dog specific stuff.
type: Answer

multithreading
tags question: http://stackoverflow.com/q/49743993
tags question: http://stackoverflow.com/q/49675189
tags question: http://stackoverflow.com/q/49690511
tags question: http://stackoverflow.com/q/49620158
tags question: http://stackoverflow.com/q/49738465
tags question: http://stackoverflow.com/q/49757694
tags question: http://stackoverflow.com/q/49620132
tags question: http://stackoverflow.com/q/49696964
type: Tag
tags question: http://stackoverflow.com/q/49625222
tags question: http://stackoverflow.com/q/49677555
tags question: http://stackoverflow.com/q/49613422
tags question: http://stackoverflow.com/q/49744842
tags question: http://stackoverflow.com/q/49615650
tags question: http://stackoverflow.com/q/49613045
tags question: http://stackoverflow.com/q/49603373
tags question: http://stackoverflow.com/q/49629722
tags question: http://stackoverflow.com/q/49731391
tags question: http://stackoverflow.com/q/49622896
tags question: http://stackoverflow.com/q/49742217
tags question: http://stackoverflow.com/q/49743879
tags question: http://stackoverflow.com/q/49652110
tags question: http://stackoverflow.com/q/49738000
tags question: http://stackoverflow.com/q/49603440
tags question: http://stackoverflow.com/q/49747048
tags question: http://stackoverflow.com/q/49740521
tags question: http://stackoverflow.com/q/49672457
tags question: http://stackoverflow.com/q/49691852
tags question: http://stackoverflow.com/q/49639698
tags question: http://stackoverflow.com/q/49715779
tags question: http://stackoverflow.com/q/49665668
tags question: http://stackoverflow.com/q/49690515
tag name: multithreading
tags question: http://stackoverflow.com/q/49692635
tags question: http://stackoverflow.com/q/49717183
tags question: http://stackoverflow.com/q/49643423
tags question: http://stackoverflow.com/q/49710987
tags question: http://stackoverflow.com/q/49723272

http://stackoverflow.com/comment/86371108
type: Comment
comment on: http://stackoverflow.com/a/49643525
has text: Python 3 support is still in a tech preview status, so you'd better just install python2.7 into your system and not edit source files.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49614467
upvote count: 1
has comment: http://stackoverflow.com/comment/86235579
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
has body: I was defining a class in python that strictly restricts itself to the innate properties of a Singly Linked List. next is a pointer to the next element. The complete class: class Node: def __init__(self, v = None): self.value = v self.next = None return ## A function to determine the length of the linked list: def length(self): if self.value == None: return(0) elif self.next == None: return(1) else: return(1+length(self.next)) Why is the expression 1+length(self.next) not valid? And why do I have to use 1+self.next.length()?
tagged with: linked-list
has answer: http://stackoverflow.com/a/49614708
accepted answer: http://stackoverflow.com/a/49614708
has comment: http://stackoverflow.com/comment/86236205
downvote count: 5
has comment: http://stackoverflow.com/comment/86236052
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/86235625
tagged with: data-structures
has comment: http://stackoverflow.com/comment/86235455
has comment: http://stackoverflow.com/comment/86235525
has comment: http://stackoverflow.com/comment/86235901
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86235718
has title: Why isn't length(self.next) a valid expression in python?
has comment: http://stackoverflow.com/comment/86236114
tagged with: algorithm

http://stackoverflow.com/a/49635642
accepted answer of: http://stackoverflow.com/q/49635591
type: AcceptedAnswer
downvote count: 0
has body: I think better is: d = {'A': ['blue', 'blue', 'blue', 'red', 'red', 'red', 'yellow', 'yellow', 'green', 'green', 'green'], 'B': ['a', 'a', 'b', 'c', 'c', 'c', 'd', 'e', 'f', 'f', 'g'], 'C': ['a1', 'a2', 'b1', 'c1', 'c2', 'c3', 'd1', 'e1', 'f1', 'f2', 'g1']} df = pd.DataFrame(d) print (df) A B C 0 blue a a1 1 blue a a2 2 blue b b1 3 red c c1 4 red c c2 5 red c c3 6 yellow d d1 7 yellow e e1 8 green f f1 9 green f f2 10 green g g1 keylist = df.apply(lambda x: '/'.join(x), axis=1).add('/X').values.tolist() print (keylist) ['blue/a/a1/X', 'blue/a/a2/X', 'blue/b/b1/X', 'red/c/c1/X', 'red/c/c2/X', 'red/c/c3/X', 'yellow/d/d1/X', 'yellow/e/e1/X', 'green/f/f1/X', 'green/f/f2/X', 'green/g/g1/X'] Or if only few columns: keylist = (df['A'] + '/' + df['B'] + '/' + df['C'] + '/X').values.tolist() Some timings: #[110000 rows x 3 columns] df = pd.concat([df] * 10000, ignore_index=True) In [364]: %%timeit ...: (df['A'] + '/' + df['B'] + '/' + df['C'] + '/X').values.tolist() ...: 60.2 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [365]: %%timeit ...: df.apply(lambda x: '/'.join(x), axis=1).add('/X').tolist() ...: 2.48 s ± 39.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [366]: %%timeit ...: list1, list2, list3 = df['A'].tolist(), df['B'].tolist(), df['C'].tolist() ...: for i in zip(list1, list2, list3): ...: val = map(str, i) ...: keylist.append('/'.join(val)) ...: keylist[-1] += '/X' ...: 192 ms ± 78.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [367]: %%timeit ...: df.iloc[:,0].str.cat([df[c] for c in df.columns[1:]],sep='/').tolist() ...: 61.1 ms ± 540 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [368]: %%timeit ...: df.assign(New='X').apply('/'.join,1).tolist() ...: 2.51 s ± 76.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [369]: %%timeit ...: ['{0}/{1}/{2}/X'.format(i, j, k) for i, j, k in df.values.tolist()] 74.6 ms ± 2.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
has comment: http://stackoverflow.com/comment/86278996
upvote count: 8
has comment: http://stackoverflow.com/comment/86279256
type: Answer
has comment: http://stackoverflow.com/comment/86278864
answers question: http://stackoverflow.com/q/49635591
score: 8
has comment: http://stackoverflow.com/comment/86278679
has comment: http://stackoverflow.com/comment/86278791
has comment: http://stackoverflow.com/comment/86278823

http://stackoverflow.com/a/49601741
downvote count: 1
has comment: http://stackoverflow.com/comment/86211431
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86211243
has body: The End of File error you are getting is due to Python 2's behaviour around the input method. It means that you need to give it a value before hitting enter. I gave it the following values "1 2" enter then 0 and received the answer [[1, 2]] is this what you would expect? You may want to try using raw_input or input in Python 3.
has comment: http://stackoverflow.com/comment/86211450
has comment: http://stackoverflow.com/comment/86211374
answers question: http://stackoverflow.com/q/49599920
upvote count: 0
has comment: http://stackoverflow.com/comment/86211996
has comment: http://stackoverflow.com/comment/86211562
has comment: http://stackoverflow.com/comment/86239852

http://stackoverflow.com/comment/86499868
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49741754
type: Comment
has text: Possible duplicate of [Unable to install python libraries](https://stackoverflow.com/questions/49734434/unable-to-install-python-libraries)

http://stackoverflow.com/a/49642178
downvote count: 0
upvote count: 1
score: 1
has body: Resolved! The issue is incompatibility of Hyperopt with networkxx2. One needs to downgrade to "networkxx1.11".
type: Answer
accepted answer of: http://stackoverflow.com/q/49628200
answers question: http://stackoverflow.com/q/49628200
type: AcceptedAnswer

http://stackoverflow.com/a/49637135
answers question: http://stackoverflow.com/q/49637025
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86282224
has body: Try this: enumerate and skip the first line import io with io.open('csus.csv',mode='r') as csus: for i, row in enumerate(csus): if(i==0): pass else: print(str(i) + " " + row)

http://stackoverflow.com/comment/86350309
score: 0
has text: valid solution for a question that is a dupe :) I mostly do not answer dupes but thats preference. +1
type: Comment
comment on: http://stackoverflow.com/a/49669805
type: AnswerComment

http://stackoverflow.com/comment/86328989
type: Comment
has text: So i would create different robot tests, create specific run configurations to them and pass arguments. In long term test execution i would run a script which executes all my robot tests so it will be difficult to specify these configurations individually when i run tests in a bulk. By any chance can the run configurations be read from a config file? If so i can update config file according to my tests
comment on: http://stackoverflow.com/a/49658504
score: 0
type: AnswerComment

http://stackoverflow.com/q/49620028
linked to: http://stackoverflow.com/q/17873855
has body: So I have a Accounts model that extends AbstractUser model. I Also have StudentProfile and TeacherApplications that have a one to one relation with Accounts. I ALSO have two forms for teacher and student to fill out. Requirement: Enable students/teachers to register via their forms. Issue: In the student/teacher form I am asking for fields that the User model needs such as email, username, first and last name etc.. However I am getting this:. Error: 1 AttributeError at /register/ Manager isn't available; 'auth.User' has been swapped for 'accounts.Accounts' Error 2 Student_profile.save() ^ TabError: inconsistent use of tabs and spaces in indentation ISSUE: I need to register the user with user fields otherwise User fields would be null and generate error as well.. But is the best approach? Or what am I doing wrong? models class Accounts(AbstractUser): email = models.EmailField('email address', unique=True) first_name = models.CharField('first name', max_length=30, blank=True) last_name = models.CharField('last name', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) # asdd bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) class StudentProfile(models.Model): user = models.OneToOneField('Accounts', related_name='student_profile') # additional fields for students AMEB_Ratings = models.PositiveIntegerField(default=0) is_student = models.BooleanField('student status', default=False) class TeacherApplications(models.Model): user = models.OneToOneField('Accounts', related_name='teacher_profile') # additional fields for teachers instrument = models.TextField(max_length=500, blank=True) skill = models.CharField(max_length=30, blank=True) experience_in_years = models.PositiveIntegerField(blank=True) is_teacher = models.BooleanField('teacher status', default=False) forms class StudentResistrationForm(forms.ModelForm): class M…
type: UnansweredQuestion
answer count: 1
tagged with: authentication
tagged with: django
tagged with: registration
has answer: http://stackoverflow.com/a/49625127
score: 0
has comment: http://stackoverflow.com/comment/86256908
has title: AttributeError: 'auth.User' has been swapped for 'accounts.Accounts'? How?
tagged with: python
type: Question
tagged with: model

http://stackoverflow.com/q/49646462
favorite count: 0
tagged with: pandas
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86301290
has answer: http://stackoverflow.com/a/49647228
has comment: http://stackoverflow.com/comment/86301081
answer count: 2
has body: Lets say I have a dataframe of the below nature: START END SHOP ACTION 2016-01-07 2016-01-10 ABC B 2016-01-10 2016-02-07 ABC B 2016-04-07 2016-05-07 ABC B 2016-05-15 2016-05-18 ABC S 2016-10-07 2016-10-07 ABC B 2016-11-07 2016-11-07 ABC B 2016-01-15 2016-01-22 DEF S 2016-05-22 2016-11-07 DEF S 2016-11-07 2016-12-07 DEF S 2016-01-04 2016-02-04 XYZ B 2016-09-07 2016-10-26 XYZ T 2016-10-25 2016-10-30 XYZ B I would like to create a new column such that for a given SHOP, it checks to see if there exists a start date (in future) that matches the end date (current date) and also matches the ACTION value. So the Dataframe can look like START END SHOP ACTION CHECK 2016-01-07 2016-01-10 ABC B 1 2016-01-10 2016-02-07 ABC B 0 2016-04-07 2016-05-07 ABC B 0 2016-05-15 2016-05-18 ABC S 0 2016-10-07 2016-10-07 ABC B 0 2016-11-07 2016-11-07 ABC B 0 2016-01-15 2016-01-22 DEF S 0 2016-05-22 2016-11-07 DEF S 1 2016-11-07 2016-12-07 DEF S 0 2016-01-04 2016-02-04 XYZ B 0 2016-09-07 2016-10-26 XYZ T 0 2016-10-25 2016-10-30 XYZ B 0
type: UnansweredQuestion
score: 0
has title: Quick way of checking for a condition while iterating the rows
upvote count: 1
has answer: http://stackoverflow.com/a/49646980
downvote count: 1

http://stackoverflow.com/comment/86281472
type: AnswerComment
score: 0
has text: It is [pyEphem](http://rhodesmill.org/pyephem/), one of the elements in my object is a pyEphem satellite, but that object is not called/used in the mapped function.
comment on: http://stackoverflow.com/a/49636565
type: Comment

http://stackoverflow.com/comment/86419664
type: Comment
comment on: http://stackoverflow.com/a/49702920
type: AnswerComment
has text: good idea - will take a look at the internals.. haven't gotten to that yet. might solve my confusion
score: 0

http://stackoverflow.com/a/63704826
answers question: http://stackoverflow.com/q/49635508
downvote count: 1
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/120465069
has comment: http://stackoverflow.com/comment/120509330
has body: If you wish to get everything you do the following. Let's say you are hitting the route /objects/{what}?human=you&thing=computer @app.route('/objects', methods=['GET']) def myobject(what): everything = app.current_request.to_dict() print("look at me: {}".format(params)) For more information see: Request from the Chalice docs
upvote count: 1

http://stackoverflow.com/comment/138482364
score: 0
type: QuestionComment
has text: example of subclassing statsmodel's [GenericLikelihoodModel](https://www.statsmodels.org/dev/examples/notebooks/generated/generic_mle.html)
comment on: http://stackoverflow.com/q/49713530
type: Comment

http://stackoverflow.com/comment/86500479
has text: mergedTuple = t1 + (t2,) This seems to be working i'll add a solution after I test some more.
comment on: http://stackoverflow.com/q/49742684
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86243515
comment on: http://stackoverflow.com/q/49618205
type: Comment
type: QuestionComment
has text: Use try/except regime to test of user input can be converted to an integer: https://stackoverflow.com/questions/8075877/converting-string-to-int-using-try-except-in-python/8075959
score: 0

http://stackoverflow.com/comment/86318469
score: 0
type: Comment
type: QuestionComment
has text: I can only work off of what I see here. Yes, I can see that there are no interdependencies for computed results for different `x`, which is why I suggested the method in my last comment. Regarding your question, we may be saying the same thing - it just took me a while to grasp what you were asking. You actually don't want to parallelize the for-loop you have shown. That would be a possibly sensible approach if `len(X)` is large.
comment on: http://stackoverflow.com/q/49646182

http://stackoverflow.com/q/49658773
tagged with: python
has title: Please explain this code , a beginner in python here
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/49658949
answer count: 1
has answer: http://stackoverflow.com/a/49658949
has body: I solved this question with long for loops and adding elements in set.As a beginner its quite complicated for me to comprehend what basically is written in this snippet.Also please explain what key does basically.In this we have to print the sorted output of the symmetric difference of two sets. I/P : 4 (Integer representing Length of first set ) 2 4 5 9 (First set ) 4 (Integer representing Length of second set ) 2 4 11 12 (Second set ) O/P 5 9 11 12 The solution: a,b = [set(raw_input().split()) for _ in range(4)][1::2] print '\n'.join(sorted(a^b, key=int))
type: Question
has comment: http://stackoverflow.com/comment/86326935

http://stackoverflow.com/comment/86294330
type: AnswerComment
comment on: http://stackoverflow.com/a/49622097
has text: Using the `.contains()` seems to be the key - the "group" headings are far more complex than the example and the `contains` method was able to parse correctly without any modification. Thanks.
type: Comment
score: 0

http://stackoverflow.com/q/49641930
upvote count: 2
has title: Python: Weird behavior while using `yield from`
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86292024
has body: In the following code, I have run into a RecursionError: maximum recursion depth exceeded. def unpack(given): for i in given: if hasattr(i, '__iter__'): yield from unpack(i) else: yield i some_list = ['a', ['b', 'c'], 'd'] unpacked = list(unpack(some_list)) This works fine if I use some_list = [1, [2, [3]]], but not when I try it with strings. I suspect my lack of knowledge in python. Any guidance appreciated.
favorite count: 0
tagged with: yield
type: Question
has answer: http://stackoverflow.com/a/49641953
has comment: http://stackoverflow.com/comment/86291691
tagged with: python
accepted answer: http://stackoverflow.com/a/49641953
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86291819
has comment: http://stackoverflow.com/comment/86291502

string.format
tags question: http://stackoverflow.com/q/49675977
type: Tag
tag name: string.format

http://stackoverflow.com/q/49677504
type: AnsweredQuestion
score: 0
answer count: 1
upvote count: 1
downvote count: 1
tagged with: plot
has title: Plot Clustering Datapoints Python
favorite count: 0
has body: I'm doing a clustering exercise and I have a list that looks something like this [ [(1, 3), (2, 5), (2, 6), (1, 2), (1, 8)], [(4, 7), (5, 5), (6, 4)] [(8, 9), (10, 9), (11, 12), (10, 12)] [(18, 20), (20, 29), (17, 16), (18, 22)] ] Basically I made the clusters into an array of arrays. I was wondering how to plot this on Python, where different clusters have different colors. I've tried using mathplotlib, but I'm quite confused.
type: Question
accepted answer: http://stackoverflow.com/a/49677731
has answer: http://stackoverflow.com/a/49677731
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/a/49633657
has body: I figured it out , in the line with the training helper: tf.contrib.seq2seq.TrainingHelper(state,batch_lengths) state needs to be the sequence batch you are wanting to decode, if you use the encoded state it throws the error.
answers question: http://stackoverflow.com/q/49619628
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/49707562
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49699286
upvote count: 1
has body: I did not find anything on the py2exe wiki about passing arguments like -i (to enter interactive mode after execution). One might be able to discover information about the argument handling in the py2exe source files. Update: It indeed looks like py2exe does not handle any command line options like the normal interpreter does, instead it just passes them to the script. But it does handle the respective environment variable, which can be used as shown below. However, as a workaround, you could try to set the PYTHONINSPECT Environment variable: If this is set to a non-empty string it is equivalent to specifying the -i option. E.g. run set PYTHONINSPECT=TRUE before running the program. But, probably even better, this can be done from within the Python script: This variable can also be modified by Python code using os.environ to force inspect mode on program termination. Here's a little test script for os.environ (also os.putenv): import os one = os.environ os.putenv("PYTHONINSPECT", "TRUE") two = os.environ os.environ["PYTHONINSPECT"] = "TRUE" three = os.environ print(one) print(two) print(three) print( set(one.items()) ^ set(two.items()) ) print( set(one.items()) ^ set(three.items()) ) The behaviour is a little weird: there does not seem to be a difference, and it seems to only last until you exit the interactive mode: G:\&gt;py test.py &gt; test.txt &gt;&gt;&gt; exit() G:\&gt;set PYTHONINSPECT Environment variable PYTHONINSPECT not defined The contents of test.txt are: environ({'ALLUSERSPROFILE': 'C:\\ProgramData', ... 'PYTHONINSPECT': 'TRUE'}) environ({'ALLUSERSPROFILE': 'C:\\ProgramData', ... 'PYTHONINSPECT': 'TRUE'}) environ({'ALLUSERSPROFILE': 'C:\\ProgramData', ... 'PYTHONINSPECT': 'TRUE'}) set() set() But it seems to work either way (double check the documentation for yourself to ensure you are not corrupting your environment variables), so you could even implement an -i argument for yourself like: import sys, os if len(sys.argv) &gt; 1 and sys.argv[1] == '-i':…
answers question: http://stackoverflow.com/q/49699286
type: Answer

http://stackoverflow.com/a/49702928
has body: Something like this should work. You use the csv library to convert the rows into an array to iterate over. The ast library will turn a string into a dict/json object you can key into. import ast import csv names = [] with open('csvFile.csv', 'r') as f: reader = csv.reader(f) for row in reader: names.append(ast.literal_eval(row)[name]) # or you could print(name) here.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49702861
score: 2
has comment: http://stackoverflow.com/comment/86419566
upvote count: 2

http://stackoverflow.com/q/49711321
score: 2
answer count: 0
favorite count: 0
tagged with: dtw
type: Question
upvote count: 2
type: UnansweredQuestion
has title: How can I align multiple trajectories in python using dtw?
downvote count: 0
tagged with: python
has body: I have 5 different trajectories for my project. First I read them from the file, then save them to a list by parsing the file. After that I digitized these values. I want to align x and y coordinates separately and plot x and y coordinates together on a grid. This is what I have done so far. I use dtw package in python, but it takes two lists and gives the path as an array. How can I convert it to an aligned trajectory of 5 different lists? x_dict = {} y_dict = {} for x in ["1", "2", "3", "4", "5"]: file = open("data-" + x + ".txt", encoding="latin-1") data = file.read() pos_list = re.findall(r'position:(.*?)orientation:', data, re.DOTALL) or_list = re.findall(r'orientation:(.*?)scale:', data, re.DOTALL) for i in range(len(pos_list)): pos_list[i] = pos_list[i].replace('\n','') regexx = re.compile(r'x: (.*?) y:') regexy = re.compile(r'y: (.*?) z:') posx_list = [m.group(1) for l in pos_list for m in [regexx.search(l)] if m] posx_list = list(map(float, posx_list)) posy_list = [m.group(1) for l in pos_list for m in [regexy.search(l)] if m] posy_list = list(map(float, posy_list)) bins = numpy.linspace(-1, 1, 100) digitized_x = numpy.digitize(posx_list, bins) digitized_y = numpy.digitize(posy_list, bins) x_dict[x] = digitized_x y_dict[x] = digitized_y dist, cost, acc, path = dtw(y_dict["5"], y_dict["4"], dist= euclidean) plt.imshow(acc.T, origin='lower', cmap=cm.gray, interpolation='nearest') plt.plot(path[0], path[1], 'w') plt.xlim((-0.5, acc.shape[0]-0.5)) plt.ylim((-0.5, acc.shape[1]-0.5))

http://stackoverflow.com/comment/86342826
has text: The data set is simply from UCI data repository on Parkinson telementery. And it's a very small sized data set of size 5876 x 20+ . The title = lgb works fine when I run it with AdaBoost at a Google Colaboratory Note book [https://colab.research.google.com/drive/1xf__2fI2xGOr4kv_YS7c5CX3TDqNLdpT]. It can reproduce the content of the regressor at the title nicely. And that's where I don't understand as Colaboratory is having same engine behind.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49666274

http://stackoverflow.com/a/49753699
score: 0
has body: here is partial solution for cleaner countries and average: import numpy as np keys = [k for d in board for k in d.keys()] values = [v for d in board for k,v in d.items()] avg = int(np.mean(values))
answers question: http://stackoverflow.com/q/49753411
type: Answer

http://stackoverflow.com/q/49670289
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9764298
accepted answer: http://stackoverflow.com/a/49670375
duplicate of: http://stackoverflow.com/q/9764298
tagged with: python
type: Question
tagged with: list
has body: Please see below 2 lists: If I append the cat and their age to two different lists, how do I sort it so that when the age of the oldest cat is printed, Luke is also printed, whereas when the age of the youngest cat is printed, Ronny is also printed. cats = ["ronny", "brodie", "fraise", "luke"] age = [5, 6, 7, 11] age.sort() print("The age of the oldest cat is {}. This cat is {}".format(age[-1], cats[THE OLDEST CAT])) print("The age of the youngest cat is {}. This cat is {}".format(age[0], cats[THE YOUNGEST CAT])) How can I do this?
has answer: http://stackoverflow.com/a/49670375
score: 1
has title: Sort one list according to the order of another list
answer count: 1
downvote count: 0

routes
type: Tag
tags question: http://stackoverflow.com/q/49664010
tags question: http://stackoverflow.com/q/49723179
tags question: http://stackoverflow.com/q/49660465
tag name: routes

http://stackoverflow.com/comment/86285171
score: 0
comment on: http://stackoverflow.com/q/49638761
type: QuestionComment
type: Comment
has text: So how should I do it?

http://stackoverflow.com/comment/86453582
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49720280
has text: So basically just use regex to extract all the numbers and then take the last four?
score: 0

http://stackoverflow.com/q/49695050
tagged with: aws-lambda
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86402919
tagged with: amazon-s3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49695119
has body: I'm trying to write a csv file into an S3 bucket using AWS Lambda, and for this I used the following code: data=[[1,2,3],[23,56,98]] with open("s3://my_bucket/my_file.csv", "w") as f: f.write(data) And this raises the following error: [Errno 2] No such file or directory: u's3://my_bucket/my_file.csv': IOError Traceback (most recent call last): File "/var/task/lambda_function.py", line 51, in lambda_handler with open("s3://my_bucket/my_file.csv", "w") as f: IOError: [Errno 2] No such file or directory: u's3://my_bucket/my_file.csv' Can I have some help with this please ? PS: I'm using python 2.7 Thanking you in advance
tagged with: python
has title: Write csv file and save it into S3 using AWS Lambda (python)
has comment: http://stackoverflow.com/comment/86403338
has answer: http://stackoverflow.com/a/59462478
upvote count: 14
answer count: 3
linked to: http://stackoverflow.com/q/40336918
has comment: http://stackoverflow.com/comment/86403497
score: 13
tagged with: amazon-web-services
downvote count: 1
has answer: http://stackoverflow.com/a/57555842

http://stackoverflow.com/q/49651085
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86319841
has comment: http://stackoverflow.com/comment/86319781
has comment: http://stackoverflow.com/comment/86310508
linked to: http://stackoverflow.com/q/27701147
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86310376
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86310742
has comment: http://stackoverflow.com/comment/86310573
has body: I am trying to add the related objects from django tutorial of it's documentation https://docs.djangoproject.com/en/1.11/intro/tutorial07 But there is no add button showing in it I've checked this answer too but it did not help Add button not showing up in Django tutorial 02 This is my admin.py from __future__ import unicode_literals from django.contrib import admin from home.models import * # Register your models here. class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None,{'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) This is my models.py from __future__ import unicode_literals from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) This is showing in my admin page python used is python 2.7
has answer: http://stackoverflow.com/a/49651437
has answer: http://stackoverflow.com/a/76291743
has title: Add button not showing in Django admin
type: Question

http://stackoverflow.com/comment/86525408
type: Comment
type: QuestionComment
has text: what python are you using?
score: 0
comment on: http://stackoverflow.com/q/49755180

http://stackoverflow.com/comment/86361219
type: QuestionComment
has text: @maraca Strictly speaking this is irrelevant here as `list` in Python isn't implemented as a linked list. :-)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49653568

http://stackoverflow.com/comment/86433702
score: 5
has text: This is a problematic approach, since the semicolon can be part of a string, like `SELECT a FROM b WHERE c == ';';`. You need a parser to obtain the commands, not split on a character.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49710109

http://stackoverflow.com/comment/86269757
has text: You already have this data in your spider? So just combine them? `"{} per {} - {}".format(name, brand, version)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49630374

http://stackoverflow.com/a/49633706
type: Answer
has body: if you don't need a class from contextlib import contextmanager @contextmanager def bird(lst): print 'enter {}'.format(lst) yield lst print 'exit {}'.format(lst) with bird([1,2,3,4]) as f: print f enter [1, 2, 3, 4] [1, 2, 3, 4] exit [1, 2, 3, 4]
answers question: http://stackoverflow.com/q/49633428
downvote count: 1
score: 4
upvote count: 5

http://stackoverflow.com/comment/86409730
type: AnswerComment
comment on: http://stackoverflow.com/a/49698209
type: Comment
has text: Thank you. Perfect.
score: 0

http://stackoverflow.com/a/49658159
answers question: http://stackoverflow.com/q/49657120
type: Answer
upvote count: 3
score: 3
downvote count: 0
has body: In code what the comments already say: # rest stays the same class Treatment(db.Model): treatmentDate = db.Column('Date of treatment', db.DateTime, default=datetime.utcnow) "Passing the function and not calling it" means leaving the brackets () at the end off. Calling the function like you do will actually pass in a datetime object, but what you want is to pass in the function itself as the default to be called in the moment you create a new instance of Treatment.

http://stackoverflow.com/a/49884368
upvote count: 2
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49697705
downvote count: 1
type: Answer
has body: I was going about emailing the back end wrong as a first time Django app creator. just simply adding: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' to settings.py....(lots of documentation just point to implementing these lines) You still need an SMTP to send the email contents, even if you are just posting to the back-end like I wanted to. (to test for successful email submission before putting the site into production). SMTP options: I saw a few different SMTP options. Google worked for me for testing purposes. I plan on switching to Sendgrid once I go to production. The reason I am not using Sendgrid yet, is because I don't have the registered domain yet. Having a registered domain is a requirement of using sendgrid for your SMTP and I don't have mine yet. So what did I add to my project to make Google SMTP email to the console backend? Settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemailaddress@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER After doing this, sign into you gmail account, go to: my account>settings>sign in and security Turn allow less secure apps ON. As a side note in my research, I found out that it is okay to use google SMTP for testing offline like this, but it is illegal to use it in production. You must use a different SMTP service such as SendGrid once you push your website into production. Also you would want to make sure you remove the EMAIL_BACKEND, because as jpmc26 pointed out, you don't want the email data logged in production.
accepted answer of: http://stackoverflow.com/q/49697705

http://stackoverflow.com/comment/86459484
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49722796
has text: No, the input for 'b' should be only from 1,2 and 3. Also can you suggest me a better title for the question? Thank you!

http://stackoverflow.com/q/49640389
score: 3
tagged with: python-dateutil
has body: I am trying to install Sphinx on OSX, with the hopes of eventually making it into a website, following this guide : I have been macporting, homebrewing, python wheelin', figuring out what a virtualenv is... figuring out if I should use python 2.7 or 3.X (which I couldn't figure out) I added this to my bash profile : export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages When I run this : python -c "import sys; print('\n'.join(sys.path))" I had expected it to return simply /usr/local/lib/python2.7/site-packages but it says the following : /Library/Python/2.7/site-packages/pip-10.0.0b2-py2.7.egg /Library/Python/2.7/site-packages/virtualenv-15.2.0-py2.7.egg /Users/nook /usr/local/lib/python2.7/site-packages /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload /Users/nook/Library/Python/2.7/lib/python/site-packages /Library/Python/2.7/site-packages /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python Anyway, I finally got a virtualenv set-up, and ran the following command: pip install sphinx I sorted out a NumPy error, and another error with six. But I am unable to get rid of the following error : jupyter-client 5.2.3 has requirement python-dateutil&gt;=2.1, but you'll have python-dateutil 1.5 which is incompatible. When I run the following command : pip install python-dateutil --upgrade --ignore-installed I get Collecting python-dateutil Using cached …
tagged with: python
tagged with: macos
favorite count: 0
type: Question
tagged with: numpy
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/86309742
has comment: http://stackoverflow.com/comment/86311421
has title: Can't upgrade python-dateutil in OSX

http://stackoverflow.com/q/49629390
answer count: 1
has comment: http://stackoverflow.com/comment/86265629
tagged with: flask
has comment: http://stackoverflow.com/comment/86266484
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86265486
accepted answer: http://stackoverflow.com/a/49629918
tagged with: python
has body: This is a client file with flask framework running inside my docker container . I would like to upload files from my local folder C:/Users/RB287JD/Desktop/upload/file.txt Unfortunately the flask application is unable to find it. If I run this, APP_ROOT = os.path.abspath(os.path.dirname(__file__)) UPLOAD_FOLD = '/c/Users/RB287JD/Desktop/upload/' UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER class mainSessRunning(): def __init__(self): host, port = FLAGS.server.split(':') channel = implementations.insecure_channel(host, int(port)) self.stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) self.request = predict_pb2.PredictRequest() self.request.model_spec.name = 'modelX' self.request.model_spec.signature_name = 'prediction' def inference(self, val_x): data = val_x self.request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(data)) result = self.stub.Predict(self.request, 5.0) return result run = mainSessRunning() # Define a route for the default URL, which loads the form @app.route('/pred', methods=['POST']) def pred(): f = request.files['file'] f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename))) result = run.inference(f) rs = json_format.MessageToJson(result) return jsonify({'result':rs}) It throws error, File "/usr/local/lib/python2.7/dist-packages/werkzeug/datastructures.py", line 2725, in save dst = open(dst,'wb') IOError: [Errno2] No such file or directory:'/c/Users/RB287JD/Desktop/upload/File.txt' But this is where (C:\Users\RB287JD\Desktop\upload\File.txt) my file exists.
has answer: http://stackoverflow.com/a/49629918
has title: IOError: [Errno2] No such file or directory: for input files to flask
tagged with: docker
type: Question
tagged with: python-2.7
score: 0
tagged with: api

http://stackoverflow.com/comment/86874757
comment on: http://stackoverflow.com/a/49636419
type: AnswerComment
has text: @PankajKulkarni: `'\section'` is not a valid Python escape, so you get `'\section'` in the regex, which sees `\s`, a metacharacter. `'\\section'` becomes a single `\` in the value, so `'\section'` is passed to the regex engine, which still sees `\s`, a meta-character. Only `'\\\\section'` becomes the value `\\section`, so now the regex engine sees `\\` as a literal backslash separate from the `section` part.
score: 0
type: Comment

http://stackoverflow.com/q/49703624
tagged with: python
has answer: http://stackoverflow.com/a/49703733
has answer: http://stackoverflow.com/a/49703920
type: Question
has comment: http://stackoverflow.com/comment/86420691
type: UnansweredQuestion
has title: How to time how long my method takes to run?
linked to: http://stackoverflow.com/q/7370801
has answer: http://stackoverflow.com/a/49703702
has body: I have a program that has multiple methods. I would like to measure how long it takes for each method to run when they are called. For example def func1: blah def func2: blah def main: call func1 and func2 and measure their times is there an easy way to do it.
linked to: http://stackoverflow.com/q/1557571
score: 0
has comment: http://stackoverflow.com/comment/86420787
answer count: 3

http://stackoverflow.com/q/49714267
tagged with: data-visualization
downvote count: 0
linked to: http://stackoverflow.com/q/4700614
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86442127
has title: Adding legend outside the bokeh plot
tagged with: plot
has comment: http://stackoverflow.com/comment/86446488
has comment: http://stackoverflow.com/comment/86666879
has body: I am adding lines to bokeh plot. I am using following code for line in lines: figure.line(x='x',y='y',source=source,legend='some_name',color='some_color') I want to place legend outside the box in above case how can i do it?
score: 1
has comment: http://stackoverflow.com/comment/87180817
tagged with: bokeh
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/46730609
answer count: 0
has comment: http://stackoverflow.com/comment/86442214
type: UnansweredQuestion

http://stackoverflow.com/a/49656810
upvote count: 2
score: 2
has body: Firstly, the edges of the bar are black because you have set edgecolor = "black" in the call to df.plot.barh. Removing this means that there will be no edgecolor. You will need to set the edgecolor of each bar to that of the bars facecolor You can do this by iterating through the rectangle patches (obtained using ax.patches) and setting the edgecolor to the facecolor using get_facecolor() and set_edgecolor(). test1 = np.array([51, 13.8, 15.5, np.NaN]) test2 = np.array([40.3, 30.4, 13.8, 15.5]) df = pd.DataFrame(dict(test1 = test1, test2 = test2), columns = ["test1","test2"]).T ax = df.plot.barh(stacked = True, cmap = "coolwarm", lw = 1.5, width = 0.8, figsize = (6,4)) for rect in ax.patches: facecolor = list(rect.get_facecolor()) rect.set_edgecolor(facecolor) facecolor[-1] = 0.5 # reduce alpha value of facecolor, but not of edgecolor rect.set_facecolor(facecolor) plt.show() Which gives:
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49656414
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49656414

http://stackoverflow.com/a/54251127
type: Answer
score: -1
has body: The rotation angel is given in 360-degree units: x = [0,10,20,30,40,50,60,70,80,90] for i in x: plt.plot(i, i, marker=(2, 0, -i), c='k',markersize=30, linestyle='None') plt.margins(0.15); plt.grid();plt.show()
upvote count: 0
answers question: http://stackoverflow.com/q/49660174
downvote count: 1

http://stackoverflow.com/a/56405092
has comment: http://stackoverflow.com/comment/139517840
downvote count: 2
has body: The problem is that you do not close the driver. I made the same mistake. Whit htop in Linux, I have noticed that I occupy all the 26 GB of my pc whit firefox unclosed process.
score: 3
has comment: http://stackoverflow.com/comment/116634227
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49734915

http://stackoverflow.com/a/49674334
answers question: http://stackoverflow.com/q/49673876
score: 0
has body: You can try sub_data.loc[[0],20:71] = sub_data.loc[[1],20:71].values
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49673876
type: Answer

http://stackoverflow.com/comment/86452667
comment on: http://stackoverflow.com/a/49719741
type: Comment
score: 0
type: AnswerComment
has text: @MatthewCasey I corrected and completed my code, and added the way you should train and compute. Backpropagation is a one-run algorithm, running it multiple times with the same initial conditions will lead to the same result.

http://stackoverflow.com/comment/86498502
has text: Exactly, i have posted the error message, the last line indicating the failure is above in bold (i think it doesn't appear in the long error message)
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49741754
type: Comment

http://stackoverflow.com/q/49653837
upvote count: 2
tagged with: signals
linked to: http://stackoverflow.com/q/49417041
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has title: Strange blocking behaviour when reading sys.stdin in python 2 while having a custom signal handler in place
answer count: 1
accepted answer: http://stackoverflow.com/a/49666321
has body: Consider this small python script odd-read-blocking.py: #!/usr/bin/python import signal import sys sig = None def handler(signum, frame): global sig sig = signum signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGTERM, handler) x = sys.stdin.read(3) print 'signal', sig print 'read bytes', len(x) exit(0) I run this and feed it with two bytes of standard input data ('a' + '\n'): &gt; echo a | ./odd-read-blocking.py signal None read bytes 2 &gt; Fine. Now I feed it with the same two bytes (by typing 'a' + '\n' into its standard input). Please note that standard input is then not at EOF yet and potentially has more data to come. So the read blocks, as it expects one more byte. I use Ctrl+C on the script. &gt; ./odd-read-blocking.py a ^Csignal 2 read bytes 2 &gt; Fine. We see that two bytes have been read and signal 2 was received. Now I open a standard input stream, but do not send any byte on it. The read blocks as expected. If I now use Ctrl+C on the script, it will keep sitting there and wait. The read will not be interrupted. The SIGINT will not be processed. &gt; ./odd-read-blocking.py ^C Nothing here. Script still running (seemingly blocked at the read). Now hitting return once, then Ctrl+C again: ^Csignal 2 read bytes 1 &gt; So, only after receiving at least some data (a single '\n' in this case) on its standard input will the script behave as I expect it and correctly interrupt the blocked read and tell me it has received signal 2 and read 1 byte. Alternative 1: instead of using Ctrl+C as shown above, I have tried this same thing using kill pid from a separate terminal. The behaviour is the same. Alternative 2: instead of using the shell standard input as described above, I have done this: &gt; sleep 2000 | ./odd-read-blocking.py When using kill pid to send SIGTERM to the odd-read-blocking.py process I get the same behaviour. Here, the script process can only be killed using SIGKILL (9). Why isn't the read interrupted, when it is blocking on an as yet…
has answer: http://stackoverflow.com/a/49666321
favorite count: 0
type: Question
tagged with: blocking

http://stackoverflow.com/q/49664603
type: Question
tagged with: python
has title: PyQt: Scrollbars are not shown with QGraphicsView class being nested under QMainWindow
has answer: http://stackoverflow.com/a/49664719
has body: I am supposed to add scrollbars to the screen. The class design shown below is the part of a software that I am supposed to modify and add scrollbars to. The scroll bar code in Window class has been added by me. It doesn't get shown when I run the program. What am I supposed to correct? import sys from PyQt4 import QtGui from PyQt4 import QtCore class Window(QtGui.QGraphicsView): def __init__(self, parent=None): QtGui.QGraphicsView.__init__(self, parent) self.scene = QtGui.QGraphicsScene(self) self.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.darkGray, QtCore.Qt.SolidPattern)) self.setScene(self.scene) self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.viewport().setCursor(QtCore.Qt.CrossCursor) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) class CityscapesLabelTool(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) Window() app = QtGui.QApplication(sys.argv) GUI = CityscapesLabelTool() GUI.show() sys.exit(app.exec_())
type: AnsweredQuestion
tagged with: pyqt
score: 0
tagged with: qmainwindow
accepted answer: http://stackoverflow.com/a/49664719
tagged with: pyqt5
answer count: 1
tagged with: qgraphicsview

http://stackoverflow.com/comment/86452636
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49719661
has text: "For example my dictinary look as below" I would expect you to actually show how the dictionary looks like.

http://stackoverflow.com/comment/86500401
comment on: http://stackoverflow.com/a/49742864
type: Comment
score: 0
type: AnswerComment
has text: something is weird. It works if i just try this regex on a string. But when I am trying on pandas column as above, it is giving even the hyphen along with the extracted string. And still fails for RMK. But that RMK thing works fine if I just use it on a string

http://stackoverflow.com/comment/86259920
type: QuestionComment
comment on: http://stackoverflow.com/q/49626150
score: 0
has text: Why is this tagged `numpy` and `scipy` instead of `python3.x`?
type: Comment

http://stackoverflow.com/a/78203812
score: 0
answers question: http://stackoverflow.com/q/49723047
has body: I've adjusted the solution proposed by Aran-Fey. This works as expected: import ast def parse_function_arguments(arg_str): # Wrap the argument string in a dummy function call to make it valid Python syntax wrapped_arg_str = f"dummy_func({arg_str})" # Safe parsing tree = ast.parse(wrapped_arg_str, mode="eval") # Use 'eval' mode for expression parsing # Assuming the first part of the tree is a Call node funccall = tree.body # Process arguments: extract literals directly with safe literal_eval args = tuple([ast.literal_eval(arg) for arg in funccall.args]) # Process keyword arguments: convert values from AST nodes to literals kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in funccall.keywords} return args, kwargs
type: Answer

http://stackoverflow.com/a/49719222
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49600870
answers question: http://stackoverflow.com/q/49600870
score: 0
has body: After reading @starrify's answer, a simple solution I hadn't gone to before: def class_factory(passed_name, passed_source, passed_allowed_domains, passed_start_urls): class ColumbusSpider(ExampleSpider): name = passed_name source = passed_source allowed_domains = passed_allowed_domains start_urls = passed_start_urls # ... other stuff def parse_item(self, response): # use any other passed parameters as needed return ColumbusSpider columbus = class_factory ( 'columbustest', 'Columbus Symphony', ['columbussymphony.com'], [ 'http://www.columbussymphony.com/events/'], ) # use as many times as needed

http://stackoverflow.com/comment/86231573
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49612286
has text: Thanks a lot. This is even more appropriate to my task.
type: Comment

http://stackoverflow.com/comment/86523877
type: QuestionComment
comment on: http://stackoverflow.com/q/49754293
score: 0
has text: @avinashse: why i am getting this error and how can i correct it.
type: Comment

http://stackoverflow.com/q/49735213
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/12791501
has comment: http://stackoverflow.com/comment/86484362
has title: Appending of items not as desired outside nested for loop
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49735277
has answer: http://stackoverflow.com/a/49735277
tagged with: python
has body: I would like to write all the permutations of 6 into blocks of 4. When I do the print(template) it actually prints the desired permutation: Permutations work fine as seen on the image However when I append them to the big_template and print the big_template (which I want to contain a list of all the permutations) all it prints is a list of [6,6,6,6]. Big_template is not as expected Here is my code: template = ['' for i in range(4)] big_template = [] j=0 for i in range(1,7): template[j]=i for i in range(1,7): template[j+1]=i for i in range(1,7): template[j+2]=i for i in range(1,7): template[j+3]=i print(template) big_template.append(template) print(big_template) My question is what I am doing wrong. Also I would like to extend this procedure to permutations of 6 in any number box. By my method I would have as many for loops as entries into the box. How can this be done using recursion functions? Cheers.

http://stackoverflow.com/q/49678158
has comment: http://stackoverflow.com/comment/86367982
score: 0
has comment: http://stackoverflow.com/comment/86367795
tagged with: python-multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86367793
has body: We have a application where we start multiple python processes and each process cache huge data (5-10 GB). is there a way i could cache this data and share the memory across all my python processes. I read about Managers(), pipe etc but they all seems to be good if all the processes are sub-process of one common parent process. my scenrio is like below . I spawn my processes as ./start_my_process.sh 1 ./start_my_process.sh 2 ./start_my_process.sh 3 This would invoke 3 different thread where actual logic happening is same but on different set of i/p based on argument i pass with each command. Now all these 3 Processes are caching the data... i want to put it at central place and make it accessible to all these 3 processes. is it available straight out of python or i have to go for some sort of in memory cache eg hazelcast, Apache ignite etc
type: Question
has title: sharing memory across different python processes(spawned on unix)
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86367750
has comment: http://stackoverflow.com/comment/86367894

http://stackoverflow.com/a/49740839
answers question: http://stackoverflow.com/q/49740814
has body: When map isn't an option, there's always replace; df['col_1'] = df['col_1'].replace(value2fixed) df col_1 col_2 0 dada 500 1 mel 650 2 hoodie 750 The difference between map and replace is that map replaces "invalid" keys with NaNs - in contrast, replace does not touch them.
downvote count: 0
type: Answer
upvote count: 4
score: 4

http://stackoverflow.com/q/49743638
answer count: 2
has comment: http://stackoverflow.com/comment/89094330
downvote count: 0
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/89125444
favorite count: 0
tagged with: zombie-process
tagged with: docker
has comment: http://stackoverflow.com/comment/89126510
type: Question
tagged with: luigi
has answer: http://stackoverflow.com/a/49772341
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49756925
score: 4
upvote count: 4
has body: I have quite complicated setup with Luigi https://github.com/spotify/luigi https://github.com/kennethreitz/requests-html and https://github.com/miyakogi/pyppeteer But long story short - everything works fine at my local Ubuntu (17.10) desktop, but when run in Docker(18.03.0-ce) via docker-compose(1.18.0) (config version 3.3, some related details here https://github.com/miyakogi/pyppeteer/issues/14) it bloats up with zombie chrome processes spawned from python. Any ideas why it might happen and what to do with it?
has title: Python script produces zombie processes only in Docker

http://stackoverflow.com/a/49700722
has comment: http://stackoverflow.com/comment/86416536
has body: Which dimensions are you try to keep? a.shape is (3,4). How can you remove 2 items from a and still have 3x4 array (3*4=12)? Your desired display is not a (3,4) array: In [638]: arr = np.array([[ 1., 2., 3.], ...: [ 2., 3., 4.], ...: [ 3., 4., 5., 6.]]) ...: In [639]: arr Out[639]: array([list([1.0, 2.0, 3.0]), list([2.0, 3.0, 4.0]), list([3.0, 4.0, 5.0, 6.0])], dtype=object) In [640]: arr.shape Out[640]: (3,) Because the rows vary in length, it creates an object dtype array, one element per row. That is basically a list of lists. For some purposes it is handy to make a MaskedArray: In [637]: np.ma.masked_equal(a, -999) Out[637]: masked_array( data=[[1.0, 2.0, 3.0, --], [2.0, 3.0, 4.0, --], [3.0, 4.0, 5.0, 6.0]], mask=[[False, False, False, True], [False, False, False, True], [False, False, False, False]], fill_value=-999.0) I see you have worked with MaskedArrays before: update numpy array where not masked
downvote count: 0
answers question: http://stackoverflow.com/q/49699951
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49657524
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49694720
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49694720
tagged with: class
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
has title: Matrix (X) is reduced in dimensionality (rows) in custom sklearn transformer class
has body: Given code below, the custom transformer class i'm trying to build - which aims to add a few columns and runt that through a grid search - works well on its own but drops in dimensionality in the rows when executed through a pipeline. Maybe someone can explain what goes wrong, im clearly missing something here. Search for comment "What happends here, dimensionality reduced in rows?" where I have print of the problem. The full code for execution can be found below! import pandas as pd import numpy as np from sklearn.datasets import load_breast_cancer from sklearn import linear_model from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin from sklearn.base import clone from sklearn.base import TransformerMixin from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.pipeline import make_pipeline dict_breast_c = load_breast_cancer() X = pd.DataFrame(dict_breast_c.data, columns=dict_breast_c.feature_names) X.columns = [col.replace(" ", "_").replace("mean", "avg") for col in X.columns] X_sub = Xcol for col in X.columns if col.find("avg") &gt;= 0 X_feat_hldr = Xcol for col in X.columns if col not in (X_sub.columns) y = pd.Series(dict_breast_c.target) print ("Full X matrix shape: {}".format(X_sub.shape)) print ("Full feature holder shape: {}".format(X_feat_hldr.shape)) print ("Target vector: {}".format(y.shape)) class c_FeatureAdder(BaseEstimator, TransformerMixin): def __init__(self, X_feat_hldr, add_error_feat = True, add_worst_feat = True): # no *args or **kargs self.add_error_feat = add_error_feat self.add_worst_feat = add_worst_feat self.list_col_error = list_col_error self.list_col_wrst = list_col_wrst self.X_feat_hldr = X_feat_hldr def fit(self, X, y=None): return self # nothing else to do def transform(self, X, y=None): if self.add_error_feat and not self.add_worst_feat: print ("Adding error (std) features:") return np.c_([X, self.X_feat_hldr[self.list_col_error]]) elif not self.add_error_fe…

http://stackoverflow.com/q/49748127
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49748326
tagged with: python-2.7
answer count: 3
has answer: http://stackoverflow.com/a/49748236
downvote count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/49748326
favorite count: 0
has comment: http://stackoverflow.com/comment/86510852
type: Question
possible better answer: http://stackoverflow.com/a/49748236
has answer: http://stackoverflow.com/a/49748261
has comment: http://stackoverflow.com/comment/86510748
linked to: http://stackoverflow.com/q/8531662
has title: Why is calling a variable twice in a conditional statement necessary for a ranged value?
has body: So, I solved my code issue where the one below didn't work originally ,but I would like a explanation as to why my original code didn't work as expected. If I specified the variable 'grade' once in the if/elif/else section and set the 'and' operator to the parameters I need for it to work shouldn't grade be compared against both without having to use it twice? This is the code that didn't work # if and elif statements for calculating grade score letters def grade_converter(grade): if grade &gt;= 90 : return "A" elif grade &gt;= 80 and &lt;= 89: return "B" elif grade &gt;= 70 and &lt;= 79: return "C" elif grade &gt;= 65 and &lt;= 69: return "D" else: return "F" # This should print an "A" print grade_converter(92) # This should print a "C" print grade_converter(70) # This should print an "F" print grade_converter(61) This was my fix # if and elif statements for calculating grade score letters def grade_converter(grade): if grade &gt;= 90 : return "A" elif grade &gt;= 80 and grade &lt;= 89: return "B" elif grade &gt;= 70 and grade &lt;= 79: return "C" elif grade &gt;= 65 and grade &lt;= 69: return "D" else: return "F" # This should print an "A" print grade_converter(92) # This should print a "C" print grade_converter(70) # This should print an "F" print grade_converter(61)
tagged with: python

http://stackoverflow.com/q/49693891
accepted answer: http://stackoverflow.com/a/49693997
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49693997
has comment: http://stackoverflow.com/comment/86400307
tagged with: http://stackoverflow.com/tag/csv
has body: i am writing a program that opens csv files, works with the data and outputs that data to a new csv file. How would i open the csv file and make a 3d array out of it? I don't want to use the csv module to do this as i cant get it to work with my code.
tagged with: python
score: -1
type: Question
downvote count: 2
has title: Split a csv file through commas in python
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86214704
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49603647
has text: Well, there is the `.dt` for dates and `.cat` for categorical columns. Other types do not have an accessor.

http://stackoverflow.com/comment/86459414
type: Comment
has text: Sorry, this is not possible in a reasonable way. You will just need to open and start the programs seperately
score: 0
comment on: http://stackoverflow.com/q/49722779
type: QuestionComment

http://stackoverflow.com/comment/86459518
score: 0
has text: Instead of adding a delay, add an extra character at the start and/or end of each number to denote where each one starts or ends. <255><150><10>
type: Comment
comment on: http://stackoverflow.com/q/49722187
type: QuestionComment

http://stackoverflow.com/q/49723540
possible better answer: http://stackoverflow.com/a/49723550
has title: PostgreSQL ts_stat in SQLAlchemy
tagged with: python
has body: Postgres uses an odd syntax for ts_stat queries where it includes a literal string containing the statement that you want statistics on, for example: SELECT * FROM ts_stat('SELECT content_ts FROM document_contents') ORDER BY nentry DESC, ndoc DESC, word; I would like to use a Query object in SQLAlchemy to work up a complex query with lots of optional filters like: SELECT content_ts FROM document_contents JOIN fact_api ON document_contents.id = fact_api.content_id WHERE fact_api.day &gt;= %(day_1)s AND fact_api.day &lt;= %(day_2)s AND fact_api.unit IN (%(unit_1)s) AND fact_api.term IN (%(term_1)s, %(term_2)s) I have SQLAlchemy code which generates that inner query. Is there a good way to generate the ts_stat query?
tagged with: tsvector
tagged with: postgresql
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49723550
tagged with: full-text-search
accepted answer: http://stackoverflow.com/a/49726653
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/49726653

http://stackoverflow.com/a/49638418
has body: The parameter that you are passing to pd.DataFrame is in fact a list of Cell objects: sh5.worksheet_by_title("Pincode - fos").range('E1:K7') You need to instead get the value property of each cell on that list: cell_list = sh5.worksheet_by_title("Pincode - fos").range('E1:K7') value_list = cell_list.get_all_values() wks5 = pd.DataFrame(value_list)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86803049
answers question: http://stackoverflow.com/q/49638126

http://stackoverflow.com/q/49721251
favorite count: 0
type: Question
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has body: Following code creates some plots in a for loop: import pandas as pd import matplotlib.pyplot as plt l = [1,2,3,4,5,6] b = [6,5,4,3,2,1] for n in range(7): dflist = [] df = pd.DataFrame(l) dflist.append(df) df2 = pd.DataFrame(b) dflist.append(df2) df = pd.concat(dflist, axis = 1) ax = plt.subplot(4, 2, n + 1) df.plot(ax=ax) In the context of writing a larger program, is there a way to process the plot but show it later?
has title: Dictate moment of plot created in a loop
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49721510
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/49721510
tagged with: python

http://stackoverflow.com/q/49709598
favorite count: 0
type: Question
has title: Express pandas operations as pipeline
has answer: http://stackoverflow.com/a/49709678
tagged with: python
accepted answer: http://stackoverflow.com/a/49709678
has comment: http://stackoverflow.com/comment/86433479
type: AnsweredQuestion
tagged with: pandas
has body: df = df.loc[:, dict_lup.values()].rename(columns={v: k for k, v in dict_lup.items()}) df['cover'] = df.loc[:, 'cover'] * 100. df['id'] = df['condition'].map(constants.dict_c) df['temperature'] = (df['min_t'] + df['max_t])/2. Is there a way to express the code above as a pandas pipeline? I am stuck at the first step where I rename some columns in the dataframe and select a subset of the columns. -- EDIT: Data is here: max_t col_a min_t cover condition pressure 0 38.02 1523106000 19.62 0.48 269.76 1006.64 1 39.02 1523196000 20.07 0.29 266.77 1008.03 2 39 1523282400 19.48 0.78 264.29 1008.29 3 39.11 1523368800 20.01 0.7 263.68 1008.29 4 38.59 1523455200 20.88 0.83 262.35 1007.36 5 39.33 1523541600 22 0.65 261.87 1006.82 6 38.96 1523628000 24.05 0.57 259.27 1006.96 7 39.09 1523714400 22.53 0.88 256.49 1007.94
downvote count: 0
has comment: http://stackoverflow.com/comment/86432657
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/49658462
has title: Index is out of bounds when training a CNN
has comment: http://stackoverflow.com/comment/86332895
has comment: http://stackoverflow.com/comment/86340950
score: 1
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/86330174
has body: So I have gathered a dataset of 100,000 inputs which consist of in-game frames (element [0]) and movements by the player (element [1]) (W, A, D). This dataset will be used to train a convolutional neural network, so an "AI" would be able to navigate throughout the environment on its own. The dataset is then shuffled, in order to balance it, to avoide having a biased-trained CNN. However I met this error when trying to execute the training process, which is: ---------------------------------Exception in thread Thread-3: Traceback (most recent call last): File "C:\Python64\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Python64\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Python64\lib\site-packages\tflearn\data_flow.py", line 187, in fill_feed_dict_queue data = self.retrieve_data(batch_ids) File "C:\Python64\lib\site-packages\tflearn\data_flow.py", line 222, in retrieve_data utils.slice_array(self.feed_dict[key], batch_ids) File "C:\Python64\lib\site-packages\tflearn\utils.py", line 187, in slice_array return X[start] IndexError: index 39977 is out of bounds for axis 0 with size 17512 I have checked on the web, and most people said that it could be a loop iteration error (which may be obvious), however even after trying to iterate until the end of the array (using the len() function), this error is still displayed. Please find my code here: import numpy as np from alexnetCNN import alexnet WIDTH = 80 HEIGHT = 60 #learning rate LR = 1e-3 EPOCHS = 8 MODEL_NAME = 'prototype-movement-{}-{}-{}-epochs.model'.format(LR, 'alexnet', EPOCHS) model = alexnet(WIDTH, HEIGHT, LR) train_data = np.load('E:\\Dataset\\training_data_balanced.npy') train = train_data[:-800] test = train_data[-800:] #feature sets #0 element refers to the frames recorded in the training set #reshape gives a new shape to an array without changing its data #--https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html X = np.array([i…
type: Question
answer count: 0
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: tflearn
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/49719009
score: 1
answers question: http://stackoverflow.com/q/49718976
downvote count: 0
upvote count: 1
type: Answer
has body: What you want is to change the default representation of an object. This is done by implementing the __repr__ function. class MyClass(object): def __init__(self, i): self.i = i def __repr__(self): return str(self.i) &gt;&gt;&gt; A = [MyClass(i) for i in range(3)] &gt;&gt;&gt; print A [0, 1, 2] When you call print on an object, the object executes __str__. Since A is a list (container), the container executes each object __repr__ function instead.

http://stackoverflow.com/a/49617921
type: Answer
score: 0
has body: There's a docx module (though it explicitly doesn't support old-style .doc files), which you could combine with a csv reader to split up the columns, then get your row index out of the first column. from docx import Document import json document = Document('existing-document-file.docx') lines = [para.text for para in document.paragraphs] lines = [line.partition('.') for line in lines] lines = [(int(row_num), row_text) for row_num, _, row_text in lines] lines = [(n, [txt.partition(':') for txt in row_text.split(',')]) for n, row_text in lines] lines = {n: {key.strip(): val.strip() for key, _, val in row} for n, row in lines} json_result = json.dumps(lines) With your sample input, I get the following output using this code: '{"1": {"Name": "ABC", "Place": "Maryland", "Country": "US", "PHONE NO.": "1234567890"}, "2": {"Name": "ABC", "Place": "Maryland", "Country": "US", "PHONE NO.": "1234567890"}, "3": {"Name": "ABC", "Place": "Maryland", "Country": "US", "PHONE NO.": "1234567890"}}'
answers question: http://stackoverflow.com/q/49617178
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/86672006
type: Comment
has text: @VadimPavlovich, any update/feedback on this?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49692817

openpyxl
tags question: http://stackoverflow.com/q/49724714
tags question: http://stackoverflow.com/q/49683075
tags question: http://stackoverflow.com/q/49742392
tags question: http://stackoverflow.com/q/49659945
tags question: http://stackoverflow.com/q/49610870
tags question: http://stackoverflow.com/q/49729416
tags question: http://stackoverflow.com/q/49743051
tags question: http://stackoverflow.com/q/49603462
tags question: http://stackoverflow.com/q/49644827
tags question: http://stackoverflow.com/q/49626182
tags question: http://stackoverflow.com/q/49607990
type: Tag
tags question: http://stackoverflow.com/q/49659411
tag name: openpyxl

http://stackoverflow.com/q/49730922
tagged with: python
tagged with: tuples
score: 0
has answer: http://stackoverflow.com/a/49731077
has title: convert list of tuple () to numpy matrix
linked to: http://stackoverflow.com/q/2402575
has comment: http://stackoverflow.com/comment/86475341
answer count: 1
has body: I want to convert a list of tuple like a = [(1,2),(2,49),(3,45)] to numpy matrix : [[1,2],[2,49],[3,45]] Can anyone help me? thanks in advance
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86488452
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/2402575

http://stackoverflow.com/q/49722520
has answer: http://stackoverflow.com/a/49722563
tagged with: python
type: AnsweredQuestion
score: 0
has title: Pandas drop rows without NAs / keep rows with NAs
has comment: http://stackoverflow.com/comment/86458561
accepted answer: http://stackoverflow.com/a/49722563
tagged with: pandas
answer count: 1
has body: I have a dataframe with missing values in some cells. I want to keep the rows that have nulls in any column. This is the opposite of pandas.DataFrame.dropna(). import pandas as pd import numpy as np df = pd.DataFrame({'a': [1,2], 'b': [np.nan, 4]}) df a b 0 1 NaN 1 2 4.0 desired result: a b 1 2 4.0 I'd like to do it in the method-chaining style, so something like this would be ideal: df.loc[lambda x: ...] df.keepna(how='any') # keepna() doesn't exist
type: Question
tagged with: indexing

http://stackoverflow.com/q/49642748
score: -3
answer count: 1
tagged with: data-science
favorite count: 0
has body: Why isn't file reading permission in python with the open function of file object? Can anyone explain me?enter image description here
tagged with: data-science-experience
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/49642843
type: Question
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has title: Why file isn't reading permission in python with open function of file object? Any one can explain me?

http://stackoverflow.com/comment/86414015
type: QuestionComment
has text: 'The parser in NumPy 1.7 is quite strict about only accepting ISO 8601 dates, with a few convenience extensions.' Pandas has more flexibility allowing you to specify a format outside of ISO 8601 dates.
type: Comment
comment on: http://stackoverflow.com/q/49700120
score: 1

http://stackoverflow.com/a/49695875
has comment: http://stackoverflow.com/comment/86404635
type: Answer
upvote count: 2
score: 1
accepted answer of: http://stackoverflow.com/q/49695751
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/86407084
answers question: http://stackoverflow.com/q/49695751
has comment: http://stackoverflow.com/comment/86406969
has body: I assume you are using pandas. Convert your series to datetime and then use functionality of datetime objects with pd.Series.apply / str.format: df['date'] = pd.to_datetime(df['date']) df['y-m'] = df['date'].apply(lambda x: '{0}-{1}'.format(x.year, x.isocalendar()[1])) # date y-m # 0 2018-04-01 2018-13 # 1 2018-04-01 2018-13 # 2 2018-04-01 2018-13 # 3 2018-04-01 2018-13 # 4 2018-05-01 2018-18
has comment: http://stackoverflow.com/comment/86407310

http://stackoverflow.com/q/49739520
type: AnsweredQuestion
has title: How to skip first two lines and last one line in python
upvote count: 0
has comment: http://stackoverflow.com/comment/86493557
tagged with: python
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/86493752
answer count: 1
has comment: http://stackoverflow.com/comment/86493537
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49739594
tagged with: python-2.7
type: Question
has answer: http://stackoverflow.com/a/49739594
has comment: http://stackoverflow.com/comment/86493789
has comment: http://stackoverflow.com/comment/86493597
has body: I have string value: str1 = """ first line second line abc def xyz 123 lastline""" How to skip first two lines and last line and print remaining lines. Code: I tried and works for to skip first two lines for index, line in enumerate(str1.split("\n")): if index &lt;= 1: continue print line Output getting from above code: abc def xyz 123 lastline Expected output: abc def xyz 123
score: -1
has comment: http://stackoverflow.com/comment/86493586
has comment: http://stackoverflow.com/comment/86493584

http://stackoverflow.com/q/49616550
type: AnsweredQuestion
downvote count: 4
has comment: http://stackoverflow.com/comment/86240043
has comment: http://stackoverflow.com/comment/86240017
upvote count: 0
accepted answer: http://stackoverflow.com/a/49619940
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/86240250
has title: Does Python have a library that produces data as fast os.urandom but is reproducible?
has answer: http://stackoverflow.com/a/49619940
has body: Is there a Python library that can produce random data as fast as os.urandom, but the data can be reproduced if given a seed?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: random-data
has comment: http://stackoverflow.com/comment/86240970
linked to: http://stackoverflow.com/q/16308989
tagged with: python

http://stackoverflow.com/q/49653568
tagged with: python
has comment: http://stackoverflow.com/comment/86364303
has comment: http://stackoverflow.com/comment/86316090
has comment: http://stackoverflow.com/comment/86330283
has comment: http://stackoverflow.com/comment/86318550
has body: I am trying to implement a recursive binary search algorithm which takes 4 arguments, a list, first, the integer index of the first item in the sorted sub-sequence, last, the integer index of the last item in the sorted sub-sequence and a target which will be compared to the values stored in the list. The algorithm needs to return the position of the target within the sorted sub-sequence (if it exists) and if not return the position in which it should be placed within the sorted sub-sequence. Here's what I have thus far; def binary_search(a_list, first, last, target): subMidpoint = (first + last) // 2 if a_list[subMidpoint] == target: return subMidpoint else: if target &lt; a_list[subMidpoint]: last = subMidpoint -1 return binarySearch(a_list, first, last, target) else: first = subMidpoint +1 return binarySearch(a_list, first, last, target) return first I am struggling to wrap my head around how it will return the position if the item does not exist, any help would be greatly appreciated. The code currently compiles however is returning 'None' rather than an index position. Many Thanks in advance. Edit; Thanks all for your help, I have managed to alter the final clause and it has passed some tests however it fails when the target is less than the smallest value in first and when the target is greater than the value in last. Here's the altered final clause. else: if target &lt; a_list[subMidpoint]: last = subMidpoint -1 return binary_search(a_list, first, last, target) else: first = subMidpoint +1 return first
has comment: http://stackoverflow.com/comment/86364258
tagged with: binary-search
tagged with: recursion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86361219
has comment: http://stackoverflow.com/comment/86363624
has answer: http://stackoverflow.com/a/49657200
has comment: http://stackoverflow.com/comment/86316028
type: Question
has answer: http://stackoverflow.com/a/49654116
tagged with: algorithm
type: UnansweredQuestion
has title: recursive binary search of a sorted sublist

http://stackoverflow.com/comment/86379591
has text: @B_Miner as you correctly surmised, the groupby/apply is a ploy to iterate through rows as if they are single row data frames. It is those data frames that are passed to the function. I know a convenient way to add columns to a data frame via assign and dictionary unpacking. However for that to work I need a series object so I can cal to_dict. But I have a single row data frame. So I use squeeze.
comment on: http://stackoverflow.com/a/49681644
score: 1
type: Comment
type: AnswerComment

scipy
tags question: http://stackoverflow.com/q/49676116
tags question: http://stackoverflow.com/q/49689741
tags question: http://stackoverflow.com/q/49723946
tags question: http://stackoverflow.com/q/49623766
tags question: http://stackoverflow.com/q/49738870
tags question: http://stackoverflow.com/q/49690962
tags question: http://stackoverflow.com/q/49606404
tags question: http://stackoverflow.com/q/49610050
tags question: http://stackoverflow.com/q/49697513
tags question: http://stackoverflow.com/q/49753131
tags question: http://stackoverflow.com/q/49738284
tags question: http://stackoverflow.com/q/49731383
tags question: http://stackoverflow.com/q/49705941
tags question: http://stackoverflow.com/q/49713568
tags question: http://stackoverflow.com/q/49713530
tags question: http://stackoverflow.com/q/49709108
tags question: http://stackoverflow.com/q/49701626
tags question: http://stackoverflow.com/q/49652985
tags question: http://stackoverflow.com/q/49755971
tags question: http://stackoverflow.com/q/49633188
type: Tag
tags question: http://stackoverflow.com/q/49747045
tags question: http://stackoverflow.com/q/49756850
tags question: http://stackoverflow.com/q/49742975
tags question: http://stackoverflow.com/q/49659236
tag name: scipy
tags question: http://stackoverflow.com/q/49721996
tags question: http://stackoverflow.com/q/49624208
tags question: http://stackoverflow.com/q/49658375
tags question: http://stackoverflow.com/q/49685160
tags question: http://stackoverflow.com/q/49709861
tags question: http://stackoverflow.com/q/49698418
tags question: http://stackoverflow.com/q/49616841
tags question: http://stackoverflow.com/q/49698922
tags question: http://stackoverflow.com/q/49683653
tags question: http://stackoverflow.com/q/49721113
tags question: http://stackoverflow.com/q/49756030
tags question: http://stackoverflow.com/q/49602620
tags question: http://stackoverflow.com/q/49646879
tags question: http://stackoverflow.com/q/49719016
tags question: http://stackoverflow.com/q/49657956
tags question: http://stackoverflow.com/q/49673059
tags question: http://stackoverflow.com/q/49677505
tags question: http://stackoverflow.com/q/49634506
tags question: http://stackoverflow.com/q/49686013
tags question: http://stackoverflow.com/q/49713637

http://stackoverflow.com/comment/86409867
type: Comment
comment on: http://stackoverflow.com/q/49697090
type: QuestionComment
has text: I'm not convinced that the module information is entirely germane to your question, but you did mention that there was a module causing issues, so I'll leave it in for now...
score: 0

http://stackoverflow.com/comment/86406113
comment on: http://stackoverflow.com/q/49696346
has text: query = cursor.mogrify(SQL, params)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50967368
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/105140466
has comment: http://stackoverflow.com/comment/105140449
has body: The error you're getting is because you're probably providing the endpoint without the "action" that in your case would be putMedia. Try to append /putMedia to your endpoint and don't forget to specify the "content-type": "application/json" header. Btw you have also to generate the v4 signatures for your request. You can use a lib or follow this python guide to do it.
has comment: http://stackoverflow.com/comment/105140500
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49713393
answers question: http://stackoverflow.com/q/49713393
upvote count: 3

http://stackoverflow.com/a/49671129
accepted answer of: http://stackoverflow.com/q/49671050
answers question: http://stackoverflow.com/q/49671050
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: You can change aggregate by specify column col2 in list and in agg use only aggregate function for avoid MultiIndex in columns: df = df.groupby(['col1'])['col2'].agg(['nunique','count']) print(df) nunique count col1 A 2 2 B 2 3 sns.jointplot(x='nunique', y='count', data=df, kind='scatter') Or flatten MultiIndex if need use dictinary in agg - e.g. aggregate another column: df = df.groupby(['col1']).agg({'col2': ['nunique','count'], 'col1':['min']}) df.columns = df.columns.map('_'.join) print (df) col1_min col2_nunique col2_count col1 A A 2 2 B B 2 3
score: 1
type: Answer

http://stackoverflow.com/comment/86343674
type: Comment
score: 2
comment on: http://stackoverflow.com/a/49666750
type: AnswerComment
has text: @user2594596 Right, by why would you allow different types in the list in the first place? I.e. instead of doing `type(x) in (a,b,c)` why not simply `isinstance(x, MyClass)` and only allow `MyClass` in the list (and get rid of `None` as well). IMO mixing unrelated types in a list is not a good practice.

datatable
tags question: http://stackoverflow.com/q/49647951
tag name: datatable
tags question: http://stackoverflow.com/q/49752809
type: Tag

http://stackoverflow.com/comment/86348651
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49666871
type: Comment
has text: Can you post your list so that I can test that please?

http://stackoverflow.com/a/49737400
has body: You're using your parentheses wrong. It appears you want to append one string to another for printing, but instead it's being interpreted as a function call. Use commas instead: print ("Sie heben ", geld_a, "€ ab")
answers question: http://stackoverflow.com/q/49737117
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86343121
type: Comment
comment on: http://stackoverflow.com/a/49648392
type: AnswerComment
has text: I tought, that np.max gives me only the value and np.argmax the index.
score: 0

for-loop
tags question: http://stackoverflow.com/q/49697477
tags question: http://stackoverflow.com/q/49680896
tags question: http://stackoverflow.com/q/49631168
tags question: http://stackoverflow.com/q/49615328
tags question: http://stackoverflow.com/q/49650604
tags question: http://stackoverflow.com/q/49744175
tags question: http://stackoverflow.com/q/49649706
tags question: http://stackoverflow.com/q/49607195
tags question: http://stackoverflow.com/q/49633315
tags question: http://stackoverflow.com/q/49723401
tags question: http://stackoverflow.com/q/49689103
tags question: http://stackoverflow.com/q/49702545
tags question: http://stackoverflow.com/q/49679287
tags question: http://stackoverflow.com/q/49616684
tags question: http://stackoverflow.com/q/49642874
type: Tag
tags question: http://stackoverflow.com/q/49670868
tags question: http://stackoverflow.com/q/49674960
tags question: http://stackoverflow.com/q/49683175
tags question: http://stackoverflow.com/q/49619868
tags question: http://stackoverflow.com/q/49663292
tags question: http://stackoverflow.com/q/49654597
tag name: for-loop
tags question: http://stackoverflow.com/q/49655375
tags question: http://stackoverflow.com/q/49602439
tags question: http://stackoverflow.com/q/49673005
tags question: http://stackoverflow.com/q/49697848
tags question: http://stackoverflow.com/q/49698020
tags question: http://stackoverflow.com/q/49689173
tags question: http://stackoverflow.com/q/49656317
tags question: http://stackoverflow.com/q/49620004
tags question: http://stackoverflow.com/q/49642866
tags question: http://stackoverflow.com/q/49641159
tags question: http://stackoverflow.com/q/49703785
tags question: http://stackoverflow.com/q/49669856

http://stackoverflow.com/comment/86239366
type: AnswerComment
has text: This is great! Thank you for pointing out a much simpler way of going about things!!
type: Comment
comment on: http://stackoverflow.com/a/49615984
score: 0

http://stackoverflow.com/q/49703387
score: 4
has comment: http://stackoverflow.com/comment/86430646
tagged with: tensorflow
favorite count: 0
has body: I'm facing this error when running my code with 3 lstm layers. Not sure how to fix it. Can anyone help. Here MAX_SEQUENCE_LENGTH=250. After running the cost function, i get the error 'ValueError: Shapes (?, 1) and (?,) are incompatible' # Generate a Tensorflow Graph tf.reset_default_graph() batch_size = 25 embedding_size = 50 lstmUnits = 64 max_label = 2 x = tf.placeholder(tf.int32, [None, MAX_SEQUENCE_LENGTH]) y = tf.placeholder(tf.int32, [None]) number_of_layers=3 # Embeddings to represent words saved_embeddings = np.load('wordVectors.npy') embeddings = tf.nn.embedding_lookup(saved_embeddings, x) def lstm_cell(): return tf.contrib.rnn.BasicLSTMCell(lstmUnits,reuse=tf.get_variable_scope().reuse) lstmCell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(number_of_layers)]) lstmCell = tf.contrib.rnn.DropoutWrapper(cell=lstmCell, output_keep_prob=0.75) outputs, final_state = tf.nn.dynamic_rnn(lstmCell, embeddings, dtype=tf.float32) predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid) cost = tf.losses.mean_squared_error(y, predictions) ValueError: Shapes (?, 1) and (?,) are incompatible full error message as below. --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-19-f261b46a6f62&gt; in &lt;module&gt;() 1 # Try 3 ----&gt; 2 cost = tf.losses.mean_squared_error(y, predictions) 3 cost 4 #y.shape 5 #y.reshape[] /home/lavared/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/losses/losses_impl.py in mean_squared_error(labels, predictions, weights, scope, loss_collection, reduction) 564 predictions = math_ops.to_float(predictions) 565 labels = math_ops.to_float(labels) --&gt; 566 predictions.get_shape().assert_is_compatible_with(labels.get_shape()) 567 losses = math_ops.squared_difference(predictions, labels) 568 return compute_weighted_loss( /home/lavared/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/tensor_s…
type: Question
has comment: http://stackoverflow.com/comment/86421157
tagged with: python
has title: Tensorflow ValueError: Shapes (?, 1) and (?,) are incompatible
tagged with: lstm
upvote count: 4
has answer: http://stackoverflow.com/a/50180397
has comment: http://stackoverflow.com/comment/90265982
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86420915
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49698127
type: Question
has title: Load dataset for DeepLearnig model
tagged with: python
type: UnansweredQuestion
tagged with: large-data
has answer: http://stackoverflow.com/a/49698216
downvote count: 0
tagged with: neural-network
score: 1
upvote count: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
has body: I'm new in deepLearning and tensorflow. I'm trying to create a neural network with tensorflow and the places365 standard dataset. I've seen in the tensorFlow's MNIST example that, at the beggining you have to load all the data. That's fine if you have a small dataset but this is not the case. Places365 dataset has 5000 images per class. I'm trying to load only 10 classes but my RAM memory can't handle all of that. This is not necesary since each iteration (epoch) I'm going to use only 128 images. Isn't it a way to divide the dataset in batches, and load the images just before to train them? This is some code that I've thought to get the batches supposing that imageTrain is a list of np.arrays where I have loaded all the photos: while(fin != (len(imageTrain)-1)): ini = counter*BATCH_SIZE fin = (counter + 1)*BATCH_SIZE if fin &gt; len(imageTrain): fin = len(imageTrain) - 1 batch_imageTrain = np.reshape(imageTrain[ini:fin],[(fin-ini),256,256,1]) batch_labelTrain = labelTrain[ini:fin] counter = counter + 1 Can anyone help me? Thank you in advance.

http://stackoverflow.com/comment/86231299
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49612312
has text: Use the append mode: `f = open('names', 'a')`. Write mode will overwrite any previous content and add the new one after.
score: 1

http://stackoverflow.com/comment/86474093
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49687881
has text: @Marcel any idea how to make the %f only three characters instead of 6?

http://stackoverflow.com/a/49602508
has body: When I run your code, the "technicals-root" div is empty. I assume javascript is filling it in. When you can't get a page statically, you can always turn to Selenium to run a browser and let it figure everything out. You may have to tweak the driver path to get it working in your environment but this works for me: import time import contextlib import selenium from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException option = webdriver.ChromeOptions() option.add_argument(" — incognito") with contextlib.closing(webdriver.Chrome( executable_path='/usr/lib/chromium-browser/chromedriver', chrome_options=option)) as browser: browser.get('https://www.tradingview.com/symbols/BTCUSD/technicals/') # wait until js has filled in the element - and a bit longer for js churn WebDriverWait(browser, 20).until(EC.visibility_of_element_located( (By.XPATH, '//*[@id="technicals-root"]/div/div/div[2]/div[2]/span'))) time.sleep(1) status = browser.find_elements_by_xpath( '//*[@id="technicals-root"]/div/div/div[2]/div[2]/span[2]') print(status[0].text)
score: 0
answers question: http://stackoverflow.com/q/49602048
type: Answer
accepted answer of: http://stackoverflow.com/q/49602048
has comment: http://stackoverflow.com/comment/86213397
type: AcceptedAnswer

http://stackoverflow.com/a/49622284
type: Answer
has body: Using awk and expecting the data to be sorted on the chr column: $ awk ' NR==1 { # store the header h=$0 # to var h next } { if(p!=$1) { # when chr changes close(p) # close previous file p=$1 # new chr, new file identifier $0=h ORS $0 # add header } print &gt; "data_" p ".txt" # output record to file }' file $ cat data_2.txt # sample output chr a_val b_val a_idx 2 1355 25d abd 2 1785 25d abd 2 1825 36g ahj If the file is not sorted, you'll get extra headers in the files. In that case you could: $ awk ' # commented only the modified parts NR==1 { h=$0 next } { if(p!=$1) { close(p) p=$1 if((p in a)==0) { # if current chr hasnt been seen before ie. new file $0=h ORS $0 # write the header a[p] # hash the chr to a } } print &gt;&gt; "data_" p ".txt" # append to the file }' file
answers question: http://stackoverflow.com/q/49621634
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/49638428
has body: super needs the information about the calling class. In Python 3, this information - along with the calling object - is automatically given once you call super. Your code super.__init__ refers to a slot on the generic super object. What you want is parentheses after super: super().__init__()
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49638390
score: 2
answers question: http://stackoverflow.com/q/49638390
type: Answer

http://stackoverflow.com/q/49679716
has body: I have a 10*22 matrix, which I am storing as a 2-D list of dots. The initial matrix(left) has to be converted to the one on the right, the logic being that if a row has no dots, it has to be converted into one with all dots. But for some reason, my matrix doesn't get updated when I call the function step. But when I print matrix , it gives me back the original unaltered one. Below is my code: WIDTH, HEIGHT =10, 22 matrix=[['.' for x in range(WIDTH)] for y in range(HEIGHT)] ''' somewhere in between I am changing the matrix, and the result gets successfully stored in 'matrix' ''' def step(): global matrix for row in matrix: if row.count('.')==0: row = ['.' for elem in row]
upvote count: 0
accepted answer: http://stackoverflow.com/a/49679829
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Global variable not getting updated
tagged with: python
has answer: http://stackoverflow.com/a/49679829
has comment: http://stackoverflow.com/comment/86371247
has comment: http://stackoverflow.com/comment/86371329
score: -1
type: AnsweredQuestion

http://stackoverflow.com/comment/111154289
comment on: http://stackoverflow.com/a/62850538
type: Comment
has text: The `__delete__` method is part of the descriptor protocol. It doesn't do what the questioner wanted in this situation.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49645177
tagged with: python
tagged with: ubuntu
type: Question
has body: Unable to do apt-get upgrade -y on Ubuntu 16.04 successfully, Tried using both apt-get upgrade -y and apt-get upgrade -y --fix-missing, Facing issue in upgrading python3, Getting the following warning/error- /home/user# apt-get upgrade -y Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done The following packages have been kept back: linux-generic-hwe-16.04 linux-headers-generic-hwe-16.04 linux-image-generic-hwe-16.04 linux-signed-generic-hwe-16.04 linux-signed-image-generic-hwe-16.04 0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded. 1 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Setting up python3-pytango (8.1.8-1) ... File "/usr/lib/python3/dist-packages/PyTango/tango_gevent.py", line 56 raise result.error_string, None, result.tb ^ SyntaxError: invalid syntax dpkg: error processing package python3-pytango (--configure): subprocess installed post-installation script returned error exit status 1 Errors were encountered while processing: python3-pytango E: Sub-process /usr/bin/dpkg returned an error code (1) On observations the issue is faced for python only., Tried doing sudo apt-get --reinstall install python3 - Setting up python3-pytango (8.1.8-1) ... File "/usr/lib/python3/dist-packages/PyTango/tango_gevent.py", line 56 raise result.error_string, None, result.tb ^ SyntaxError: invalid syntax dpkg: error processing package python3-pytango (--configure): subprocess installed post-installation script returned error exit status 1 Errors were encountered while processing: python3-pytango E: Sub-process /usr/bin/dpkg returned an error code (1)
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86298877
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86298453
upvote count: 1
has title: Ubuntu 16.04 Unable to upgrade completely
downvote count: 1
has comment: http://stackoverflow.com/comment/86299687
favorite count: 0
tagged with: ubuntu-16.04

http://stackoverflow.com/comment/86460498
score: 0
has text: @PaulRooney the else clause is used to call the function recursively. with newton's method, the approximation one gets from plugging in the first guess becomes the second guess and so on until conditions are met.
comment on: http://stackoverflow.com/q/49723357
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86295041
type: AnswerComment
comment on: http://stackoverflow.com/a/49643735
score: 1
type: Comment
has text: Please edit to show what values of `a` your example is working with, otherwise it makes little sense...

sys
tags question: http://stackoverflow.com/q/49680723
type: Tag
tag name: sys
tags question: http://stackoverflow.com/q/49723266

http://stackoverflow.com/comment/86324284
type: AnswerComment
has text: `shutil.copy(filename , dir_dist+"/"+folder_name)`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49657458

http://stackoverflow.com/comment/86207519
type: Comment
type: QuestionComment
has text: There's nothing wrong with the string `"Test\u200bTest"`. My guess is that your terminal can't display the zero-width character and replaces it with a question mark.
score: 6
comment on: http://stackoverflow.com/q/49600250

http://stackoverflow.com/q/49673471
has title: Multiple ForeignKey keys in SQLAlchemy
has comment: http://stackoverflow.com/comment/86358821
tagged with: sql
has comment: http://stackoverflow.com/comment/86357808
tagged with: python
has body: In pure SQL I can declare multiple foreign keys like: ALTER TABLE available_routes ADD FOREIGN KEY (client_id, site_id) REFERENCES sites(client_id, id); I am trying to create model, that have some constrains. But can't understand how to do it: mytable = Table ('mytable', metadata, #... Column('client_id', ForeignKey("clients.id")) )
linked to: http://stackoverflow.com/q/7504753
tagged with: sqlalchemy
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86358163
score: 0
tagged with: foreign-keys

http://stackoverflow.com/q/49683171
upvote count: 1
has comment: http://stackoverflow.com/comment/86378208
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86377977
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I have a function in django that check for selected date and then convert that date to julian date then it extract data from the database based on the selected date. but i am getting an error: time data 'selected_date' does not match format '%Y-%M-%d' my view.py def sum_asset_fundmanager(request): if "selectdate" in request.POST: selected_date = request.POST["selectdate"] if selected_date==selected_date: convert=datetime.datetime.strptime("selected_date", "%Y-%M-%d").toordinal() #calculating date MID Rate engine=create_engine('mssql+pymssql://username:password1@hostname /db') connection=engine.connect() metadata=MetaData() rate=Table('mccurtdt',metadata,autoload=True,autoload_with=engine) statmt=select([rate]) statmt=statmt.where(and_(rate.columns.from_currency=='AUD', rate.columns.rate_type=='MID',rate.columns.convert_date==convert)) CORP101=connection.execute(statmt).fetchall() return render(request,'template.html',locals()) my template.html Select a Date: {% csrf_token %}
has title: Python julian date format
tagged with: django-templates
tagged with: django-views
answer count: 0
score: 1
downvote count: 0

http://stackoverflow.com/comment/86225112
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49609123
has text: Ah my mistake - I tried that and it still isn't working unfortunately. I added 'password2` to `exclude` and that also doesn't work - so it must be something different.
type: Comment

http://stackoverflow.com/q/49640644
type: Question
has body: While I run python manage.py collectstatic It says You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. This is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] How can I solve this issue?
score: 1
tagged with: python
has title: Django collect the static files fails
possible better answer: http://stackoverflow.com/a/49640688
has answer: http://stackoverflow.com/a/49640787
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49640688
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49640735
tagged with: django
upvote count: 1
accepted answer: http://stackoverflow.com/a/49640787
favorite count: 0

http://stackoverflow.com/comment/86349694
has text: Is this what you want? `['Insurtech', '.....Some data', 'Biometrics']` or only the text surrounded by `strong` tags?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49668147
type: Comment

http://stackoverflow.com/comment/86288987
type: AnswerComment
comment on: http://stackoverflow.com/a/49639289
has text: I made an assumtion that you want to strip the empty spaces off the values before comparison and then with the clarification you wanted the key to be the secondary sort i figured out what your rule was
score: 0
type: Comment

dbus
type: Tag
tags question: http://stackoverflow.com/q/49704350
tag name: dbus

http://stackoverflow.com/comment/86275649
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49634108
has text: how did u initialize the csv reader

http://stackoverflow.com/comment/86293114
score: 5
type: Comment
type: QuestionComment
has text: It looks like you're asking for the complete solution to an assignment. This is [off-topic](https://stackoverflow.com/help/on-topic) here. You'll have to try to code something on your own first, then when you get stuck on your own attempt, come back here with a [sample of the work you've done so far](https://stackoverflow.com/help/mcve) to solve the problem so that others can help you.
comment on: http://stackoverflow.com/q/49642780

http://stackoverflow.com/comment/86285596
type: QuestionComment
has text: A) I really wouldn't put this in root's home... on Redhat derivatives I normally put it in /var/www (and then set static to point to /var/www/html/static) B) /root/ (.. in your list above) doesn't have rx set C) Does /var/log/error given any more hints?
comment on: http://stackoverflow.com/q/49638900
score: 1
type: Comment

http://stackoverflow.com/comment/86294977
has text: @user2357112 Or maybe I'm thinking of something that was public in `contextlib2` but ended up being an implementation detail of `@contextmanager` when it went into the stdlib. Probably better to read the docs than to rely on my memory (both for me and for the OP and others who seek the same answer)…
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49643547
type: Comment

http://stackoverflow.com/a/49717743
accepted answer of: http://stackoverflow.com/q/49717720
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49717720
score: 2
has body: Use melt with sort_values: df = df.melt('YearQ', var_name='Area', value_name='Value').sort_values(['YearQ','Area']) A bit slowier alternative with set_index, stack and reset_index: df = df.set_index('YearQ').stack().rename_axis(('YearQ','Area')).reset_index(name='Value') print (df) YearQ Area Value 0 2017Q1 Area A 1234.0 4 2017Q1 Area B 9252.0 8 2017Q1 Area C 3421.0 1 2017Q2 Area A 1245.0 5 2017Q2 Area B 9368.0 9 2017Q2 Area C 3321.0 2 2017Q3 Area A 1350.0 6 2017Q3 Area B 9440.0 10 2017Q3 Area C 3225.0 3 2017Q4 Area A 1333.0 7 2017Q4 Area B 9501.0 11 2017Q4 Area C 3625.0
type: Answer

http://stackoverflow.com/comment/104944243
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49760990
has text: FYI that modern implementations don't need `session.begin()`: https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.begin
score: 5

http://stackoverflow.com/a/49677839
has body: img.decode("utf-8") You can decode the variable with the above. Then convert it to base64. "&lt;img src='data:image/png;base64,{}'/&gt;".format( base64.b64encode(img.decode("utf-8")) ) UPDATED: What you really want is this: raw_img = repr(img) "&lt;img src='data:image/png;base64,{}'/&gt;".format( base64.b64encode(raw_img) )
downvote count: 1
has comment: http://stackoverflow.com/comment/98560628
has comment: http://stackoverflow.com/comment/86367034
has comment: http://stackoverflow.com/comment/86371423
type: Answer
has comment: http://stackoverflow.com/comment/86376257
has comment: http://stackoverflow.com/comment/86402779
score: 2
upvote count: 3
answers question: http://stackoverflow.com/q/49677790
has comment: http://stackoverflow.com/comment/98562815
has comment: http://stackoverflow.com/comment/86402806

http://stackoverflow.com/q/49731792
possible better answer: http://stackoverflow.com/a/49731896
has body: I have a 3D tensor A x B x C. For each matrix B x C, I want to extract the leading diagonal. Is there a vectorized way of doing this in numpy or pytorch instead of looping over A?
favorite count: 0
has answer: http://stackoverflow.com/a/49731896
type: Question
upvote count: 2
tagged with: numpy
has title: Get all 2D diagonals of a 3D tensor in numpy
downvote count: 0
tagged with: pytorch
has answer: http://stackoverflow.com/a/49731940
accepted answer: http://stackoverflow.com/a/49731940
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/66764185

http://stackoverflow.com/comment/86369792
type: QuestionComment
has text: @user308827 wouldnt that be 24*30 for each month and 24*30*12 approx. for whole year? just having doubt
score: 0
comment on: http://stackoverflow.com/q/49620140
type: Comment

http://stackoverflow.com/q/49713387
type: AnsweredQuestion
tagged with: mongodb
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has title: Using Regex in Python to Delete MongoDB databases with "expn" at end of name
has body: Given the number of questions on regex on StackOverFlow, I am sorry to add yet another, but I can't seem to figure out the error in my script. It is supposed to run through all the collections in my database and take a conditional action based on whether they contain the string "_Clean" at the end. I'm pretty sure I'm using the wrong regex. from pymongo import MongoClient from bson.son import SON import re db = MongoClient().guns pattern = re.compile("(?!)(_Clean)\Z") for collection in db.collection_names(): if pattern.match(str(collection)): print(str(collection)) print("No, I should be dropped") else: print("Yay, I am clean") print(str(collection)) The output I receive is: Yay, I am clean Accidental_Injuries_Clean Yay, I am clean Massshootings_Clean Yay, I am clean Accidental_Injuries_Teens_Clean Yay, I am clean Officer_Involved_Shootings_Clean Yay, I am clean Accidental_Deaths_Children Yay, I am clean Accidental_Injuries_Children_Clean Yay, I am clean Thank you all so much for your time, and I appreciate any suggestions you may offer.
favorite count: 0
accepted answer: http://stackoverflow.com/a/49713402
tagged with: pymongo-3.x
type: Question
has answer: http://stackoverflow.com/a/49713402
tagged with: python
tagged with: regex

teradata
type: Tag
tags question: http://stackoverflow.com/q/49616964
tag name: teradata
tags question: http://stackoverflow.com/q/49610780
tags question: http://stackoverflow.com/q/49661232

http://stackoverflow.com/q/49718639
has title: Select columns of pandas dataframe using a dictionary list value
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49718682
tagged with: dataframe
tagged with: python
has body: I have column names in a dictionary and would like to select those columns from a dataframe. In the example below, how do I select dictionary values 'b', 'c' and save it in to df1? import pandas as pd ds = {'cols': ['b', 'c']} d = {'a': [2, 3], 'b': [3, 4], 'c': [4, 5]} df_in = pd.DataFrame(data=d) print(ds) print(df_in) df_out = df_in[[ds['cols']]] print(df_out) TypeError: unhashable type: 'list'
has answer: http://stackoverflow.com/a/49718682
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/38969267
score: 1
possible better answer: http://stackoverflow.com/a/49718684
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49718684
tagged with: python-3.x

http://stackoverflow.com/q/49672548
has title: Indentation with python code
has comment: http://stackoverflow.com/comment/86355702
tagged with: python
has comment: http://stackoverflow.com/comment/86355507
duplicate of: http://stackoverflow.com/q/45621722
has body: i was actually adding a loop in my code and an error of " inconsistent use of tabs and spaces in indentation " with the line of " while ind&lt;3242:" So if you can help me, here is the code : ind=0 X=[] Y=[] xtemp=[] for i in x: r=open('DataSets/Corpus/'+i,'r') text=r.read() fin=text.split('^') for j in fin: while ind&lt;3242: Y.append(str(i)) xtemp.append(j) ind=ind+1 r.close() I checked the number of spaces and indentation and it looks the same actually. Thanks in advance !
downvote count: 6
linked to: http://stackoverflow.com/q/5685406
has answer: http://stackoverflow.com/a/49672717
answer count: 1
score: -6
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45621722
tagged with: indentation
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86299654
comment on: http://stackoverflow.com/q/49645703
type: Comment
type: QuestionComment
has text: Do you actually instantiate your queue class somewhere? It looks like you are just trying to use the class directly
score: 0

http://stackoverflow.com/a/49614538
upvote count: 1
score: 1
has body: [Is it] OK to add code in the module level to initialize a class that is contained in the module? Yes, what you have is fine. This is what the word "dynamic" means when people describe Python as a dynamic language: you may alter the definition of a type at runtime. The entire module in which the class is defined must import successfully before the DoSomething name can be used, so it is not possible for someone to accidentally use an "unpatched" version of the class. However, should you want the behaviour of the class to be entirely defined within the class block, rather than applying a "monkeypatch" after the class definition, you have some other options available. Using a metaclass: class DoSomethingMeta(type): def __init__(self, name, bases, attrs): super(DoSomethingMeta, self).__init__(name, bases, attrs) self.set_all_to_five() class DoSomething(object): __metaclass__ = DoSomethingMeta # for Python3, pass metaclass kwarg instead foo = 0 bar = 0 @classmethod def set_all_to_five(cls): cls.bar = 5 cls.foo = 5 @classmethod def set_all_to_ten(cls): cls.bar = 10 cls.foo = 10 Or, more simply, by using a decorator: def mydecorator(cls): cls.set_all_to_five() return cls @mydecorator class DoSomething(object): ....
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49614245
answers question: http://stackoverflow.com/q/49614245
has comment: http://stackoverflow.com/comment/86236192
type: Answer

http://stackoverflow.com/comment/86355487
score: 0
comment on: http://stackoverflow.com/q/49669112
type: Comment
type: QuestionComment
has text: Actually edge weights denote the relationship between nodes. 1 means nodes are related, 0 means they are not related. So if one connected component is collection of related nodes and there exist a single non related edge with a second connected component (which is also collection of related nodes), it means all nodes of first CC are not related to second CC. I want to generate all these new connections and are required for my research analysis on the graph.

http://stackoverflow.com/q/49695528
tagged with: python
has comment: http://stackoverflow.com/comment/86404004
has comment: http://stackoverflow.com/comment/86404049
linked to: http://stackoverflow.com/q/47155569
score: 0
answer count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/47155569
type: UnansweredQuestion
has title: Plotting y-axis out of order in Pyplot
downvote count: 1
tagged with: weather-api
has comment: http://stackoverflow.com/comment/86403979
favorite count: 0
has comment: http://stackoverflow.com/comment/86403778
type: Question
has body: I have the following program: from weather import Weather import matplotlib.pyplot as plt weather = Weather() highTemp = [] lowTemp = [] city = input('Enter the city for weather forecast \n: ') location = weather.lookup_by_location(city) condition = location.condition print("The weather forecast for",city,"is",condition.text) forecast = location.forecast for forecast in forecast: forecasthigh = forecast.high forecastlow = forecast.low print(forecast.date) print("High temperature:",forecast.high) print("forecast.low",forecast.low) print(forecast.text) highTemp.append(forecasthigh) lowTemp.append(forecastlow) #plt.axis([1,10,0,40]) plt.plot(highTemp, '-r',lowTemp,'-b') plt.ylabel('Temperature') plt.xlabel('Days') plt.pause(0.05) print("----------------------------------------------") plt.show The program shows the weather forecast using the Weather-API. I wanted to plot the high and low temperature variations for the occurring days. The problem is that the Y-label plots out of order causing the graph to go all over the place. Is there a way to better plot the graph or define the Y-axis ?
tagged with: matplotlib

http://stackoverflow.com/q/49739978
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49740646
has answer: http://stackoverflow.com/a/49740646
downvote count: 0
has title: Filling in an allocation % column and have it display nicely
tagged with: python
type: AnsweredQuestion
tagged with: smartsheet-api
score: 1
has body: As part of my ongoing project of filling in project sheets programmatically with python, I am filling the % Allocated column (which is a column with the TAG 'GANTT_ALLOCATION'). I have been sending my values as floats, which works for the resource views, but displays as floats in smartsheet. Using the curl sdk however seems to display as a percentage. With Python: this_allocation = 0.5 SS.models.Cell({ 'column_id': column_map['% Allocated'], 'value': this_allocation, # 'display_value': "{:d}%".format(int(this_allocation*100)) }) Displays in Smartsheet: 0.5 with our own old python api that was using the rest api directly, it was getting displayed as 50%. Also if I type it directly in the UI it displays 50%. I have tried setting a display value with no success. I have also tried sending the value as an int (it caps at 1), as a string/unicode (it displays properly but doesn't calculate). What am I missing? Thanks.
answer count: 1
upvote count: 1

http://stackoverflow.com/a/49749497
has comment: http://stackoverflow.com/comment/86514375
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86513928
answers question: http://stackoverflow.com/q/49749215
has body: Long lines are not necessarily a bad thing if they do not affect readability. It's a matter of taste. You can disable the warning by adding # noqa, or you can split the line into multiple ones: E.g. using parentheses: charr_prob = (float(self.char_freq(kgram, char) * 1.0 / (self.kgram_freq(kgram) * 1.0))) As float already uses parentheses: charr_prob = float(self.char_freq(kgram, char) * 1.0 / (self.kgram_freq(kgram) * 1.0)) You can also use \ at the end of the first line to include the second one in the current expression. Here, it will be redundant with the parentheses defined for float, but assuming that you remove the call to float, it will be: charr_prob = (self.char_freq(kgram, char) * 1.0) \ / (self.kgram_freq(kgram) * 1.0) You can also simplify the expression whenever possible. Assuming you're using Python3 (and thus / is not the integer division): charr_prob = self.char_freq(kgram, char) / self.kgram_freq(kgram) Or, for Python2 (79 characters!): charr_prob = float(self.char_freq(kgram, char)) / float(self.kgram_freq(kgram)) Or, as suggested by @Blender, even: charr_prob = float(self.char_freq(kgram, char)) / self.kgram_freq(kgram) ... the second float being unecessary as the first operand of / is already a float. Another possibility is to import the behavior of / from Python3 to Python2: from __future__ import division
has comment: http://stackoverflow.com/comment/86514084
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/86513818

http://stackoverflow.com/comment/86213760
has text: Your payload key should be username, not userid.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49601155

http://stackoverflow.com/q/49701802
tagged with: python
accepted answer: http://stackoverflow.com/a/49701930
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86417540
has title: Python writing to a csv file produces extra space in excel
answer count: 1
has answer: http://stackoverflow.com/a/49701930
tagged with: excel
type: Question
tagged with: http://stackoverflow.com/tag/csv
has body: Hello I currently have the following function for my write method that behaves in the correct way with one error. The error being each output of the csv document opened in excel has a blank row in between rows with data. How could I fix the following function. def fileWrite(output,failed_list_csv_out): fileToWrite = open('SampleId_ExecutionId.csv','w') with fileToWrite: writer = csv.writer(fileToWrite) writer.writerows(output) writer.writerows(failed_list_csv_out)

http://stackoverflow.com/q/49752560
has comment: http://stackoverflow.com/comment/86611689
has comment: http://stackoverflow.com/comment/86549392
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86521335
has comment: http://stackoverflow.com/comment/86612548
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86641994
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/49813906
tagged with: http
favorite count: 0
tagged with: thingworx
has comment: http://stackoverflow.com/comment/86521608
type: Question
has title: Not able to upload the data on thingworx with api
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49813906
has body: Tried many ways to upload the data(postman, httpie etc as given on their site) on thingworx but not able to do that. Please have a look on the following code to upload the data on thingworx: import requests import json app_key = 'xxxx' url = 'http://pp-1804040542ze.devportal.ptc.io/Thingworx/Things/lmtech_thing/Properties/humidity' prms = {'appKey': app_key} hdrs = { 'Accept': 'application/json', 'Content-Type': 'application/json' } data = {'humidiy': '20'} text = json.dumps(data) print 'data: ' + text r = requests.put(url, params=prms, headers=hdrs, data=text) print r.status_code Have created thing and key successfully. but it always return 404 error. Tried with postman too. Here are the screenshots as shown below:

http://stackoverflow.com/comment/86339650
comment on: http://stackoverflow.com/q/49664966
type: Comment
score: 0
type: QuestionComment
has text: you want to use the `subprocess` module to spawn processes. You can't import jar files directly in python.

http://stackoverflow.com/comment/86423032
type: QuestionComment
comment on: http://stackoverflow.com/q/49704660
score: 0
has text: `readline` works with terminal drivers, not sockets.
type: Comment

http://stackoverflow.com/a/49636777
score: 1
answers question: http://stackoverflow.com/q/49627534
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49627534
has body: Using literal() simply reverse the operation: literal('foo').op('regexp')(MyTable.column)

http://stackoverflow.com/q/49638390
score: 1
answer count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49638428
has answer: http://stackoverflow.com/a/49638428
type: Question
tagged with: python
tagged with: tornado
has title: Calling super.__init__() in a subclass of tornado TCPServer
has body: I am trying to inherit from the TCPServer class in tornado, and I keep getting this error when I run my code. I am using python3.6 Traceback (most recent call last): File "tornado_collector.py", line 38, in &lt;module&gt; main() File "tornado_collector.py", line 30, in main server = TelemetryServer() File "tornado_collector.py", line 9, in __init__ super.__init__() TypeError: descriptor '__init__' of 'super' object needs an argument I have the following code: from tornado.tcpserver import TCPServer from tornado.iostream import StreamClosedError from tornado import gen from tornado.ioloop import IOLoop from struct import Struct, unpack class MyServer(TCPServer): def __init__(self): super.__init__() self.header_size = 12 self.header_struct = Struct('&gt;hhhhi') self._UNPACK_HEADER = self.header_struct.unpack @gen.coroutine def handle_stream(self, stream, address): print(f"Got connection from {address}") while True: try: header_data = yield stream.read_bytes(self.header_size) msg_type, encode_type, msg_version, flags, msg_length = self._UNPACK_HEADER(header_data) print(header_data) data = yield stream.read_until(b"\n") print(data) yield stream.write(data) except StreamClosedError: break I have even tried adding arguments to the super.init() Changed super.__init__() To super.__init__(ssl_options=None, max_buffer_size=None, read_chunk_size=None)
upvote count: 2
tagged with: super
type: AnsweredQuestion

http://stackoverflow.com/comment/86311403
type: Comment
type: QuestionComment
has text: @chrisz recommended in the python docs: https://pypi.python.org/pypi/redis . Generally agree, tho
comment on: http://stackoverflow.com/q/49638445
score: 1

http://stackoverflow.com/comment/86393368
score: 0
type: Comment
has text: what's fclass? An attribute?
comment on: http://stackoverflow.com/q/49690748
type: QuestionComment

http://stackoverflow.com/a/49748067
score: 3
has body: The array has the shape (row, col, channel). Of course it depends on the mode you are loading, grayscale will yield a 2D array.
accepted answer of: http://stackoverflow.com/q/49747708
type: Answer
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49747708
upvote count: 3

http://stackoverflow.com/comment/86522145
type: QuestionComment
comment on: http://stackoverflow.com/q/49753477
type: Comment
has text: Yes, I've looked at svd based method of solving matrices but all of them are much more complex than taking one row of matrix and dividing it by the last element of the row. Unless my matrices are a special case.
score: 0

http://stackoverflow.com/comment/86315113
type: QuestionComment
has text: @eagle, how would I go about doing this??
type: Comment
comment on: http://stackoverflow.com/q/49653155
score: 0

http://stackoverflow.com/a/49737557
accepted answer of: http://stackoverflow.com/q/49737489
score: 3
answers question: http://stackoverflow.com/q/49737489
type: Answer
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: You should not iterate rows for vectorisable calculations. This is one way you can implement your logic via pd.DataFrame.loc: df.loc[df['start'] == df['end'], 'start'] = df['end'].shift(1) + 1 # ID end start # 0 a 200 100.0 # 1 b 300 250.0 # 2 c 300 301.0 # 3 d 500 350.0 # 4 e 600 501.0 # 5 f 900 700.0

http://stackoverflow.com/q/49633193
type: Question
has answer: http://stackoverflow.com/a/49651405
tagged with: python-3.x
has title: Test django project with native unittest lib
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86497394
downvote count: 0
has comment: http://stackoverflow.com/comment/86497309
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86275203
favorite count: 0
tagged with: django-unittest
has body: Is it possible not to use a unit test tool provided by Django but use native python unittest library? I know that for simple tests it works just fine. But when i involve other apps and models into the test i get various exceptions like 'apps are not loaded yet and so on'. So is there a workaround to test django project with unittest lib that works in most cases ?
score: 1
tagged with: python-unittest

http://stackoverflow.com/q/49674105
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49684918
has answer: http://stackoverflow.com/a/49675781
has body: This is the trial I tried so far. from urllib.request import urlopen from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException url ='http://marketdata.krx.co.kr/mdi#document=080120&amp;547c5e15ef32e37dc099b89d69ac8970-[object%20HTMLDivElement]=1&amp;547c5e15ef32e37dc099b89d69ac8970-[object%20HTMLDivElement]=2&amp;547c5e15ef32e37dc099b89d69ac8970-[object%20HTMLDivElement]=1&amp;547c5e15ef32e37dc099b89d69ac8970-object%20HTMLDivElement]=1' driver = webdriver.Chrome() driver.get(url) element = driver.find_element_by_xpath('//select[@name="upclss"]') all_options = element.find_elements_by_tag_name("option") for option in all_options : if option.text == "원자재": option.click() driver.implicitly_wait(5) another = driver.find_element_by_xpath('//li[@class="active"]') another.click() driver.implicitly_wait(5) html = driver.page_source soup = BeautifulSoup(html, "html.parser") table = soup.findChildren('table')[0] rows = table.findChildren('tr') for row in rows: cells = row.findChildren('td') for cell in cells: cell_content = cell.getText() print(cell_content) What shall I do more to get below table contents from the above url and print it? Many thanks!!
tagged with: python
has title: I like to get table text from using selenium
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86359581
answer count: 3
has answer: http://stackoverflow.com/a/49674469
possible better answer: http://stackoverflow.com/a/49675781
accepted answer: http://stackoverflow.com/a/49674469
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/86359367
has comment: http://stackoverflow.com/comment/86359793
has comment: http://stackoverflow.com/comment/86359191
type: Question

http://stackoverflow.com/a/63447732
type: Answer
answers question: http://stackoverflow.com/q/49702173
score: 0
has body: print(A,end="") replace the last line with this

http://stackoverflow.com/q/49651639
has title: Plotting data at high frequency using matplotlib:animation
has comment: http://stackoverflow.com/comment/86314337
tagged with: python
linked to: http://stackoverflow.com/q/14391280
upvote count: 2
answer count: 0
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86315161
has body: I am trying to write a script that will accomplish a few different things: 1) Read data from a text file that keeps being filled up by sensor data. 2) Filter this data. 3) Plot the unfiltered data. At the moment, my script works fine for 1) and 2), but I can't get the plot to work. I think that this is complicated by the very high sampling rate I have on the sensor, 5376 Hz. At the moment, my script polls the text file each 0.1 ms to see if a new line has been written into the document with this code: # Function that continually looks at thefile. def follow(thefile): thefile.seek(0,2) # Look at the last line in the file while True: line = thefile.readline() # line is now equal to the last line in thefile if not line: # If the last line in the file was empty, this will be true, time.sleep(0.0001) # and the function will sleep for 0.1 ms before continuing continue yield line # If the last line was not empty, it will be yielded I then have my main script that analyses the data: import time from scipy.signal import butter, filtfilt import matplotlib.pyplot as plt import numpy as np import os import pylab as pl # Opening text file in subdirectory script_dir = os.path.dirname(__file__) #&lt;-- absolute dir the script is in rel_path = "python_data.txt" abs_file_path = os.path.join(script_dir, rel_path) # Vectors for storing unfiltered data in xar = [] yar = [] zar = [] pl.ion() # Interaction on x = np.arange(0,10) # x-array pl.line, = plt.plot(x,np.sin(x)) # Initiate line logfile = open(abs_file_path,"r") # Open text file loglines = follow(logfile) # Look for changes in text file for line in loglines: # For each new line in text file try: x,y,z = line.split(' \t ') # Split up x-, y- and z- data into different arrays. xar.append(int(x)) yar.append(int(y)) zar.append(int(z)) line.set_ydata(int(x)) # Update the line pl.draw() # Redraw the canvas except: pass # I then perform the filtering of xar, yar and zar when they have reached a certain length, and reset them after filter…
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: matplotlib

http://stackoverflow.com/a/49677051
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49676630
has body: I think you get confused on the formula of Pearson's coefficient. Say you have two random variables X and Y. Then Pearson's coefficient is defined as r = Cov(X, Y)/(s_X*s_Y) Where Cov(X, Y) is the covariance between X and Y, and s_Y and s_Y their standard deviation. Cov(X, Y) = E[(X-E[X])*(Y - E[Y])] Where E[Z] designs the expected value of the random variable Z. Ok, now we have the formula, so how to compute that. Actually you can't since you don't have access to the real standard deviations and real expected values. Instead, what we usually do is compute the sample correlation coefficient, which is based on this formula but replacing the real values by the values given by estimators. A natural (minimum variance non biased) estimator for the expected values in the formula, is simply the mean (given by np.mean), and samewise, the right estimator for the standard deviation is the empirical standard deviation given by np.std. So putting it all together, the formula would become r = np.mean((x-np.mean(x))*(y-np.mean(y)))/(np.std(x)*np.std(y)) which is actually the same as np.mean(X*Y) where X = (x-np.mean(x))/np.std(x)and Y = (y-np.mean(y))/np.std(y)
answers question: http://stackoverflow.com/q/49676630
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86367895

http://stackoverflow.com/a/49623526
score: 0
has body: To open the link in new tab you have to use the ActionChains implementation and you can use the following code block : from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys # code block action = ActionChains(driver) great_per = driver.find_element_by_partial_link_text("Know more Thoughts") action.key_down(Keys.CONTROL).click(great_per).key_up(Keys.CONTROL).perform()
type: Answer
has comment: http://stackoverflow.com/comment/86299563
answers question: http://stackoverflow.com/q/49623250
has comment: http://stackoverflow.com/comment/86299400

http://stackoverflow.com/q/49753131
accepted answer: http://stackoverflow.com/a/49753364
type: AnsweredQuestion
has body: How can I find details about the implementation of the non-central chi-squared distribution in scipy.stats.ncx2? The scipy documentation has no information about implementation. Tracing the source, it seems as if the function is implemented via scipy.special.chndtr. But there is no link to this source from the scipy pages: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chndtr.html I feel I'm missing something obvious, but haven't been able to find any info on this.
score: 0
has answer: http://stackoverflow.com/a/49753364
tagged with: scipy
type: Question
has title: implementation of scipy.stats.ncx2
answer count: 1
tagged with: python

http://stackoverflow.com/comment/86470629
type: Comment
type: QuestionComment
score: 0
has text: Is `gmshutils` specifically imported in `my_module_name`? Where does `gmshutils` reside? For example, if it was installed in the current directory then that is often something which is different in an IDE.
comment on: http://stackoverflow.com/q/49728251

http://stackoverflow.com/comment/86493537
type: QuestionComment
has text: `(if index <= 1) or (index >= len(str.split("\n")) - 1)`? Or better yet, precompute the number of lines and store it as a variable.
comment on: http://stackoverflow.com/q/49739520
score: 1
type: Comment

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/49677173
tags question: http://stackoverflow.com/q/49734797
tags question: http://stackoverflow.com/q/49736700
tags question: http://stackoverflow.com/q/49632828
tags question: http://stackoverflow.com/q/49739047
tags question: http://stackoverflow.com/q/49672484
tags question: http://stackoverflow.com/q/49721675
tags question: http://stackoverflow.com/q/49700936
tags question: http://stackoverflow.com/q/49729771
tags question: http://stackoverflow.com/q/49706831
tag name: decision-tree
tags question: http://stackoverflow.com/q/49673029
tags question: http://stackoverflow.com/q/49730159
tags question: http://stackoverflow.com/q/49654883

http://stackoverflow.com/q/49640219
downvote count: 2
has comment: http://stackoverflow.com/comment/86288170
linked to: http://stackoverflow.com/q/10690233
score: 1
has body: This seems like a simple thing to do but I could not figure it out... first = np.array([0,1,2,0,4,2]) second = np.array([1,2]) I'd like to do element-wise comparison so that the answer will be array([False, True, True, False, False, True], dtype=bool) Basically I want it to say True for each of the elements in first which is also in second. So if first has 100 elements, then the output should have 100 elements, too. But I can't figure out how. I've tried using np.equal, np.any, first==np.any(second) to no avail. Of course, I can write a loop to do this but I know there must be a way to do this relatively simple task!
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49640337
duplicate of: http://stackoverflow.com/q/10690233
possible better answer: http://stackoverflow.com/a/49640329
has answer: http://stackoverflow.com/a/49640337
has title: Elementwise comparison of numpy arrays of different lengths
tagged with: python
has answer: http://stackoverflow.com/a/49640329
tagged with: comparison
type: Question
tagged with: numpy
tagged with: elementwise-operations
answer count: 2
has comment: http://stackoverflow.com/comment/86288138
upvote count: 3

http://stackoverflow.com/comment/86275170
type: Comment
has text: Thank you, I have managed to use your second suggestion to group the data. I was hoping to put this data into a new data frame, is there a way to do this? Sorry if this is a stupid question, I am very new to programming
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49633132

http://stackoverflow.com/comment/86320772
has text: Amazingly explained Kudos! just got it working. And i am facing a problem while extracting these contours it is returning kind of duplicates. So should i post another question? Would you be able to help me? Thank you Cheers! @Andriy Makukha
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49644835

http://stackoverflow.com/a/49656582
downvote count: 0
score: 1
has body: you can use exclude with in condition SampleTable.objects.exclude(status__in=['Fail','Success'])
has comment: http://stackoverflow.com/comment/86322488
has comment: http://stackoverflow.com/comment/86322766
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49656220
has comment: http://stackoverflow.com/comment/86323136

http://stackoverflow.com/q/49743234
has answer: http://stackoverflow.com/a/49928792
tagged with: list
tagged with: syntax
score: 0
has body: This my first post on StackOverflow, so please be forgiving with any faux pas I may be making. I'm also new to Python, so any and all tips are welcome. My questions is simple, but no matter what I've tried I can't seem to figure it out. Here is my code: import os from bs4 import BeautifulSoup import string import nltk from nltk import WordNetLemmatizer from nltk.corpus import stopwords from nltk import FreqDist # For TF-IDF calculations import math from textblob import TextBlob as tb def tf(word, blob): return blob.words.count(word) / len(blob.words) def n_containing(word, bloblist): return sum(1 for blob in bloblist if word in blob.words) def idf(word, bloblist): return math.log(len(bloblist) / (1 + n_containing(word, bloblist))) def tfidf(word, blob, bloblist): return tf(word, blob) * idf(word, bloblist) rootDir ='D:\rootDir' testPath = r'D:\testPath' trainPath = r'D:\trainPath' data = [] lemmatizer = WordNetLemmatizer() stop = stopwords.words("english") stop += ['also'] bloblist_train = [tb('')] #Before EDIT: bloblist_train = tb('') bloblist_test = [tb('')] #Before EDIT: bloblist_test = tb('') for currentDirPath, subDirs, files in os.walk(rootDir): for file in files: with open(os.path.join(currentDirPath, file)) as dataFile: inFile = dataFile.read() html = BeautifulSoup(inFile, "html.parser") text = html.get_text() text_no_punc = text.translate(str.maketrans("", "", string.punctuation)) if testPath in currentDirPath: bloblist_test += (tb(text_no_punc)) elif trainPath in currentDirPath: bloblist_train += tb(text_no_punc) words = text_no_punc.split() data = data + words I'm iterating over a larger directory of files with HTML documents and am parsing them and then further trying to find the TF-IDF for each word. I'm using a mix of packages and classes for this including BeautifulSoup, NLTK, and TextBlob. I'm using TextBlob to find the TF-IDF, but have run into the issue of creating a list of TextBlobs. The specific lines I'm having issues with are these: if testPat…
tagged with: textblob
answer count: 1
type: Question
tagged with: python-3.x
has title: How to create a list of TextBlobs?
tagged with: python
accepted answer: http://stackoverflow.com/a/49928792
type: AnsweredQuestion

c++
tags question: http://stackoverflow.com/q/49757245
tags question: http://stackoverflow.com/q/49687487
tags question: http://stackoverflow.com/q/49734949
tags question: http://stackoverflow.com/q/49744870
tags question: http://stackoverflow.com/q/49724370
tags question: http://stackoverflow.com/q/49633990
tags question: http://stackoverflow.com/q/49618409
tags question: http://stackoverflow.com/q/49726082
tags question: http://stackoverflow.com/q/49653205
type: Tag
tags question: http://stackoverflow.com/q/49650962
tags question: http://stackoverflow.com/q/49692794
tags question: http://stackoverflow.com/q/49708209
tags question: http://stackoverflow.com/q/49733639
tags question: http://stackoverflow.com/q/49639006
tags question: http://stackoverflow.com/q/49747698
tags question: http://stackoverflow.com/q/49744351
tags question: http://stackoverflow.com/q/49692157
tags question: http://stackoverflow.com/q/49645945
tags question: http://stackoverflow.com/q/49603690
tag name: c++
tags question: http://stackoverflow.com/q/49600636
tags question: http://stackoverflow.com/q/49698060
tags question: http://stackoverflow.com/q/49634528
tags question: http://stackoverflow.com/q/49725393

http://stackoverflow.com/a/49645982
downvote count: 1
type: Answer
has body: There are 2 problems with your code: init needs to be surrounded by double underscore. An instance variable needs to be accessed via the class instance, not the class itself. Try this instead: class chainlist: def __init__(self): self.chain = [6 ,7] blockchain = chainlist() print(blockchain.chain)
answers question: http://stackoverflow.com/q/49645900
upvote count: 2
score: 1

http://stackoverflow.com/comment/130274962
type: AnswerComment
comment on: http://stackoverflow.com/a/73515103
score: 1
has text: Thank you for the update! I will test locally to be sure, but I worked up a compat shim by stuffing a treeview widget into a canvas widget and making horizontal scroll requests scroll the canvas' x-axis (also required clobbering the treeview's xview_scroll with that of the canvas'). For backwards compat, I'll probably keep that hack in place for older versions of Tk and for 8.6.10+, see about using the Treeview natively. Hopefully it'll all still work right...
type: Comment

http://stackoverflow.com/q/49631758
has body: I am struggling with Doc2Vec and I cannot see what I am doing wrong. I have a text file with sentences. I want to know, for a given sentence, what is the closest sentence we can find in that file. Here is the code for model creation: sentences = LabeledLineSentence(filename) model = models.Doc2Vec(size=300, min_count=1, workers=4, window=5, alpha=0.025, min_alpha=0.025) model.build_vocab(sentences) model.train(sentences, epochs=50, total_examples=model.corpus_count) model.save(modelName) For test purposes, here is my file: uduidhud duidihdd dsfsdf sdf sddfv dcv dfv dfvdf g fgbfgbfdgnb i like dogs sgfggggggggggggggggg ggfggg And here is my test: test = "i love dogs".split() print(model.docvecs.most_similar([model.infer_vector(test)])) No matter what parameter for training, this should obviously tell me that the most similar sentence is the 4th one (SENT_3 or SENT_4, I don't know how their indexes work, but the sentence labels are this form). But here is the result: [('SENT_0', 0.15669342875480652), ('SENT_2', 0.0008485736325383186), ('SENT_4', -0.009077289141714573)] What am I missing ? And if I try with the same sentence (I LIKE dogs), I have SENT_2, then 1 then 4... I really don't get it. And why such low numbers ? And when I run few times in a row with a load, I don't get the same results either. Thanks for your help
tagged with: python
tagged with: gensim
tagged with: nlp
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49635851
tagged with: sentence-similarity
has answer: http://stackoverflow.com/a/49635851
upvote count: 3
tagged with: doc2vec
answer count: 1
downvote count: 0
favorite count: 0
type: Question
score: 3
has title: Gensim Doc2Vec most_similar() method not working as expected

http://stackoverflow.com/a/58741202
has comment: http://stackoverflow.com/comment/130906435
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/49732639
score: 9
has comment: http://stackoverflow.com/comment/130910548
downvote count: 0
has body: I'm visiting this question because i was searching this topic. As of today (2019), the pytrends library has a method that returns daily data for a keyword. I recommend checking their github repository. I should point out that i didn't test it how far we can get data, but i'm sure that somewhere in the documentation has this information. Example: from pytrends.request import TrendReq from pytrends import dailydata df = dailydata.get_daily_data('cinema', 2019, 1, 2019, 10, geo = 'BR') print(df) Output cinema_unscaled cinema_monthly isPartial scale cinema date 2019-01-01 60 NaN NaN NaN NaN 2019-01-02 76 NaN NaN NaN NaN 2019-01-03 82 NaN NaN NaN NaN 2019-01-04 71 NaN NaN NaN NaN 2019-01-05 100 NaN NaN NaN NaN ... ... ... ... ... 2019-10-26 74 38.0 NaN 0.38 28.12 2019-10-27 74 33.0 True 0.33 24.42 2019-10-28 53 33.0 NaN 0.33 17.49 2019-10-29 37 33.0 NaN 0.33 12.21 2019-10-30 34 33.0 NaN 0.33 11.22

http://stackoverflow.com/a/55260657
upvote count: 4
answers question: http://stackoverflow.com/q/49734915
score: 2
downvote count: 2
has body: The likely real issue behind this is that the DOM has not loaded yet and you are triggering searches on the next page. That's why the sleep(3) is working in most cases. The proper fix is to use a wait class. This is an example test case using a wait function for Nextcloud. It's from my docker-selenium-firefox-python image: https://hub.docker.com/r/nowsci/selenium Notice how the wait class is called surrounding any click or get calls. Basically, what this does is takes advantage of the fact that selenium changes the ID for the HTML tag on page load. The wait function checks if the new ID is different than the old, and when it is, the DOM has loaded. import time from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.keys import Keys class wait(object): def __init__(self, browser): self.browser = browser def __enter__(self): self.old_page = self.browser.find_element_by_tag_name('html') def page_has_loaded(self): new_page = self.browser.find_element_by_tag_name('html') return new_page.id != self.old_page.id def __exit__(self, *_): start_time = time.time() while time.time() &lt; start_time + 5: if self.page_has_loaded(): return True else: time.sleep(0.1) raise Exception('Timeout waiting for page load.') def test(): try: opts = Options() opts.headless = True assert opts.headless # Operating in headless mode browser = Firefox(options=opts) except Exception as e: print(" -=- FAIL -=-: Browser setup - ", e) return # Test title try: with wait(browser): browser.get('https://nextcloud.mydomain.com/index.php/login') assert 'Nextcloud' in browser.title except Exception as e: print(" -=- FAIL -=-: Initial load - ", e) return else: print(" Success: Initial load") try: # Enter user elem = browser.find_element_by_id('user') elem.send_keys("MYUSER") # Enter password elem = browser.find_element_by_id('password') elem.send_keys("MYPASSWORD") # Submit form elem = browser.find_element_by_id('submit') with wait(browser):…
type: Answer

http://stackoverflow.com/q/49634844
has title: Matplotlib Boolean Plot Rectangle Fill
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has body: I would like to create a boolean data plot with Matplotlib &amp; Python. I have several boolean channels and I would like to fill with a colour if the channel is = 1 (or True) I have found this C# question which shows pretty much what I want in the bottom plot of this image. My current idea is to use multiple subplots with a shared x-axis and use fill_between to fill the times when my channel is =1. Before I press ahead with coding this, I wondered if there is already something in Matplotlib that would make this easier? I'd like to not have to worry about y values to control heights, but rather treat it more like a horizontal bar plot , except that my x axis is time series and my bar has gaps in it.
accepted answer: http://stackoverflow.com/a/52718426
answer count: 1
has comment: http://stackoverflow.com/comment/86284879
has comment: http://stackoverflow.com/comment/86343243
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/43748455
has answer: http://stackoverflow.com/a/52718426
tagged with: matplotlib
tagged with: python

wunderground
tag name: wunderground
tags question: http://stackoverflow.com/q/49728262
type: Tag

http://stackoverflow.com/q/49720443
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86454053
answer count: 1
has answer: http://stackoverflow.com/a/49721771
favorite count: 0
has comment: http://stackoverflow.com/comment/86454165
type: Question
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/49721771
downvote count: 0
has title: Pandas: Append existing CSV file, extra columns
tagged with: python
linked to: http://stackoverflow.com/q/20062470
has comment: http://stackoverflow.com/comment/86453963
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86453957
has body: I'm trying to create csv file, save it, read it later and then add (concat) data to the bottom - and do this process multiple times. As an example, my setup is: import pandas as pd df3 = pd.DataFrame(columns=('col1','col2')) df3.to_csv('example.csv', sep=',') print(df3) which generates a blank csv file only containing column headers that looks like this (this is what i want my data to look like): Empty DataFrame Columns: [col1, col2] Index: [] Then, I generate a new dataframe with row information (index), open the old (df3) csv file and .concat() to the file. df1 = pd.DataFrame({'col1':list("abc"),'col2':list("def")}) df3 = pd.read_csv('example.csv', sep=',') print(df3) print(df1) df3 = pd.concat([df3, df1], ignore_index=True) print(df3) df3.to_csv('example.csv', sep=',') but when I read the example.csv file (df3) it actually generates a dataframe that looks like this: Empty DataFrame Columns: [Unnamed: 0, col1, col2] Index: [] There is now an extra column. My actual code constrains the .read_csv/.to_csv and it throws an error because what I'm trying to read/write in isn't what I sent it (I don't think). I've tried adding ignore_index=True to the method but that doesn't do it. I've also tried reading back exactly what I put in, but it still generates the Unnamed column. There is some information here on bad data within the column - not quite on point. There is obviously a simple answer to this, I just can't figure it out.

http://stackoverflow.com/comment/86279101
has text: In fact Python 2 won't be maintained after 2019 - EOL is at 2029-12-31T23:59.
comment on: http://stackoverflow.com/a/49635631
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49706501
favorite count: 0
type: Question
tagged with: opencv
has title: Fill holes on a 3D image
has comment: http://stackoverflow.com/comment/86426977
has answer: http://stackoverflow.com/a/49708506
type: UnansweredQuestion
has body: I have an image of size 301,512,512 which is a binary mask image . the one values are concentrated near a patch,but there are a few holes inside the path.I would like to fill them with value one. i have tried img_fill_holes = scipy.ndimage.binary_fill_holes(array_to_be_filled[:,:,:]).astype(int) and import SimpleITK as sitk filledImage = sitk.BinaryFillhole(array_to_be_filled) but both of the methods dont give the desired outputs, Any suggestions which may help me would be great. Thanks in advance.
has comment: http://stackoverflow.com/comment/86426600
tagged with: scikit-image
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/86426837
tagged with: itk
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86426435
has comment: http://stackoverflow.com/comment/86426280
has comment: http://stackoverflow.com/comment/86426497

http://stackoverflow.com/comment/86502457
score: 0
type: Comment
has text: Yes, I have run the code multiple times. It creates the dictionary, but doesn't change the excel. I even checked the directory to see if I was using the wrong file, but everything seems in order. What you explained reg. key-value makes sense- thank you.
type: AnswerComment
comment on: http://stackoverflow.com/a/49724759

http://stackoverflow.com/a/49663725
downvote count: 0
upvote count: 4
has body: Why are you having this output? I believe layers such as Dense and Activation used to accept only a 2-rank tensor of dimensions (batch_size, features) in earlier days. The following declaration would behave like your model, outputting predictions of shape (batch_size, steps, 1): x = Input(shape=(299, 299, 3)) y = Conv2D(...)(x) y = Conv2D(...)(y) ... conv_model = Model(x, y) x = Input(shape=(steps, 299, 299, 3)) y = TimeDistributed(conv_model)(x) y = TimeDistributedDense(1)(y) # or TimeDistributed(Dense(1))(y) model = Model(x, y) Whereas this would raise an error: x = Input(shape=(299, 299, 3)) y = Conv2D(...)(x) y = Conv2D(...)(y) ... conv_model = Model(x, y) x = Input(shape=(steps, 299, 299, 3)) y = TimeDistributed(conv_model)(x) y = Dense(1)(y) model = Model(x, y) But then some assumptions were taken so multiple existing layers (e.g. BatchNormalization, Dropout, Activation) could be applied in a larger context, such as RNNs' outputs. Nowadays, Dense and Activation layers accept inputs of arbitrary rank and will, by default, operate in the last one (see the docs on Dense). Hence TimeDistributed(Dense(1)) and Dense(1) are logically equivalent, but kept as valid choices for the users. You can read issue #278 for more on this discussion. How to solve your problem? Dealing with independent images If the samples images in each input from your dataset don't hold any relationship other than the associated output (e.g. different captures of a same class). I would start by keeping your conv model and combining the results with average pooling before applying the dense layer: x = Input(shape=(299, 299, 3)) y = Conv2D(...)(x) y = Conv2D(...)(y) ... y = Conv2D(kernels, ...)(y) conv_model = Model(x, y) x = Input(shape=(steps, 299, 299, 3)) y = TimeDistributed(conv_model)(x) # K.get_variable_shape(y) == (?, samples, height/k, width/l, kernels) y = GlobalAveragePooling3D()(y) # K.get_variable_shape(y) == (?, kernels) y = Dense(1)(y) model = Model(inputs=x, outputs=y) If you alre…
has comment: http://stackoverflow.com/comment/86339156
accepted answer of: http://stackoverflow.com/q/49662869
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49662869
type: AcceptedAnswer

data-science
tags question: http://stackoverflow.com/q/49604218
tags question: http://stackoverflow.com/q/49695188
tags question: http://stackoverflow.com/q/49642748
tags question: http://stackoverflow.com/q/49604269
tags question: http://stackoverflow.com/q/49693485
tags question: http://stackoverflow.com/q/49656386
tags question: http://stackoverflow.com/q/49712002
tags question: http://stackoverflow.com/q/49716968
type: Tag
tags question: http://stackoverflow.com/q/49755230
tag name: data-science
tags question: http://stackoverflow.com/q/49734374
tags question: http://stackoverflow.com/q/49603937
tags question: http://stackoverflow.com/q/49607163
tags question: http://stackoverflow.com/q/49709352
tags question: http://stackoverflow.com/q/49628420
tags question: http://stackoverflow.com/q/49747045

http://stackoverflow.com/q/49726617
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49726671
accepted answer: http://stackoverflow.com/a/49726671
score: 3
tagged with: python
type: AnsweredQuestion
upvote count: 3
has title: populate missing values for multiple columns with multiple values
downvote count: 0
tagged with: pandas
has body: I have gone through the posts that are similar to filling out the multiple columns for pandas in one go, however it appears that my problem here is a little different, in the sense that I need to be able to populate a missing column value with a specific column value and be able to do that for multiple columns in one go. Eg: I can use the commands as below individually to fill the NA's result1_copy['BASE_B'] = np.where(pd.isnull(result1_copy['BASE_B']), result1_copy['BASE_S'], result1_copy['BASE_B']) result1_copy['QWE_B'] = np.where(pd.isnull(result1_copy['QWE_B']), result1_copy['QWE_S'], result1_copy['QWE_B']) However, if I were to try populating it one go, it does not work: result1_copy['BASE_B','QWE_B'] = result1_copy['BASE_B', 'QWE_B'].fillna(result1_copy['BASE_S','QWE_S']) Do we know why ? Please note I have only used 2 columns here for ease of purpose, however I have 10s of columns to impute. And they are either object, float or datetime. Is datatypes the issue here ?

http://stackoverflow.com/comment/86394949
comment on: http://stackoverflow.com/q/49684422
type: Comment
type: QuestionComment
score: 0
has text: Why do the names and years combinations look so realistic? Have you made them up so carefully, or have you just dumped real data of your customers on some publicly available website on the internet? Is everyone in the world supposed to know that those peoples (with their full names and birth years) have somehow made it into your database on the given date? In any case, I vote to close, because the problem was not in the code, but in the spreadsheet program used to inspect the output.

robotframework
tags question: http://stackoverflow.com/q/49654291
tags question: http://stackoverflow.com/q/49739628
tags question: http://stackoverflow.com/q/49611640
tag name: robotframework
tags question: http://stackoverflow.com/q/49756797
tags question: http://stackoverflow.com/q/49700854
tags question: http://stackoverflow.com/q/49754614
tags question: http://stackoverflow.com/q/49645432
type: Tag

http://stackoverflow.com/comment/86495125
score: 0
type: AnswerComment
has text: @DibuEscobedo The edit you wanted is incorrect, my snippet does not produce that ouput!
comment on: http://stackoverflow.com/a/49738805
type: Comment

http://stackoverflow.com/q/49667248
upvote count: 3
downvote count: 0
tagged with: python
favorite count: 0
has body: I have many images of different sizes in my directory, however i want to resize them all by a certain ratio, let's say 0.25 or 0.2, it should be a variable i can control from my code and i want the resulting images to be an output in another directory. I looked into this approach supplied by this previous question How to resize an image in python, while retaining aspect ratio, given a target size? Here is my approach, aspectRatio = currentWidth / currentHeight heigth * width = area So, height * (height * aspectRatio) = area height² = area / aspectRatio height = sqrt(area / aspectRatio) At that point we know the target height, and width = height * aspectRatio. Ex: area = 100 000 height = sqrt(100 000 / (700/979)) = 373.974 width = 373.974 * (700/979) = 267.397 but it lacks lots of details for example:how to transform these sizes back on the image which libraries to use and so on.. Edit: looking more into the docs img.resize looks ideal (although i also noticed .thumbnail) but i can't find a proper example on a case like mine.
tagged with: opencv
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/33701929
accepted answer: http://stackoverflow.com/a/49667647
has comment: http://stackoverflow.com/comment/86344779
has answer: http://stackoverflow.com/a/49667749
has answer: http://stackoverflow.com/a/49667647
tagged with: image-processing
has title: How can i resize images given a certain ratio?
tagged with: image
type: Question
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/49667749

http://stackoverflow.com/comment/86262561
type: QuestionComment
has text: https://stackoverflow.com/a/8010133/4794459
type: Comment
comment on: http://stackoverflow.com/q/49627752
score: 1

http://stackoverflow.com/a/49638996
downvote count: 0
answers question: http://stackoverflow.com/q/49638899
upvote count: 1
type: Answer
has body: One easy way is M.swapaxes(0, X)[1] *= C
score: 1

http://stackoverflow.com/q/49684787
has answer: http://stackoverflow.com/a/49733722
has body: To use Happybase - Python, we need to get our Thrift server up and running for Hbase as mentioned in the Happybase docs. I'm getting the following java runtime exception while kick starting the Thrift server for Happybase. Exception in thread "main" java.lang.AbstractMethodError: org.apache.hadoop.metrics2.sink.timeline.HadoopTimelineMetricsSink.init(Lorg/apache/phoenix/shaded/org/apache/commons/configuration/SubsetConfiguration; I'm using the following command to start the Thrift server.. hbase thrift start
type: Question
tagged with: happybase
has comment: http://stackoverflow.com/comment/86428566
tagged with: hbase
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Trying to connect to Thrift server for Hbase. Getting the following error
tagged with: thrift
score: 0

http://stackoverflow.com/q/49734666
score: 0
answer count: 0
tagged with: pyqt
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/86492696
has comment: http://stackoverflow.com/comment/86492578
has title: What causes the error "setNativeLocks failed: Resource temporarily unavailable"?
has body: I'm writing this code in PyQt, but when I try to open a file, I get this error: setNativeLocks failed: Resource temporarily unavailable Why can't I open and save a file? # class Main class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(300, 300)) self.setWindowTitle("TP1") # Create new action openAction = QAction(QIcon('open.png'), '&amp;Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open document') openAction.triggered.connect(self.openCall) # Save new action saveAction = QAction(QIcon('save.png'), '&amp;Save', self) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('Save document') saveAction.triggered.connect(self.newSave) # Copy new action copyAction = QAction(QIcon('copy.png'), '&amp;Copy', self) copyAction.setShortcut('Ctrl+C') copyAction.setStatusTip('Copy document') copyAction.triggered.connect(self.CopyCall) # Create exit action exitAction = QAction(QIcon('quit.png'), '&amp;Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.exitCall) # Create menu bar and add action menuBar = self.menuBar() fileMenu = menuBar.addMenu('&amp;File') fileMenu.addAction(openAction) fileMenu.addAction(saveAction) fileMenu.addAction(copyAction) fileMenu.addAction(exitAction) def openCall(self): fileName = QFileDialog.getOpenFileName(self,"Open Image","/home/m1/icheva/a","*.txt") print('Open') def newSave(self): fileName1 = QFileDialog.getSaveFileName(self,"Save File","/home/m1/icheva/a/savefile.txt","*.txt") print('Save ') def CopyCall(self): print('Copy app') def exitCall(self): print('Exit app') #main if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit( app.exec_() )
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/94627556
comment on: http://stackoverflow.com/q/49678975
type: Comment
has text: My issue was that I had named the script fedex.py. No idea why that was causing an error. Thanks @LukeWoodward
score: 0
type: QuestionComment

http://stackoverflow.com/comment/112894007
type: Comment
type: QuestionComment
has text: have you found any proper alternative for mongomock or workaround for the solution.
comment on: http://stackoverflow.com/q/49628968
score: 0

http://stackoverflow.com/comment/86283799
has text: For the use case I'm describing (trying to fetch and process pages in parallel), would I even need to call `Queue.join()` though? Why could I not just keep calling `Queue.get_nowait()` until it throws the `Queue.Empty` exception and know that I'm done at that point? Is `task_done()`/`Queue.join()` only useful when I need to ensure that every item is processed before the queue is terminated? For cases where I just need to ensure I've gotten all the items, can I do away with `queue.join()` altogether?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49637357
type: AnswerComment

http://stackoverflow.com/q/49748063
tagged with: pypi
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49748407
linked to: http://stackoverflow.com/q/38903415
has answer: http://stackoverflow.com/a/49748407
has comment: http://stackoverflow.com/comment/86510656
duplicate of: http://stackoverflow.com/q/49768770
has comment: http://stackoverflow.com/comment/86510753
accepted answer: http://stackoverflow.com/a/49748494
tagged with: pip
tagged with: python
upvote count: 143
has answer: http://stackoverflow.com/a/49748494
has comment: http://stackoverflow.com/comment/86510619
linked to: http://stackoverflow.com/q/31719816
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/86510586
linked to: http://stackoverflow.com/q/43218164
linked to: http://stackoverflow.com/q/16237490
score: 142
has title: 'pip install' fails for every package ("Could not find a version that satisfies the requirement")
has comment: http://stackoverflow.com/comment/86510732
linked to: http://stackoverflow.com/q/49734434
has comment: http://stackoverflow.com/comment/86510892
has comment: http://stackoverflow.com/comment/86510703
has body: pip install &lt;package name&gt; is failing for every package for me. This is what I get: Could not find a version that satisfies the requirement &lt;package-name (from versions: ) No matching distribution found for &lt;package-name&gt; I saw similar questions on Stack&nbsp;Overflow, but they don't seem to be fully related to this one. Also, this post suggests that this might happen if PyPI is down or my IP address is blacklisted. It seems both are not true for my case. pip shows up-to-date on running pip install --upgrade pip.
downvote count: 1

http://stackoverflow.com/q/49721738
upvote count: 1
favorite count: 0
type: Question
has body: I need some help with adding a column with PySpark. I am trying to slice my date string just so I can get the year. I tried the following, but it didn't work: df = sqlContext.createDataFrame( [ ("12/12/1980",1,2) ], ("Date","Num", "#")) df = df.withColumn("Year", df.Date[-4:]) df.show()
tagged with: apache-spark-sql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49722008
tagged with: pyspark
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49722059
has title: PySpark error getting year from date string by slicing
answer count: 2
tagged with: apache-spark
downvote count: 0
score: 1

http://stackoverflow.com/comment/86559221
comment on: http://stackoverflow.com/q/49750577
type: QuestionComment
type: Comment
has text: Any suggestion please?
score: 0

http://stackoverflow.com/a/49701780
downvote count: 0
has body: On every loop iteration, you start with a clean list. Move the initialization outside the loop: movies_dataL=[] for title_movies in d2.keys(): #give list as output #pprint.pprint(title_movies) y=omdb.get(title=title_movies, timeout=5)
score: 3
accepted answer of: http://stackoverflow.com/q/49701750
type: Answer
answers question: http://stackoverflow.com/q/49701750
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86417208

http://stackoverflow.com/comment/86281157
comment on: http://stackoverflow.com/q/49636659
type: Comment
type: QuestionComment
score: 0
has text: I had to stare at this question for 3 minutes with a confused look on my face until I finally realized that the content of the text file is included with the output of the text for whatever reason, and then it took me another minute to figure out why the expected output is 12 instead of 1.

http://stackoverflow.com/comment/86438750
type: AnswerComment
comment on: http://stackoverflow.com/a/49712423
type: Comment
has text: The performance tests surprise me, especially against a for loop. Do you know of any reason behind this? Is there some overhead to `itertools`?
score: 0

http://stackoverflow.com/q/49645135
answer count: 1
has comment: http://stackoverflow.com/comment/86300213
has comment: http://stackoverflow.com/comment/86298298
has comment: http://stackoverflow.com/comment/86299645
has comment: http://stackoverflow.com/comment/86298945
has comment: http://stackoverflow.com/comment/86299766
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86299688
has comment: http://stackoverflow.com/comment/86298799
has comment: http://stackoverflow.com/comment/86298715
has comment: http://stackoverflow.com/comment/86299119
has comment: http://stackoverflow.com/comment/86298767
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/86299619
has comment: http://stackoverflow.com/comment/86299977
has comment: http://stackoverflow.com/comment/86299077
has comment: http://stackoverflow.com/comment/86298871
favorite count: 0
has comment: http://stackoverflow.com/comment/86298271
has title: Pandas display extra unnamed columns for an excel file
has comment: http://stackoverflow.com/comment/86298586
type: Question
accepted answer: http://stackoverflow.com/a/49646170
has comment: http://stackoverflow.com/comment/86299556
has answer: http://stackoverflow.com/a/49646170
downvote count: 0
tagged with: python
has body: I'm working on a project using pandas library, in which I need to read an Excel file which has following columns: 'invoiceid', 'locationid', 'timestamp', 'customerid', 'discount', 'tax', 'total', 'subtotal', 'productid', 'quantity', 'productprice', 'productdiscount', 'invoice_products_id', 'producttax', 'invoice_payments_id', 'paymentmethod', 'paymentdetails', 'amount' But when I read this file by using the Python code below: df_full = pd.read_excel('input/invoiced_products_noinvoiceids_inproduct_v2.0.xlsx', sheet_name=0,) df_full.head() it returns some rows along with 6 unnamed columns with values as NAN.I don't know why these columns are displaying here? Below is the link to a sample file as requested: https://mega.nz/#!0MlXCBYJ!Oim9RF56h6hUitTwqSG1354dIKLZEgIszzPrVpfHas8 Why are these extra columns appearing?
has comment: http://stackoverflow.com/comment/86298978
has comment: http://stackoverflow.com/comment/86298226

http://stackoverflow.com/comment/86456886
has text: How did you install pushbullet?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49721813
type: Comment

http://stackoverflow.com/a/49749699
has comment: http://stackoverflow.com/comment/86513777
type: Answer
has comment: http://stackoverflow.com/comment/86514064
has comment: http://stackoverflow.com/comment/86514156
score: 0
has body: Are you sure you don't have to supply the API key something like this? {'Auth': 'Token my_key'} That's how most API's do it, but I can't find any reference to their API docs anywhere.
answers question: http://stackoverflow.com/q/49749498
has comment: http://stackoverflow.com/comment/86513884
has comment: http://stackoverflow.com/comment/86513989

http://stackoverflow.com/q/49606686
upvote count: 0
has comment: http://stackoverflow.com/comment/86220054
downvote count: 5
accepted answer: http://stackoverflow.com/a/49606887
tagged with: python
tagged with: dictionary
has body: While updating parameters using gradient descent, I am using for l in range(L): parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate* grads("dW" + str(l+1)) parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate* grads("db" + str(l+1)) but I receive the error that 'dict' object is not callable. How to solve this?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86220081
score: -5
has comment: http://stackoverflow.com/comment/86220340
has title: Updating dictionary in python, during gradient descent
answer count: 1
has comment: http://stackoverflow.com/comment/86220553
tagged with: machine-learning
favorite count: 0
has answer: http://stackoverflow.com/a/49606887
type: Question
linked to: http://stackoverflow.com/q/6634708
has comment: http://stackoverflow.com/comment/86220044

http://stackoverflow.com/q/49656909
answer count: 0
has body: I'm trying to do a couple of calculations using the following code: import numpy as np import xarray as xr import pandas as pd ds1 = xr.open_mfdataset('HIST/*nc') ds1 = ds1.loc[dict(time=slice('1996-01-01','2005-12-31'))] ds1 = ds1.resample(time='24H').sum('time') ds_yrmax1 = ds1.resample(time='AS').max('time') The complete error I get back is this: Traceback (most recent call last): File "GFDL-CM3_interp_hist.py", line 29, in &lt;module&gt; ds2 = ds2.resample(time='D').sum('time') File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/common.py", line 53, in wrapped_func **kwargs) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/resample.py", line 303, in reduce func, self._dim, keep_attrs, **kwargs) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/groupby.py", line 654, in reduce return self.apply(reduce_dataset) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/resample.py", line 272, in apply combined = self._combine(applied) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/groupby.py", line 619, in _combine combined = self._maybe_restore_empty_groups(combined) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/groupby.py", line 342, in _maybe_restore_empty_groups combined = combined.reindex(**indexers) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/dataset.py", line 1767, in reindex tolerance, copy=copy) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/alignment.py", line 374, in reindex_variables new_var = var._getitem_with_mask(key) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/variable.py", line 659, in _getitem_with_mask data = duck_array_ops.where(mask, fill_value, data) File "/opt/apps/python/3.6.4/lib/python3.6/site- packages/xarray/core/duck_array_ops.py", line 164, in where return _where(condition, *as_shared_dtype([x, y])) File "/opt/apps/python/3.6.4/lib/python3.6/site…
score: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86363071
tagged with: python-xarray
tagged with: typeerror
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/86325601
tagged with: pandas
has comment: http://stackoverflow.com/comment/86335594
has title: Resample with xarray gives back: TypeError: invalid type promotion
type: Question
has comment: http://stackoverflow.com/comment/86331012

http://stackoverflow.com/q/49689581
type: AnsweredQuestion
tagged with: many-to-many
has comment: http://stackoverflow.com/comment/86392609
has comment: http://stackoverflow.com/comment/86391470
has body: I have a many to many relation. Inserting data is no problem, but I dont know how to correctly get the data in jinja2 / view. I have a working approach but it feels like a workaround. class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(Text, nullable=False) description = Column(Text, nullable=True) children_PostBelongsCategory = relationship("PostBelongsCategory") # etc. class Category(Base): __tablename__ = 'categories' category_name = Column(Text, primary_key=True) # etc. Many to Many relation of Post and Category: class PostBelongsCategory(Base): __tablename__ = 'postbelongstocategories' post_id = Column(Integer, ForeignKey('posts.id'), primary_key=True) category_id = Column(Text, ForeignKey('categories.category_name'), primary_key=True) child = relationship("Category") The way I am doing it right now is query all Post items, query all PostBelongsCategory items and then make two nested for loops with an if loop comparing the id's: {% for post in posts %} {{ post.title }} {{ post.description }} {% for cat in categories %} {% if cat.post_id == post.id %} {{ cat.category_id }} {% endif %} {% endfor %} {% endfor %} I think my approach could lead to performance issues if the tables are very large (but I am not sure here, maybe someone can help me here). Also as mentioned before my approach feels like a workaround. Is there a better way to get the data from many to many? What I tried so far is using lazyload: Post.query.options(lazyload('children_PostBelongsCategory')).order_by(desc("created_on")).all() This gave no errors, but also nothing new. I am currently reading about join/load options but I am not sure whether I am on the correct path.
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/49690432
score: 0
has comment: http://stackoverflow.com/comment/86390900
has answer: http://stackoverflow.com/a/49690432
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86390962
tagged with: flask
tagged with: jinja2
has title: Python Sqlalchemy access many to many data in view

http://stackoverflow.com/a/50462691
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/111100055
has body: I found that I needed to add the __namespace__ field to the Python class implementing the interface. As far as I understand, it this field with represent the .NET namespace for your Python class that implements the interface. As an example. I have made a C# library with the following interface: public interface ITestInterface { string StringAdd(string text, int number); } and a trivial static function that consumes the interface: public static string InvokeStringAdd(ITestInterface testInterface, string text) { return "*** " + testInterface.StringAdd(text, 7) + " ***"; } Then on the Python side I define the following class implementing the interface: class TestInterfaceSubClass(ITestInterface): __namespace__ = "MyNameSpace" def StringAdd(self,text,x): return 'My text <{}> with number <{}>'.format(text, x) Note that I added the __namespace__ field and give it the "MyNameSpace" value. I think any non-colliding .NET namespace name would do. To test the implementation in Python test_interface_subclass = TestInterfaceSubClass() print(TestClass.InvokeStringAdd(test_interface_subclass,'My Text')) which returns *** My text <My Text> with number <7> *** Finally note, that the python class TestInterfaceSubClass is given the namespace "MyNameSpace". This means that reevaluation the class definition code in e.g a Jupyter notebook will result in a namepsace clash on the .NET side, so you either have to give it a different namespace value or restart the kernel.
type: Answer
accepted answer of: http://stackoverflow.com/q/49736531
answers question: http://stackoverflow.com/q/49736531
downvote count: 0
score: 21
upvote count: 21

http://stackoverflow.com/q/49643369
accepted answer: http://stackoverflow.com/a/49643501
type: Question
has answer: http://stackoverflow.com/a/49643496
has comment: http://stackoverflow.com/comment/86294659
has answer: http://stackoverflow.com/a/49643501
tagged with: list
has comment: http://stackoverflow.com/comment/86294519
score: 0
tagged with: string
has answer: http://stackoverflow.com/a/49644245
has body: I have some tweets which contain some shorthand text like ur,bcz etc. I am using dictionary to map the correct words. I know we cannot mutate strings in python. So after replacing the with correct word, i am storing a copy in a new list. Its working. I am facing issue if any tweet have more than one shorthand text. My code is replacing one word at a time. How can i replace words multiple times in a single string. Here is my code # some sample tweets tweet = ['stats is gr8', 'india is grt bcz it is colourfull', 'i like you','your movie is grt', 'i hate ur book of hatred' ] short_text={ "bcz" : "because", "ur" : "your", "grt" : "great", "gr8" : "great", "u" : "you" } import re def find_word(text,search): result = re.findall('\\b'+search+'\\b',text,flags=re.IGNORECASE) if len(result) &gt; 0: return True else: return False corrected_tweets=list() for i in tweet: tweettoken=i.split() for short_word in short_text: print("current iteration") for tok in tweettoken: if(find_word(tok,short_word)): print(tok) print(i) newi = i.replace(tok,short_text[short_word]) corrected_tweets.append(newi) print(newi) my output is ['stats is great', 'india is grt because it is colourfull', 'india is great bcz it is colourfull', 'your movie is great', 'i hate your book of hatred'] What I need is tweet 2 and 3 should be appended once with all correction. I am new to python. Any help will be great.
tagged with: string-matching
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/86294557
tagged with: python
possible better answer: http://stackoverflow.com/a/49643496
has title: string manipulation in python using list

http://stackoverflow.com/q/49682127
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86376267
favorite count: 0
type: Question
has title: How to print SQL query result without unwanted characters in python?
tagged with: python
has comment: http://stackoverflow.com/comment/86376217
has body: I have the following code engine = create_engine('database info',convert_unicode=True) result = engine.execute(" select title from table") line=(result.fetchall()) print(line) Some of the results have "\xa0" inserted in them Is there a way to return my query so that I don't have to try to fix it after the fact?
answer count: 0

http://stackoverflow.com/comment/86408963
comment on: http://stackoverflow.com/q/49697477
score: 0
has text: @thebjorn I don't do rgb to grayscale computations, I was just pointing out a good way to understand the constants Bill was asking about.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49713111
has body: Parsing multiple structures in a row from a single stream can be achieved by something like: from msg_log import Message from kaitaistruct import KaitaiStream f = open("yourfile.bin", "rb") stream = KaitaiStream(f) obj1 = Message(stream) obj2 = Message(stream) obj3 = Message(stream) # etc stream.close() I'm not sure what you mean by "paging through a byte buffer". The method above by itself does not load whole file into memory, it reads it using normal read()-like calls as requested. If you want somewhat better performance, and you deal with a large file of a fixed size, you can opt to do a memory mapping. This way you would be just using a region of memory, and OS would take care of input/output required to load relevant parts of the file into actual physical memory. For Python, there is a PR for runtime that implements helpers for that, or, you can just do it yourself by doing: from kaitaistruct import KaitaiStream import mmap f = open("yourfile.bin", "rb") with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as buf: stream = KaitaiStream(BytesIO(buf)) obj1 = Message(stream) obj2 = Message(stream) obj3 = Message(stream) # etc
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49699820
has comment: http://stackoverflow.com/comment/86441171
answers question: http://stackoverflow.com/q/49699820
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/86488652

http://stackoverflow.com/a/49718450
type: Answer
score: 0
has body: To avoid an IndexError, it might sometimes be easier to just adapt the range, like so: from string import punctuation as punct def remove_punctuation(old_string): """Remove punctuation from "string" if not between 2 letters.""" new_string ='' s = ' ' + old_string + ' ' for i in range(1, len(s) - 1): if s[i] in punct and (not s[i - 1].isalpha() or not s[i + 1].isalpha()): continue else: new_string += s[i] return new_string
answers question: http://stackoverflow.com/q/49715274

http://stackoverflow.com/comment/86460515
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49723266
type: QuestionComment
has text: it works but breaks `python -m unittest`: `ValueError: attempted relative import beyond top-level package`

http://stackoverflow.com/q/49756350
upvote count: 4
has answer: http://stackoverflow.com/a/49756401
has comment: http://stackoverflow.com/comment/86527695
has comment: http://stackoverflow.com/comment/86551236
has body: I have a string that looks like this: { "key A":[ ["some val", "value a1"], ["some val", "value a2"], .................... ["some val", "value an"] ], "key B":[ ["some val", "value b1"], ["some val", "value b2"], ... ], ... , "key X":[ ["some val", "value x1"], ["some val", "value x2"], ... ] } Can anyone tell me what is the proper way in python to get a dictionary out of it where the dictionary should be { "key A": ["val a1", "val a2", ..."val an"], "key B": ["val b1", "val b2", ..."val bn"], ..... "key X": ["val x1", "val x2", ..."val xn"], } I'm asking this because right now the only code I can think of is a pretty dirty one with a lot of list, splits and replaces and I'm quite sure that this is very wrong way to do it :D. Thanks a lot in advance.
has title: Pythonic way to parse a formatted string and get a dictionary out of it
downvote count: 0
linked to: http://stackoverflow.com/q/4917006
has answer: http://stackoverflow.com/a/49756542
tagged with: string
has comment: http://stackoverflow.com/comment/86527824
favorite count: 0
possible better answer: http://stackoverflow.com/a/49757116
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49757116
has comment: http://stackoverflow.com/comment/86550663
tagged with: python
has answer: http://stackoverflow.com/a/49784255
tagged with: dictionary
score: 4
accepted answer: http://stackoverflow.com/a/49756401
answer count: 4
linked to: http://stackoverflow.com/q/23705304

http://stackoverflow.com/a/69191078
score: 0
has body: For Django 3.2 I had to upgrade mysql from 5.5 to 5.7.
type: Answer
answers question: http://stackoverflow.com/q/49624954

http://stackoverflow.com/a/49684692
type: Answer
downvote count: 0
has body: When you print something in python, you need to put your whole message between parentheses. You can separate your values from text with comas. Try for exemple : print("Ah, so your name is,",name,"your quest is",quest,"and your favorite color is",color) This is assuming you're working in python 3.
answers question: http://stackoverflow.com/q/49684586
score: 1
upvote count: 1

http://stackoverflow.com/q/49682839
tagged with: tensorflow
type: Question
tagged with: python
has body: I'm new to tensorflow. I intended to flatten a tensor of shape (28,28,1) to a 1-D tensor by using tf.reshape, but didn't get the expected result. Here is the piece of the code I used. def input_pipeline(self, batch_size, num_epochs=None): images_tensor = tf.convert_to_tensor(self.image_names, dtype=tf.string) labels_tensor = tf.convert_to_tensor(self.labels, dtype=tf.int64) input_queue = tf.train.slice_input_producer([images_tensor, labels_tensor], num_epochs=num_epochs) labels = input_queue[1] images_content = tf.read_file(input_queue[0]) images = tf.image.convert_image_dtype(tf.image.decode_png(images_content, channels=N_CHANNELS), tf.float32) new_size = tf.constant([IMAGE_SIZE_CHN, IMAGE_SIZE_CHN], dtype=tf.int32) images = tf.image.resize_images(images, new_size) reshape_vec = tf.constant([-1], dtype=tf.int32) print(images.get_shape()) tf.reshape(images, reshape_vec) print(images.get_shape()) image_batch, label_batch = tf.train.shuffle_batch([images, labels], batch_size=batch_size, capacity=50000, min_after_dequeue=10000) return image_batch, label_batch The result of the two print functions are both (28,28,1). Can anyone help me on this? Thanks!
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49683140
accepted answer: http://stackoverflow.com/a/49683140
answer count: 1
has title: tensorflow tf.reshape not working

http://stackoverflow.com/comment/86426779
score: 0
has text: it prints the data in the df2. no error here. The error message thrown : dbCur.executemany(query, df2) TypeError: not all arguments converted during string formatting
type: QuestionComment
comment on: http://stackoverflow.com/q/49703520
type: Comment

http://stackoverflow.com/comment/86498230
score: 2
comment on: http://stackoverflow.com/q/49741823
has text: No, this is not possible. Pickle is the closest thing you can get to that.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86489234
type: Comment
has text: Thanks for your help.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49716983

http://stackoverflow.com/q/49738465
has answer: http://stackoverflow.com/a/49739159
tagged with: python
possible better answer: http://stackoverflow.com/a/49739159
score: -1
accepted answer: http://stackoverflow.com/a/49738917
type: AnsweredQuestion
tagged with: python-2.7
tagged with: ubuntu-16.04
downvote count: 2
answer count: 2
upvote count: 1
tagged with: multithreading
has answer: http://stackoverflow.com/a/49738917
has comment: http://stackoverflow.com/comment/86492577
favorite count: 0
type: Question
has body: I am implementing a multi-threading code in python. This example is printing a message every 2 seconds. The output of the terminal in Ubuntu is not logical compared to the result of Pycharm in Windows 10. I think that time module should work in both environments. I do not know why it is not working in Linux. Also, is there other module similar to time to be used ? I appreciate your help Code: from threading import Thread from time import sleep from time import clock as clk ## To create a thread in Python you'll want to make your class work as a thread. ## For this, you should subclass your class from the Thread class s2 = 0 class Book(Thread): def __init__(self): Thread.__init__(self) self.message = ("Hello Parallel Python!!\n") def print_message(self): print (self.message) ##The run method prints the message def run(self): print ("Thread Starting") x=0 while (x &lt; 10): self.print_message() sleep(2) print "Time is : ", clk() x += 1 print ("Thread Ended\n") s2 = clk() print "2st s2 is: ", s2 #start the main process print ("Process Started") # create an instance of the HelloWorld class hello = Book() # print the message...starting the thread s1 = clk() hello.start() #end the main process print ("Process Ended\n") print "1st s2 is: ", s2 The output using Pycharm in Windows 10 is: Pycharm result The output using gedit in Ubuntu 16.04 LTS is: terminal result
tagged with: time
has title: Getting the time of compilation using Python in Ubuntu

http://stackoverflow.com/comment/86214929
has text: which line throws the error, show us the stacktrace.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49603600

http://stackoverflow.com/q/49661089
has comment: http://stackoverflow.com/comment/86332429
has comment: http://stackoverflow.com/comment/86332811
has comment: http://stackoverflow.com/comment/86332530
has body: im trying to grep from a file a string 'MB/s' ,below is my code import re raw = open('C:\\Python27\\BCF013K.txt',encoding='UTF-8') data=raw.read() raw.close() print(re.match(r'MB/s',data)) not sure why i am keep seeing this error. My file is simple text file see below: MB/s = 1,000,000 bytes/s [SATA/600 = 600,000,000 bytes/s] KB = 1000 bytes, KiB = 1024 bytes its keeps saying None when i run the code
has comment: http://stackoverflow.com/comment/86332757
type: Question
has comment: http://stackoverflow.com/comment/86333418
has comment: http://stackoverflow.com/comment/86333472
has comment: http://stackoverflow.com/comment/86332038
has comment: http://stackoverflow.com/comment/86332567
has comment: http://stackoverflow.com/comment/86333489
has comment: http://stackoverflow.com/comment/86332004
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86332005
has comment: http://stackoverflow.com/comment/86332131
has comment: http://stackoverflow.com/comment/86332679
tagged with: python
has comment: http://stackoverflow.com/comment/86332080
has comment: http://stackoverflow.com/comment/86332144
score: 0
has comment: http://stackoverflow.com/comment/86332893
answer count: 0
has title: how to grep a string from a txt file in Python
has comment: http://stackoverflow.com/comment/86332099
has comment: http://stackoverflow.com/comment/86332541

http://stackoverflow.com/a/49635552
has comment: http://stackoverflow.com/comment/124282447
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49625006
has comment: http://stackoverflow.com/comment/127308606
downvote count: 0
has body: ℹ️ Quick Tip: PubNub accepts GZIP content on Publish This is not a direct answer. It's just a good tip! You can publish larger image sizes when you gzip POST your publish calls. You can publish gzip compressed data in many languages easily. Here is a quick example in bash. There will be another below for nodejs. #!/bin/bash ## -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## PubNub POST GZIP Example ## -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- echo '{"hello":["world",123,null]}' | gzip -c9 | \ curl \ -H "Content-Encoding: gzip" \ --data-binary @- \ 'http://pubsub.pubnub.com/publish/demo/demo/0/my_channel/0' echo POST GZIP Data with NodeJS Also you can do this in Node.JS with the following example. var http = require("http"); var zlib = require("zlib"); exports.publish = function(msg) { var req = http.request({ "host" : "pubsub.pubnub.com", "method" : "POST", "path" : "/publish/demo/demo/0/my_channel/0", "headers" : { "Content-Encoding" : "gzip", "Content-Type" : "application/json; charset=UTF-8", }, }, function (res) { var body = ""; res.on("data", function (chunk) { body += chunk; }); res.on("end", function () { console.log(body) }) }); req.on("error", function (e) { console.error("ERROR:", e.message); }); zlib.gzip(msg, function (error, result) { console.log("data:", result); req.write(result); req.end(); }); }; exports.publish('{"hello":["world",123,null]}');
upvote count: 1

http://stackoverflow.com/q/49691443
has body: I want to update the posts i posted,they contain title,city etc fields and 10 image fields(image,image1,image2....etc),whenever i click update, the update form comes with all the text fields filled with previously saved data but image fields are not getting previously submitted images(they're showing empty)..i want them there and let the user change them or delete them etc...can anybody help me? my images are saving with this method in models.py def get_image_filename(instance, filename): title = instance.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename) here's my views for update_post def update_post(request, post_id): post_form = Posts.objects.get(pk=post_id) if request.method == "POST": form = AddFile(request.POST, request.FILES, instance=post_form) if form.is_valid(): form.title = request.POST.get('title') form.city = request.POST.get('city') form.price = request.POST.get('price') form.brand = request.POST.get('brand') form.modelyear = request.POST.get('modelyear') form.condition = request.POST.get('condition') form.mileage = request.POST.get('mileage') form.details = request.POST.get('details') form.image = request.POST.get('image') form.image1 = request.POST.get('image1') form.image2 = request.POST.get('image2') form.image3 = request.POST.get('image3') form.image4 = request.POST.get('image4') form.image5 = request.POST.get('image5') form.image6 = request.POST.get('image6') form.image7 = request.POST.get('image7') form.image8 = request.POST.get('image8') form.image9 = request.POST.get('image9') form.user = request.user form.save() messages.success(request, 'Post updated Successfully!') return render(request, 'vehicles_app/addfile.html', { 'form': form, 'post_form': post_form, 'post_id': post_id, }) else: messages.success(request, 'Post not updated Successfully!') print(form.errors) else: form = AddFile(instance=post_form) return render(request, 'vehicles_app/update_post.html', {'form': form, 'post_form':post_form, 'post_id': post_id}) he…
answer count: 0
has comment: http://stackoverflow.com/comment/86397130
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/86398204
tagged with: python
has comment: http://stackoverflow.com/comment/86397317
has comment: http://stackoverflow.com/comment/86396985
has comment: http://stackoverflow.com/comment/86396339
has comment: http://stackoverflow.com/comment/86395745
has comment: http://stackoverflow.com/comment/86396498
score: 0
has title: while updating/editing my post,previously uploaded images are not showing in my update_post.html template
tagged with: django-views
has comment: http://stackoverflow.com/comment/86395870
has comment: http://stackoverflow.com/comment/86396096
has comment: http://stackoverflow.com/comment/86394980
has comment: http://stackoverflow.com/comment/86395123
linked to: http://stackoverflow.com/q/1696877
has comment: http://stackoverflow.com/comment/86394661
has comment: http://stackoverflow.com/comment/86396956
has comment: http://stackoverflow.com/comment/86396819
has comment: http://stackoverflow.com/comment/86395625
has comment: http://stackoverflow.com/comment/86396605
type: Question
duplicate of: http://stackoverflow.com/q/1696877
has comment: http://stackoverflow.com/comment/86397273
has comment: http://stackoverflow.com/comment/86395246
has comment: http://stackoverflow.com/comment/86397237
has comment: http://stackoverflow.com/comment/86396881
has comment: http://stackoverflow.com/comment/86395999

http://stackoverflow.com/comment/86426348
type: QuestionComment
has text: @Primusa yes dear, I want to export output.
comment on: http://stackoverflow.com/q/49702923
score: 0
type: Comment

http://stackoverflow.com/q/49627471
tagged with: flask
tagged with: flask-sqlalchemy
has body: So am trying to implement multiprocessing in my Flask app that implements RSS/Atom feed parsing and i've run into a new error. Here's my very rudimentary-looking code, the parsing function: def parallelParse(obj1,obj2, app): parsed = [] d = feedparser.parse(obj1) modified = time.mktime(d.feed.get('modified_parsed', None)) if modified != obj2.feedModified: obj2.feedModified = modified with app.app_context: db.session.commit() and the view function: @feeds.route('/') def home(): #Query the feed URL and Modified records and store them in a list of tuples FEEDS = db.session.query(Feed).all() try: p = multiprocessing.Process(target=parallelParse, args=((item.feedURL,item) for item in FEEDS), kwargs={'app' : current_app._get_current_object()}) p.start() p.join() except AttributeError as e: print(e) feed_entries = FeedEntryTest.query.order_by(FeedEntryTest.TestEntryTime.desc()).all() return render_template("main.html", feed_entries = feed_entries) Everytime I try to run this however I keep getting the following error: Can't pickle local object 'SQLAlchemy.init_app.&lt;locals&gt;.shutdown_session' 127.0.0.1 - - [03/Apr/2018 12:50:02] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [03/Apr/2018 12:50:02] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 - 127.0.0.1 - - [03/Apr/2018 12:50:02] "GET /static/css/custom.css HTTP/1.1" 200 - Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\users\imran-pc\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "c:\users\imran-pc\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) EOFError: Ran out of input After doing some bit of research I learned that only certain types of objects are 'picklable'. So I tried converting my query result into a dict as shown here but I got another error whilst doing so. Am I approaching the problem the wrong way? What else shoul…
tagged with: multiprocessing
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86264307
tagged with: python
has comment: http://stackoverflow.com/comment/86273050
linked to: http://stackoverflow.com/q/17717877
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86268638
has title: Can't pickle local object 'SQLAlchemy.init_app.<locals>.shutdown_session'

http://stackoverflow.com/q/49722389
has answer: http://stackoverflow.com/a/49722994
has comment: http://stackoverflow.com/comment/86458896
tagged with: python
has comment: http://stackoverflow.com/comment/86458387
tagged with: integer
type: AnsweredQuestion
tagged with: list
has body: I have two lists a and b(both have same length) where the list b has only 1, 2 and 3 as its elements(random repetition allowed).Now , for all the indices of 1 in list 'b' I want to print a min integer from list a.And same for 2 and 3 in list 'b'. For example: a = [10,33,42,17,9,32,33,43,12,2,5,22] b = [3,1,3,2,1,3,2,1,3,1,2,2] As the indices at which 1 is(in list 'b') are 1,4,7,9 respectively I want to print the minimum integer (answer for example is 2) from list 'a' at such indices. The same should be done for 2 and 3 from list 'b'. Also if it is possible to calculate that for 1, 2 and 3 altogether from list 'b' then please tell. Expected output(according to the example): The min integer for 1, 2 and 3 are 2, 5 and 10 respectively. a and b here are just an example. Please answer if a and b are taken as user inputs and b has the same constraints i.e b can contain only 1, 2 and 3(with random repetition).
has comment: http://stackoverflow.com/comment/86458634
answer count: 3
tagged with: python-3.5
score: 1
has answer: http://stackoverflow.com/a/49726018
tagged with: arrays
accepted answer: http://stackoverflow.com/a/49722796
downvote count: 0
has title: Print minimum integer of list's elements based on indices from other list
has comment: http://stackoverflow.com/comment/86458844
upvote count: 1
has answer: http://stackoverflow.com/a/49722796
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49722994
has comment: http://stackoverflow.com/comment/86458156

http://stackoverflow.com/comment/86526431
type: AnswerComment
comment on: http://stackoverflow.com/a/49734212
score: 0
has text: Oh well, that's in fact really easy. Works perfect! And again: Thank you very much!
type: Comment

http://stackoverflow.com/q/49743549
favorite count: 0
type: Question
type: UnansweredQuestion
has title: SyntaxError: invalid syntax file.close()
has comment: http://stackoverflow.com/comment/86501988
tagged with: python
has answer: http://stackoverflow.com/a/49743573
downvote count: 6
score: -5
has body: I keep getting an error here, any help? file = open(FILENAME,'r') is on the same line as file.close with no indentations. Why do I keep getting this error?
answer count: 1
upvote count: 1

http://stackoverflow.com/q/49615905
tagged with: sockets
tagged with: python
score: -4
accepted answer: http://stackoverflow.com/a/49616012
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49616012
downvote count: 4
has comment: http://stackoverflow.com/comment/86239353
upvote count: 0
answer count: 1
has title: why recv accept mort than expected number of bytes ?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86238663
has body: When i call recv to receive exactly 7 bytes i recv more than bytes expected ? I don't know how bufsize parameter work. for i in range(data2[1]): try: tuple = envois.recv(7) time.sleep(0.1) except Exception as e: print(e) if (tuple[-2:] != myport): tuples.append(tuple) print("tuples : {x}".format(x = tuples)) last_msg = envois.recv(3) envois.close() return (last_msg,tuples)

http://stackoverflow.com/comment/86457113
comment on: http://stackoverflow.com/a/49721803
has text: It does not work. It return for my case a wrong output.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86532071
has text: Thanks! That's exactly the information I needed! Also I found out that my text file was actually in the GloVe format, so I ended up using these lines: ```from gensim.scripts.glove2word2vec import glove2word2vec glove2word2vec(glove_file, tmp_file)``` After that, I could import my vectors with ```KeyedVectors.load_word2vec_format(tmp_file)```.
score: 7
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49750326

http://stackoverflow.com/comment/86388791
comment on: http://stackoverflow.com/q/49688697
score: 0
type: Comment
type: QuestionComment
has text: The linked post says "Not that I suggest using it, but..." while others correctly say that you should use an HTML parser and not regex.

http://stackoverflow.com/q/49645929
possible better answer: http://stackoverflow.com/a/49658799
accepted answer: http://stackoverflow.com/a/49647484
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49658799
tagged with: format
tagged with: numbers
linked to: http://stackoverflow.com/q/5513615
has body: I have an issue with formatting number output in Python. I found quite some examples how to do it with .format(), but I can not figure it out how to set it up to my desired output. I would like to have "." as thousand separator and "," as decimal (e.g. 7.654,32). If I want to do it vice-versa, I would use e.g. print("{0:,.2f}".format(7654.321)), but I can not find the opposite. If nothing else, I could use replace(), but would prefer an elegant solution, as I would use that further with Jinja2 in my html template. Thank you and best regards, Bostjan
has comment: http://stackoverflow.com/comment/86300118
tagged with: python
has comment: http://stackoverflow.com/comment/86300983
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49647484
answer count: 2
has title: Python number formatting
downvote count: 0
score: 4

http://stackoverflow.com/q/49645252
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49647489
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49645609
has answer: http://stackoverflow.com/a/49647489
has body: I'm working in Python. I have two dataframes df1 and df2: d1 = {'timestamp1': [88148 , 5617900, 5622548, 5645748, 6603950, 6666502], 'col01': [1, 2, 3, 4, 5, 6]} df1 = pd.DataFrame(d1) d2 = {'timestamp2': [5629500, 5643050, 6578800, 6583150, 6611350], 'col02': [7, 8, 9, 10, 11], 'col03': [0, 1, 0, 0, 1]} df2 = pd.DataFrame(d2) I want to create a new column in df1 with the value of the minimum timestamp of df2 greater than the current df1 timestamp, where df2['col03'] is zero. This is the way I did it: df1['colnew'] = np.nan TSs = df1['timestamp1'] for TS in TSs: values = df2['timestamp2'][(df2['timestamp2'] &gt; TS) &amp; (df2['col03']==0)] if not values.empty: df1.loc[df1['timestamp1'] == TS, 'colnew'] = values.iloc[0] It works, but I'd prefer not to use a for loop. Is there a better way to do this?
score: 2
has answer: http://stackoverflow.com/a/49645609
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86298649
has title: Find the minimum value of a column greater than another column value in Python Pandas
tagged with: pandas
linked to: http://stackoverflow.com/q/34962104
favorite count: 0
type: Question

http://stackoverflow.com/q/49663284
answer count: 1
tagged with: python
favorite count: 0
type: Question
has title: Ubuntu, Installing opencv-contrib by pip command, but some algorithms are still not working
downvote count: 0
upvote count: 1
tagged with: ubuntu
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49666172
has answer: http://stackoverflow.com/a/49666172
score: 1
has body: I use the following command to install opencv: pip3 install opencv-python pip3 install opencv-contrib-python But for some algorithms, such as SIFT, KNearest, it still gives me an error : module `cv2.cv2` has no attribute `KNearest` Does that mean the unique way to solve it is using cmake to install opencv and opencv-contrib? Thanks in advance.

http://stackoverflow.com/comment/86359701
has text: @Joseph What about `print(repr(self.id[self.currentQ]))` ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49674017

http://stackoverflow.com/a/49746582
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49746500
has body: This error is probably because the video file is not in the working directory. I would recommend you give the full path to the video. cap = cv2.VideoCapture('path/to/where/video/is/Crop_DownResolution.mp4')
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86597951
upvote count: 1
has comment: http://stackoverflow.com/comment/86523867
accepted answer of: http://stackoverflow.com/q/49746500

http://stackoverflow.com/a/49722418
type: Answer
accepted answer of: http://stackoverflow.com/q/49722225
has comment: http://stackoverflow.com/comment/86458480
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49722225
has body: Is this what you're looking for? import pandas as pd import seaborn as sns ''' method metric 0 1 HASH L2_TCM 287 296 HASH TOT_CYC 6211 6100 RECV L2_TCM 331 323 RECV TOT_CYC 10881 7524 SYNTH L2_TCM 869 856 SYNTH TOT_CYC 29117 29560 ''' df = pd.read_clipboard() # this is what your data looks like... df.groupby([ 'method', 'metric' ]).agg({ '0' : 'max', '1' : 'max' }) # I reshaped it to have no multiindex... # And then melt the data to work with seaborn df1 = df.melt(id_vars = [ 'method', 'metric' ]) sns.boxplot(data = df1, x = 'method', y = 'value', hue = 'metric');

http://stackoverflow.com/a/49747678
score: 4
type: Answer
upvote count: 4
has body: For instance clicking on the 5 of march 2017: driver.get("https://www.nseindia.com/products/content/derivatives/equities/archieve_fo.htm") datepicker = driver.find_element_by_id("date") datepicker.click() selectMonth = driver.find_element_by_xpath('//select[@class="ui-datepicker-month"]') for option in selectMonth.find_elements_by_tag_name('option'): if option.text == 'Mar': option.click() break selectYear = driver.find_element_by_xpath('//select[@class="ui-datepicker-year"]') for option in selectYear.find_elements_by_tag_name('option'): if option.text == '2017': option.click() break days = driver.find_elements_by_xpath('//a[@class="ui-state-default"]') days[4].click()
downvote count: 0
answers question: http://stackoverflow.com/q/49747034

http://stackoverflow.com/comment/86480645
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49732807
has text: Thanks for your answer! Sorry if this was the wrong place, i am pretty new to this whole ecosystem. I will take a look on codereview.stackexchange.com! Thank you very much!
score: 0

http://stackoverflow.com/comment/86500049
comment on: http://stackoverflow.com/q/49742624
has text: Yep, that did it. I knew I was forgetting something haha. I'll answer my own question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49619412
tagged with: bokeh
has answer: http://stackoverflow.com/a/52658241
answer count: 4
has body: I'm developing a python application which uses Bokeh and PubSub and other python modules. I'm almost done with it and it's running fine. But when I tried to make an executable out of it by using PyInstaller, I ran into a lot of problems. I solved the Jinja2 TemplateNotFound and the unregistered loader type issue by using @dzman's post from this thread. I solved the PubSub import problem by using @Stefano's post from this thread. Now the problem is, when I am trying to run the .exe file it throws error as shown below Traceback (most recent call last): File "module1.py", line 191, in &lt;lambda&gt; File "module1.py", line 274, in getQueryItems File "module1.py", line 353, in queryTheDatabaseToGetResult File "module1.py", line 399, in createDataframeFromTheResult File "module2.py", line 17, in __init__ File "module2.py", line 75, in plotFunction File "site-packages\bokeh\models\callbacks.py", line 68, in from_coffeescript File "site-packages\bokeh\util\compiler.py", line 190, in nodejs_compile File "site-packages\bokeh\util\compiler.py", line 169, in _run_nodejs File "site-packages\bokeh\util\compiler.py", line 164, in _run RuntimeError: module.js:538 throw err; ^ Error: Cannot find module 'C:\Users\user_name\Desktop\PYTHON~1\dist\PATHWA~1\bokeh\server\static\js\compiler.js' at Function.Module._resolveFilename (module.js:536:15) at Function.Module._load (module.js:466:25) at Function.Module.runMain (module.js:676:10) at startup (bootstrap_node.js:187:16) at bootstrap_node.js:608:3 In the code the error occurs right at the very last line of the following code snippet, checkbox.callback = CustomJS.from_coffeescript(args = dict(plot = fig, checkbox = checkbox), code=""" rends = plot.select("hideable"); rends[i].visible = i in checkbox.active for i in [0...rends.length]; """) #This is line 68 as shown in the error message So, it's the CustomJS where the code is failing. I could not find a single post that describes how to use PyInstaller with Custom JS in Bokeh. But I real…
tagged with: python-2.7
linked to: http://stackoverflow.com/q/49203844
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: py2exe
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/40769018
has answer: http://stackoverflow.com/a/49619721
has title: Using PyInstaller with Bokeh and CustomJS
has answer: http://stackoverflow.com/a/50733006
tagged with: pyinstaller
linked to: http://stackoverflow.com/q/47811533
score: 1
has answer: http://stackoverflow.com/a/49639423
tagged with: python

http://stackoverflow.com/comment/86299861
score: 0
has text: Just iterate the dictionary. If you do this often, a dictionary *may* not be the ideal structure for you. You may wish to implement your own class which "records" the location of each leaf-level key.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49645763

http://stackoverflow.com/q/49732826
has body: There are multiple SO questions addressing some form of this topic, but they all seem terribly inefficient for removing only a single row from a csv file (usually they involve copying the entire file). If I have a csv formatted like so: fname,lname,age,sex John,Doe,28,m Sarah,Smith,27,f Xavier,Moore,19,m What is the most efficient way to remove Sarah's row? If possible, I would like to avoid copying the entire file.
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49734847
has comment: http://stackoverflow.com/comment/86488774
has comment: http://stackoverflow.com/comment/86480100
has answer: http://stackoverflow.com/a/49733330
answer count: 7
has comment: http://stackoverflow.com/comment/86479763
has comment: http://stackoverflow.com/comment/86486464
score: 21
has comment: http://stackoverflow.com/comment/86479339
has comment: http://stackoverflow.com/comment/86479917
favorite count: 0
has comment: http://stackoverflow.com/comment/86479728
type: Question
has comment: http://stackoverflow.com/comment/86479869
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86493300
has comment: http://stackoverflow.com/comment/86482685
possible better answer: http://stackoverflow.com/a/49734119
has comment: http://stackoverflow.com/comment/86480911
has answer: http://stackoverflow.com/a/49733128
has comment: http://stackoverflow.com/comment/86479312
has comment: http://stackoverflow.com/comment/86479700
has answer: http://stackoverflow.com/a/49734119
downvote count: 2
has answer: http://stackoverflow.com/a/49733417
has comment: http://stackoverflow.com/comment/86492947
tagged with: python
linked to: http://stackoverflow.com/q/19128876
upvote count: 23
accepted answer: http://stackoverflow.com/a/49733354
has title: Remove a single row from a csv without copying files
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49732894
has answer: http://stackoverflow.com/a/49733354

http://stackoverflow.com/q/49683175
accepted answer: http://stackoverflow.com/a/49686172
tagged with: pandas
tagged with: dataframe
tagged with: python
type: Question
upvote count: 2
score: 2
answer count: 2
tagged with: for-loop
downvote count: 0
possible better answer: http://stackoverflow.com/a/49683375
has title: Dataframe value matching in Python
has answer: http://stackoverflow.com/a/49683375
has comment: http://stackoverflow.com/comment/86378209
favorite count: 0
has body: I have a problem I am working on for days. I have 2 data-frames as below. Index by definition means a set of TEST, NAME and SEQUENCE triple which is unique. Goal is to get the 'index' value from the index file which matches: one of the sequence values such as for [111,222,333] in config ( for example can be 111 or 222 or 333) and the TEST and the NAME. Config file is what matters, and aim is to find the index values corresponding to that. Nothing that do not exist in config should show up in the output file. I want to have a final output which includes: INDEX, TEST, NAME and SEQUENCE. So the final output will be a subset of the config file but it will only include one SEQUENCE (instead of 3) and corresponding TEST and NAME and INDEX. such as : Example output file: index TEST NAME SEQUENCE 901922 A john 111 238394 C ashley 555 930293 B sam 444 I have tried to write a for loop but was not successful with the indexing as below: for x in range(0, config.shape[0]): find1=eval(config.SEQUENCE[x]) find1='|'.join(str(i) for i in find1) find1 = '(' + find1 + ')' First dataframe : config SEQUENCE TEST NAME [111,222,333] A john [222,444,888] B sam [111,222,333] A ashley [999,777,555] C ashley [111,222,333] D john [111,222,333] A john G kelly Second dataframe: index index TEST NAME SEQUENCE 901922 A john 111 930293 B sam 444 238203 A ashley 888 238394 C ashley 555 483472 D john 777 901922 A john 111 264225 F greg 111 465126 A mary 555 554216 B peter 333
tagged with: lookup
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49686172

http://stackoverflow.com/q/49755721
tagged with: tree
tagged with: python
has comment: http://stackoverflow.com/comment/86618978
linked to: http://stackoverflow.com/q/25297470
has comment: http://stackoverflow.com/comment/86585001
score: 0
has body: I downloaded the Networkx libary and used it in order to find Hu-Gomory tree. I created the following simple graph weight_edge_lst = [] weight_edge_lst.append((0,1,0)) weight_edge_lst.append((1,2,1)) weight_edge_lst.append((0,2,1)) G.add_weighted_edges_from(weight_edge_lst) It plotted this tree: [(0, 1), (1, 2)] This is weird, because in articles it has been written that Cut-tree is optimal communication tree, which means that sum of edges (cut) capacity is minimal, and the tree of (1,2),(0,2) would have sum of 2 and not 3 as this tree. If i change the order of edges this way - weight_edge_lst.append((0,1,1)) weight_edge_lst.append((1,2,1)) weight_edge_lst.append((0,2,0)) It works, and edges of the tree are on the one-capacity edges, but this is the exact same graph (with changes in names!) Does anyone has any explanation for that ? Thanks
has title: Why is the Hu-Gomory from Networkx is not minimal communication tree or uniuqe?
answer count: 0
has comment: http://stackoverflow.com/comment/86585026
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86601280
tagged with: networkx
type: Question
tagged with: graph

http://stackoverflow.com/comment/86262509
type: Comment
has text: I want to create quick search function in pyw tkinter window. I also want to add arguments to be more precise with my search query (that's why I have extension searcher and posiblity to turn off case sensitivity)
type: AnswerComment
comment on: http://stackoverflow.com/a/49627785
score: 0

http://stackoverflow.com/comment/86275818
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49634166
type: QuestionComment
has text: Does it really have the unbalanced quotation marks?

http://stackoverflow.com/a/49780607
accepted answer of: http://stackoverflow.com/q/49740247
downvote count: 0
answers question: http://stackoverflow.com/q/49740247
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/86601225
upvote count: 4
has body: tf.reshape won't discard shape information for -1 dimensions. That's just a shorthand for "whatever's left over": &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; a = tf.constant([1.,2.,3.]) &gt;&gt;&gt; a.shape TensorShape([Dimension(3)]) &gt;&gt;&gt; tf.reshape(a, [-1, 3]).shape TensorShape([Dimension(1), Dimension(3)]) &gt;&gt;&gt; If you want to destroy static shape information, see tf.placeholder_with_default: &gt;&gt;&gt; tf.placeholder_with_default(a[None, :], shape=[None, 3]).shape TensorShape([Dimension(None), Dimension(3)])
type: AcceptedAnswer

http://stackoverflow.com/a/49625980
has comment: http://stackoverflow.com/comment/86260046
has body: You could simply use str.rsplit() for the key: &gt;&gt;&gt; lst = ['tmp_1483228800-1485907200_1', 'tmp_1483228800-1485907200_2','tmp_1483228800-1485907200_0'] &gt;&gt;&gt; sorted(lst, key=lambda x: int(x.rsplit('_', 1)[-1])) ['tmp_1483228800-1485907200_0', 'tmp_1483228800-1485907200_1', 'tmp_1483228800-1485907200_2']
answers question: http://stackoverflow.com/q/49625891
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86259913
downvote count: 0
has comment: http://stackoverflow.com/comment/86258985
has comment: http://stackoverflow.com/comment/86259628
has comment: http://stackoverflow.com/comment/86259256
has comment: http://stackoverflow.com/comment/86259931
has comment: http://stackoverflow.com/comment/86260098
type: Answer
has comment: http://stackoverflow.com/comment/86259159

http://stackoverflow.com/a/49632316
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49626782
answers question: http://stackoverflow.com/q/49626782
has body: It is a good thing to make a small running example which shows the problem. In your case, that is not the fact since we are missing some variables. Like i said in the other comment, your list you map over is made of tuples. Like you already know, you cannot unpack the tuples anymore, but you can use indices like you would use on an array. A simple working example: val = reduce(lambda a, b: a+b, map(lambda t: t[0]*t[1], zip([10, 20, 30], [0.1, 0.3, 0.7])), 0.0) print(val) Like you see, the lambda function passed to the map function just has one parameter now. I called it t to make clear that this is a tuple, you can call it x if you want. In the function-body i use indices to get the first and second element of the tuple. If you run this code, you see that it works. So next step is to adept that to your code: return self.activator(reduce(lambda a, b: a+b, map(lambda t: t[0]*t[1], zip(input_vec, self.weights)), 0.0) + self.bias) And that should do the trick.
type: Answer
score: 8
upvote count: 8

http://stackoverflow.com/comment/86234988
comment on: http://stackoverflow.com/q/49614195
score: 4
type: QuestionComment
has text: Possible duplicate of [How can I read inputs as integers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers)
type: Comment

http://stackoverflow.com/comment/86361450
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49675074
type: Comment
has text: @PedroLobito See edit. pyfiddle.io is a linux server

http://stackoverflow.com/q/49695767
downvote count: 2
tagged with: python
type: AnsweredQuestion
has body: example 1 : a = [['w1' , 'w3'] , ['w2' , 'w4']] df=pd.DataFrame({'a': a }) print(df) mlb = MultiLabelBinarizer() print(np.array(mlb.fit_transform(df['a'].as_matrix()))) renders : a 0 [w1, w3] 1 [w2, w4] [[1 0 1 0] [0 1 0 1]] example 2 : a = ['w1 w2' , 'w1 w3'] df=pd.DataFrame({'a': a }) print(df) mlb = MultiLabelBinarizer() print(np.array(mlb.fit_transform(df['a'].as_matrix()))) renders : a 0 w1 w2 1 w1 w3 [[1 1 1 0 1] [1 1 0 1 1]] example 1 appears to one hot encode the dataframe at word level. What is example 2 computing ? It also appears to be one hot encoding but is not at word level ? I initially thought it was at character level but dataframe contains characters 1,2,3,w , 4 characters but each array element : [[1 1 1 0 1] [1 1 0 1 1]] Is 5 characters in length. Above code utilizes MultiLabelBinarizer http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html
score: -1
upvote count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49696263
has title: Is this one hot encoded?
possible better answer: http://stackoverflow.com/a/49728930
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49696263
answer count: 2
has answer: http://stackoverflow.com/a/49728930

http://stackoverflow.com/comment/86251726
comment on: http://stackoverflow.com/a/49615804
has text: I have a header (extra row) in my template file (which I want to keep) but I want to paste my data (from a .csv file) starting from the second row. I have edited my question with the pictures so that it becomes easier to understand how my files look like. Additionally, [this will give some insight](https://stackoverflow.com/questions/49607990/python-copying-the-data-from-one-excel-file-to-another-excel-file-template-a)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86283231
type: Comment
comment on: http://stackoverflow.com/a/49637676
type: AnswerComment
has text: thanks, this helps a lot with this and will with the rest of my script
score: 0

http://stackoverflow.com/a/49604164
answers question: http://stackoverflow.com/q/49603616
has body: @bunji made a good point. There are actually several problems based on your sample data: header should not be set to None because you do have a header; You may want to set sep or delimiter appropriately based on your data. The sample data you gave does not seem to be a standard format. I tried both space and tab (\t) and neither worked. You can try to print dataset or call dataset.columns to check if you have read it correctly.
type: Answer
score: 0

http://stackoverflow.com/comment/86374702
score: 5
comment on: http://stackoverflow.com/q/49681363
type: Comment
type: QuestionComment
has text: Does `df_1['B'][df_1['B'] < 0] = 0` work for you?

http://stackoverflow.com/a/49721111
has comment: http://stackoverflow.com/comment/86456780
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49721042
has body: You are resetting top_answer to 0 all the time from decimal import * for line in output.split('\n'): top_answer = 0 # set to zero on each begin of line if "Maximum" in line: ext = line.strip()[10:-1] ans = Decimal(ext) print(ext,top_answer) if ans &gt; top_answer: # whatever, top_answer will be replaced by 0 anyway. You should put top_answer=0 before the loop. Your last line in output does not contain any "Maximum" - but the top_answer will be reset to 0 non the less - so you only ever get zeros for it. In python 2.x you do not need parenthesis arount print btw - thats why you get a "tuple" like output
score: 1
type: Answer

http://stackoverflow.com/a/70739397
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49639006
has comment: http://stackoverflow.com/comment/125060446
has body: If you're using Conda, it seems you need the libpython-dev package.

http://stackoverflow.com/comment/86512503
has text: Is this pattern safe when you have multiple response for one request? E.g I ask for an histogram, but then the server streams the answer with one response per bar in the histogram?
type: AnswerComment
comment on: http://stackoverflow.com/a/49697190
score: 0
type: Comment

http://stackoverflow.com/q/49755687
tagged with: python
possible better answer: http://stackoverflow.com/a/49756627
has answer: http://stackoverflow.com/a/49756627
has body: Python newbie here. My problem is the following. I have this (80, 1002) DataFrame of continuous data loaded from a .csv file. My goal with it is to go through every row of this df (80) and plot each row on a basic pyplot.plot. In this df, the first 2 columns are to be used as title so that each plot has it's specific name (here it's the time of the recording and the name of the electrode). What I did to plot one row is : import matplotlib.pyplot as plt import pandas as pd Location = r'/pathtothefile/name.csv' df=pd.read_csv(Location,sep=';') time=range(1,1001); plt.plot(time,df.loc[0, "0":"999"],'g') plt.axhline(0, color='black',linewidth=0.5) plt.xlabel('Time (ms)') plt.ylabel('Power (mV)') plt.axis([1, 1000, -5, 5]) plt.title(str(df.iloc[0,0]) + str(df.iloc[0,1])) plt.show() row.savefig('/pathwheretosave/name.eps', format='eps', dpi=1000) The "time" variable is to be plotted with the rows data. From here I want to loop on the rows of a data frame and plot/save each row in a separated file but so far : I failed. Any idea on how to do that ? Ideally I want to write the title of the plot in the name of the file to be saved.
type: AnsweredQuestion
score: 0
tagged with: row
accepted answer: http://stackoverflow.com/a/49757667
tagged with: pandas
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49757667
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86527453
has title: Generate and save plots from rows of a data frame

http://stackoverflow.com/q/49745881
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
duplicate of: http://stackoverflow.com/q/18366797
type: Question
type: UnansweredQuestion
has title: How to skip reading rows with prefix in a data file using Pandas?
tagged with: python
has body: I have a data file in which columns are separated with one or more spaces consistently. Header rows that are prefixed with a '#' exist here and then. How do I read the file with read_csv('filename.csv') while omitting the header rows only. The header rows have 10 columns while other data rows have 9 columns. A portion of the data file looks like: #POM00008579 1948 01 11 15 9999 6 ncdc6310 387670 -91330 21 -9999 102100B 106 170B 690 -9999 -9999 -9999 10 -9999 100000 182B 150B 700 -9999 -9999 -9999 10 -9999 85000 1529B 40B 600 -9999 -9999 -9999 10 -9999 70000 3083B -30B 100 -9999 -9999 -9999 10 -9999 50000 5671B -200B 100 -9999 -9999 -9999 10 -9999 40000 7240B -360B 100 -9999 -9999 -9999 #POM00008579 1948 01 12 03 9999 5 ncdc6310 387670 -91330 21 -9999 102900B 106 110B 790 -9999 -9999 -9999 10 -9999 100000 244B 110B 700 -9999 -9999 -9999 10 -9999 85000 1573B 10B 700 -9999 -9999 -9999 10 -9999 70000 3136B -10B 200 -9999 -9999 -9999 10 -9999 50000 5739B -180B 300 -9999 -9999 -9999 #POM00008579 1948 01 13 03 9999 5 ncdc6310 387670 -91330 21 -9999 103200B 106 100B 830 -9999 -9999 -9999 10 -9999 100000 267B 100B 800 -9999 -9999 -9999 10 -9999 85000 1614B 80B 300 -9999 -9999 -9999 10 -9999 70000 3191B 10B 200 -9999 -9999 -9999 10 -9999 50000 5809B -180B 300 -9999 -9999 -9999
linked to: http://stackoverflow.com/q/18366797
has answer: http://stackoverflow.com/a/49745899
score: 0

http://stackoverflow.com/a/49752504
has comment: http://stackoverflow.com/comment/86547493
has body: It would perhaps make sense to use a formal ForeignKey relationship between Item and UserDetail since that relationship is one to many. class UserDetail(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) ... You could then query the data you want more efficiently: usernames = [username1, username2, ...] items = [2, 3, 4, 6] users_data = UserDetail.objects.filter(username__in=usernames, item__in=items)\ .select_related('item')\ .order_by('item_id').latest(DateRecorded) And then structure the result how you need it: from collections import defaultdict by_username = defaultdict(dict) for user_data in users_data: by_username[user_data['username']]['username'] = user_data['username'] by_username[user_data['username']][user_data.item.item_name] = [user_data.record] return by_username.values()
type: Answer
has comment: http://stackoverflow.com/comment/86538454
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49745153
upvote count: 1
has comment: http://stackoverflow.com/comment/86535621
has comment: http://stackoverflow.com/comment/86553463

http://stackoverflow.com/q/49684815
has comment: http://stackoverflow.com/comment/86382368
has body: I am trying to make a iris scanner using Python and open CV. While using the template matching function I get the following error: import cv2 import numpy as np img1 = cv2.imread('canny.jpg'); img2 = cv2.imread('frame1.jpg'); edges=cv2.Canny(img2,100,100) w,h=edges.shape[::-1] res = cv2.matchTemplate(img1 , edges, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res &gt;= threshold) print loc Following is the error: Traceback (most recent call last): File "E:/OpenCV Programs/threshold2img1.py", line 9, in &lt;module&gt; res = cv2.matchTemplate(img1 , edges, cv2.TM_CCOEFF_NORMED) error: OpenCV(3.4.1) C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\templmatch.cpp:1102: error: (-215) (depth == 0 || depth == 5) &amp;&amp; type == _templ.type() &amp;&amp; _img.dims() &lt;= 2 in function cv::matchTemplate
has answer: http://stackoverflow.com/a/49686315
favorite count: 0
tagged with: opencv
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86382392
downvote count: 3
tagged with: python
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86388171
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: iris-recognition
score: -3
has title: Error in template matching

http://stackoverflow.com/comment/86444654
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49715746
has text: I have read this. In that case, the condition is in an easy form (x > 18). So the user need only enter in a number greater than 18. My question is how can the condition be set to read if the user entered in their response as 15/20? I have used while num1 != '?/?': but this does not work. (I use the ? as a placeholder )
type: Comment

http://stackoverflow.com/a/49689319
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86451214
type: Answer
answers question: http://stackoverflow.com/q/49687811
has comment: http://stackoverflow.com/comment/86451117
has body: You can use for this matplotlib.pyplot.subplot. import matplotlib.pyplot as plt In a single cell: iterate over the values i in range(11) In iteration i Call plt.subplot(6, 2, i + 1) Plot the DataFrame consisting of inputs i and i +
has comment: http://stackoverflow.com/comment/86403997
upvote count: 1
has comment: http://stackoverflow.com/comment/86450783
has comment: http://stackoverflow.com/comment/86401332

http://stackoverflow.com/q/49743301
type: UnansweredQuestion
answer count: 1
has title: Displaying number of int datatypes in a column using pandas python
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/86529142
has body: Hello i'm new to coding python and using a dataset(csv file) to get knowledge on pandas. I need to output number of int in a given column of the file. i have tried using com.str.extract('(^\d*)') to code but it is displaying integers in between the strings then i used com.str.extract('(^\d*$)') which displays pure int , but i dont know how to display number of ints that appeared in that column
tagged with: pandas
has answer: http://stackoverflow.com/a/49744106
has comment: http://stackoverflow.com/comment/86504315
downvote count: 1
tagged with: python
type: Question
upvote count: 1

http://stackoverflow.com/q/49719015
answer count: 1
linked to: http://stackoverflow.com/q/46088442
tagged with: selenium
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86451075
tagged with: geckodriver
downvote count: 0
has body: I am using Selenium Python bindings with geckodriver. After each browser session rust_mozprofile directories are created in my Windows 7 Temp directory. The houndreds of newly created directories can quickly add up to 5 - 6 GB. I looked for a solution, but I haven't found anything so far. I can manually delete these directories, but this is not optimal. Is there a way to solve this problem programmatically in Selenium? This is not a duplicate, here is why: I checked the answer here but it does not solve my problem. I would like to find a way to create a separate Firefox Profile and use it in Selenium Test Execution or any other way to solve this problem programmatically in Selenium if possible.
has answer: http://stackoverflow.com/a/49817725
tagged with: python
linked to: http://stackoverflow.com/q/15067107
tagged with: selenium-webdriver
score: 3
has title: Geckodriver is creating rust_mozprofile directories when I use Selenium Webdriver
upvote count: 3

http://stackoverflow.com/a/49701094
type: Answer
answers question: http://stackoverflow.com/q/49673248
has body: Here is what you could do: [re.search("(?&lt;=:g.)(\d*)_?(\d*)", item).group() for item in location.split("\n")] What I did here was to make a list comprehension to do everything in a single line. Going by parts: for item in location.split("\n") This iterates over a list built from the location string, where I split the string in all the line breaks. Now the for loop will iterate over every part of the string between the line breaks. Each of these parts is now called 'item'. re.search("(?&lt;=:g.)(\d*)_?(\d*)", item).group() Here I perform a positive lookbehind assertion, which means that the regex will look for ':g.' (the ?&lt;=:g. part), match everything after that, and ditch the ':g.'. As for group(), this is just to print the match from the re.search() method. Read the python documentation on regex, it helps a lot: https://docs.python.org/2/library/re.html
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49693770
has answer: http://stackoverflow.com/a/49693931
has answer: http://stackoverflow.com/a/49694550
favorite count: 0
has answer: http://stackoverflow.com/a/49693885
type: Question
has answer: http://stackoverflow.com/a/49694764
has title: get index of the first block of at least n consecutive False values in boolean array
has comment: http://stackoverflow.com/comment/86400246
tagged with: python
has comment: http://stackoverflow.com/comment/86400426
answer count: 6
has comment: http://stackoverflow.com/comment/86400290
upvote count: 10
score: 8
has answer: http://stackoverflow.com/a/49694608
tagged with: numpy
type: AnsweredQuestion
tagged with: boolean
accepted answer: http://stackoverflow.com/a/49695146
tagged with: cumsum
linked to: http://stackoverflow.com/q/62746907
possible better answer: http://stackoverflow.com/a/49694550
has answer: http://stackoverflow.com/a/49695146
downvote count: 2
has body: I have a numpy boolean array w=np.array([True,False,True,True,False,False,False]) I would like to get the index of the first time there are at n_at_least false values. For instance here `n_at_least`=1 -&gt; desired_index=1 `n_at_least`=3 -&gt; desired_index=4 I have tried np.cumsum(~w) which does increase every time a False value is encountered. However, when True is encountered the counter is not starting from 0 again so I only get the total count of False elements rather than the count of the last consecutive ones.

http://stackoverflow.com/comment/86419936
comment on: http://stackoverflow.com/q/49702923
score: 0
has text: Please check [how to ask question](https://stackoverflow.com/help/how-to-ask) and [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) Please remove the `ssssssssssssssssssssssss.................``
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86444304
has text: The output is **Median time of death: 196 days 00:00:00** I want it to be just **196** days in integer
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49715385
type: QuestionComment

http://stackoverflow.com/q/49638617
tagged with: python
has body: In Perl one can do this: my %seen; foreach my $dir ( split /:/, $input ) { $seen{$dir}++; } This is a way to remove duplicates by keeping track of what has been "seen". In python you cannot do: seen = {} for x in ['one', 'two', 'three', 'one']: seen[x] += 1 The above python results in KeyError: 'one'. What is python-y way of making a 'seen' hash?
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49638684
type: Question
has answer: http://stackoverflow.com/a/49638684
has comment: http://stackoverflow.com/comment/86285168
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86284892
has title: How to make "seen" hash with python dict?
favorite count: 0
has answer: http://stackoverflow.com/a/49638687
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49638656
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49638656

http://stackoverflow.com/a/49676143
answers question: http://stackoverflow.com/q/49675860
has comment: http://stackoverflow.com/comment/93821250
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49675860
upvote count: 72
has comment: http://stackoverflow.com/comment/86370228
has comment: http://stackoverflow.com/comment/93822001
has body: You can do the following newJson = '{"Name":"something","Url":"https://stackoverflow.com","Author":"jangcy","BlogEntries":100,"Caller":"jangcy"}' df = spark.read.json(sc.parallelize([newJson])) df.show(truncate=False) which should give +------+-----------+------+---------+-------------------------+ |Author|BlogEntries|Caller|Name |Url | +------+-----------+------+---------+-------------------------+ |jangcy|100 |jangcy|something|https://stackoverflow.com| +------+-----------+------+---------+-------------------------+
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/133808216
score: 72
has comment: http://stackoverflow.com/comment/93823180
has comment: http://stackoverflow.com/comment/93824550
has comment: http://stackoverflow.com/comment/93821727

http://stackoverflow.com/comment/86527452
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49753225
score: 0
has text: The suggestion from Julian was to add `django.setup()`, that's why I said to remove it. I would try running the commands directly in your terminal, e.g. `python manage runserver`. That way you can narrow down whether it's a problem in your code or Sublime config,

http://stackoverflow.com/q/49640751
upvote count: 3
has comment: http://stackoverflow.com/comment/86289286
has title: Why do `max` and `min` have such strange behavior with numpy.nan?
tagged with: max
downvote count: 0
tagged with: nan
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86289269
score: 3
has body: I accidentally stumbled upon some strange behavior with max, min and numpy.nan and I'm curious about what's going on under the hood. Consider the following code run in python3: import numpy as np max(np.nan, 0) # outputs nan max(np.nan, 10000) # outputs nan max(0, np.nan) # outputs 0 max(10000, np.nan) # outputs 10000 I've played around with a number of values, and it seems that the first value given is always what's returned. The same behavior can be observed with min. I would have expected the output to consistently be nan, or even to throw an error, but this is quite unexpected. Math.nan does the same thing. I'm very curious about this behavior -- does anyone have any ideas?
accepted answer: http://stackoverflow.com/a/49640789
tagged with: python
has answer: http://stackoverflow.com/a/49640789
possible better answer: http://stackoverflow.com/a/49640794
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49640794
answer count: 2
tagged with: min

http://stackoverflow.com/a/49720957
score: 1
answers question: http://stackoverflow.com/q/49720892
type: Answer
has body: As far as I know, you cannot do this. Numpy arrays cannot have entries of varying shape. Your request to make an array like [[1, [1, 1, 1]], [3, 4]] is impossible. However, you could make a numpy matrix of dimensions (3x2x3) to get [ [ [1,0,0], [1,1,1], [0,0,0], ] [ [3,0,0], [4,0,0], [0,0,0] ] ] Your only option is to pad empty elements with some number (I used 0s above) or use another data structure.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86494745
comment on: http://stackoverflow.com/a/49739500
type: Comment
score: 0
type: AnswerComment
has text: Cursor is a pymsql method. I don't know how can I solve that.

http://stackoverflow.com/comment/86231274
comment on: http://stackoverflow.com/a/49607616
score: 0
type: Comment
has text: Thanks, But Javac and Jar tools are not found in the environment of lambda
type: AnswerComment

http://stackoverflow.com/a/49822499
has body: I'm confused because I assumed that making a prediction would not in itself increase memory. That is actually not true, so it's the likely reason for OOM. Estimator.predict() rebuilds the graph from scratch on each call and loads the weights from disk for inference. See this question and this issue on GitHub for more details. Yes, the graph, tensors are other objects become available for GC after the call, but it doesn't mean all of them are collected immediately. When this method is called a thousand times, the stability of the whole application depends on how quickly previously allocated memory can be reclaimed. But python GC can be postponed for a long time. And even if GC collects the garbage regularly, you may still face the problem of defragmentation. This means that you should try to call Estimator.predict() fewer times with more input data to predict, or migrate from estimator API to keras, tf slim or pure tensorflow implementation.
type: Answer
answers question: http://stackoverflow.com/q/49720697
score: 0

http://stackoverflow.com/q/49722777
type: Question
has comment: http://stackoverflow.com/comment/86458987
accepted answer: http://stackoverflow.com/a/49722800
has answer: http://stackoverflow.com/a/49722800
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86459102
has body: If I have a .txt file with a whole bunch of data, lets say movie reviews that is currently formatted like this: 1 The Da Vinci Code book is just awesome. 1 this was the first clive cussler i've ever read, but even books like Relic, and Da Vinci code were more plausible than this. 1 i liked the Da Vinci Code a lot. 1 i liked the Da Vinci Code a lot. 1 I liked the Da Vinci Code but it ultimatly didn't seem to hold it's own. 1 that's not even an exaggeration ) and at midnight we went to Wal-Mart to buy the Da Vinci Code, which is amazing of course. How could I alter this file or write its contents to a new file so that after the end of each sentence, the next starts on a new line rather than the same one?
tagged with: replace
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 1
has title: Replace blank space with new line in txt file with Python

http://stackoverflow.com/comment/86322915
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49654351
has text: Possible duplicate of [Sqlite / SQLAlchemy: how to enforce Foreign Keys?](https://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys)

http://stackoverflow.com/a/49751780
answers question: http://stackoverflow.com/q/49751716
downvote count: 0
type: Answer
has body: One way is to use pd.Series.value_counts and extract the index: df = pd.DataFrame({'A': [1, 2, 1, 2, 2, 3]}) res = pd.DataFrame({col: df[col].value_counts().head(2).index for col in df}) # A # 0 2 # 1 1
upvote count: 1
score: 1

http://stackoverflow.com/comment/86406717
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49695104
type: Comment
has text: Very much doubt that 50MB is taken up by the python code that you wrote. It is mostly the python interpreter. So that 50MB will be shared among all threads in that interpreter and also among processes on Linux as shared process memory. Either way, cx_freeze will bundle whatever the python script given to it is running. If it is starting 1000 processes, they will all share the same python distribution.

http://stackoverflow.com/comment/86236955
type: QuestionComment
comment on: http://stackoverflow.com/q/49614798
type: Comment
has text: just the list of words, where the corresponding numeric value is between 1 and -1, basically 0.x
score: 0

http://stackoverflow.com/comment/86365666
score: 1
type: Comment
has text: @Cing no idea if it's faster. haven't tested. if you have just 4 functions, and aren't calling them very often, performance shouldn't be an issue. Make sure you (and your team) use the one that is more readable :)
type: QuestionComment
comment on: http://stackoverflow.com/q/49658794

http://stackoverflow.com/comment/113677058
type: Comment
score: 22
comment on: http://stackoverflow.com/q/49637853
has text: The trick is to press `Alt` + `Shift` + `E` all at the same time. I can't believe they made it this hard; running code must be the most common thing people do in PyCharm. Don't you wish PyCharm was half as convenient as RStudio?
type: QuestionComment

http://stackoverflow.com/comment/86411783
type: Comment
comment on: http://stackoverflow.com/a/49699104
type: AnswerComment
has text: Can do. Thank you!
score: 0

http://stackoverflow.com/comment/86441065
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49713857
type: Comment
has text: @zwer They are really in a list, and not all individual variables. This was to just simplify the question (at least in my mind).

http://stackoverflow.com/comment/86441708
score: 0
has text: @zwer I'm, it explains the first of my question, but it doesn't explain why it is gradually slowing down.
comment on: http://stackoverflow.com/q/49713281
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49662504
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49664218
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86366160
answer count: 2
possible better answer: http://stackoverflow.com/a/49679307
has title: Function to create LineString from Points using Shapely
tagged with: shapely
has comment: http://stackoverflow.com/comment/86368574
has answer: http://stackoverflow.com/a/49679307
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49664218
has body: I have a list of points: points = [Point(2.2, 4.2), Point(7.2, -25.1), Point(9.26, -2.456)] I am trying to write a function that will check that this list contains point objects and return then a LineString, so far: def createLineGeom(giveLine): if type(giveLine) is shapely.geometry.point.Point: return LineString(giveLine) else: return 'pointList must contain shapely point object(s)' I am only able to return the else message from createLineGeom(points). Not sure if my problem is with the type() function or my first return statement, I am very much a beginner writing functions. Thanks! Update after J_H answer vertices = [Point(2.2, 4.2), Point(7.2, -25.1), Point(9.26, -2.456)] # function def createLineGeom(giveLine): if isinstance(giveLine, Point): return LineString(giveLine) Still returns no value from pls_work = createLineGeom(vertices)
favorite count: 0
type: Question

http://stackoverflow.com/a/71851916
upvote count: 1
has body: Try with this command pip install bayesian-optimization
type: Answer
answers question: http://stackoverflow.com/q/49685821
score: 1
downvote count: 0

http://stackoverflow.com/comment/86267291
score: 0
type: Comment
has text: You are fetching data from a table called `printerdetails` and saying "it doesn't work". But you haven't shown us your data. *The id's are string* is not enough detail. What does the result of `print row` look like? And why are you creating an instance of `Usb` from the last row in the table?
type: QuestionComment
comment on: http://stackoverflow.com/q/49627214

http://stackoverflow.com/q/49636200
has comment: http://stackoverflow.com/comment/86281209
score: 1
has title: Pandas: Fill rows with values based on condition in other rows
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49636872
has comment: http://stackoverflow.com/comment/86280652
upvote count: 1
has answer: http://stackoverflow.com/a/49636872
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86279932
tagged with: python
has comment: http://stackoverflow.com/comment/86281348
has comment: http://stackoverflow.com/comment/86280733
has body: I am trying to work out how to fill some rows with text based on other columns but am struggling to figure it out. Below is an example of a subset of data I have in a pandas data frame. Group Name_X Name_Y Code Group_Code Group_Correct 0 Group_A Company_PJ Company_PJ M001 1-00-002 Group_A 1 Group_A_Ltd Company_PJ NaN NaN NaN NaN 2 Group_B Company_XYZ NaN NaN NaN NaN 3 Group_GTY Company_R Company_R M020 1-00-033 Group_GTY 4 Group_A Company_PJ NaN NaN NaN NaN 5 Group_BGG Company_VV Company_VV M023 1-00-233 Group_BGG 6 Group_B Company_XYZ NaN NaN NaN NaN 7 Group_B Company_XYZ Company_XYZ M003 1-00-003 Group_B 8 Group_B_Limited Company_XYZ NaN NaN NaN NaN 9 Group_B Company_DEF Company_DEF M004 1-00-006 Group_B 10 Group_B+ Company_DEF NaN NaN NaN NaN And what I would like is to get something like the below. The text shown in red are the text that needs to be filled or changed based on conditions of text in other rows. What's the easiest way I could go about doing it in python.
has comment: http://stackoverflow.com/comment/86280893
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/86280823

http://stackoverflow.com/q/49685900
has body: class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({'form': form, 'object': self.obj}) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: # new content Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, 'object': self.obj}) please I use django version: 1.11.10 and python version: 3.6.2. Below is the traceback Traceback: File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = w…
score: 1
answer count: 1
tagged with: web
type: Question
has answer: http://stackoverflow.com/a/49686000
upvote count: 3
type: UnansweredQuestion
downvote count: 2
tagged with: django
tagged with: python
favorite count: 0
has title: Django: please aid, i get "is_valid() missing 1 required positional argument:'self'"...below is the block of code...thanks

http://stackoverflow.com/comment/86643766
type: AnswerComment
has text: Thanks, you are right. In LibreOffice its Sheet -> Show Sheet and it will show hidden sheets.
comment on: http://stackoverflow.com/a/49751279
score: 0
type: Comment

http://stackoverflow.com/a/49608369
score: 1
upvote count: 1
has body: You can try this if you have only limited formats : from datetime import datetime list1=["30-4-1994","1994-30-04","30/04/1994","30-apr- 1994","30/apr/1994","1994-30-apr"] for i in list1: for fmt in ('%Y-%m-%d', '%d-%m-%Y', '%d/%m/%Y', '%Y-%d-%m', '%Y-%d-%b', '%d-%b-%Y', '%d/%b/%Y'): try: example_time = datetime.strptime(i, fmt).date() final_output = datetime.strftime(example_time, "%d-%m-%Y") print(final_output) except ValueError: continue
has comment: http://stackoverflow.com/comment/86223399
type: Answer
answers question: http://stackoverflow.com/q/49608039
downvote count: 0

http://stackoverflow.com/q/49741048
has title: What does it mean to "restart" a program (in my case IDLE)?
possible better answer: http://stackoverflow.com/a/49741140
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/86498090
has answer: http://stackoverflow.com/a/49741140
has comment: http://stackoverflow.com/comment/86498109
downvote count: 6
has comment: http://stackoverflow.com/comment/86496590
linked to: http://stackoverflow.com/q/16833285
has comment: http://stackoverflow.com/comment/86496781
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49758241
answer count: 2
has answer: http://stackoverflow.com/a/49758241
has body: This answer on Stack Overflow offers a solution I am trying to implement. In particular, see the sections "Installation Instructions" and "How to Use". Can anyone tell me the steps required to "restart" IDLE? New Information: Just as people have suggested I thought this simply meant closing the program and opening it back up again...but I already tried that. The other twist to my situation is that I'm working on a virtual machine so I was unable to do the installation of IDLE2HTML.py myself. My work's Help Desk had to do it so I cannot speak for the accuracy of their work. For now I'm assuming they did it correctly, but when I go to the "Options" menu there is no option to "Save as HTML". My only guess at this point is that I still need to "restart IDLE". Just wanted to double check if there was something else I could do before going back to my Help Desk department.
has comment: http://stackoverflow.com/comment/86497095
has comment: http://stackoverflow.com/comment/86497371
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86497414
score: -5

http://stackoverflow.com/q/49685677
has comment: http://stackoverflow.com/comment/86385109
has comment: http://stackoverflow.com/comment/86384903
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
tagged with: pdf-generation
has title: Creating Embeded PDF with Python
tagged with: python-2.7
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86384137
type: Question
score: 0
has body: Hello first of all I'm noob in python don't get mad please. / FIXED / I'm asking you guys for help to how can I do this. Thank you. this is what I want to do https://youtu.be/TBpwJY9jzoc SOURCE : / REDACTED / Thanks Guys I figured out.

http://stackoverflow.com/q/49743051
tagged with: python
tagged with: image
upvote count: 2
score: 2
has title: Aligning images with openpyxl
has comment: http://stackoverflow.com/comment/86530275
tagged with: openpyxl
has answer: http://stackoverflow.com/a/60974631
answer count: 1
has comment: http://stackoverflow.com/comment/137652853
downvote count: 0
has body: I have been looking for a couple days now and cannot find an answer. I am creating a worksheet with python and is using the openpyxl module. I am able to format cells and insert values in the cells. I can insert images in cells, but i need to align the images. align = Alignment(horizontal = 'left', vertical = 'center', wrap_text = True IMAGECELL = ws.cell['A1'] IMAGECELL.alignment = align This is my code for aligning text. It is not working with images.
has comment: http://stackoverflow.com/comment/86522914
tagged with: excel
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/55309671
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86513766

http://stackoverflow.com/q/49704350
accepted answer: http://stackoverflow.com/a/50256988
has answer: http://stackoverflow.com/a/50256988
answer count: 1
tagged with: timeout
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
tagged with: python
has title: Python dbus get_object set timeout
has body: Code: def get_user_totp_status (user_name = ''): key_name = 'tfaEnable' try: bus = dbus.SystemBus() except: print "connect dbus error!" sys.exit(1) infopipe_obj = bus.get_object("org.freedesktop.sssd.infopipe", "/org/freedesktop/sssd/infopipe") ifp = dbus.Interface(infopipe_obj,dbus_interface='org.freedesktop.sssd.infopipe') print "get user totp status from dbus error!" result = ifp.GetUserAttr(user_name, [key_name]) user_totp_status = 'True' if result: for status in result[key_name]: user_totp_status = status return user_totp_status =========== Error: dbus.exceptions.DBusException: org.freedesktop.DBus.Error.TimedOut: Activation of org.freedesktop.sssd.infopipe timed out ======== If DBUS has problems, it will take a long time when "get_object". How do I set timeout to shorten the time?
type: AnsweredQuestion
score: 2
tagged with: dbus

http://stackoverflow.com/q/49602333
downvote count: 0
tagged with: wordpress
upvote count: 1
tagged with: xml-rpc
type: AnsweredQuestion
score: 1
has body: Making website for my town library using wordpress. The site will have several thousand posts, one for each book. I'm trying to get it so if that if a post with the same title already exists, it prints out something to let me know before I post it. I have this snippet of code but it's pretty old and the documentation for xmlrpc wordpress especially with python is very lax. post_id=find_id(post.title) if post_id: print ("Sorry, we already have such a post" + post_id) else: pass This is the rest of my publishing code. #client info# wp = Client(wp_url, wp_username, wp_password) post = WordPressPost() post.title = 'Dracula' post.post_status = 'draft' post.terms_names = { 'post_format': ['book'], 'category': [tag], } post.custom_fields = [] post.custom_fields.append({'key':'dp_desc','value':desc}) post.custom_fields.append({'key':'fifu_image_url','value':thumb}) wp.call(NewPost(post)) Sorry if the answer exists already, all that I've seen have been in php.
tagged with: python
accepted answer: http://stackoverflow.com/a/49603056
has title: Wordpress xmlrpc python check if post title exists
favorite count: 0
has answer: http://stackoverflow.com/a/49603056
type: Question
tagged with: python-3.x
answer count: 1

http://stackoverflow.com/comment/86434363
has text: Can you make sure the setup is fine? Use steps listed in this https://github.com/zlorb/scapy and also make sure you run your program with admin rights
type: Comment
comment on: http://stackoverflow.com/a/49704206
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86290229
has text: Just looking for syntax
comment on: http://stackoverflow.com/q/49641277
score: 0
type: Comment
type: QuestionComment

pipeline
type: Tag
tags question: http://stackoverflow.com/q/49701448
tag name: pipeline

http://stackoverflow.com/comment/86242904
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49617919
type: Comment
has text: That sounds kind of in the direction (Despite I was hoping that there still was a simple approach like JUnit setup teardown but with access to the current test of the data driven parameters) How you combine those fixtures with data driven ?

http://stackoverflow.com/q/49630752
tagged with: python
has comment: http://stackoverflow.com/comment/86269953
accepted answer: http://stackoverflow.com/a/49632208
has comment: http://stackoverflow.com/comment/86268470
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49632208
tagged with: tkinter
score: 1
has title: Why are my labels and entry's not visible in python tkinter?
tagged with: user-interface
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: This a a segment for my code creating a register screen, when run it creates no errors, however none of the labels or entry's are visible on the GUI, only the two buttons are visible on the tkinter window. Another frame i have uses exactly the same method to enter data, and works fine. Any help would be much appreciated, thanks! class register(Frame): def __init__(self,master): super().__init__(master) self.labelEmail = Label(self, text="Enter email:") self.labelUsername = Label(self,text="Enter username:") self.labelPassword = Label(self, text ="Enter password:") self.labelPassword2 = Label(self, text ="Re-enter password:") self.entryEmail = Entry(self) self.entryUsername = Entry(self) self.entryPassword = Entry(self, show="*") self.entryPassword2 = Entry(self, show="*") self.labelEmail.grid(row=0, sticky=E) self.labelUsername.grid(row=1, sticky=E) self.labelPassword.grid(row=2, sticky=E) self.labelPassword2.grid(row=3, sticky=E) self.entryEmail.grid(row=0, column=1) self.entryUsername.grid(row=1, column=1) self.entryPassword.grid(row=2, column=1) self.entryPassword2.grid(row=3, column=1) self.confirmBtn = Button(text="Confirm", command=self.confirmBtnClicked) self.confirmBtn.grid(row=4, column=0) self.cancelBtn = Button(text="Cancel",command=self.cancelBtnClicked) self.cancelBtn.grid(row=4, column=1) ..... root = Tk() ls = register(root) root.mainloop()

http://stackoverflow.com/q/49648180
tagged with: dictionary
tagged with: python-3.6
favorite count: 0
has body: I tried to do a simple title but I'm a bit lost with this one. I'm using a python module Python-HPILO in order to gather some information like Hard Drive Disk and DIMM details on HP Blades, this is working. Example : import hpilo ilo = hpilo.Ilo('10.0.0.1', 'USER', 'PASSWORD') health = ilo.get_embedded_health() logical_drives = (health['storage']['Controller on System Board']['logical_drives']) print(logical_drives) Result (anonymized) : [{**'label': '01', 'status': 'OK', 'capacity': '419 GiB', 'fault_tolerance': 'RAID 1/RAID 1+0', 'logical_drive_type': 'Data LUN', 'encryption_status': 'Not Encrypted', 'physical_drives': **[{**'label': 'Port 1I Box 1 Bay 1', 'status': 'OK', 'serial_number': 'SXXXXXXXX', 'model': 'YYYYYY', 'capacity': '419 GiB', **'marketing_capacity': '450 GB'**, 'location': 'Port 1I Box 1 Bay 1', 'fw_version': 'HPD9', 'drive_configuration': 'Configured', 'encryption_status': 'Not Encrypted', 'media_type': 'HDD'**}**, {'label': 'Port 1I Box 1 Bay 2', 'status': 'OK', 'serial_number': 'SXXXXXX', 'model': 'YYYYYY', 'capacity': '419 GiB', 'marketing_capacity': '450 GB', 'location': 'Port 1I Box 1 Bay 2', 'fw_version': 'HPD9', 'drive_configuration': 'Configured', 'encryption_status': 'Not Encrypted', 'media_type': 'HDD'**}]}] I would like to collect the value of marketing_capacity, which is 450GB here. I found some other topics related to incursive search in list or dict but I were not able to make it work with this specific listed-dictonary-listed-dictonary thing. Does anyone have a simple way/function to do research in this kind of list ?
type: Question
has answer: http://stackoverflow.com/a/49648481
tagged with: python-3.x
has title: Python 3.6 - Search word in a list that contain dictionary that containt dictionary in list
tagged with: list
has answer: http://stackoverflow.com/a/49648296
downvote count: 0
has comment: http://stackoverflow.com/comment/86304471
answer count: 5
upvote count: 1
has answer: http://stackoverflow.com/a/49648223
possible better answer: http://stackoverflow.com/a/49648223
accepted answer: http://stackoverflow.com/a/49648317
has answer: http://stackoverflow.com/a/49648235
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49648317
tagged with: python

http://stackoverflow.com/comment/86373008
type: QuestionComment
has text: https://drive.google.com/file/d/12axINSw2fCO6rog56lxFjFj5evvKj9aS/view?usp=sharing Here are the code and result after adding a column one to x. @Eolmar https://drive.google.com/file/d/1-UaU34w3c5-VunYrVz9fD7vRb0c-XDqk/view?usp=sharing Also the csv file I entered
type: Comment
comment on: http://stackoverflow.com/q/49674212
score: 0

http://stackoverflow.com/comment/86637977
type: Comment
type: AnswerComment
has text: I have to wait 4 more hours before I can award the bounty. :D And yes, as specific as possible is good, as it's often easier to see what's happening.
score: 0
comment on: http://stackoverflow.com/a/49800234

http://stackoverflow.com/q/49641707
score: 13
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/67990164
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72459953
tagged with: pandas
has answer: http://stackoverflow.com/a/49641723
has answer: http://stackoverflow.com/a/65832595
accepted answer: http://stackoverflow.com/a/49641723
tagged with: python
tagged with: standardized
answer count: 4
upvote count: 13
tagged with: sklearn-pandas
has title: Standardize some columns in Python Pandas dataframe?
has body: Python code below only return me an array, but I want the scaled data to replace the original data. from sklearn.preprocessing import StandardScaler df = StandardScaler().fit_transform(df'cost', 'sales') df output array([[ 1.99987622, -0.55900276], [-0.49786658, -0.45658181], [-0.5146864 , -0.505097 ], [-0.48104676, -0.47814412], [-0.50627649, 1.9988257 ]]) original data id cost sales item 1 300 50 pen 2 3 88 bottle 3 1 70 drink 4 5 80 cup 5 2 999 ink
possible better answer: http://stackoverflow.com/a/65832595
downvote count: 0

http://stackoverflow.com/comment/86308109
has text: Yes, I'm getting int is not iterable after calling reduceByKey on that. Dont know why
type: Comment
comment on: http://stackoverflow.com/a/49648845
score: 0
type: AnswerComment

http://stackoverflow.com/q/49694836
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49705276
has answer: http://stackoverflow.com/a/49705276
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86408534
has title: Tensorflow Dataset is 3 Times Slower Than the Queue Pipeline?
tagged with: tensorflow-datasets
type: AnsweredQuestion
score: 1
has body: I have suffered for the speed of tensorflow dataset api. I test the speed of the dataset pipline and the queue pipline with this code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import time import tensorflow as tf def disk_image_batch_dataset(img_paths, batch_size, shuffle=True, buffer_batch=128, repeat=-1): def parse_func(path): img = tf.read_file(path) img = tf.image.decode_png(img) return img dataset = tf.data.Dataset.from_tensor_slices(img_paths).map(parse_func) dataset = dataset.batch(batch_size) if shuffle: dataset = dataset.shuffle(buffer_batch) else: dataset = dataset.prefetch(buffer_batch) dataset = dataset.repeat(repeat) # make iterator iterator = dataset.make_one_shot_iterator() return iterator.get_next() def disk_image_batch_queue(img_paths, batch_size, shuffle=True, num_threads=4, min_after_dequeue=100): _, img = tf.WholeFileReader().read( tf.train.string_input_producer(img_paths, shuffle=shuffle, capacity=len(img_paths))) img = tf.image.decode_png(img) img.set_shape([218, 178, 3]) # batch datas if shuffle: capacity = min_after_dequeue + (num_threads + 1) * batch_size img_batch = tf.train.shuffle_batch([img], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue, num_threads=num_threads) else: img_batch = tf.train.batch([img], batch_size=batch_size) return img_batch paths = glob.glob('img_align_celeba/*.jpg') with tf.Session() as sess: with tf.device('/cpu:0'): batch = disk_image_batch_dataset(paths, 128, shuffle=True, buffer_batch=128, repeat=-1) for _ in range(10): start = time.time() for _ in range(100): sess.run(batch) elapse = time.time() - start print('Dataset Average: %f ms' % (elapse / 100.0 * 1000)) batch = disk_image_batch_queue(paths, 128, shuffle=True, num_threads=4, min_after_dequeue=100) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) for _ in range(10): start = time.time() for _ in range(100):…
answer count: 1

http://stackoverflow.com/a/49709310
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86436472
upvote count: 5
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49709309
has comment: http://stackoverflow.com/comment/86452328
has body: See this answer: https://stackoverflow.com/a/34997357/1619432 print() usually writes to sys.stdout. The following are excerpts of the documentation, for non-interactive mode: stdout is used for the output of print() sys.stdout: File object used by the interpreter for standard ... output These streams are regular text files like those returned by the open() function. character encoding on Windows is ANSI standard streams are ... block-buffered like regular text files. Note To write or read binary data from/to the standard streams, use the underlying binary buffer object. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc'). Let's try this direct approach first: import sys print("one\ntwo") sys.stdout.write('three\nfour') sys.stdout.buffer.write(b'five\nsix') results in five\n sixone\r\n two\r\n three\r\n four The buffer write seems to work as desired, although it's "messing" with the output order. Flushing before writing to the buffer directly helps: import sys print("one\ntwo") sys.stdout.write('three\nfour') sys.stdout.flush() sys.stdout.buffer.write(b'five\nsix') results in one\r\n two\r\n three\r\n fourfive\n six But still it's not "fixing" print(). Back to the file objects / streams / text files (short info on IO objects in Python Data model): https://docs.python.org/3/glossary.html#term-text-file A file object able to read and write str objects. Often, a text file actually accesses a byte-oriented datastream and handles the text encoding automatically. Examples of text files are files opened in text mode ('r' or 'w'), sys.stdin, sys.stdout, and instances of io.StringIO. So (how) can the sys.stdout file be reconfigured or reopened to control the newline behaviour? And what exactly is it? &gt;&gt;&gt; import sys &gt;&gt;&gt; type(sys.stdout) &lt;class '_io.TextIOWrapper'&gt; Docs: class io.TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False): newline controls how line endings are handled.…
answers question: http://stackoverflow.com/q/49709309

http://stackoverflow.com/a/49722136
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49721113
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49721113
score: 5
has body: I think you can get a hint at why the style you describe is popular by looking at one of the imports in the code you quoted: from ..externals import six This import gets the six module from inside the sklearn.internals package. But six is a module that can be distributed separately. It's been "vendored" by the sklearn project. Vendoring a module means they're including their own copy of it inside their own project, rather than having it as an external dependency. Making it possible for your package to be vendored is one reason you might favor relative imports. If your package is normally named my_package, but some other project has vendored it as some_other_package.externals.my_package, your internal imports will still work if you used relative import syntax. If you used absolute imports, they'd all break (and the vendoring project would need to rewrite each of them). It isn't perfect though. The other package will need to edit your imports if they're also vendoring some of your external dependencies (that you're accessing with absolute imports). Vendoring also has some severe downsides when it comes to fixing bugs. If the vendored version of a package has a security flaw, then so does the project including it. If the outer package only accessed an external version of its dependency, it could benefit from a fix to the external package without needing to be changed itself. It's worth noting that some Python developers are not entirely happy with how the current system works, as it can be hard to resolve some common issues. A recent thread on the Python-dev mailing list discussed how the current support is imperfect. Vendoring can be awkward, and it is often undone by downstream packagers, like Linux distros, who need to be able to reliably fix security vulnerabilities. But without it, it's hard to for a package to rely upon version-specific behavior from its dependencies. There's no versioning of imports, so if your code breaks when some_package gets upgraded from ve…
type: AcceptedAnswer

http://stackoverflow.com/q/49755027
has title: Python- defining a function that takes data-frame as an Input
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49755137
accepted answer: http://stackoverflow.com/a/49755137
has body: I am trying to create a function that alters the datatypes of the columns. def ChangeDatatypes(df): df['Name'] = df['Name'] .astype('category') df['Character'] = df['Character'] .astype('category') cat_columns = df.select_dtypes(['category']).columns df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes) return(df) Actual_Dataframe = ChangeDatatypes(Actual_DataFrame) ' calling that function I want to change the Actual_Dataframe and therefore calling the function that I created but it's not throwing any error and at the same time, it is not changing the data types of the columns. Where am I going wrong in the code?
tagged with: python-3.x
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49639151
upvote count: 2
type: Answer
has body: An algorithm being O(n) means that the number of operations is eventually bounded by some linear function a * n where a is a constant. In the case of algorithms that rely on list traversal it does not mean that they must traverse the list only once. It means they must traverse the list at most a times and that a does not depend on the list length. In your case, you have two pointers, but they each traverse the list only once. This means you always traverse the list only twice. One more remark is that while the number of substrings in a n-string grows by O(n^2), you are not traversing all of them. Indeed only up to n of them are valid and these are the only ones you are inspecting with the two-pointers traversal. By example in the string 'abcdef' with k = 3, you do not check the substring 'abcd'.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49638176

http://stackoverflow.com/a/49696659
downvote count: 0
answers question: http://stackoverflow.com/q/49641277
score: 2
type: Answer
upvote count: 2
has body: Indeed, you can use a dict comprehension, but you shouldn't. If you are ready, let's go. I will start with a little cleanup of your code. First, I replace cpPtr.split(" ")[0] and cpPtr.split(" ")[1] with u and v, where u,v = cpPtr.split(" "). It's a destructuring assignement. Then I inline the following lines: if domainKey in domainAggregator.keys(): domainAggregator[domainKey] = int(domainAggregator[domainKey]) + int(u) else: domainAggregator[domainKey] = int(u) into: domainAggregator[domainKey] = int(domainAggregator[domainKey])+int(u) if domainKey in domainAggregator.keys() else int(u) I get now the following code: for cpPtr in cpdomains: u,v = cpPtr.split(" ") for domainKey in self.domainSplitter(v): domainAggregator[domainKey] = int(domainAggregator[domainKey])+int(u) if domainKey in domainAggregator.keys() else int(u) and I want to turn it in a dict comprehension. Now, some little hacks. You can't use assignements inside a list or dict comprehension. In order to put that in a list comprehension (and then a dict comprehension, see later), I need to get rid of =s: u, v = cpPtr.split(" ") ... domainAggregator[domainKey] = int(domainAggregator[domainKey])+int(u) if domainKey in domainAggregator.keys() else int(u) Becomes: for u, v in [cpPtr.split(" ")]: # this is a singleton ... domainAggregator.update({domainKey:int(domainAggregator[domainKey])+int(u) if domainKey in domainAggregator.keys() else int(u)}) # I update the dict The code is now: for cpPtr in cpdomains: for u,v in [cpPtr.split(" ")]: for domainKey in self.domainSplitter(v): domainAggregator.update({domainKey:int(domainAggregator[domainKey])+int(u) if domainKey in domainAggregator.keys() else int(u)}) Now, I can use a list comprehension to create a side-effect. You just have to insert everything inside square brackets: [domainAggregator.update({domainKey:int(domainAggregator[domainKey])+int(u) if domainKey in domainAggregator.keys() else int(u)}) for cpPtr in cpdomains for u,v in [cpPtr.split(" ")] for …

http://stackoverflow.com/q/49602262
tagged with: windows-10
tagged with: unicode
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86212208
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86212202
has title: Is there a way to know if an unicode character is available in installed fonts?
downvote count: 0
answer count: 0
tagged with: fonts
score: 1
has body: I'm using the Blocks.txt from unicode.org which defines unicode character ranges. I made some tool to display those character, per range, in a browser. I downloaded the Noto font package. Obviously I don't need to install all of those fonts, so is there a "programmingly" way to know if the browser/system is rendering a character, so I can only install the fonts I need? Or maybe to query if the system has an installed fonts for this character? Maybe an easier way would be to learn what range of codepoints each single TTF from noto is supposed to render... I just want to browse character as a hobby project.
upvote count: 1
has comment: http://stackoverflow.com/comment/86218368
tagged with: utf-8

http://stackoverflow.com/a/49657354
accepted answer of: http://stackoverflow.com/q/49656013
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49656013
downvote count: 0
type: Answer
upvote count: 1
has body: The checkbar needs attributes for the maximum and current number of buttons checked. You then need a command that is called each time a checkbutton is clicked. The command is called without arguments after the variable is changed. If possible, code should be posted without dependency on as external file. In this case, just pass a list of strings. (I copied before Aran-Fey's edit.) from tkinter import * def checkmax(bar, var): # called after the intvar is changed def _check(): print(bar.numpicks, var.get()) if var.get(): # checked if bar.numpicks &lt; bar.maxpicks: bar.numpicks += 1 else: var.set(0) else: # unchecked bar.numpicks -= 1 return _check class Checkbar(Frame): def __init__(self, parent=None, picks=[], maxpicks=2, side=LEFT, anchor=W): Frame.__init__(self, parent) self.maxpicks = maxpicks self.numpicks = 0 self.vars = [] for pick in picks: var = IntVar() chk = Checkbutton(self, text=pick, variable=var, command=checkmax(self, var)) chk.pack(side=side, anchor=anchor, expand=YES) self.vars.append(var) def state(self): return map((lambda var: var.get()), self.vars) if __name__ == '__main__': root = Tk() lng = Checkbar(root, ['a', 'b', 'c', 'd'], 2) lng.pack(side=TOP, fill=BOTH) lng.config(relief=GROOVE, bd=2) def allstates(): print( list(lng.state() ) ) Button(root, text = 'Quit', command = root.quit).pack(side = RIGHT) Button(root, text = 'submit', command = allstates).pack(side = RIGHT) root.mainloop() You should add a label as to the max number that can be checked. Added note: When the Python IntVar is passed as the Checkbutton variable, it is replaced by a _tkinter.Tcl_Obj that does not have the .get and .set methods. So the command needs a reference to the IntVar instance as chk['variable'].get does not work.

http://stackoverflow.com/q/49735841
has comment: http://stackoverflow.com/comment/86485658
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/49736670
downvote count: 1
possible better answer: http://stackoverflow.com/a/49736221
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Efficient way of assigning dicts to objects in Python
has body: I'm looking for the most efficient/ python way of solving the following Problem: I have a list of local objects (list_a), a list of objects on a server (list_b). list_b is a list of dictionaries, not objects. I want to update some information in the local object with the ones given by the server. The assignment can be done by the attribute name or the identifier 'name', in the dictionary. Both lists could be a subset of each other. Here is my current solution with some example data: class Dummy(): def __init__(self, name): self._name = name self._attr = '' def __str__(self): return "Test-Object[" + self._name + ", " + self._attr + "]" def update(self, obj): self._attr = obj['attr'] __repr__ = __str__ list_a = [Dummy(str(x)) for x in xrange(10)] list_b = [{'name': str(x), 'attr': str(x*2)} for x in xrange(8, -1, -1)] extracted_names_a = [x._name for x in list_a] extracted_names_b = [x['name'] for x in list_b] filtered_list_a = (x for x in list_a if x._name in extracted_names_b) filtered_list_b = (x for x in list_b if x['name'] in extracted_names_a) sorted_list_a = sorted(filtered_list_a, key=lambda k: k._name) sorted_list_b = sorted(filtered_list_b, key=lambda k: k['name']) for obj, d in zip(sorted_list_a, sorted_list_b): obj.update(d) print(list_a) This is just a simple example, in the real world there are 2000+ entries and a little bit more data
has answer: http://stackoverflow.com/a/49736670
has comment: http://stackoverflow.com/comment/86486676
tagged with: python
has comment: http://stackoverflow.com/comment/86486805
tagged with: dictionary
tagged with: lambda
has answer: http://stackoverflow.com/a/49736221
tagged with: optimization
has comment: http://stackoverflow.com/comment/86485824
has comment: http://stackoverflow.com/comment/86485786
answer count: 2

http://stackoverflow.com/a/49660880
score: 1
type: Answer
has body: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html It appears that the .read_sql() method has a chunksize argument. Have you tried something like df = pd.read_sql(query, session, chunksize = 100,000)? (I'm using a chunksize of 100k since you said 100k records weren't a problem).
answers question: http://stackoverflow.com/q/49658348
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49635871
has comment: http://stackoverflow.com/comment/86279834
downvote count: 0
has comment: http://stackoverflow.com/comment/86280015
has answer: http://stackoverflow.com/a/49637354
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86280071
tagged with: numpy
has comment: http://stackoverflow.com/comment/86279855
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86279948
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86280037
has answer: http://stackoverflow.com/a/49637568
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86279995
has body: I am trying to load data from csv by row, then create 2d array out of each row and store it inside array: loading: with open('data_more.csv', newline='') as csvfile: data = list(csv.reader(csvfile)) parsing: def getTrainingData(): label_data = [] for i in range( 0 , len(data) - 1): y = list(data[i][1:41:1]) y = list(map(lambda x: list(map(lambda z: int(z),x)),y)) y = create2Darray(y) label_data.append(y) labelY = np.array(label_data,dtype=float) create2Darray func: def create2Darray( arr ): final_arr = [] index = 0 while( index &lt; len(arr)): temp = arr[index:index+4:1] final_arr.append(temp) index+=4 return final_arr This is simple task, yet i keep recieving erro: ValueError: setting an array element with a sequence. I have read that its related to situation when the shape of elements isnt same. However when i print shape of all elements inside labelY it outputs same shape. What is causing this problem then? The problem occurs on this line labelY = np.array(label_data,dtype=float) my csv has format number, number, number basicly N numbers in row separated by "," example thanks for help.
has comment: http://stackoverflow.com/comment/86280088
has comment: http://stackoverflow.com/comment/86281303
answer count: 2
has title: ValueError: setting an array element with a sequence. on data read from csv

http://stackoverflow.com/a/49741121
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86511780
has comment: http://stackoverflow.com/comment/86498245
has body: If you put all your widgets in one frame, inside the window, like this: root=Tk() main=Frame(root) main.pack() widget=Button(main, text='whatever', command=dosomething) widget.pack() etc. Then you can clear the screen like this: main.destroy() main=Frame(root) Or in a button: def clear(): global main, root main.destroy() main=Frame(root) main.pack() clearbtn=Button(main, text='clear', command=clear) clearbtn.pack() To clear the screen.
answers question: http://stackoverflow.com/q/49728308

http://stackoverflow.com/a/49696652
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49638489
has comment: http://stackoverflow.com/comment/86497435
has body: Try import "google/protobuf/timestamp.proto"; This shouldn't happen using the Python grpc_tools, but for other distributions of protoc, protoc might complain, that it does not know where "google/protobuf/timestamp.proto" is. In such case you will need to specify the root to the built-in protobuf files using an -I flag. Why does this work? Based on my experience with protoc (aka. not confirmed with documentation or source code), it looks like when .proto files are compiled to Python, the import statements in .proto change from: import "path/to/file.proto"; To: import path.to.file_pb2 The protobuf compiler does not try to resolve the location of the files (which makes sense, since it is unaware of your Python environment, and does not know where other compiled .proto files are). As of 4/9/2018 the pip grpc package includes built-in protobuf types from the google.protobuf package. That is why we want our imports to include the google/protobuf prefix. Side note Protobuf's import resolution can be especially annoying if you want the root of your compiled .proto project to be different than the root of your Python project (e.g. you might want to store all your protos in a protos package). So far, the only solutions I found to that were: Hack around protoc and add the new root to all import statements (e.g. change import "path/to/file.proto" to import "protos/path/to/file.proto"). This can be done programmatically before each compilation. Add the root of your compiled proto project to your Python path: import sys sys.path.append('path/to/protos_root/')
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86496147
type: Answer
answers question: http://stackoverflow.com/q/49638489
score: 4

http://stackoverflow.com/a/49660569
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86331746
has body: If you have a list (or orther iterable collection) of strings, you can do the following: mylist = [some strings] mylist.sort(key=lambda s: s.strip()) This will sort mylist, ignoring left/right spacing without actually deleting the spaces
answers question: http://stackoverflow.com/q/49660139

http://stackoverflow.com/q/49681446
tagged with: pandas
has title: Selecting multiple rows from a dataframe using a column
upvote count: 1
has answer: http://stackoverflow.com/a/49681506
downvote count: 1
favorite count: 0
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49681506
has body: So, I have a dataframe with a lot of rows and I'm trying to select just a column of some of those rows using a column of data. is there a command that asks for a column with certain values and returns the rows that contain that column? Oh, and I want to select just a column of the rows that are returned.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49681945
possible better answer: http://stackoverflow.com/a/49681945
score: 0

rfid
tag name: rfid
type: Tag
tags question: http://stackoverflow.com/q/49703958

http://stackoverflow.com/a/49733325
upvote count: 1
has comment: http://stackoverflow.com/comment/86490450
type: Answer
has body: Instead of sorting, maybe try different logic when you have to process unsorted array everytime: def get_next_optimized(input_word): # Collect only animals who are alphabetically greater than input word b = [animal for animal in a if animal[0] &gt; input_word[0]] return min(b) if len(b) &gt; 0 else ("No value greater than input") Or else, if you have access to presorted list, try a generator expression - def get_next_optimized_pre_sorted(input_word): next_alphabet_word_generator = (animal for animal in sorted_a if animal[0] &gt; input_word[0]) return next(next_alphabet_word_generator) Keep in mind to do sanity check and validation for input. Specifically for cases where input_word is empty or you could have an empty element in a. Change code to suit your requirements.
answers question: http://stackoverflow.com/q/49711793
score: 1
downvote count: 0

http://stackoverflow.com/a/49743962
has body: So here's the breakdown. The problem, somewhat surprisingly, is caused by tf.contrib.layers.flatten() because it changes the random seed differently in the different versions. There are two ways to seed the random number generator in Tensorflow, either you seed it for the whole graph with tf.set_random_seed() or you can specify a seed argument where it makes sense. As per the docs on tf.set_random_seed(), note point 2: Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds. This sets the graph-level seed. Its interactions with operation-level seeds is as follows: If neither the graph-level nor the operation seed is set: A random seed is used for this op. If the graph-level seed is set, but the operation seed is not: The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence. If the graph-level seed is not set, but the operation seed is set: A default graph-level seed and the specified operation seed are used to determine the random sequence. If both the graph-level and the operation seed are set: Both seeds are used in conjunction to determine the random sequence. In our case the seed is set at the graph level, and Tensorflow does some deterministic calculation to calculate the actual seed to use in the operation. This calculation apparently depends on the number of operations as well. In addition, the implementation of tf.contrib.layers.flatten() has changed exactly between the versions 1.3 and 1.4. You can look it up in the repository, but basically the code was simplified and moved from tensorflow/contrib/layers/python/layers/layers.py into tensorflow/tensorflow/python/layers/core.py, but for us the important part is that it changed the number of operations performed, thereby changing the random seed applied in the Xavier initializer on your fully connected layer. A possible workaround would be specifying the seed for each weight…
accepted answer of: http://stackoverflow.com/q/49742061
has comment: http://stackoverflow.com/comment/86518174
type: Answer
answers question: http://stackoverflow.com/q/49742061
has comment: http://stackoverflow.com/comment/86516348
has comment: http://stackoverflow.com/comment/86517084
downvote count: 0
has comment: http://stackoverflow.com/comment/86525830
type: AcceptedAnswer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/86528856

http://stackoverflow.com/q/49624840
has title: Confusing behavior of np.random.multivariate_normal
has body: I am sampling from a multivariate normal using numpy as follows. mu = [0, 0] cov = np.array([[1, 0.5], [0.5, 1]]).astype(np.float32) np.random.multivariate_normal(mu, cov) It gives me the following warning. RuntimeWarning: covariance is not positive-semidefinite. The matrix is clearly PSD. However, when I use a np.float64 array, it works fine. I need the covariance matrix to be np.float32. What am I doing wrong?
tagged with: python
tagged with: numpy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49625150
has answer: http://stackoverflow.com/a/49625150
downvote count: 0
answer count: 1
favorite count: 0
type: Question
score: 8
upvote count: 8

http://stackoverflow.com/comment/116589682
comment on: http://stackoverflow.com/a/62064145
type: AnswerComment
score: 1
has text: This doesn't solve the problem. I posted now a new question on this: https://stackoverflow.com/questions/65934783/python-debug-adapter-not-being-found-in-vscode-wslubuntu
type: Comment

http://stackoverflow.com/comment/86375920
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49661725
has text: Thanks, i use the toordinal . >>>from datetime import datetime >>> datetime.strptime("2016-10-20", "%Y-%m-%d").toordinal()

http://stackoverflow.com/a/49646148
type: Answer
accepted answer of: http://stackoverflow.com/q/49645721
has comment: http://stackoverflow.com/comment/86301588
answers question: http://stackoverflow.com/q/49645721
downvote count: 0
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86301663
has body: Two things you will need to do: First change your URL's to: path('accounts/profile/&lt;str:slug&gt;/', ProfileDetailView.as_view(), name="to_profile"), Second define the method to get the SlugField class ProfileDetailView(DetailView): model = Profile template_name = "account/profile.html" def get_slug_field(self): """Get the name of a slug field to be used to look up by slug.""" return 'user__username'
score: 7

http://stackoverflow.com/comment/86463282
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49724663
has text: The problem seems to be the commas _inside_ your lambda. Try parenthesizing the whole thing.
score: 1

http://stackoverflow.com/q/49616381
answer count: 1
downvote count: 1
favorite count: 0
tagged with: tree
has body: [scrapy &amp; python] I want to follow and extract all the links located at the xpath (//div[@class="work_area_content"]/a'), and go through all the links using the same xpath until the deepest layer of each link. I've tried using the code below: however, it only goes through main layer and doesn't follow each link. I feel it has something to do with the links variable containing no values in the list. Not sure why the list is empty though. class DatabloggerSpider(CrawlSpider): # The name of the spider name = "jobs" # The domains that are allowed (links to other domains are skipped) allowed_domains = ['1.1.1.1'] # The URLs to start with start_urls = ['1.1.1.1/TestSuites'] # Method for parsing items def parse(self, response): # The list of items that are found on the particular page items = [] # Only extract canonicalized and unique links (with respect to the current page) test_str = response.text # Removes string between two placeholders with regex regex = r"(Back to)(.|\n)*?&lt;br&gt;&lt;br&gt;" regex_response = re.sub(regex, "", test_str) regex_response2 = HtmlResponse(regex_response) ##TODO: fix here! #print(regex_response2) links = LinkExtractor(canonicalize=True, unique=True, restrict_xpaths = ('//div[@class="work_area_content"]/a')).extract_links(regex_response2) print(type(links)) # #Now go through all the found links print(links) for link in links: item = DatabloggerScraperItem() item['url_from'] = response.url item['url_to'] = link.url items.append(item) print(items) yield scrapy.Request(links, callback=self.parse, dont_filter=True) #Return all the found items return items
type: Question
tagged with: python
type: UnansweredQuestion
has title: How to follow multiple links in scrapy?
score: 0
has answer: http://stackoverflow.com/a/49625498
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/q/49616986
has comment: http://stackoverflow.com/comment/86241041
tagged with: python
has body: Using Python 3.6 &amp; Enum Flag (note: Enum is new to v3.4, Flag is new in v3.6) I'm trying to figure out if there is a "automagic" way of assignment of Enum Flags that referenced dictionary by a string. In my case, a JSON config file is loaded with text specifying the Enum Flags but I have to perform a bunch of "if" statements to reassign the node to the actual Enum. The example below works but gets kludgy when you have a a lot of references to udpate. The config file is larger and contains text, numeric, and enums. Sample Code #import json from enum import Enum, Flag class stream_data(Flag): wind= (0x00000001) humidity = (0x00000002) #with open('strings.json') as json_file: # config = json.load(json_file) # Assume we loaded with json.load config = { "options": { "stream": { "capture_rate": "1", "stream_data": "wind", "stream_pull_rate": 5, "stream_type": "binary" } } } print('type before: %s' % type(config['options']['stream']['stream_data'])) if config['options']['stream']['stream_data'] == stream_data.wind.name: config['options']['stream']['stream_data'] = stream_data.wind print('type after: %s' % type(config['options']['stream']['stream_data'])) results: type before: &lt;class 'str'&gt; type after: &lt;enum 'stream_data'&gt; Is there some python magic for this that I am unware of? (I was thinking I could iterate through the dict and enum classes to see if the names match but that also seem a bit kludgy.)
score: 0
has title: Python 3.6 Referencing Enum Flag from config file
has comment: http://stackoverflow.com/comment/86288421
answer count: 1
has comment: http://stackoverflow.com/comment/86242438
has answer: http://stackoverflow.com/a/49617165
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/49749516
has comment: http://stackoverflow.com/comment/86514300
has comment: http://stackoverflow.com/comment/86513892
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49750647
tagged with: url
has comment: http://stackoverflow.com/comment/86514524
tagged with: scrapy
has answer: http://stackoverflow.com/a/49750647
type: Question
has title: Python Scrapy check xpath url image exists
has body: It is possible to check the url of the image extracted with xpath? The idea is to check the url if it's broken or not, if is not, extract the image url, else show a referential image. I have this code: for ntp in response.css('div.content-1col-nobox'): for imgurl in ntp.xpath('//div/p[3]/img/@src'): if imgurl != 404: picUrl = response.urljoin(ntp.xpath('//div/p[3]/img/@src').extract_first()) else: picUrl = ("https://i.ebayimg.com/images/g/ZIMAAOSwImRYLZw9/s-l1600.jpg") writer.writerow({ 'PicURL': picUrl\}) Any help will be appreciate it
tagged with: python
has comment: http://stackoverflow.com/comment/86514795
tagged with: xpath
type: AnsweredQuestion

http://stackoverflow.com/comment/86528458
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49756598
has text: yes, there can be more than one "52" in the string & the string will always start with "6060"

http://stackoverflow.com/comment/86287174
has text: ive been trying this but i get an error saying iter_list[position] cant be interpreted as an integer
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49620109

http://stackoverflow.com/comment/105140449
has text: Noticed an [issue on github](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-java/issues/26) says that the payload hash should be excluded from the v4 signature.
comment on: http://stackoverflow.com/a/50967368
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86486703
type: QuestionComment
has text: Did you make a file in your working directory called `docx.py`? If so, rename it.
comment on: http://stackoverflow.com/q/49735807
type: Comment
score: 0

http://stackoverflow.com/a/49650874
has comment: http://stackoverflow.com/comment/86321617
answers question: http://stackoverflow.com/q/49650214
score: 1
downvote count: 0
has body: Alternatively, you could use pandas (https://pandas.pydata.org/pandas-docs/stable/api.html) (assuming that there are no duplicate lines within each file that you want to keep). import pandas app = pandas.read_csv('applist.csv', encoding="ISO-8859-1") machine = pandas.read_csv('machine.csv', encoding="ISO-8859-1") # Combine both dataframes into one dataframe = app.append(machine, ignore_index=True) # Only keep the first of each set of duplicates # This should give us the machine list (without any of the lines # duplicated in the applist) plus the full applist dataframe.drop_duplicates(keep='first', inplace=True) # Now add the applist again dataframe = dataframe.append(app, ingore_index=True) # Now drop all the duplicates # (since the applist was added again, this should drop the entire applist) dataframe.drop_duplicates(keep=False, inplace=True) dataframe.reset_index(inplace=True) # Now 'dataframe' should be the machine list without any lines from applist If these files are relatively small, then using a loop will be about the same time as using pandas, but if these files large pandas should be significantly faster.
upvote count: 1
has comment: http://stackoverflow.com/comment/86391486
type: Answer
has comment: http://stackoverflow.com/comment/86433570

http://stackoverflow.com/comment/86499138
comment on: http://stackoverflow.com/a/49736558
type: Comment
has text: Ad image datatyp: Usual datatypes for images are uint8, and for some images uint16 where the sensor couldn't get actually beyond 10-14 bit per chanel. 16 bits are usual because this is easier to handle, but this can also be optimized... Check what is really sufficient here. Please make also clear the access pattern and the possibly not so random nonzero places and values in between (this may also get common lossless compression algorithms in front). Your images may also (or not) be somewhat correlated to another. There is no fastest\best compressing algorithm without knowing the exact data.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86505470
has text: Check the answer!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49745012

http://stackoverflow.com/comment/86327449
has text: That sounds very strange have you remembered to save the launch.json file?
type: Comment
comment on: http://stackoverflow.com/a/49639592
type: AnswerComment
score: 1

http://stackoverflow.com/q/49677625
type: UnansweredQuestion
score: 1
tagged with: pickler
tagged with: pickle
tagged with: python
tagged with: python-3.6
answer count: 0
downvote count: 0
upvote count: 1
has body: I am trying to pickle lambdas with the native pickle module by providing custom serializing function as: from six.moves import copyreg import pickle, types copyreg.pickle(types.FunctionType, _custom_pickle_func) However, this doesn't work for following types which pickle supports natively: import pickle pickle._Pickler.dispatch {NoneType: &lt;function pickle._Pickler.save_none&gt;, bool: &lt;function pickle._Pickler.save_bool&gt;, bytes: &lt;function pickle._Pickler.save_bytes&gt;, dict: &lt;function pickle._Pickler.save_dict&gt;, float: &lt;function pickle._Pickler.save_float&gt;, frozenset: &lt;function pickle._Pickler.save_frozenset&gt;, function: &lt;function pickle._Pickler.save_global&gt;, int: &lt;function pickle._Pickler.save_long&gt;, list: &lt;function pickle._Pickler.save_list&gt;, set: &lt;function pickle._Pickler.save_set&gt;, str: &lt;function pickle._Pickler.save_str&gt;, tuple: &lt;function pickle._Pickler.save_tuple&gt;, type: &lt;function pickle._Pickler.save_type&gt;} This is because C{pickle._Pickler} looks for entries in its own dispatch table C{pickle.dispatch} first and then in the C{copyreg.dispath_table}. This prevents our registered handlers to come into play. A workaround here would be to override dispatch functions for native types in both _pickle and pickle. We can do this for pure Python C{pickle._Pickler} as is done by dill, but overriding these entries for _pickle seems impossible as type of _pickle.Pickler.dispatch_table is member_descriptor which doesn’t support assignment from Python interpreter. Please correct me if I am wrong or if there is any way to override for _pickle.
favorite count: 0
type: Question
has title: C implementation _pickle doesn't respect dispatch_table for native types in Python 3.6

http://stackoverflow.com/comment/86329763
has text: Why not get a stronger parser? How are you planning to build a multi-line token with these constraints, regardless of what your regexes look like?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49649606

http://stackoverflow.com/comment/122499321
score: 0
comment on: http://stackoverflow.com/a/57841836
type: Comment
has text: Note than the size of the frequency vector should be `int(1 + nperseg / 2)` like the Gideon Kogan's answer. In the given answer, frequency size is said to be related to sample frequency, but sample frequency does not play a role in the size of the vector, just the mapping of the vector onto frequencies. You can run the example `f, t, Sxx= signal.spectrogram(np.ones(7240320) , sr)` with `sr = 44100` and `sr = 1` and see that the size of f does not change.
type: AnswerComment

http://stackoverflow.com/q/49678099
type: Question
has title: Match multiple keys values to database entry in TinyDB?
has answer: http://stackoverflow.com/a/49823320
possible better answer: http://stackoverflow.com/a/49823320
tagged with: python
has answer: http://stackoverflow.com/a/49823566
accepted answer: http://stackoverflow.com/a/49823566
type: AnsweredQuestion
answer count: 2
has body: I am having a hard time finding out if I can check multiple key values at once with TinyDB. Currently I can check multiple fields by using and in an if statement like this: def check_table(FNAME="NULL", LNAME="NULL", MNAME="NULL"): if (HHK_STAFF.search(Query().FNAME == FNAME)) != [] \ and (HHK_STAFF.search(Query().MNAME == MNAME)) != [] \ and (HHK_STAFF.search(Query().LNAME == LNAME)) != []: print(HHK_STAFF.search(Query().FNAME == FNAME)[0]) else: print("user does not exist") check_table(FNAME="Some", MNAME="Random", LNAME="Person") It does what I want however it seams bulky. I am hoping there is something built into TinyDB that can perform the same function without the need for many and statements. I am trying to do something akin to: HHK_STAFF.search(where(("FNAME", "MNAME", "LNAME")) == (FNAME, MNAME, LNAME))) Question: Is anyone aware of a way to Query() the table for multiple key values instead of just one at a time? Can you list a link to this information? I have had a hard time locating this bit of info if it exist. Here is a simple version of what I am ding with TinyDB: from tinydb import TinyDB, Query #~~~~~~~~~~~~~~~~~~~~~~&lt; CURRENT DBPATH &gt;~~~~~~~~~~~~~~~~~~~~~~ DB = TinyDB('./DB_PATH/HHK_DB.json') #~~~~~~~~~~~~~~~~~~~~~~&lt; CURRENT TABLES &gt;~~~~~~~~~~~~~~~~~~~~~~ HHK_STAFF = DB.table("HHK_STAFF") HHK_STAFF.insert({'EMPLOYEE_ID':'00000001', 'FNAME': 'Some', 'LNAME':'Person', 'MNAME':'Random'}) def check_table(FNAME="NULL", LNAME="NULL", MNAME="NULL"): if (HHK_STAFF.search(Query().FNAME == FNAME)) != [] \ and (HHK_STAFF.search(Query().MNAME == MNAME)) != [] \ and (HHK_STAFF.search(Query().LNAME == LNAME)) != []: print(HHK_STAFF.search(Query().FNAME == FNAME)[0]) else: print("user does not exist") check_table(FNAME="Some", MNAME="Random", LNAME="Person") Results: {'EMPLOYEE_ID': '00000001', 'FNAME': 'Some', 'LNAME': 'Person', 'MNAME': 'Random'}
tagged with: tinydb
score: 7
downvote count: 0
upvote count: 7
favorite count: 0

http://stackoverflow.com/comment/86394726
score: 0
comment on: http://stackoverflow.com/q/49689785
type: Comment
has text: @ Pratik Kumar how can i get results like this ?
type: QuestionComment

http://stackoverflow.com/comment/86422574
comment on: http://stackoverflow.com/a/49704631
type: Comment
has text: @Kronos - Yop, what is your next query?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86294607
type: QuestionComment
type: Comment
has text: The following code worked wget --header='Accept: text/html' http://www.17500.cn/getData/ssq.TXT -O out.txt
score: 1
comment on: http://stackoverflow.com/q/49641112

http://stackoverflow.com/a/49738685
type: Answer
upvote count: 4
downvote count: 0
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/49738552
has body: No, this will not be sufficient in 2018, and even less so in the future. You should tell them to use python3 -m http.server, and that Python 3 is required, but with a note saying they can use SimpleHTTPServer from Python 2 if they have that instead—and probably mentioning than Mac users do already have Python 2 instead. (I'd like to say that you can get away with ignoring Python 2 entirely, because anyone who chooses to use it ought to know what they're doing by this point, but thanks to OS X, you can't quite get away with that yet.) Windows: Users who go to python.org to install Python will be presented with 3.6 as the first choice, and 2.7 as the second choice. And in a year and a half, 2.7 will likely be moved to the "old versions" page along with 3.5 and 2.6. Mac: Python 2.7 comes preinstalled. If they go to python.org, or use Homebrew, they'll be presented with 3.6 as the default, but if they know that they already have Python, they won't try that. And Apple may well keep shipping 2.7 long beyond 2020. Linux: Current versions of most distros have 3.x preinstalled, and some do not have 2.x. And in a year and a half, most of the big ones are planning on relegating 2.x to community-package status. However, there are plenty of people still using older "Long-Term Support" versions of their distros, and these will continue to support (and maybe pre-install) 2.7 until they go out of support, which ranges from 2-8 years from now.
answers question: http://stackoverflow.com/q/49738552

http://stackoverflow.com/comment/86508129
type: QuestionComment
comment on: http://stackoverflow.com/q/49746822
has text: for future reference, it would be helpful if, when you have an error with your code, you actually posted the code that throws the error. The original sample you posted was perfectly fine and you failed to mention that you'd changed it to create the error you were seeing. Had you posted your actual code (with the `is`) originally, your question would have been solved in seconds.
type: Comment
score: 1

http://stackoverflow.com/q/49604569
has comment: http://stackoverflow.com/comment/86219869
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86218927
has body: When I click on text 1, the page does not respond this is urls： from django.conf.urls import url from . import views urlpatterns = [ url(r'$',views.blog_title,name='blog_title'), url(r'(?P<article_id>\d)/$',views.blog_article,name='blog_article'), ] this is views： def blog_article(request,article_id): article = models.BlogArticle.objects.get(id = article_id) return render(request,'blog/article.html',{'article':article}) this is html： {{ article.body }} this is html: {% for blog in blogs %} {{ blog.title }} {% endfor %} this is models： from django.db import models from django.utils import timezone from django.contrib.auth.models import User class BlogArticle(models.Model): title = models.CharField(max_length=300) author = models.ForeignKey(User,related_name='blog_post',on_delete=models.DO_NOTHING) body = models.TextField() pub = models.DateTimeField(default=timezone.now) def __str__(self): return self.title There is my text1 data：enter image description here
accepted answer: http://stackoverflow.com/a/49606717
favorite count: 0
has comment: http://stackoverflow.com/comment/86216615
type: Question
has comment: http://stackoverflow.com/comment/86219780
has answer: http://stackoverflow.com/a/49606717
tagged with: django
has comment: http://stackoverflow.com/comment/86216623
tagged with: python
has comment: http://stackoverflow.com/comment/86216299
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86217450
has title: django：When I click on the text1 page, the page does not jump to my article
has comment: http://stackoverflow.com/comment/86218524
score: 1

http://stackoverflow.com/comment/86375746
type: Comment
has text: @CortAmmon which is why these sorts of questions are discouraged.
type: AnswerComment
comment on: http://stackoverflow.com/a/49679769
score: 2

http://stackoverflow.com/q/49720280
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49720312
has answer: http://stackoverflow.com/a/49720312
tagged with: python
score: -1
tagged with: regex
has body: I have some text: Bounding box for object 1 "PASpersonWalking" (Xmin, Ymin) - (Xmax, Ymax) : (160, 182) - (302, 431) And I need to extract the numbers 160, 182, 302 and 431. I could come up with some splitting etc, but it seems too long. Is there a way to extract it using regexp?
has title: exctracting numbers with regexp
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49720334
answer count: 2
has answer: http://stackoverflow.com/a/49720334
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/86453582

http://stackoverflow.com/q/49609062
type: Question
has body: I am doing handwritten digit recognition using SciKit-learn so for that I need to crop the clicked picture so I have prepared a template on the Word. Now what I want is the image to be cropped along the border so that I can crop it further to extract the digits. Sample Image is given below: For cropping the image I am using this Code. Below is the parent Image from which the above rectangle has been cropped: Note: The parent image has a border too(which is not visible in the image) so trimming the white space might help in getting a modified parent image so that predefined (height, width) would be almost same for various crops to be done on the image.
has title: Trimming the white space in an image using PIL in python
has answer: http://stackoverflow.com/a/49644835
answer count: 1
has comment: http://stackoverflow.com/comment/86227016
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/86226487
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86226310
has comment: http://stackoverflow.com/comment/86227381
accepted answer: http://stackoverflow.com/a/49644835

http://stackoverflow.com/comment/86367999
has text: @PauTrepat If your program is structured so that the determination of what file/folder to read is in its own function/method, then just `mock` out that function/method and tell `mock` to return the one that contains your test data.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49677810
score: 0

http://stackoverflow.com/q/49671124
has answer: http://stackoverflow.com/a/49671299
has comment: http://stackoverflow.com/comment/86352933
has comment: http://stackoverflow.com/comment/86352508
has comment: http://stackoverflow.com/comment/86353461
has title: Matplotlib - Plot does not show after plt.show()
has comment: http://stackoverflow.com/comment/86375547
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/86352760
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/86352515
has body: When trying to plot something using matplotlib, the plot is shown immediately after running plt.plot(), but not after plt.show(). Any changes that were done after plt.plot(), such as added axis labels, also do not show. I tried to run the code in Atom and Rodeo, both did not work. Does anyone know how to fix this? import matplotlib.pyplot as plt year = [1950, 1970, 1990, 2010] pop = [2.519, 3.692, 5.263, 6.972] plt.figure() plt.plot(year,pop) plt.xlabel("Year") plt.ylabel("Population") plt.show()
tagged with: plot

http://stackoverflow.com/comment/86253153
type: Comment
comment on: http://stackoverflow.com/a/49622885
score: 0
type: AnswerComment
has text: @NabihBawazir - Super, nice day!

http://stackoverflow.com/q/49756058
tagged with: pygobject
answer count: 1
tagged with: python
tagged with: gtk3
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49756763
has title: Get number of columns in Gtk.Grid?
has body: My sample code below creates a 2 row x 10 column Grid. The len() of the Grid seems to print the number of widgets within, not the row or column count. How can I get the column count? import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk window = Gtk.Window() window.connect("destroy", Gtk.main_quit) grid = Gtk.Grid(column_homogenous=True) for i in range(5): grid.add(Gtk.Label(str(i))) grid.attach(Gtk.Label("123456789A"), 0, 1, 10, 1) window.add(grid) window.show_all() print(len(grid)) Gtk.main() I have considered the following: Loop over child widgets and find MAX(width + column) Connect to Gtk.Grid signal emitted when column is added and update counter. Problem with (1) is that it seems like it'll be slow when my Grid contains 1000s of children. Problem with (2) is that I don't see a documented signal for this purpose.
downvote count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49756763
upvote count: 3

http://stackoverflow.com/comment/86332429
has text: here is what i see : RESTART: C:\Users\RAKhan\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.5\asadkhan.py None >>>
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49661089

http://stackoverflow.com/q/49739651
has answer: http://stackoverflow.com/a/49739707
accepted answer: http://stackoverflow.com/a/49739707
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: anaconda
score: -2
tagged with: python
tagged with: dictionary
has body: I have three lists (esferas, vdif and valores), forming a dictionary. I want to assign to a new variable, one value from valores, given the value of vdif, which is equal to the maximum or minimum of another list (small). I have tried the next, but it's not working: d = dict(zip(valores, zip(esferas,vdif))) vsup = d['valores' == max[small]] vinf = d['valores' == min[small]] s = d['esferas' == min[dif]] These are the results I would like to have: enter image description here
has title: Obtaining a value from dictionary given certain condition
tagged with: boolean
upvote count: 0
downvote count: 2
answer count: 1
tagged with: key

http://stackoverflow.com/comment/86288965
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49640513
has text: Is that really the full output from `pip`?
type: Comment

http://stackoverflow.com/comment/86230925
type: AnswerComment
has text: `TypeError: class "cookielib.DefaultCookiePolicy" does not have a __new__ method; perhaps it is an old-style class not derived from `object`; add `object` as a base class to encode it` Python 2.7.5
type: Comment
comment on: http://stackoverflow.com/a/49612085
score: 0

http://stackoverflow.com/comment/86330363
comment on: http://stackoverflow.com/q/49660153
type: Comment
type: QuestionComment
has text: I can't figure out a way to do it. I want them [r,g,b][r,g,b]....
score: 0

http://stackoverflow.com/a/49742769
type: Answer
answers question: http://stackoverflow.com/q/49742729
downvote count: 0
upvote count: 1
has body: Could you just use regular python? Let df be your dataframe, and row be the name of your row. series = df.row new_list = [i.split('-')[2] for i in series] new_series = pd.Series(new_list)
has comment: http://stackoverflow.com/comment/86500230
score: 1

http://stackoverflow.com/a/49608206
downvote count: 0
type: Answer
has body: You can sort the 2 different lists and return the concatenation of the 2, like this : def my_sorting(words): x_words = [w for w in words if w and w[0] == 'x'] o_words = [w for w in words if w and w[0] != 'x'] return sorted(x_words) + sorted(o_words) To call the function: l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] sorted_l = my_sorting(l) print(sorted_l) The result is : ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49608160

http://stackoverflow.com/comment/86536583
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49757799
has text: Normally the circular plot should visualize a probability distribution over the possible continuations of the blue line. So the coordinates of the blue line must stay the same.
type: Comment

http://stackoverflow.com/comment/86244012
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49618400
has text: @user3.1415927 No, they are the same in list-comps and yes it does take some getting used to :)

http://stackoverflow.com/q/49702465
has answer: http://stackoverflow.com/a/49702624
accepted answer: http://stackoverflow.com/a/49702624
type: Question
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: python
tagged with: python-3.x
has body: I have a csv file of weather station data which has non continuous timestamps: logstamp temp rh snow wind gust wind_dir 2018-01-26 21:00:00 -10.120 63.93 207.1 4.018 9.806 173.900 2018-01-26 22:00:00 -9.750 58.54 207.0 3.856 11.149 158.500 2018-01-26 23:00:00 -9.710 60.92 206.9 6.505 13.759 159.100 2018-01-27 00:00:00 -10.110 57.45 206.7 6.602 12.488 167.700 2018-01-28 13:00:00 -7.574 84.90 212.4 5.594 15.736 134.100 2018-01-28 14:00:00 -4.347 88.20 213.1 5.663 15.242 170.700 2018-01-28 15:00:00 -1.360 89.30 213.0 4.896 19.051 175.300 I would like to use the pandas reindex function to add rows where there are missing timestamps so I can interpolate data for the missing times. For example our weather station cuts out Jan 27 in the above table. I tried using the reindex function with pandas. This results in new interpolated rows for the missing times, however it turns all of the original column data to NaN. ts1 = pd.read_csv("mtmaya-2018-02-20.csv", index_col='logstamp', infer_datetime_format='TRUE') index = pd.date_range(ts1.index.min(),ts1.index.max(), freq="H") ts1 = ts1.reindex(index) air temp rh snow wind spd wind spd max wind dir \ 2018-01-25 14:00:00 NaN NaN NaN NaN NaN NaN 2018-01-25 15:00:00 NaN NaN NaN NaN NaN NaN 2018-01-25 16:00:00 NaN NaN NaN NaN NaN NaN I assume I am missing something.
answer count: 1
has title: Pandas reindex turning all non-index columns to NaN

http://stackoverflow.com/q/49710186
upvote count: 2
tagged with: pyqt
has body: I'm still quite a newbie with Python and PyQt5, so I have a really basic question. My idea is to build application to download a URL. Here is a picture of my design: When I right click on the URL from any website, copy it, and go to my application and press on icon on toolbar named (Add URL), the URL should be pasted immediately inside the QLineEdit. Here is my code: from PyQt5.QtWidgets import* from PyQt5.QtCore import* from PyQt5.QtGui import* from PyQt5.uic import loadUiType from PyQt5.QtWidgets import QApplication ,QMainWindow,QAction from os import path import sys FORM_CLASS,_= loadUiType(path.join(path.dirname(__file__),"main.ui")) class MainApp(QMainWindow , FORM_CLASS): def __init__(self, parent=None): super(MainApp, self).__init__(parent) QMainWindow.__init__(self) self.setupUi(self) self.idm_UI() self.idm_Buttons() def idm_UI(self): self.setWindowTitle("Download URL") self.setFixedSize(631,400) self.setWindowIcon(QIcon("download.jpg")) # To Create the Icone exitAct = QAction(QIcon('exit.png'),'Exit',self) exitAct.triggered.connect(self.idm_exit) pasteAction = QAction(QIcon("paste.png"), "Add URL", self) pasteAction.triggered.connect(self.idm_add) self.toolbar = self.addToolBar('Toolbar') self.toolbar.addAction(exitAct) self.toolbar.addAction(pasteAction) def idm_exit(self): self.close() def idm_add(self): # What is the right method that I can use to paste the URL inside lineEdit_4? pass The name of define method of function is def def idm_add(self): So, what function or method do I need to use to paste the URL inside the LineEditor box?
tagged with: qclipboard
has answer: http://stackoverflow.com/a/49710298
downvote count: 0
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
has title: copy from clipboard
type: AnsweredQuestion
tagged with: python
score: 2
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49710298

http://stackoverflow.com/a/49624959
score: 0
has body: You need to perform split on f depending on the delimiter and iterate over it. import sys strcmd = "curve -d 3" f = open("cam_data.dex","r") for line in f.split(): (x,y,z)=line.split(",") strcmd = strcmd+" -p"+" "+x+" "+y+" "+z.rstrip() print(strcmd) print("\nDONE\n") # curve -d 3 -p 1 2 3 -p 3 2 1 -p 4 5 6 -p 6 5 4 -p 7 8 9 -p 9 8 7 # DONE
answers question: http://stackoverflow.com/q/49624660
type: Answer

http://stackoverflow.com/comment/86342339
comment on: http://stackoverflow.com/q/49666036
has text: Thanks. But this does not answers my questions. The case indicated there could be done by 2 loops, what if i have 10 or 20 or even X numbers of nested lists? Also i have here INT so second loop will not work as python cannot iterate through INT.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49634659
has comment: http://stackoverflow.com/comment/86287195
answers question: http://stackoverflow.com/q/49633321
type: Answer
has body: I generated synthetic data and trained with your codes. The NaN issue doesn't occur to me. You probably need to check your data to see if there're any corruptions. Another thing to try is to only keep one Conv/Pooling/Dropout layer and see if the issue still occurs.
has comment: http://stackoverflow.com/comment/86287453
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49669965
type: Answer
accepted answer of: http://stackoverflow.com/q/49669856
score: 0
has comment: http://stackoverflow.com/comment/86350163
has body: By creating a function: import random def randMerge(l:list, count:int) -&gt; list: """Returns the input list expanded by a joined element consisting of count elements from itself (no repeats allowed)""" return l + [''.join(random.sample(l,k=count))] and calling it repeatedly: num = 2 aList = ['A','B','C','D'] newList = aList[:] for _ in range(6): print(newList) newList = randMerge(newList,num) print(newList) Output: ['A', 'B', 'C', 'D'] ['A', 'B', 'C', 'D', 'DC'] ['A', 'B', 'C', 'D', 'DC', 'ADC'] ['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD'] ['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA'] ['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA', 'CDC'] ['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA', 'CDC', 'ADCCDC']
upvote count: 1
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/49669856

http://stackoverflow.com/a/49608006
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49607824
score: 1
type: Answer
has body: As Paul Panzer commented, this can be done simply by B[...] = A.

http://stackoverflow.com/q/49643737
favorite count: 0
tagged with: datetime-format
accepted answer: http://stackoverflow.com/a/49644087
type: AnsweredQuestion
score: 1
tagged with: epoch
has title: 'Unknown' timestamp format while converting in epoch
tagged with: python
has answer: http://stackoverflow.com/a/49644087
type: Question
tagged with: python-3.x
upvote count: 1
downvote count: 0
answer count: 1
has body: I want to convert this '2018-03-15T05:13:24.000-0400' datetime format to the epoch time format. While converting I am getting the time format error. Plz help me with this issue. Here is my python Code: import time start='2018-03-15T05:13:24.000-0400' start1 = str(start) start_date = int(time.mktime(time.strptime(start1,'%Y-%m-%d %H:%M:%S')))*1000 print(start_date) Expecting output: 1521105204000 Thanks :)

http://stackoverflow.com/q/49617213
downvote count: 1
has title: Is this Python regex good enough for email address?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86243231
has comment: http://stackoverflow.com/comment/86241412
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/201323
has comment: http://stackoverflow.com/comment/86242457
upvote count: 1
tagged with: python
tagged with: regex
has body: I have been reviewing regex for Python3 to capture an email address. I have seen the doc on the popular regular-expressions website. And read the pydocs, SO answers, etc. I would like to know if this regex is good enough to capture an email address or if I am missing something. re.findall(r'[\w.+-]+@[\w.+-]+', some_string)
has comment: http://stackoverflow.com/comment/86245584
duplicate of: http://stackoverflow.com/q/8022530
score: 0
has comment: http://stackoverflow.com/comment/86243420
answer count: 1
linked to: http://stackoverflow.com/q/8022530
has answer: http://stackoverflow.com/a/49617261
has comment: http://stackoverflow.com/comment/86242348

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/49713433
tags question: http://stackoverflow.com/q/49657362
tag name: matplotlib-basemap

http://stackoverflow.com/comment/86655147
score: 0
type: AnswerComment
has text: This is great! It is definitely possible to crop the image to get rid of the labels and extra info or even get individual legs. I'll try this out now. Thank you for this, this is exactly what I was looking for!
type: Comment
comment on: http://stackoverflow.com/a/49756009

http://stackoverflow.com/comment/86488335
type: Comment
comment on: http://stackoverflow.com/q/49736782
type: QuestionComment
has text: @jasonharper i have tried print e1.get() outside, but it still doesn't work....
score: 0

http://stackoverflow.com/q/49619817
has comment: http://stackoverflow.com/comment/86270890
has body: Where/how does one hook up a custom provider URL patterns? I can't find anywhere in the code that automatically installs the providers... e.g. allauth.socialaccount.providers.shopify URLs. My custom provider worked on older versions like 0.2x.x but now I am getting reversal errors in the provider list template because the URLs are not registered
tagged with: python
type: AnsweredQuestion
upvote count: 2
tagged with: django
score: 1
has comment: http://stackoverflow.com/comment/86246657
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49632710
has comment: http://stackoverflow.com/comment/86247286
favorite count: 0
has title: Allauth Custom Provider URLs
type: Question
tagged with: django-allauth
accepted answer: http://stackoverflow.com/a/49632710

http://stackoverflow.com/q/49697737
has comment: http://stackoverflow.com/comment/86411959
has body: I would like to create a tree style structure from a dataframe in Python. The desired output would look something like this: { "Cat1": { "Band1" : { "PE1": { "1995-01": { "GroupCalcs": { "Count": 382.0, "EqWghtRtn": -0.015839621267015727, "Idx_EqWghtRtn": 0.9841603787329842, "Idx_WghtRtn": 0.9759766819565102, "WghtRtn": -0.02402331804348973 } }, "1995-02": { "GroupCalcs": { "Count": 382.0, "EqWghtRtn": -0.015839621267015727, "Idx_EqWghtRtn": 0.9841603787329842, "Idx_WghtRtn": 0.9759766819565102, "WghtRtn": -0.02402331804348973 } } } } } I am looking for the most efficient way of building this from a Dataframe. I have 20k+ rows to parse out which currently look like this snippet Data Snippett I was thinking something like this but I know this is very inefficient. dctcat = {} for cat in alldf.index.levels[0]: dctMktBand = {} for mktband in alldf.index.levels[1]: dctpe = {} for pe in alldf.index.levels[2]: dctMonth = {} for month in alldf.index.levels[3]: dctMonth[month]=alldf.loccat,mktband,pe,month.filter(items=['Count', 'EqWghtRtn', 'Idx_EqWghtRtn','Idx_WghtRtn', 'WghtRtn']).to_dict() dctpe[str(pe)]=dctMonth dctMktBand[str(mktband)] = dctpe dctcat[str(cat)] = dctpe Possible Solution I stumbled across this article https://gist.github.com/hrldcpr/2012250 and using defauldict(tree) I was able to accomplish what I needed in under 2 seconds. Which while that sounds long, it is considerably faster than what I had. Sharing the code below, if someone has updates or improvements on this I would appreciate it. def tree(): return defaultdict(tree) def dicts(t): if isinstance(t ,defaultdict): outval = {k: dicts(t[k]) for k in t } else: outval = t return outval alldf.set_index(['category','marketCapBand','peGreaterThanMarket','Month'], inplace=True) tmp = alldf.filter(items=['Count', 'EqWghtRtn', 'Idx_EqWghtRtn','Idx_WghtRtn', 'WghtRtn']).to_dict('index') outjson = tree() for k,v in tmp.items(): (cat,mkb,pe,mon) = k outjson[str(cat)][str(mkb)][str(pe)][str(mon)] = v # conver…
favorite count: 0
score: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/86416461
tagged with: dataframe
tagged with: python
has title: Dataframe to JSON in tree format?
has comment: http://stackoverflow.com/comment/86417054
type: Question
has comment: http://stackoverflow.com/comment/86413392
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49630374
accepted answer: http://stackoverflow.com/a/49637532
has comment: http://stackoverflow.com/comment/86269757
has title: Scrapy add.xpath or join xpath
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has body: I hope everyone is doing well. I have this code(part of it) for a spider, now this is the last part of the scraping, here it start to scrape and then write in the csv file, so I got this doubdt, it is possible to join or add xpath with the result printed in the file, for example: Soundbooster Filtro attuale Catalogo: Aliant Marca e Modello: Mazda - 3 Versione: (3th gen) 2013-now (Petrol) I want to join the following for one field in the csv file, should be something like this: Soundbooster per Mazda - 3 - (3th gen) 2013-now (Petrol) And here it is where I am lost, It is possible? I don't know if I have to use add.xpath or join or another method and how to use it right. This is part of my code: def parse_content_details(self, response): exists = os.path.isfile("ntp/ntp_aliant.csv") with open("ntp/ntp_aliant.csv", "a+", newline='') as csvfile: fieldnames = ['*Action(SiteID=Italy|Country=IT|Currency=EUR|Version=745|CC=UTF-8)','*Category','*Title','Model','ConditionID','PostalCode',\ 'VATPercent','*C:Marca','Product:EAN','*C:MPN','PicURL', 'Description','*Format','*Duration','StartPrice','*Quantity','PayPalAccepted','PayPalEmailAddress',\ 'PaymentInstructions','*Location','ShippingService-1:FreeShipping', 'ShippingService-1:Option','ShippingService-1:Cost', 'ShippingService-1:Priority',\ 'ShippingService-2:Option','ShippingService-2:Cost','ShippingService-2:Priority','ShippingService-3:Option','ShippingService-3:Cost',\ 'ShippingService-3:Priority','ShippingService-4:Option','ShippingService-4:Cost','ShippingService-4:Priority','*DispatchTimeMax',\ '*ReturnsAcceptedOption','ReturnsWithinOption','RefundOption','ShippingCostPaidByOption'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) if not exists: writer.writeheader() for ntp in response.css('div.content-1col-nobox'): name = ntp.xpath('normalize-space(//h5/text())').extract_first() brand = ntp.xpath('normalize-space(//div/blockquote[1]/p/text()[4])').extract_first() version = ntp.xpath('normalize-space(//div/bl…
tagged with: scrapy
type: Question
tagged with: xpath
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49637532
score: 0

http://stackoverflow.com/comment/86409904
score: 0
has text: Are the arrays `get_heuristics` returns different in size? Numpy can only process arrays where the sublists have the same size. In the other case, it will generate a 1d array of references to arrays, but that is *not* the same. (In C#, that would be the difference between `float[][]`, and `float[,]`).,
type: QuestionComment
comment on: http://stackoverflow.com/q/49698418
type: Comment

http://stackoverflow.com/comment/127566674
comment on: http://stackoverflow.com/a/49728484
type: Comment
type: AnswerComment
has text: "Sorry, you are right. First line works. The problem for my warning was a filtering of the original data." That is the most important information here.
score: 0

http://stackoverflow.com/q/49623927
answer count: 1
has title: Yii2 MongoDB Aggregation Error
has body: How can I resolve following error on Yii collection aggregate: “each item in the pipeline must be a document” with this code: $collection = Yii::$app-&gt;mongodb-&gt;getCollection('lc_executive_allocate'); $asCursor = true; $result = $collection-&gt;aggregate([ [ '$match' =&gt; [ 'stage' =&gt; '2', 'completed' =&gt; '1', 'status' =&gt; '1', 'assignedOn' =&gt; ['$gte' =&gt; '2018-03-01', '$lte' =&gt; '2018-03-29'], ], ], [ '$group' =&gt; [ '_id' =&gt; ['userId' =&gt; '$userId', 'count' =&gt; ['$sum' =&gt; '1']], ], ], ['$sort' =&gt; ['count' =&gt; '-1']], ['$limit' =&gt; '1'], $asCursor, ]);
score: -2
has answer: http://stackoverflow.com/a/49821498
favorite count: 0
tagged with: mongodb
type: Question
linked to: http://stackoverflow.com/q/5963269
upvote count: 0
tagged with: yii2
downvote count: 2
has comment: http://stackoverflow.com/comment/86254780
tagged with: python
type: UnansweredQuestion
tagged with: php

http://stackoverflow.com/q/49697991
type: Question
accepted answer: http://stackoverflow.com/a/49699125
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
answer count: 1
has body: I have a dataframe that index is date in format(2017_01_31,....) and I have a column called 'Energy' and three other columns 'I_Base','U_Win', 'Occ'. I want to have a scatter plot of each with y set to be 'Energ' but for the condition that index is January. I tried the following code but its totally wrong. fig, r = plt.subplots(nrows=1, ncols=3, figsize=(14,4)) for index, xcol, ax in zip(r.index.month==1,['U_Win', 'I_Base', 'Occ'], r): df.plot(kind='scatter', x=xcol, y='Energy', ax=ax, alpha=0.5, color='r') Thats how my dataframe is : Index I_Base U_Win Energy Occ 2017_01_31 0.3 0.9 2.2989e+11 96 2017_01_31 0.5 0.8 2.29892e+11 40 .... 2017_02_28 0.7 0.9 2.40001e+11 80 ....
has title: plotting subplots in pandas with month as index
has answer: http://stackoverflow.com/a/49699125

http://stackoverflow.com/comment/86260471
has text: As mentioned here `input()` evaluates what you enter as Python code and then thinks it's a tuple because of the comma. Use `raw_input()`. https://stackoverflow.com/a/4960216/102315
comment on: http://stackoverflow.com/q/49626726
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/49757211
upvote count: 25
answers question: http://stackoverflow.com/q/49756646
type: Answer
has comment: http://stackoverflow.com/comment/86530573
has comment: http://stackoverflow.com/comment/86529891
has comment: http://stackoverflow.com/comment/86530194
score: 25
has comment: http://stackoverflow.com/comment/86529614
has body: There are two meanings of “built-in” here, although they both mean “part of the interpreter”. The library reference uses it to indicate that a function is available without an import (it is “not part of a module”, although see builtins). The interpreter itself uses it to indicate that a function is implemented natively rather than in Python (in CPython, it is at least nominally implemented in C). There is yet another meaning on the C side: an extension module (i.e., one written in C) is built-in if the Python binary incorporates it rather than loading it if and when needed.
downvote count: 0
has comment: http://stackoverflow.com/comment/86529722

http://stackoverflow.com/q/49716853
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49716972
downvote count: 0
tagged with: image-processing
has answer: http://stackoverflow.com/a/49721635
possible better answer: http://stackoverflow.com/a/49721635
favorite count: 0
type: Question
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/49716972
has title: Opencv python - check if particular pixel value in image
has body: Lets say I have an image in opencv. E.g. img = cv2.imread(file_path) Lets also say I have a pixel value. E.g. pixel = np.array([200,200,200]) I want to know if there is any pixel in img with the value of pixel. What is the best way to do this? I tried img.any(pixel) but that doesn't work. I know you can probably manually check using loops, but I'm sure a more elegant way must exist. I just need a boolean yes or no response.
tagged with: python
has comment: http://stackoverflow.com/comment/106663705
tagged with: opencv

http://stackoverflow.com/a/53241091
downvote count: 0
upvote count: 1
has body: It is due to Nan values; try to remove or substitute them and check whether it works.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49649675

http://stackoverflow.com/comment/86511088
score: 0
has text: Are you trying to run the program under Python 2 or 3?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49748278

http://stackoverflow.com/a/49726245
has comment: http://stackoverflow.com/comment/86466659
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49726089
score: 1
has comment: http://stackoverflow.com/comment/86466589
has comment: http://stackoverflow.com/comment/86468133
type: Answer
has comment: http://stackoverflow.com/comment/86468018
answers question: http://stackoverflow.com/q/49726089
has body: You can do something like: models from your_app.mixins import ValidationMixin class YourSerializer(ModelSerializer, ValidationMixin): def create(self, validated_data): # First check self.raise_if_something_wrong(validated_data['value']) # Second check self.get_object_if_exist(validated_data['title']) # This will happen ONLY if your previous check's were ok your_model = YourModel.objects.create( **validated_data ) return your_model mixins from django.conf import settings from rest_framework.serializers import ValidationError class ValidationMixin: def raise_if_something_wrong(self, value): if value not in settings.UNIT_OF_MEASURE_NAME: raise ValidationError( 'Invalid' ) else: pass def get_object_if_exist(self, obj_title): try: return YourModel.objects.get(title=obj_title) except YourModel.DoesNotExist: raise ValidationError( 'Cant get that object' ) settings Also add this to your project's main settings.py file, keep it like a tuple: UNIT_OF_MEASURE_NAME = ( 'Each', 'Grams', 'Ounces', 'Pounds', 'Kilograms', 'Metric Tons' ) As a result you will be able to use ValidationMixin wherever you want to validate data, and keep validation logic in one place.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86466566

http://stackoverflow.com/comment/86229842
type: Comment
comment on: http://stackoverflow.com/q/49611608
score: 1
type: QuestionComment
has text: use different name instead of import "use_model as model" . Try using import use_model as model1 or any other name and then use model1.preprocess(data)

http://stackoverflow.com/a/49616454
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49615844
has body: The problem is that initially you connect to the QFontComboBox and QComBoBox correctly: ... fontBox.currentFontChanged.connect(self.FontFamily) ... fontSize.activated.connect(self.FontSize) but then you connect the triggered signals with the same functions, and since the combobox is never seen, only the triggered signal is emited: font_family = QtGui.QAction("&amp;Font", self) font_family.triggered.connect(self.FontFamily) #Font Size Input font_size = QtGui.QAction("&amp;Font Size", self) font_size.triggered.connect(self.FontSize) What you must do is that the Settings menu must have 2 sub-menus that open the QFontComboBox and QComboBox widgets, respectively, but to include these widgets in the submenus you must use QWidgetAction: class Window(QtGui.QMainWindow): #Window Settings def __init__(self): ... #Font Family Input #Settings Menubar settings = menubar.addMenu('&amp;Settings') menu_font = settings.addMenu("&amp;Font") font_family = QtGui.QWidgetAction(self) font_family.setDefaultWidget(fontBox) menu_font.addAction(font_family) font_size = QtGui.QWidgetAction(self) font_size.setDefaultWidget(fontSize) menu_size = settings.addMenu("&amp;Font Size") menu_size.addAction(font_size) self.toolbar() ...
has comment: http://stackoverflow.com/comment/86240013
answers question: http://stackoverflow.com/q/49615844
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49727254
tagged with: python
accepted answer: http://stackoverflow.com/a/49732953
score: -1
has comment: http://stackoverflow.com/comment/86469831
type: AnsweredQuestion
has title: python : sqlalchemy batch insert with on_conflict_update
has comment: http://stackoverflow.com/comment/86468896
tagged with: psql
upvote count: 0
linked to: http://stackoverflow.com/q/44864985
answer count: 1
downvote count: 1
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/86469448
favorite count: 0
has answer: http://stackoverflow.com/a/49732953
type: Question
has comment: http://stackoverflow.com/comment/86472553
has body: I have to insert approx. 30000 rows daily in my postgres database, I have 4 columns in my database namely : id(pkey), category, createddate, updatedon. My requirement is to update updatedon and category column with today's date and new category if id is present, else insert a new row with createddate and updateon being same. I found Ilja Everilä's [answer]:https://stackoverflow.com/a/44865375/5665430 for batch update insert_statement = sqlalchemy.dialects.postgresql.insert(id_tag) upsert_statement = insert_statement.on_conflict_do_update( constraint='id', set_={ "createddate": insert_statement.excluded.createddate } ) insert_values = df.to_dict(orient='records') conn.execute(upsert_statement, insert_values) Its throwing AttributeError, Traceback (most recent call last): File "&lt;ipython-input-60-4c5e5e0daf14&gt;", line 5, in &lt;module&gt; set_= dict(createddate = insert_statement.excluded.createddate) File "/home/bluepi/anaconda2/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 764, in __get__ obj.__dict__[self.__name__] = result = self.fget(obj) File "/home/bluepi/anaconda2/lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/dml.py", line 43, in excluded return alias(self.table, name='excluded').columns File "/home/bluepi/anaconda2/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py", line 161, in alias return _interpret_as_from(selectable).alias(name=name, flat=flat) AttributeError: 'TextClause' object has no attribute 'alias' I have tried one by one update as shown here http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#postgresql-insert-on-conflict , but I am getting the same error. Please help me understand where I am going wrong, thanks in advance.
has comment: http://stackoverflow.com/comment/86475606

http://stackoverflow.com/a/49610304
score: 2
has comment: http://stackoverflow.com/comment/86256050
type: Answer
upvote count: 2
has body: You need to set the authorization header in Postman as JWT &lt;your_token_here&gt;. See the curl example in http://getblimp.github.io/django-rest-framework-jwt/: $ curl -H "Authorization: JWT your_token" http://localhost:8000/protected-url/
accepted answer of: http://stackoverflow.com/q/49610120
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49610120

http://stackoverflow.com/q/49640513
has comment: http://stackoverflow.com/comment/86289066
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86289094
tagged with: pip
has answer: http://stackoverflow.com/a/64549704
has comment: http://stackoverflow.com/comment/86288857
has answer: http://stackoverflow.com/a/70923999
downvote count: 1
has comment: http://stackoverflow.com/comment/86288927
favorite count: 0
has comment: http://stackoverflow.com/comment/86289189
type: Question
has comment: http://stackoverflow.com/comment/86288785
has title: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position X: character maps to <undefined>
answer count: 5
score: 21
has answer: http://stackoverflow.com/a/78214473
has answer: http://stackoverflow.com/a/49642852
has comment: http://stackoverflow.com/comment/86288965
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/86289007
has comment: http://stackoverflow.com/comment/86289103
upvote count: 22
has comment: http://stackoverflow.com/comment/86288718
has body: When I'm trying to install StringGenerator with pip, I am prompted with this error: C:\Users\Administrator&gt; pip install StringGenerator Collecting StringGenerator Using cached StringGenerator-0.3.0.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 "C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-build-mdvrj2cf\StringGenerator\setup.py", line 7, in &lt;module&gt; long_description = file.read() File "c:\users\administrator\appdata\local\programs\python\python36-32\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 0x9d in position 1264: character maps to &lt;undefined&gt; ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-build-mdvrj2cf\StringGenerator\
has answer: http://stackoverflow.com/a/49640648

http://stackoverflow.com/a/49657730
upvote count: 1
has comment: http://stackoverflow.com/comment/86340168
has comment: http://stackoverflow.com/comment/86381341
has comment: http://stackoverflow.com/comment/86340103
has comment: http://stackoverflow.com/comment/86368724
type: Answer
answers question: http://stackoverflow.com/q/49653274
has body: Looking at the provided traceback, you can see the exception is being raised on the line while 'extranet.chem' not in driver.title:: File "scraper.py", line 55, in get_table while 'extranet.chem' not in driver.title: which is not in a try/except block. I'm not sure i've seen that exact exception raised while checking driver.title, but i suppose it is normal. Without knowing anything about the page you are working with, we aren't able to help you much more than that. your option is to catch the exception that is generated at that line. with an alert box being present, you will more than likely be prevented from navigating away from or refreshing that page until the alert is dealt with. you should build in a way to handle the alert.
downvote count: 0
score: 1

http://stackoverflow.com/q/49602048
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86211729
favorite count: 0
type: Question
tagged with: xpath
accepted answer: http://stackoverflow.com/a/49602508
has answer: http://stackoverflow.com/a/49602508
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86211556
has body: I'm trying to get the xpath of an element in site https://www.tradingview.com/symbols/BTCUSD/technicals/ Specifically the result under the summary speedometer. Whether it's buy or sell. Speedometer Using Google Chrome xpath I get the result //*[@id="technicals-root"]/div/div/div[2]/div[2]/span[2] and to try and get that data in python I plugged it into from lxml import html import requests page = requests.get('https://www.tradingview.com/symbols/BTCUSD/technicals/') tree = html.fromstring(page.content) status = tree.xpath('//*[@id="technicals-root"]/div/div/div[2]/div[2]/span[2]/text()') When I print status I get an empty array. But it doesn't seem like anything is wrong with the xpath. I've read that google does some shenanigans with incorrectly written HTML tables which will output the wrong xpath but that doesn't seem to be the issue.
has comment: http://stackoverflow.com/comment/86211520
type: AnsweredQuestion
has title: Python print Xpath element gives empty array
upvote count: 0

http://stackoverflow.com/q/49740461
answer count: 2
linked to: http://stackoverflow.com/q/1346034
has body: Related to Determine the endianness of a numpy array Given an array x = np.arange(3) I can get the byte order by doing &gt;&gt;&gt; x.dtype.byteorder '=' How do I find out if this is big or little endian? I would like to get '&lt;', '&gt;' or '|' as the output, not '='. To be clear, I am not hung up on what format the information comes in. I just want to know "big endian", "little endian" or "irrelevant", but I don't care if it's "native" or not.
downvote count: 0
tagged with: python
upvote count: 7
tagged with: endianness
accepted answer: http://stackoverflow.com/a/49740608
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86495530
score: 7
has answer: http://stackoverflow.com/a/49740663
possible better answer: http://stackoverflow.com/a/49740663
has comment: http://stackoverflow.com/comment/86495642
has title: How to get endianness of numpy dtype
favorite count: 0
has answer: http://stackoverflow.com/a/49740608
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86495495
linked to: http://stackoverflow.com/q/34097845

http://stackoverflow.com/q/49634567
has comment: http://stackoverflow.com/comment/86276728
has comment: http://stackoverflow.com/comment/86278706
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49635759
downvote count: 0
has body: I extract the features with the compute() function and add them to a list. I then try to convert all the features to float32 using NumPy so that they can be used with OpenCV for classification. The error I am getting is: ValueError: setting an array element with a sequence. Not really sure what I can do about this. I am following a book and doing the same steps except they use HOS to extract the features. I am extracting the features and getting back matrices of inconsistent sizes and am not sure how I can make them all equal. Related code (which might have minor syntax errors cause I truncated it from the original code): def get_SURF_feature_vector(area_of_interest, surf): # Detect the key points in the image key_points = surf.detect(area_of_interest); # Create array of zeros with the same shape and type as a given array image_key_points = np.zeros_like(area_of_interest); # Draw key points on the image image_key_points = cv2.drawKeypoints(area_of_interest, key_points, image_key_points, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Create feature discriptors key_points, feature_descriptors = surf.compute(area_of_interest, key_points); # Plot Image and descriptors # plt.imshow(image_key_points); # Return computed feature description matrix return feature_descriptors; for x in range(0, len(data)): feature_list.append(get_SURF_feature_vector(area_of_interest[x], surf)); list_of_features = np.array(list_of_features, dtype = np.float32);
score: 1
upvote count: 1
has title: Converting OpenCV SURF features to float32 arrays in Python
answer count: 1
linked to: http://stackoverflow.com/q/13310347
favorite count: 0
type: Question
tagged with: numpy
tagged with: opencv
has comment: http://stackoverflow.com/comment/86277887
accepted answer: http://stackoverflow.com/a/49635759
tagged with: surf
tagged with: python

http://stackoverflow.com/comment/86246309
type: Comment
comment on: http://stackoverflow.com/q/49617350
score: 0
has text: Maybe [`warp_coords`](http://scikit-image.org/docs/dev/api/skimage.transform.html#warp-coords) is what you're looking for?
type: QuestionComment

http://stackoverflow.com/comment/86551368
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49751512
has text: @ps0604 - Do you need finally ouput like `merged` only added `df_c` ? I think it is not possible in pandas, because native dont supported. Also `merge` by multiple dataframes is possible only in `reduce` hack in same columns names, also not native supported. So sorry. :(

http://stackoverflow.com/a/49690960
has comment: http://stackoverflow.com/comment/86394063
has comment: http://stackoverflow.com/comment/86393901
downvote count: 0
score: 4
has body: In Python 3.4 we got some statistic functions in the standard library, including statistics.mean. Using this function and a generator-expression: from statistics import mean a = [1, 2, 3, 4] b = [1, 1, 1, 1] mean(abs(x - y) for x, y in zip(a, b)) # 1.5
type: Answer
has comment: http://stackoverflow.com/comment/86393995
answers question: http://stackoverflow.com/q/49690851
upvote count: 4

http://stackoverflow.com/comment/86404583
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49695909
has text: do `userinput = [int(x) for x in input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> ")]`

http://stackoverflow.com/a/49746657
upvote count: 2
answers question: http://stackoverflow.com/q/49746487
type: Answer
has body: In Python 3, the zip() function returns an iterator, meaning that you can only exhaust elements once, whereas Python 2 returns an iterable itself. see here: Python 2 Doc, Python 3 Doc
score: 2
downvote count: 0

http://stackoverflow.com/a/49672408
has body: Replace _currentRoom = 'Entrance'_ with currentRoom = 'Entrance'
type: Answer
answers question: http://stackoverflow.com/q/49672351
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/86344753
comment on: http://stackoverflow.com/q/49664523
score: 0
type: Comment
type: QuestionComment
has text: I managed to shorten it to about 20 minutes. What's fast with cdist is if you do it with two lists, so I batched my path into chunks of 1000 and did cdist(path[x:x+1000], map) and it sped up immensely.

http://stackoverflow.com/q/49641435
type: Question
has comment: http://stackoverflow.com/comment/86368566
type: UnansweredQuestion
has title: Error when fetching PDB files
tagged with: python
tagged with: biopython
has answer: http://stackoverflow.com/a/49679149
score: 0
has comment: http://stackoverflow.com/comment/86369270
has body: I'm trying to download PDB files using Bio.PDB module (BioPython). The list of accession numbers is coming from a pandas DataFrame. This is the code I'm currently using: def get_pdb(accession, dir='/Users/my_folder'): pdb1 = PDBList() pdb1.retrieve_pdb_file(accession, pdir=dir) for i in df.loc[:, 'Structure_(PDB)_id']: get_pdb(i) The code was able to download 2 files to my_folder, but after that, this error appeared: 550 Can\'t change directory to pdb1p87.ent.gz: No such file or directory Any help or hints of what's going on? It could be an FTP issue?
answer count: 1
has comment: http://stackoverflow.com/comment/86365551

http://stackoverflow.com/a/49696677
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49694895
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: You can call the function that boxplot uses to calculate the data. I have always had good luck looking and searching through the Matplotlib source to find how it does stuff. boxplot uses the function matplotlib.cbook.boxplot_stats to do the calcs. You can call this function yourself and inspect the returned data: from matplotlib import cbook print(help(cbook.boxplot_stats)) data = cbook.boxplot_stats(values) From the boxplot_stats docstring: Returns ------- bxpstats : list of dict A list of dictionaries containing the results for each column of data. Keys of each dictionary are the following: ======== =================================== Key Value Description ======== =================================== label tick label for the boxplot mean arithemetic mean value med 50th percentile q1 first quartile (25th percentile) q3 third quartile (75th percentile) cilo lower notch around the median cihi upper notch around the median whislo end of the lower whisker whishi end of the upper whisker fliers outliers ======== =================================== Source links are for the current master on this date. Current Matplotlib version is 2.2.2
answers question: http://stackoverflow.com/q/49694895

http://stackoverflow.com/q/49606675
has comment: http://stackoverflow.com/comment/86223594
tagged with: python
has comment: http://stackoverflow.com/comment/86224174
tagged with: python-3.x
has title: Smooth curved shapes in opencv, Python
has body: I'm trying to create filled smooth curves and save it in .png file using python. The example of what I would like to get is this: The shape of this closed curve is not important, the only requirement is that it should be smooth and closed. Is it possible to generate such curves using OpenCV, or should I use another library?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86220230
type: Question
tagged with: opencv
score: 0

http://stackoverflow.com/comment/86290342
score: 3
type: Comment
comment on: http://stackoverflow.com/q/49641319
type: QuestionComment
has text: Possible duplicate of [Viewing all defined variables](https://stackoverflow.com/questions/633127/viewing-all-defined-variables)

http://stackoverflow.com/a/49653062
score: 1
has comment: http://stackoverflow.com/comment/86314972
has comment: http://stackoverflow.com/comment/86314779
downvote count: 0
type: Answer
upvote count: 1
has body: If you want three variables, the best way to do it is to assign them like this: df1, df2, df3 = list_B This will unpack the list giving values to each variable. For too many variables use: {'df{}'.format(i): df for i, df in enumerate(list_B, 1)}
answers question: http://stackoverflow.com/q/49652846

bit
tag name: bit
type: Tag
tags question: http://stackoverflow.com/q/49675922

http://stackoverflow.com/comment/86372648
type: Comment
score: 0
type: QuestionComment
has text: You probably ought to know what a solid and a shell are. I don't explain it in my answer, but I do try to point you in a direction so you can look into it.
comment on: http://stackoverflow.com/q/49661543

http://stackoverflow.com/q/49703958
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/29158220
favorite count: 0
type: Question
has title: Tkinter GUI RFID Reader
has comment: http://stackoverflow.com/comment/86424001
type: UnansweredQuestion
tagged with: python
tagged with: rfid
has body: I'm making a gui for my rfid reader but when i run the program it only operates on the shell window and does not open a tkinter gui window. I'm kind of new with python and it's gui so can anybody help me. even a tutorial for a solution to my problem can help. here is my code. thank you for the help. from tkinter import * import binascii import socket import time import signal import sys import Adafruit_PN532 as PN532 root = Tk(className="Team Baboy") root.geometry("800x480") welcome = Label(root,text="Welcome to Hog Traceability System") welcome.pack() welcome.config(font=("Gothic", 18)) back = Frame(width=800, height=480) back.pack() instruction = Label(master=back, text='Tap your Authorization Card') instruction.pack() instruction.config(font=("Gothic", 30)) instruction.grid(row=0, column=1, padx=0, pady=150) CS = 18 MOSI = 23 MISO = 24 SCLK = 25 CARD_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] Delay = 1 HEADER = b'BG' def close(signal, frame): sys.exit(0) signal.signal(signal.SIGINT, close) pn532 = PN532.PN532(cs=CS, sclk=SCLK, mosi=MOSI, miso=MISO) pn532.begin() pn532.SAM_configuration() print('PN532 NFC RFID 13.56MHz Card Reader') while True: uid = pn532.read_passive_target() if uid is None: continue print('') print('Card UID 0x{0}'.format(binascii.hexlify(uid))) if not pn532.mifare_classic_authenticate_block(uid, 4, PN532.MIFARE_CMD_AUTH_B, CARD_KEY): print('Failed to authenticate with card!') continue data = pn532.mifare_classic_read_block(4) if data is None: print('Failed to read data from card!') continue if data[0:2] != HEADER: print('Card is not written with proper block data!') continue print('User Id: {0}'.format(int(data[2:8].decode("utf-8"), 16))) root.mainloop()
has answer: http://stackoverflow.com/a/49705710
tagged with: tkinter
score: 1
upvote count: 1

http://stackoverflow.com/a/49719042
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: If this is for an isolated task, you can retrieve the argument as part of a list comprehension: class MyClass(object): def __init__(self, var): self.var = var A = [MyClass(i) for i in range(10)] print([x.var for x in A]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Otherwise, as demonstrated by @Vinny, you can add a __repr__ method to your class.
answers question: http://stackoverflow.com/q/49718976

datetime
tags question: http://stackoverflow.com/q/49601018
tags question: http://stackoverflow.com/q/49618942
tags question: http://stackoverflow.com/q/49674902
tags question: http://stackoverflow.com/q/49671138
tag name: datetime
tags question: http://stackoverflow.com/q/49721246
tags question: http://stackoverflow.com/q/49700898
tags question: http://stackoverflow.com/q/49631555
tags question: http://stackoverflow.com/q/49715385
tags question: http://stackoverflow.com/q/49733439
tags question: http://stackoverflow.com/q/49757871
tags question: http://stackoverflow.com/q/49612045
tags question: http://stackoverflow.com/q/49692084
tags question: http://stackoverflow.com/q/49657317
tags question: http://stackoverflow.com/q/49612378
tags question: http://stackoverflow.com/q/49750172
tags question: http://stackoverflow.com/q/49601091
tags question: http://stackoverflow.com/q/49601166
tags question: http://stackoverflow.com/q/49621847
tags question: http://stackoverflow.com/q/49738197
tags question: http://stackoverflow.com/q/49601597
tags question: http://stackoverflow.com/q/49610175
type: Tag
tags question: http://stackoverflow.com/q/49662291
tags question: http://stackoverflow.com/q/49650000
tags question: http://stackoverflow.com/q/49669627
tags question: http://stackoverflow.com/q/49617685
tags question: http://stackoverflow.com/q/49610591
tags question: http://stackoverflow.com/q/49757620
tags question: http://stackoverflow.com/q/49754741
tags question: http://stackoverflow.com/q/49683706
tags question: http://stackoverflow.com/q/49649917
tags question: http://stackoverflow.com/q/49721920
tags question: http://stackoverflow.com/q/49719627
tags question: http://stackoverflow.com/q/49688574
tags question: http://stackoverflow.com/q/49624124
tags question: http://stackoverflow.com/q/49608039
tags question: http://stackoverflow.com/q/49695681
tags question: http://stackoverflow.com/q/49695751
tags question: http://stackoverflow.com/q/49649393
tags question: http://stackoverflow.com/q/49634468
tags question: http://stackoverflow.com/q/49611520
tags question: http://stackoverflow.com/q/49628384
tags question: http://stackoverflow.com/q/49730416
tags question: http://stackoverflow.com/q/49715824
tags question: http://stackoverflow.com/q/49700120

http://stackoverflow.com/q/49661827
has comment: http://stackoverflow.com/comment/86333890
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86334310
score: 5
has title: Resolve a variable name given only a stack frame object
has body: I'm trying to find out if it's possible to resolve variables in stack frames (as returned by inspect.currentframe()). In other words, I'm looking for a function def resolve_variable(variable_name, frame_object): return value_of_that_variable_in_that_stackframe For an example, consider the following piece of code: global_var = 'global' def foo(): closure_var = 'closure' def bar(param): local_var = 'local' frame = inspect.currentframe() assert resolve_variable('local_var', frame) == local_var assert resolve_variable('param', frame) == param assert resolve_variable('closure_var', frame) == closure_var assert resolve_variable('global_var', frame) == global_var bar('parameter') foo() Local and global variables are trivially looked up through the f_locals and f_globals attributes of the frame object: def resolve_variable(variable_name, frame_object): try: return frame_object.f_locals[variable_name] except KeyError: try: return frame_object.f_globals[variable_name] except KeyError: raise NameError(varname) from None But the problem are closure variables. They aren't stored in a dictionary like the local and global variables, as far as I know. To make things even worse, variables only become closure variables if the function actually accesses them (for example by reading its value like _ = closure_var or writing to it with nonlocal closure_var; closure_var = _). So there are actually 3 different cases: global_var = 'global' def foo(): unused_cvar = 'unused' # actually not a closure variable at all readonly_cvar = 'closure' nonlocal_cvar = 'nonlocal' def bar(param): nonlocal nonlocal_cvar local_var = 'local' _ = readonly_cvar nonlocal_cvar = 'nonlocal' frame = inspect.currentframe() assert resolve_variable('local_var', frame) == local_var assert resolve_variable('param', frame) == param assert resolve_variable('unused_cvar', frame) == 'unused' assert resolve_variable('readonly_cvar', frame) == readonly_cvar assert resolve_variable('nonlocal_cvar', frame) == nonlocal_cvar ass…
downvote count: 0
tagged with: cpython
answer count: 1
has comment: http://stackoverflow.com/comment/86334123
has answer: http://stackoverflow.com/a/49661908
accepted answer: http://stackoverflow.com/a/49661908
has comment: http://stackoverflow.com/comment/86334234
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86333750
tagged with: stack-frame
has comment: http://stackoverflow.com/comment/86334265

http://stackoverflow.com/a/70555294
downvote count: 0
has body: Like @Tosha answered, pyproject.toml is your friend. Here is an example from my project which uses jinja2: setup.py: # Simplified - removed all actual code import jinja2 from setuptools import setup setup(name='test') Building with: python -m build --wheel will break: * Creating venv isolated environment... * Installing packages in isolated environment... (setuptools >= 40.8.0, wheel) * Getting dependencies for wheel... Traceback (most recent call last): File "/tmp/venv/lib/python3.6/site-packages/pep517/in_process/_in_process.py", line 363, in <module> main() File "/tmp/venv/lib/python3.6/site-packages/pep517/in_process/_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/tmp/venv/lib/python3.6/site-packages/pep517/in_process/_in_process.py", line 130, in get_requires_for_buil d_wheel return hook(config_settings) File "/tmp/build-env-4zi79uth/lib/python3.6/site-packages/setuptools/build_meta.py", line 163, in get_requires_fo r_build_wheel config_settings, requirements=['wheel']) File "/tmp/build-env-4zi79uth/lib/python3.6/site-packages/setuptools/build_meta.py", line 143, in _get_build_requ ires self.run_setup() File "/tmp/build-env-4zi79uth/lib/python3.6/site-packages/setuptools/build_meta.py", line 268, in run_setup self).run_setup(setup_script=setup_script) File "/tmp/build-env-4zi79uth/lib/python3.6/site-packages/setuptools/build_meta.py", line 158, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 1, in <module> import jinja2 ModuleNotFoundError: No module named 'jinja2' ERROR Backend subproccess exited when trying to invoke get_requires_for_build_wheel However, adding a pyproject.toml: [build-system] requires = [ "setuptools", "jinja2", ] fixes the issue Note I'm including also setuptools as a requirement. Omitting it will also break
type: Answer
answers question: http://stackoverflow.com/q/49715799
score: 3
upvote count: 3

http://stackoverflow.com/q/49604194
favorite count: 0
score: -1
type: Question
has comment: http://stackoverflow.com/comment/86216588
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
downvote count: 1
has body: Large text file with 1 million records i would like to search for a matching string,(e.g 2580552) from file and print from those lines fields in the 1st, 5th, and 45th and 46th columns, using awk i capture data, but need answer in python. grep 2580552 /tmp/myfile.txt |awk -F'\t' '$5 == "2580552" {print $1","$5 $41","$46}' Thx, Sai.
has answer: http://stackoverflow.com/a/49663686
has title: Python search string match from line then print few columns
has comment: http://stackoverflow.com/comment/86215577

http://stackoverflow.com/comment/86207079
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49599865
score: 0
has text: You would need to store this differently. Storing it as a set and searching would take linear time.

http://stackoverflow.com/q/49616259
tagged with: python
has title: Pandas read_fwf use in file with contiguous bytes and no line terminators
has body: I have a file with fixed-width records that are not separated by newlines or any other terminator; the file is just a contiguous byte stream. Pandas read_fwf correctly reads the first record then stops. Is there a way to force read_fwf to continue reading all records to the end of file? I did not see any arg for this in the docs.
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/1187078
answer count: 1
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49617414

http://stackoverflow.com/q/49628300
tagged with: formsets
linked to: http://stackoverflow.com/q/49604076
score: 0
has body: I have searched this issue but couldn't get the right answer where as there are so many questions being asked before related to that. i am using a model for post with multiple fields and other model (having foreign key of post model) for multiple image fields.I Want to update the posts i create. Here's my views.py for update_post def update_post(request, post_id): ImageFormSet = modelformset_factory(PostPicture, form=AddPictures, extra=10, min_num=1) post_form = get_object_or_404(Posts, pk=post_id) if request.method == "POST": form = AddFile(request.POST, instance=post_form) formset = ImageFormSet(queryset=PostPicture.objects.filter(post=post_id)) if form.is_valid() and formset.is_valid(): form.save() formset.save() for form in formset: if form: image = form['image'] photo = PostPicture(post=form, image=image) photo.save() messages.success(request, 'Post updated Successfully!') return render(request, 'vehicles_app/update_post.html', { 'form': form, 'formset': formset, 'post_form': post_form, 'post_id': post_id, }) else: print(form.errors, formset.errors) else: form = AddFile() formset = ImageFormSet(queryset=PostPicture.objects.none()) return render(request, 'vehicles_app/update_post.html', {'form': form, 'formset': formset, 'post_form':post_form, 'post_id': post_id}) here's my update_post.html {% csrf_token %} Ad Title City Islamabad Karachi Lahore Peshawar Quetta Multan Faisalabad Price Brand Honda Audi BMW Suzuki Toyota Lexus Hyundai Jeep Mazda Mitsubishi Daewoo Model-Year Condition NEW USED Mileage Type details here {{ formset.management_form }} {% if formset %} {% for form in formset %} {% if form %} {{ form }} {% endif %} {% endfor %} {% endif %}
tagged with: django-views
duplicate of: http://stackoverflow.com/q/49604076
has title: i wanna update my formset factory images post, i am able to update posts text fields but formset factory images are noot updating
has comment: http://stackoverflow.com/comment/86266736
has comment: http://stackoverflow.com/comment/86268486
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/86268554
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86268430
tagged with: django
tagged with: python

http://stackoverflow.com/comment/86460795
has text: Sure, happy to help; also no objections to your addition. :)
comment on: http://stackoverflow.com/a/49713212
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49626726
has comment: http://stackoverflow.com/comment/86261131
has answer: http://stackoverflow.com/a/49626836
has comment: http://stackoverflow.com/comment/86260471
tagged with: split
possible better answer: http://stackoverflow.com/a/49626795
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86260404
has answer: http://stackoverflow.com/a/49626795
downvote count: 0
linked to: http://stackoverflow.com/q/4960208
answer count: 3
accepted answer: http://stackoverflow.com/a/49626866
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49626866
has title: Python split on comma without parenthesis
favorite count: 0
type: Question
has body: I have a question regarding Python syntax. When parsing a string and casting it to a float, I am running in to an issue. I have the code print "Please enter in x1 and y1 separated by a comma" in1 = input() sp1 = str(in1).split(',') x1 = sp1[0] If I enter in 5.4,3.2 and print out x1, I get (5.4 This extra parenthesis makes it hard for me to convert into a floating point for further calculation. However, if I split based on a a decimal, such as print "Please enter in x1 and y1 separated by a comma" in1 = input() sp1 = str(in1).split('.') I am able to print x1 as 5 I do not get the parenthesis which is good, however I am not getting the correct number either. Any help would be greatly appreciated, thank you
score: 1

http://stackoverflow.com/comment/86257694
has text: Your question isn't really very clear. Are you asking how to make the PC boot up at a particular time, or how to make it do something automatically after it boots?
type: Comment
comment on: http://stackoverflow.com/q/49625311
type: QuestionComment
score: 0

http://stackoverflow.com/q/49627205
tagged with: python
has title: Memory Leak in my Python code(lists)
has comment: http://stackoverflow.com/comment/86264091
score: 2
tagged with: memory-management
answer count: 0
has body: So I implemented a DQN code in tensorflow for my research work but while training I found that I have memory leak. After debugging the whole day I found that its the Replay Memory array which causes the memory leak. I have set a limit of 25000 samples for my replay memory list and once it crosses the limit it collects the recent 25000 samples. Here is the code for replay memory dataset collection Replay_Memory.extend(New_sample) if(len(Replay_Memory)&gt;25000): temp=Replay_Memory[len(Replay_Memory)- 25000: len(Replay_Memory) Replay_Memory=temp del(temp) gc.collect()
has comment: http://stackoverflow.com/comment/86263189
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: memory-leaks
downvote count: 0
tagged with: garbage-collection

http://stackoverflow.com/q/49747632
has answer: http://stackoverflow.com/a/49824844
has comment: http://stackoverflow.com/comment/86533651
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86570534
tagged with: python
has comment: http://stackoverflow.com/comment/86524873
tagged with: inheritance
score: 2
has body: I am not happy with YAML/JSON. I am missing inheritance. Is it possible to export a hierarchy of Python classes to YAML/JSON? This way I can use my favorite IDE with auto-completion to build my data structures. The result should be fed into SaltStack in my case. But this is not related to configuration management at all, since the result should be plain YAML/JSON. I want to export the classes to yaml. There will always be classes only, never instances. At least that's what I think today. I think it makes sense to use this constraint: classes won't have methods, except properties. And only get-properties, never set-properties. I took the example json from: https://www.json2yaml.com/ { "json": [ "rigid", "better for data interchange" ], "yaml": [ "slim and flexible", "better for configuration" ], "object": { "key": "value", "array": [ { "null_value": null }, { "boolean": true }, { "integer": 1 } ] }, "paragraph": "Blank lines denote\nparagraph breaks\n", "content": "Or we\ncan auto\nconvert line breaks\nto save space" } Here is one example of above json in python syntax: class json: data = ['rigi', 'better for data interchange'] class yaml: data = ['slim and flexible', 'better for configuration'] class object: key = 'value' array = [dict(null_value=None), dict(boolean=True), dict(integer=1)] class paragraph: data = 'Blank lines denote\nparagraph breaks\n' class content: data = '''Or we can auto convert line breaks to save space''' Above is just a simple of how data structures could get created using python classes.
has answer: http://stackoverflow.com/a/49747983
answer count: 2
has title: Python classes to Yaml/JSON
upvote count: 3
has comment: http://stackoverflow.com/comment/86509887
tagged with: yaml
tagged with: salt-project
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86564987
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86522388

http://stackoverflow.com/q/49604632
tagged with: django
has answer: http://stackoverflow.com/a/49604688
tagged with: python
has body: Here's my template: {% if instance.ad or instance.user == request.user or request.user.is_authenticated == False %} I recently added request.user.is_authenticated == False in this condition and now it is not working. It should fire if the user is not logged in. Any idea what the problem is?
has title: request.user is false condition not working in template
score: 0
has answer: http://stackoverflow.com/a/49604658
type: Question
has comment: http://stackoverflow.com/comment/86216387
answer count: 2
has comment: http://stackoverflow.com/comment/86216378
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86216467

http://stackoverflow.com/q/49662522
has body: This question is a partial resolution to the question I posted today at CTypes error loading DLL that calls another DLL. I posted this as a separate post because the problem is in dependencies with the Python C/API, not in the source code that I posted there. I have a 64-bit NASM dll that calls a 64-bit C dll on Windows 7. The C dll uses the Python C/API; the NASM dll is called using CTypes. However, when I load the NASM dll using ctypes in Visual Studio, I get the error "[WinError 126] The specified module could not be found." The C dll was compiled using GCC in MSYS2. Calling the NASM dll into Dependency Walker showed that libpython3.6m.dll and libwinpthread-1.dll were missing. Those dlls are in the distribution for MSYS2, so I copied them from there into the folder containing the NASM dll. That fixed that problem, but now Dependency Walker says it's missing all these DLLs: API-MS-WIN-CORE-COM-L1-1-0.DLL API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL API-MS-WIN-CORE-WINRT-L1-1-0.DLL API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL API-MS-WIN-SHCORE-SCALING-L1-1-0.DLL DCOMP.DLL IESHIMS.DLL This problem appears to be related to the Python C/API, which apparently depends on these DLLs. Does anyone know how to fix this? The full source code is at the link above.
answer count: 0
has comment: http://stackoverflow.com/comment/86335469
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86335214
has comment: http://stackoverflow.com/comment/86346678
downvote count: 0
has title: DLL calling Python C/API has dependency issues
has comment: http://stackoverflow.com/comment/86335224
upvote count: 1
tagged with: c-api
favorite count: 0
tagged with: dll
has comment: http://stackoverflow.com/comment/86335364
tagged with: msys2
score: 1
has comment: http://stackoverflow.com/comment/86473747
tagged with: python
has comment: http://stackoverflow.com/comment/86335570
has comment: http://stackoverflow.com/comment/86335540
has comment: http://stackoverflow.com/comment/86335520
type: Question
has comment: http://stackoverflow.com/comment/86361784

http://stackoverflow.com/comment/86356999
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49673030
has text: This actually belongs to another SE site, maybe codereview
score: 0

http://stackoverflow.com/q/49627752
type: Question
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49627950
has comment: http://stackoverflow.com/comment/86262460
has comment: http://stackoverflow.com/comment/86262561
has title: Read huge file using a 'for' loop
has body: I have a huge file, abc.txt, and wanted to read line by line, not all at once. I can do it as below: filename="c:\abc.txt" with open (filename, "r") as fb: for content in fb: # Do something .... Here I am not understanding one thing. As you see, "fb" is a file pointer over here. How is the "for" loop processing the pointer directly internally even without using any readline or read function? I just wanted to know how the for loop is working here.
downvote count: 4
has comment: http://stackoverflow.com/comment/86262578
type: UnansweredQuestion
upvote count: 0
score: -4
answer count: 1
linked to: http://stackoverflow.com/q/8009882
linked to: http://stackoverflow.com/q/3277503
favorite count: 0

http://stackoverflow.com/a/49604837
has body: Two pandas way df.Text.sum() Out[72]: 'abcdefghijklmno' ''.join(df.Text) Out[77]: 'abcdefghijklmno' Using for loop . s='' for x,y in df.iterrows(): s+=y['Text']
upvote count: 3
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49604817
downvote count: 0

http://stackoverflow.com/q/49707924
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49708303
has comment: http://stackoverflow.com/comment/86430095
upvote count: 3
has comment: http://stackoverflow.com/comment/86429250
answer count: 1
has comment: http://stackoverflow.com/comment/86430620
downvote count: 0
has comment: http://stackoverflow.com/comment/86429745
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/86430201
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86430117
has title: Ingest columns as lists, sets, dictionaries in Python
has body: Given a csv file where some columns contain lists, sets or dictionaries like one with the structure below: | user_id| items | methods | dict_col | |--------|-------------------------|----------------|---------------| | ID01 | [potato, apple, potato] | {card, cash} | {F: [AB, CD]} | | ID02 | [carrots, papaya] | {bitcoin, card}| {F: [AB, CD]} | Is there a way to ingest it in Python in tabular way where the type of the values in those columns in maintained? If not, what is the best approach to convert them back to list, set, dictionaries? The question stems from the fact that once one has a DataFrame with this structure and it is saved into a csv, when the csv is loaded back with pandas.read_csv(), the values inside those columns are no longer lists,set or dictionaries. Below the code to recreate the scenario explained above. import pandas as pd # Create dummy example df = pd.DataFrame({'user_id': ['ID01', 'ID02'], 'items': [['potato', 'apple', 'potato'],['carrots', 'papaya']], 'methods': [{'card', 'cash'}, {'bitcoin', 'card'}], 'dict_col': [{'F': ['AB', 'CD']}, {'F': ['AB', 'CD']}]}) df'user_id', 'items', 'methods', 'dict_col' type(df.iloc[0]['dict_col']) # Return a dict df.to_csv('dummy_table.csv', index = False) # Reload the table df_loaded = pd.read_csv('dummy_table.csv') """ Line below returns a str and not a dict as in the original dataframe. How we go back to the original datatypes (e.g. list, dict, set)in a pythonic way? """ type(df_loaded.iloc[0]['dict_col']) Attempt after Kyle J. comment on trying with cvs.DictReader I tried with DictReader, but the objective was not met. However, I am not sure this is what the Kyle had in mind. Attempt with DictReader import csv import pandas as pd df = pd.DataFrame() with open('dummy_table.csv', newline = '') as csvfile: reader = csv.DictReader(csvfile) for row in reader: df = pd.concat([df, pd.DataFrame(row, index = [0])], axis = 0) type(df.iloc[0]['dict_col']) # Still a str
tagged with: python
tagged with: tabular
has comment: http://stackoverflow.com/comment/86430847
accepted answer: http://stackoverflow.com/a/49708303
has comment: http://stackoverflow.com/comment/86429680

http://stackoverflow.com/q/49617980
downvote count: 0
has title: Score short quote in text with Python
has comment: http://stackoverflow.com/comment/86243116
has body: Background Using Python, I need to score the existence of a quote, containing around 2-7 words, a longer text. The quote doesn't have to match the text precisely, but similar words should have the same order. For example, given the following long text: The most beautiful things in the world cannot be seen or touched, they are felt with the heart The following quotes should be scored high (say, above 80 / 100): The beautiful thing in our world World cannot see They feel with the heart Since they are not precise, but they preserve the order. While, on the other hand, these quotes should be scored lower (say, below 50 / 100): The beautiful heart cannot be felt or seen They are the most seen in the world These words don't even appear on this text Because (the first 2) appear entirely in the text, but do not preserve the order. The problem This task cannot be accomplished by simply checking the existence of each word in the text. I don't know which algorithm fits best for this task. What I have tried Most of the functions in fuzzywuzzy (partial_token_sort_ratio, token_sort_ratio and etc) scored the later terms higher. partial_ratio did score the earlier terms higher, but the quote These words don't even appear on this text Got 52 / 100 which is unreasonably high. My question How can I use python to score the existence of short quotes in longer texts as mentioned above?
favorite count: 0
tagged with: fuzzywuzzy
type: Question
has answer: http://stackoverflow.com/a/49618148
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49618813
tagged with: nlp
answer count: 2
has comment: http://stackoverflow.com/comment/86243130
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86243162

http://stackoverflow.com/q/49649634
has title: Not able to make slug work in Django
accepted answer: http://stackoverflow.com/a/49649749
has comment: http://stackoverflow.com/comment/86308408
has answer: http://stackoverflow.com/a/49649756
possible better answer: http://stackoverflow.com/a/49649756
downvote count: 1
favorite count: 0
type: Question
has body: I am building one project in which i used slug for urls. But it doesn't seem to be working. My regex pattern is right I have tested it. I have used id before and then it worked fine but if i use slug in place of id it creates error. Here is my code models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Country(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' def __str__(self): return self.name class News(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) description = models.TextField(max_length=1500) pub_date = models.DateTimeField() class Meta: verbose_name = 'News' verbose_name_plural = 'News' def __str__(self): return self.title urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.Home, name='index'), url(r'^[a-z0-9-]+$/detail', views.detail, name='detail')] views.py def detail(request, slug): nd = get_object_or_404(News, slug=slug) return render(request, template_name="app/detail.html", context={'nd':nd}) detail.html {% extends "base.html" %} {% block title %}Detail{% endblock %} {% block content %} {% for n in nd %} {{ n.title }} {{ n.category }} {{ n.pub_date }} {{ n.description }} {% endfor %} {% endblock %}
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49649749

http://stackoverflow.com/comment/86239551
type: QuestionComment
has text: python callbacks
score: 0
comment on: http://stackoverflow.com/q/49613528
type: Comment

http://stackoverflow.com/comment/86479593
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49732829
has text: Ahh, so close. I do actually need the keyword arguments to work correctly, half the point of introspecting for these argument names is to know what keyword arguments to use for them.

http://stackoverflow.com/comment/86258818
score: 0
has text: It has to work...I am pretty sure that you have some name problem..Make sure you named it correctly...that {test2.py} does not contain any spaces or other characters....
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49624483

http://stackoverflow.com/comment/86412105
has text: Are you loading weights from somewhere? What is the model summary and the shapes of X and Y? Please provide a minimum info to answer this question.
comment on: http://stackoverflow.com/q/49699242
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86340622
has text: His function is called `write_tab_seperated()`, so I'm fairly sure he wants to write.
comment on: http://stackoverflow.com/a/49662495
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49699678
answer count: 1
has body: I have the following string columns. Str1 Str2 Str3 OK I Go Yes Hm Fine I see I want to combine them into one list variable AllStr ["ok", "I", "Go"] ["Yes", "Hm"] ["Fine", "I see"] I tried different method, I came close but not quite right: df_manual_label['AllStr'] = df_manual_label'Str1', 'Str2', 'Str3'.apply(lambda x: ', '.join(x.astype(str)), axis=1)
tagged with: variables
favorite count: 0
accepted answer: http://stackoverflow.com/a/49699768
type: AnsweredQuestion
has title: How to merge multiple columns into one variable (which is a list) in Pandas
score: 1
tagged with: dataframe
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/49699768
type: Question
downvote count: 0
tagged with: pandas
upvote count: 1

http://stackoverflow.com/q/49624744
score: 0
type: Question
has title: Pyspark saveAsTextFile Error
has comment: http://stackoverflow.com/comment/86256485
has body: here is my code: alist = [('A',1),('B',2),('C',3)] rdd = sc.parallelize(alist) import json rdd.map(lambda o: json.dumps(o)).saveAsTextFile("data/jsonedTSV") Here is the error Py4JJavaError Traceback (most recent call last) &lt;ipython-input-56-4fc40f9b6100&gt; in &lt;module&gt;() 1 import json ----&gt; 2 rdd.map(lambda o: json.dumps(o)).saveAsTextFile("data/jsonedTSV") C:\spark\python\pyspark\rdd.pyc in saveAsTextFile(self, path, compressionCodecClass) 1566 keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path, compressionCodec) 1567 else: -&gt; 1568 keyed._jrdd.map(self.ctx._jvm.BytesToString()).saveAsTextFile(path) 1569 1570 # Pair functions C:\spark\python\lib\py4j-0.10.6-src.zip\py4j\java_gateway.py in __call__(self, *args) 1158 answer = self.gateway_client.send_command(command) 1159 return_value = get_return_value( -&gt; 1160 answer, self.gateway_client, self.target_id, self.name) 1161 1162 for temp_arg in temp_args: C:\spark\python\pyspark\sql\utils.pyc in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---&gt; 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() C:\spark\python\lib\py4j-0.10.6-src.zip\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 raise Py4JJavaError( 319 "An error occurred while calling {0}{1}{2}.\n". --&gt; 320 format(target_id, ".", name), value) 321 else: 322 raise Py4JError( Py4JJavaError: An error occurred while calling o523.saveAsTextFile. On the internet same people say, it might be because of the hadoop version, but i dont know what to do if it is the reason.
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/86257144
answer count: 0
tagged with: apache-spark

http://stackoverflow.com/comment/86371630
type: Comment
score: 0
has text: Traceback (most recent call last): File "hnbtest.py", line 25, in <module> stdin=subprocess.PIPE, stdout = subprocess.PIPE) File "/opt/rh/python27/root/usr/lib64/python2.7/subprocess.py", line 211, in check_output raise ValueError('stdout argument not allowed, it will be overridden.') ValueError: stdout argument not allowed, it will be overridden.
type: AnswerComment
comment on: http://stackoverflow.com/a/49678003

http://stackoverflow.com/q/49616250
linked to: http://stackoverflow.com/q/45685703
has answer: http://stackoverflow.com/a/49618920
has comment: http://stackoverflow.com/comment/86240755
linked to: http://stackoverflow.com/q/46702722
has comment: http://stackoverflow.com/comment/86285732
downvote count: 0
has comment: http://stackoverflow.com/comment/86241035
accepted answer: http://stackoverflow.com/a/49637812
has comment: http://stackoverflow.com/comment/86240500
has comment: http://stackoverflow.com/comment/86240955
has comment: http://stackoverflow.com/comment/86240979
tagged with: python
has comment: http://stackoverflow.com/comment/86240547
score: 4
has comment: http://stackoverflow.com/comment/86264910
has comment: http://stackoverflow.com/comment/86241188
has answer: http://stackoverflow.com/a/49637812
has comment: http://stackoverflow.com/comment/86240818
favorite count: 0
has title: Timestamp incompatibility (NiFi's PutSQL)
tagged with: postgresql
type: AnsweredQuestion
answer count: 3
linked to: http://stackoverflow.com/q/42352064
tagged with: java
has body: I'm facing issues with the insertion of timestamps in to a PostgreSQL database using the Nifi PutSQL processor. More specifically when trying to insert a date in the format '2018-01-31T19:01:09+00:00' in to a timestamptz column I get the following error message: 2018-04-01 19:29:40,091 ERROR [Timer-Driven Process Thread-5] o.apache.nifi.processors.standard.PutSQL PutSQL[id=7997503a-0162-1000-ee81-a0361cad5e0c] Failed to update database for StandardFlowFileRecord[uuid=d02e8b39-e564-4c37-a08a-dab8931e9890,claim=StandardContentClaim [resourceClaim=StandardResourceClaim[id=1522615075930-15, container=default, section=15], offset=11492, length=163],offset=0,name=32836401373126,size=163] due to java.sql.SQLDataException: The value of the sql.args.5.value is '2018-01-31T20:19:35+00:00', which cannot be converted to a timestamp; routing to failure: java.sql.SQLDataException: The value of the sql.args.5.value is '2018-01-31T20:19:35+00:00', which cannot be converted to a timestamp java.sql.SQLDataException: The value of the sql.args.5.value is '2018-01-31T20:19:35+00:00', which cannot be converted to a timestamp at org.apache.nifi.processors.standard.PutSQL.setParameters(PutSQL.java:711) at org.apache.nifi.processors.standard.PutSQL.lambda$null$5(PutSQL.java:313) at org.apache.nifi.processor.util.pattern.ExceptionHandler.execute(ExceptionHandler.java:127) at org.apache.nifi.processors.standard.PutSQL.lambda$new$6(PutSQL.java:311) at org.apache.nifi.processors.standard.PutSQL.lambda$new$9(PutSQL.java:354) at org.apache.nifi.processor.util.pattern.PutGroup.putFlowFiles(PutGroup.java:91) at org.apache.nifi.processor.util.pattern.Put.onTrigger(Put.java:101) at org.apache.nifi.processors.standard.PutSQL.lambda$onTrigger$20(PutSQL.java:574) at org.apache.nifi.processor.util.pattern.PartialFunctions.onTrigger(PartialFunctions.java:114) at org.apache.nifi.processor.util.pattern.RollbackOnFailure.onTrigger(RollbackOnFailure.java:184) at org.apache.nifi.processors.standard.PutSQL.onTr…
tagged with: http://stackoverflow.com/tag/json
tagged with: apache-nifi
possible better answer: http://stackoverflow.com/a/64176156
linked to: http://stackoverflow.com/q/11133759
has comment: http://stackoverflow.com/comment/86240247
has answer: http://stackoverflow.com/a/64176156
type: Question
upvote count: 4

http://stackoverflow.com/q/49690851
downvote count: 2
has answer: http://stackoverflow.com/a/49690936
duplicate of: http://stackoverflow.com/q/1663807
type: UnansweredQuestion
favorite count: 0
has title: Average difference between ints in two lists in one line - Python
type: Question
has answer: http://stackoverflow.com/a/49690997
has comment: http://stackoverflow.com/comment/86393517
has answer: http://stackoverflow.com/a/49690942
has body: There are two non-empty lists, containing only ints, both have the same length. Our function needs to return the average absolute difference between ints of same index. For example, for the lists [1, 2, 3, 4] and [1, 1, 1, 1], the answer will be 1.5. The function needs to be completed in one line. I had a little something that does that, but as you can probably guess, it's not a one-liner: def avg_diff(a, b): sd = 0.0 for x, y in zip(a, b): sd += abs(x - y) return sd / len(a) Thanks.
score: 1
duplicate of: http://stackoverflow.com/q/13909052
has comment: http://stackoverflow.com/comment/86393505
tagged with: python
has comment: http://stackoverflow.com/comment/86393377
has answer: http://stackoverflow.com/a/49690960
answer count: 4
linked to: http://stackoverflow.com/q/4362586
linked to: http://stackoverflow.com/q/1663807
upvote count: 3

http://stackoverflow.com/comment/86284165
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49637830
score: 0
has text: Use a `metavar='<value>'` parameter to change the default uppercase form. https://docs.python.org/3/library/argparse.html#metavar

http://stackoverflow.com/q/49670686
has comment: http://stackoverflow.com/comment/86358042
has answer: http://stackoverflow.com/a/49696722
has body: I am new in python and I started to create an automation test suite about a GUI(multiple test cases in different file). I want to execute all my test cases in one selenium webdriver, so I created a singleton webdriver class and I want to use this class all my test cases. Here is my singleton webdriver class: from selenium import webdriver class Webdriver(object): """ Singleton class based on overriding the __new__ method """ def __new__(cls): """ Override __new__ method to control the obj. creation :return: Singleton obj. """ if not hasattr(cls, 'instance'): cls.instance = super(Webdriver, cls).__new__(cls) return cls.instance @staticmethod def get_driver(): """ :return: Selenium driver """ dir = "C:\\Python36\\Lib\\site-packages\\selenium\\webdriver\\ie" ie_driver_path = dir + "\\IEDriverServer.exe" return webdriver.Ie(ie_driver_path) and my setUp example: from Core.Webdriver import Webdriver class LoginExternal(unittest.TestCase): def setUp(self): # Create Instances self.web = Webdriver.get_driver() self.matcher = TemplateMatcher() self.gif = GifCapture("C:\\wifi\\Videos\\" + self._testMethodName + ".gif") self.gif.start() time.sleep(3) def test_LoginExternal(self): # Open External Login Page self.web.maximize_window() Here is my problem, when I execute my test suite, my code create a new selenium instance but I want only one selenium instance to be used in all test cases. I use pytest as a test runner with following cmd command: pytest --pyargs --html=Report/External_04052018.html ExternalTestSuite/ I think the problem is pytest use a new proccess in every test case execution. Is there any way to prevent or use like this way?
downvote count: 0
tagged with: python
tagged with: pytest-html
has title: Python Selenium run multiple test classes in one selenium webdriver using with pytest
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86384883
tagged with: pytest
answer count: 1
tagged with: selenium
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86352900
favorite count: 0
accepted answer: http://stackoverflow.com/a/49696722
type: Question

http://stackoverflow.com/q/49619732
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86254324
has comment: http://stackoverflow.com/comment/86247872
has comment: http://stackoverflow.com/comment/86247357
type: UnansweredQuestion
has title: Regex: Find word but not allow repetition
tagged with: python
has answer: http://stackoverflow.com/a/49620660
has comment: http://stackoverflow.com/comment/86246972
has comment: http://stackoverflow.com/comment/86255405
tagged with: python-2.7
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86247266
tagged with: regex
has comment: http://stackoverflow.com/comment/86247619
has comment: http://stackoverflow.com/comment/86247041
has answer: http://stackoverflow.com/a/49626255
has comment: http://stackoverflow.com/comment/86247919
has body: I have the following test and i want to extract all codes following HAB: and they must have REST in front but can have other words in between: REST gfdjj REST HAB: 75RF-3729-70D-01 CLUE HAB: 234-543 REST tt HAB: 75RF-3729-70D-02 CLUE ytr HAB: 34829-5467 REST HAB: 75RF-3729-70D-03 REST REST REST HAB: 54783-04 REST HA: 837483 REST dfhjdf REST 347845-34 REST rehs HAB: 45923 REST HAB: REST sdfdgdsd HAB: 456734 https://regex101.com/r/4inYr4/3 I tried (REST.*?) *(HAB:) (.*?)( |$) but it also returns the many redundant RESTs, (REST) *(HAB:) (.*?)( |$) but it doesn't return the second code, and (REST(?!.*REST).*?) *(HAB:) (.*?)( |$) but it only returns the last one. I need some kind of conditional regex that only allows other words than REST to be inbetween REST and HAB:, which I expected the last one to do? EDIT: I want to extract: REST 75RF-3729-70D-01 REST 75RF-3729-70D-02 REST 75RF-3729-70D-03 REST 54783-04 REST 45923 EDIT 2: I need the REST part, i updated the question and added some CLUEs to emphasize that i need REST I use Python 2.7 EDIT 3: I also need to find REST 456734 in: REST HAB: REST sdfdgdsd HAB: 456734
has comment: http://stackoverflow.com/comment/86246938
favorite count: 0

http://stackoverflow.com/q/49674684
linked to: http://stackoverflow.com/q/46586651
favorite count: 0
type: Question
tagged with: ruamel.yaml
score: 3
tagged with: python
tagged with: python-2.7
has body: I am facing a similar situation to the questions asked here: Python Import error on installing ruamel.yaml in custom directory I am aware that we will want to use some form of python environment isolation mechanism like virtualenv to create isolated environments within which our python code can run. However, in the industry I'm in, it is not uncommon that we write several pieces of python packages that will need to be used within other off-the-shelf software that come with their own python interpreter and so we are limited by the python version that the software(e.g. autodesk maya) uses and we don't have the flexibility of using virtualenv. pip install --install-option="--prefix=\\vm-fs-001\prod\sww\proj\general\python\python-2.7.14" &lt;package_name&gt; We deploy these code that we write into a custom 3rd party directory using something similar to the above command. We set our environments to include the site-packages and scripts of the 3rd party deployment folder. PYTHONPATH=\\vm-fs-001\prod\sww\proj\general\python\python-2.7.14\Lib\site-packages;%PYTHONPATH% PATH=\\vm-fs-001\prod\sww\proj\general\python\python-2.7.14\Scripts;%PATH%; In this case, the software is bundle with a python 2.7.14 interpreter and we wrote a package that requires ruamel.yaml I get the below error when trying to import ruamel.yaml within the python interpreter of the 3rd party software. ImportError: No module named ruamel.yaml I get the same ImportError even if I were to import ruamel from within my standard python 2.7.14 interpreter. λ python Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import ruamel.yaml Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named ruamel.yaml &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '\\\\vm-fs-001\\prod\\sww\\proj\\general\\python\\python-2.7.14\\Lib\\site-packag…
has answer: http://stackoverflow.com/a/49680008
has title: ImportError when ruamel.yaml is installed in a custom folder
has comment: http://stackoverflow.com/comment/86360481
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: pip

http://stackoverflow.com/q/49732176
answer count: 1
downvote count: 0
upvote count: 1
has title: How to validate a variable from the server when the client didn't write anything in it (I only pressed ENTER) in Python
favorite count: 0
linked to: http://stackoverflow.com/q/3363395
type: Question
has answer: http://stackoverflow.com/a/49732489
tagged with: server
type: UnansweredQuestion
tagged with: sockets
has comment: http://stackoverflow.com/comment/86478050
tagged with: python
tagged with: client
has comment: http://stackoverflow.com/comment/86478936
has comment: http://stackoverflow.com/comment/86478163
score: 1
has body: I have a simple client that sends data to a server, and a simple server that takes the data from the client and just sends it back to the client, and so the client receives it again from the server and prints it (look the code below). But when I don't write anything at the client, when I only press ENTER and nothing else at all, the server seems to freeze and the commands below var0 = connectionSocket.recv(1024) don't get executed at all. EDIT: Let me rephrase the question, I don't want to make any change at the client's code. But only write/change the server's code that way that when nothing is written by the client but a "" is sent to the server, I don't want the server to stop working. Is this even possible and if yes, how? I have this code for the server: from socket import * serverPort = 11000 serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('127.0.0.1', serverPort)) serverSocket.listen(10) while 1: connectionSocket, addr = serverSocket.accept() var0 = connectionSocket.recv(1024) var0 = str(var0) if(var0==""): print("THIS COMMAND HERE IS WHAT I WANT TO BE EXCECUTED, BUT IT NEVER DOES") connectionSocket.send(str.encode(var0)) connectionSocket.close() And this code for the client: import socket serverName = "localhost" serverPort = 11000 while 1: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverName, serverPort)) var = input("Write a sentence: ") if(var==""): print("ODD ISN'T IT?") s.sendall(str.encode(var)) data = s.recv(1024) data = str(data) print(data) s.close()
tagged with: validation

http://stackoverflow.com/q/49725614
upvote count: 2
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/49730746
score: 2
has body: This error has pretty much come out of no where. I'm running a simple linear regression in pysark using the following code: from pyspark.ml.regression import LinearRegression # initialize regression model object linreg = LinearRegression() # Fit 2 models, using different regularization parameters modelA = linreg.fit(X_train_vector) preds = modelA.transform(X_test_vector) from pyspark.ml.evaluation import RegressionEvaluator evaluator = RegressionEvaluator(metricName="r2") R2 = evaluator.evaluate(preds) print("ModelA: R2 = " + str(R2)) My first thought was that there could be null values, but I've already taken care of that prior to creating my feature set. Here is the full error: IllegalArgumentException: u'requirement failed: init value should &lt;= bound' --------------------------------------------------------------------------- IllegalArgumentException Traceback (most recent call last) &lt;command-37272&gt; in &lt;module&gt;() 5 6 # Fit 2 models, using different regularization parameters ----&gt; 7 modelA = linreg.fit(X_train_vector) 8 9 preds = modelA.transform(X_test_vector) /databricks/spark/python/pyspark/ml/base.pyc in fit(self, dataset, params) 62 return self.copy(params)._fit(dataset) 63 else: ---&gt; 64 return self._fit(dataset) 65 else: 66 raise ValueError("Params must be either a param map or a list/tuple of param maps, " /databricks/spark/python/pyspark/ml/wrapper.pyc in _fit(self, dataset) 263 264 def _fit(self, dataset): --&gt; 265 java_model = self._fit_java(dataset) 266 return self._create_model(java_model) I'm not entirely sure what this means tbh.
tagged with: apache-spark
answer count: 1
downvote count: 0
has title: Pyspark: IllegalArgumentException: u'requirement failed: init value should <= bound'
favorite count: 0
type: Question

http://stackoverflow.com/q/49739591
has body: I noticed a bizarre inconsistency between how Python [3.6.5] BeautifulSoup [4.6.0] with "lxml" [4.2.1] parser handles long bytes objects vs long strings. (Apparently, "long" is >16,384=2**14 characters or bytes.) For example, I download the text of Othello from the MIT website and feed it to BS both in the raw (bytes) form and after decoding to a string. Both objects have the same length, because there are no multibyte characters in the document. from bs4 import BeautifulSoup import urllib url = "http://shakespeare.mit.edu/othello/full.html" html_raw = urllib.request.urlopen(url).read() html_str = urllib.request.urlopen(url).read().decode("iso-8859-1") type(html_raw), len(html_raw) #(&lt;class 'bytes'&gt;, 304769) type(html_str), len(html_str) #(&lt;class 'str'&gt;, 304769) The resulting soup is the same for shorter strings/bytes but differs for longer strings/bytes. Namely, the soup produced from a string abruptly starts treating words as separate characters, while the soup produced from bytes correctly handles the whole file: BeautifulSoup(html_raw[:16410], "lxml") #... &lt;i&gt;Enter OTHELLO, IAGO, and Attendants with torches&lt;/i&gt; #&lt;/blockquote&gt; #&lt;a&gt;&lt;/a&gt;&lt;/body&gt;&lt;/html&gt; BeautifulSoup(html_str[:16410], "lxml") #... &lt;i&gt;Enter OTHELLO, IAGO, and Attendants with torch e s / i &amp;gt; # / b l o c k q u o t e &amp;gt; # # A &lt;/i&gt;&lt;/blockquote&gt;&lt;/body&gt;&lt;/html&gt; This holds both for the subset of the document (above) and for the whole document: BeautifulSoup(html_raw, "lxml") #... #&lt;p&gt;&lt;i&gt;Exeunt&lt;/i&gt;&lt;/p&gt; #&lt;/blockquote&gt;&lt;/body&gt; #&lt;/html&gt; BeautifulSoup(html_str, "lxml") #... # p &amp;gt; i &amp;gt; E x e u n t / i &amp;gt; / p &amp;gt; # / h t m l &amp;gt; # # # &lt;/i&gt;&lt;/blockquote&gt;&lt;/body&gt;&lt;/html&gt; There is no difference between the outputs when I use "html.parser". Is this a bug in the implementation of BS? Or am I violating some undocumented (or documented?) …
score: 7
answer count: 1
has answer: http://stackoverflow.com/a/53353702
duplicate of: http://stackoverflow.com/q/17859832
upvote count: 8
favorite count: 0
has title: Python BeautifulSoup with "lxml" parser breaks long strings into characters
type: Question
tagged with: decode
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17859832
tagged with: python
has comment: http://stackoverflow.com/comment/86494318
downvote count: 1
tagged with: beautifulsoup

ontology
tags question: http://stackoverflow.com/q/49678160
tag name: ontology
type: Tag
tags question: http://stackoverflow.com/q/49728777
tags question: http://stackoverflow.com/q/49687824

http://stackoverflow.com/comment/86495530
score: 1
type: QuestionComment
has text: Maybe this? https://stackoverflow.com/a/1346039/4909087
comment on: http://stackoverflow.com/q/49740461
type: Comment

http://stackoverflow.com/comment/89635237
has text: Did you try it with the typo fixed in the string? "${PYTHONPATH}:/your/custom/path"
score: 7
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49631407

http://stackoverflow.com/q/49737198
has comment: http://stackoverflow.com/comment/86489022
has answer: http://stackoverflow.com/a/49737230
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: How do I get today's date in SQLite?
has comment: http://stackoverflow.com/comment/86489464
has answer: http://stackoverflow.com/a/49737650
score: 1
has comment: http://stackoverflow.com/comment/86489377
tagged with: pandasql
tagged with: sqlite
has body: I am trying to use Pandasql to query my dataframe. However, it is giving me an empty dataframe even though I know it shouldn't. I think it is because I have used today's date incorrectly in the where clause. Below is part of my code: df_event2import=[] today = now.strftime("%Y-%m-%d") q = """ select e.Date, e.SITA, e.Events from df_event e where e.Date &gt;= date('today') """ df_event2import=((pandasql.sqldf(q, locals()))) df_all_event2import=df_all_event2import.append(df_event2import,ignore_index=True) print(df_all_event2import) As requested here is some example data. This is what I get after I use date('now') instead of date('today') in the where clause. As you can see it gives me data from January onward which is not what I want, I want data from today onward. Date SITA Events 0 2018/01/01 ABZPD New Years Day Bank Holiday 1 2018/01/02 ABZPD 2 2018/01/03 ABZPD 3 2018/01/04 ABZPD 4 2018/01/05 ABZPD 5 2018/01/06 ABZPD 6 2018/01/07 ABZPD 7 2018/01/08 ABZPD 8 2018/01/09 ABZPD 9 2018/01/10 ABZPD 10 2018/01/11 ABZPD 11 2018/01/12 ABZPD 12 2018/01/13 ABZPD 13 2018/01/14 ABZPD 14 2018/01/15 ABZPD 15 2018/01/16 ABZPD 16 2018/01/17 ABZPD 17 2018/01/18 ABZPD 18 2018/01/19 ABZPD
has comment: http://stackoverflow.com/comment/86488756
has comment: http://stackoverflow.com/comment/86489392
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/49642607
has comment: http://stackoverflow.com/comment/86298236
type: UnansweredQuestion
downvote count: 0
tagged with: file
upvote count: 1
score: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/86313504
favorite count: 0
has comment: http://stackoverflow.com/comment/86293540
has body: I have a very large csv file (11 Million lines). I would like to create batches of data. I cannot for the life of me figure out how to read n lines in a generator (where I specifiy what n is, sometimes I want it to be 50, sometimes 2). I came up with a kluge that works one time, but I could not get this to iterate a second time. Generators are quite new to me, so it took me a bit even to get the calling down. (For the record, this is a clean dataset with 29 values every line) import numpy as np import csv def getData(filename): with open(filename, "r") as csv1: reader1 = csv.reader(csv1) for row1 in reader1: yield row1 def make_b(size, file): gen = getData(file) data=np.zeros((size,29)) for i in range(size): data[i,:] = next(gen) yield data[:,0],data[:,1:] test=make_b(4,"myfile.csv") next(test) next(test) The reason for this is to use an example of batching data in keras. While it is possible to use different methods to get all of the data into memory, I am trying to introduce to students the concepts of batching data from a large dataset. Since this is a survey course, I wanted to demonstrate batching in data from a large text file, which has proved frustrating difficult for such an 'entry-level' task. (its actually much easier in tensorflow proper, but i am using keras to introduce high level concepts of the MLP).
has comment: http://stackoverflow.com/comment/86298423
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86292788
has comment: http://stackoverflow.com/comment/86293470
has comment: http://stackoverflow.com/comment/86293973
linked to: http://stackoverflow.com/q/8290397
tagged with: generator
has title: Making a generator read multiple lines
type: Question
answer count: 0

http://stackoverflow.com/a/52011299
has comment: http://stackoverflow.com/comment/90993236
downvote count: 0
answers question: http://stackoverflow.com/q/49749706
type: Answer
score: 4
upvote count: 4
has body: if p is a Tensor of probabilities (or unnormalized relative probabilities) where p[i] is the probability that dataset i is chosen, you can use tf.multinomial in conjunction with tf.contrib.data.choose_from_datasets: # create some datasets and their unnormalized probability of being chosen datasets = [ tf.data.Dataset.from_tensors(['a']).repeat(), tf.data.Dataset.from_tensors(['b']).repeat(), tf.data.Dataset.from_tensors(['c']).repeat(), tf.data.Dataset.from_tensors(['d']).repeat()] p = [1., 2., 3., 4.] # unnormalized # random choice function def get_random_choice(p): choice = tf.multinomial(tf.log([p]), 1) return tf.cast(tf.squeeze(choice), tf.int64) # assemble the "choosing" dataset choice_dataset = tf.data.Dataset.from_tensors([0]) # create a dummy dataset choice_dataset = choice_dataset.map(lambda x: get_random_choice(p)) # populate it with random choices choice_dataset = choice_dataset.repeat() # repeat # obtain your combined dataset, assembled randomly from source datasets # with the desired selection frequencies. combined_dataset = tf.contrib.data.choose_from_datasets(datasets, choice_dataset) Note that the dataset needs to be initialized (you can't use a simple make_one_shot_iterator): choice_iterator = combined_dataset.make_initializable_iterator() choice = choice_iterator.get_next() with tf.Session() as sess: sess.run(choice_iterator.initializer) print ''.join([sess.run(choice)[0] for _ in range(20)]) &gt;&gt; ddbcccdcccbbddadcadb

http://stackoverflow.com/q/49730559
accepted answer: http://stackoverflow.com/a/49730810
has body: I just need pointers on where to begin. I have some experience with Python, but nothing to brag about. My end goal is to create a website that will allow multiple users to access it from different computers to fill the table with simple data, very simillar to what Google Sheets alows, and then printing it on a single sheet of paper. Idealy I want my programm to intelegently determine the width of rows and columns so that the table would look decently and would fill the page accordingly. Right now all I need is some pointers on where to begin. Like can I use SQL to create these tables and have online fuctionality for users to access and fill the spreadsheet, and how to go about printing it. I know this is very noob question, but I can't seem to find anything relevant here on by just using google. Thank you.
tagged with: python
type: AnsweredQuestion
tagged with: printing
tagged with: google-sheets
has title: Recreating Google Sheets functionality
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49730810
type: Question

http://stackoverflow.com/comment/125899205
type: AnswerComment
comment on: http://stackoverflow.com/a/71158709
score: 0
has text: This technically works, but is there a way to make the widths lock together so they can change if needed if the plot is zoomed or something? This is manually setting a width of 100 which happens to work, but what if I didn't know that 100 was a good idea and I wanted it to be allowed to update automatically? I'm giving it +1 for being better than nothing but not accepting it yet because I hope for more.
type: Comment

http://stackoverflow.com/comment/86372836
has text: Trademark capitalization; acronym capitalization; grammar; layout.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49677555
score: 0

http://stackoverflow.com/q/49639242
type: Question
has body: I have this dictionary and I want to sort it by values. d = {3: '__init__', 5: 'other', 7: 'hey', 11: 'hey'} Expected output: {3:'__init__', 7: 'hey', 11: 'hey' 5: 'other'} I wrote this function def ordenar(dic): d = {} list_2 = list(dic.values()) list_1 = list(dic.keys()) list_3 = [] for i,j in zip(list_1,list_2): list_3.append((i,j)) def quicksort(l): if len(l) &lt;= 1: return l else: (less_eq, piv, greater) = partition(l) less_eq = quicksort(less_eq) greater = quicksort(greater) return less_eq + [piv] + greater def partition(l): piv = l[0] i = 1 less_eq = [] greater = [] while i &lt; len(l): current = l[i] if current &lt;= piv: less_eq.append(current) else: greater.append(current) i = i + 1 return (less_eq, piv, greater) s = quicksort(list_3) for i in s: d[i[0]] = i[1] return d Output obtained: {3: '__init__', 5: 'other', 7: 'hey', 11: 'hey'} How can I fixed it witouth modules? Can you help me please? Edit: I want to order the dictionary by values. If the values are equal what I want is that values sort by it keys. Is it posible?
tagged with: python
tagged with: sorting
tagged with: dictionary
tagged with: python-3.6
downvote count: 6
has answer: http://stackoverflow.com/a/49639289
tagged with: list
has title: Python: Sort dictionary by value (equal values)
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/86286563
has comment: http://stackoverflow.com/comment/86287601
has comment: http://stackoverflow.com/comment/86286404
accepted answer: http://stackoverflow.com/a/49639289
answer count: 1
favorite count: 0
score: -6

http://stackoverflow.com/a/49617442
score: 0
answers question: http://stackoverflow.com/q/49617180
type: Answer
has body: One way to do this would be to use itertools to chain a number of sentinel values to a 3 way tee of the original list, e.g.: In []: xl = [45, 51, 73, 82, 76, 56, 57, 78, 89, 59] ts = [it.chain([0]*c, t) for c, t in enumerate(it.tee(xl, 3))] [sum(x)/sum(1 for i in x if i) for x in it.zip_longest(*ts, fillvalue=0)] Out[]: [45.0, 48.0, 56.333333333333336, 68.66666666666667, 77.0, 71.33333333333333, 63.0, 63.666666666666664, 74.66666666666667, 75.33333333333333, 74.0, 59.0] If 0 is a valid value in the list then you can use another sentinel and explicitly filter it out. Alternatively, you can use collections.deque with a maxlen=3, e.g.: In []: from collections import deque d = deque(maxlen=3) r = [] for x in xl: d.append(x) r.append(sum(d)/len(d)) for _ in range(len(d)-1): d.popleft() r.append(sum(d)/len(d)) r Out[]: [45.0, 48.0, 56.333333333333336, 68.66666666666667, 77.0, 71.33333333333333, 63.0, 63.666666666666664, 74.66666666666667, 75.33333333333333, 74.0, 59.0]

http://stackoverflow.com/q/49725616
answer count: 1
has title: "TypeError: 'int' object is not subscriptable" using PIL
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/49725866
tagged with: python
type: Question
score: 0
has body: Im trying to apply the logarithmic mapping using PIL but i got the error TypeError: 'int' object is not subscriptable My code is: from PIL import Image import math photo = Image.open('TurtleLuminance.jpg') data = photo.getdata() c = 255 / math.log(1+255) logarithmic = [int(c * math.log(1+data[x][0]) + c * math.log(1+data[x][1]) + c * math.log(1+data[x][2])) for x in range(len(data))] gray_image = Image.new('L', photo.size) gray_image.putdata(logarithmic) gray_image.save('TurtleLogarithmic.jpg') photo.close() gray_image.close() Someone could help me?
has comment: http://stackoverflow.com/comment/86465162
type: UnansweredQuestion

http://stackoverflow.com/comment/86330468
type: QuestionComment
score: 0
has text: @sciroccorics: Have you actually compared timings? Your current ad-hoc parser may operate faster than you can get input, but something out of a parser generator would likely also outpace your input speed, with the benefit of being less error-prone. It might even be faster than your current code, depending on the grammar and the parser generator.
type: Comment
comment on: http://stackoverflow.com/q/49649606

http://stackoverflow.com/q/49607549
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86248113
tagged with: python
has comment: http://stackoverflow.com/comment/86222390
has comment: http://stackoverflow.com/comment/86247708
has comment: http://stackoverflow.com/comment/86222459
has comment: http://stackoverflow.com/comment/86221763
score: 2
tagged with: pandas
answer count: 0
has body: I have the data similar to this dictionary and I am working on Win32 bit Win7 machine. Following code working fine on Win64 bit Win10 but not in Win32. I am getting this "TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'" if I run this on Win32 Win7. I searched the answer everywhere and not sure where to put the .astype('int32') codes. in my code. What I wanted to achieve was there are rows, for this case, 4th row, under PA column, data is with comma, I would like to split them into next row as well as respective columns "var2" and "var3". Something like this in separate row d with var2=2 and var3=65. Then, in another row, e with var2=2 and var3=65, then in another row, f is with var2=2 and var3=65. Can someone please help me with this? Thanks millions. import pandas as pd import numpy as np a = DataFrame([{'PA': 'a', 'var2': 1, 'var3': 3}, {'PA': 'b', 'var2': 3, 'var3': 54}, {'PA': 'c', 'var2': 54,'var3': 3}, {'PA': 'd,e,f', 'var2': 2, 'var3':65}]) lst_col = 'PA' x = a.assign(**{lst_col:a[lst_col].str.split(',')}) TS1 = pd.DataFrame({ col:np.repeat(x[col].values, x[lst_col].str.len()) for col in x.columns.difference([lst_col])}).assign(**{lst_col:np.concatenate(x[lst_col].values)})[x.columns.tolist()] error: TypeErrorTraceback (most recent call last) &lt;ipython-input-12-4f61e3646357&gt; in &lt;module&gt;() 11 TS1 = pd.DataFrame({ 12 col:np.repeat(x[col].values, x[lst_col].str.len()) ---&gt; 13 for col in x.columns.difference([lst_col])}).assign(**{lst_col:np.concatenate(x[lst_col].values)})[x.columns.tolist()] 14 &lt;ipython-input-12-4f61e3646357&gt; in &lt;dictcomp&gt;((col,)) 11 TS1 = pd.DataFrame({ 12 col:np.repeat(x[col].values, x[lst_col].str.len()) ---&gt; 13 for col in x.columns.difference([lst_col])}).assign(**{lst_col:np.concatenate(x[lst_col].values)})[x.columns.tolist()] 14 D:\Users\gexakz\AppData\Local\Continuum\anaconda2\lib\site-packages\numpy\core\fromnumeric.pyc in repeat(a, repeats, axis) 421 422 …
downvote count: 0
favorite count: 0
has title: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'
type: Question
tagged with: numpy
upvote count: 2

http://stackoverflow.com/a/49697053
answers question: http://stackoverflow.com/q/49696701
accepted answer of: http://stackoverflow.com/q/49696701
upvote count: 5
type: Answer
has body: In general, dunder methods define how an object behaves in a particular context. They aren't intended to be used directly. (The major exception being when you are overriding a dunder method inherited from a parent class.) In the case of __str__, there are three documented uses; it is used by the built-in functions str, format, and print so that (roughly speaking) str(myObj) == myObj.__str__() format("{}", myObj) == format("{}", myObj.__str__()) print(myObj) == print(myObj.__str__()). The key here is that __str__ allows code that isn't built-in to Python to work with these functions; the __str__ method provides the common interface all three can use.
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49704498
has title: How do I search if a word exists in a file in python?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86422321
has comment: http://stackoverflow.com/comment/86422382
linked to: http://stackoverflow.com/q/16922214
has answer: http://stackoverflow.com/a/49704599
has answer: http://stackoverflow.com/a/49704556
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49704542
has answer: http://stackoverflow.com/a/49704633
tagged with: python
answer count: 6
downvote count: 6
has comment: http://stackoverflow.com/comment/86422297
has comment: http://stackoverflow.com/comment/86422269
upvote count: 2
has answer: http://stackoverflow.com/a/49704645
has body: I have a file called 'dictionary.txt' which contains words of the dictionary in alphabetical order. I want to search if certain words are in this dictionary. Could anyone help me write code that could open this file, then I write a word as an input and I receive an output that says if the word is in the dictionary file or not? Here's what I have so far:- dicfile = open('dictionary.txt', 'r') word = input('enter a word: ') if word in dicfile: print('true') else: print('false')
score: -4
tagged with: file
has answer: http://stackoverflow.com/a/49704629

http://stackoverflow.com/q/49646954
downvote count: 0
tagged with: loops
favorite count: 0
has comment: http://stackoverflow.com/comment/86310166
has title: python: increase performance of finding the best timeshift for a correlation between each X column and y
tagged with: performance
type: Question
upvote count: 2
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86313092
has body: I have a dataframe X with several columns and a dataframe y with only one column (series). The rows in X represent timesteps and I want to find the interval I need to shift each column of X to obtain the highest correlation with y. I wrote a function that loops over all columns and then loops over all timesteps and correlates the X column with y. If the R² is better than before I store the timestep. However, with over 300 columns this routine is really taking some time and I need to increase the performance. Is there a nice way to simplify this code? (In the example I used the iris data set which is of course not a timeseries...) from sklearn import datasets import pandas as pd import numpy as np #import matplotlib.pyplot as plt from copy import deepcopy def get_best_shift(dfX, dfy, ti=60, maxt=1440): """ determines the best correlation for the last maxt minutes based on a timestep of ti minutes. Creates a dataframe with the shifted variables based on the best match (strongest correlation). """ df_out = deepcopy(dfX) for xcol in dfX: bestshift = 0 Rmax = 0 for ishift in range(0, int(maxt / ti)): xvals = dfX[xcol].iloc[0:(dfX.shape[0] - ishift)].values yvals = np.array([val[0] for val in dfy.iloc[ishift:dfy.shape[0]].values]) selector = np.array([str(val)!="nan" for val in (xvals*yvals)],dtype=bool) xvals = xvals[selector] yvals = yvals[selector] R = np.corrcoef(xvals,yvals)[0][1] # plt.figure() # plt.plot(xvals,yvals,'k.') # plt.show() if R ** 2 &gt; Rmax: Rmax = R ** 2 # print(Rmax) bestshift = ishift df_out[xcol] = list(np.zeros(bestshift)) + list(dfX[xcol].iloc[0:dfX.shape[0] - bestshift].values) df_out = df_out.rename(columns={xcol: ''.join([str(xcol), '_t-', str(bestshift)])}) return df_out iris = datasets.load_iris() X = pd.DataFrame(iris.data) y = pd.DataFrame(iris.target) df = get_best_shift(X,y)
tagged with: pandas
score: 2
answer count: 0

http://stackoverflow.com/comment/86220615
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49606856
has text: I know the JSON library can help with the final dump formatting, but making the data parse into the proper timeseries subgroupings is what Im having difficulty with. Just updated to show output example.

http://stackoverflow.com/comment/86285996
has text: I cannot even put a `NaN` in an index array, because `NaN` is `float` not integer. Example `a = np.arange(10)` `a[0] = np.nan` raises a `ValueError`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49639038
score: 0
type: Comment

http://stackoverflow.com/q/49674875
favorite count: 0
type: Question
tagged with: evaluation-strategy
answer count: 2
has comment: http://stackoverflow.com/comment/94782262
has body: Question Is there any way to declare function arguments as non-strict (passed by-name)? If this is not possible directly: are there any helper functions or decorators that help me achieve something similar? Concrete example Here is a littly toy-example to experiment with. Suppose that I want to build a tiny parser-combinator library that can cope with the following classic grammar for arithmetic expressions with parentheses (numbers replaced by a single literal value 1 for simplicity): num = "1" factor = num | "(" + expr + ")" term = factor + "*" + term | factor expr = term + "+" + expr | term Suppose that I define a parser combinator as an object that has a method parse that can take list of tokens, current position, and either throw a parse error, or return a result and a new position. I can nicely define a ParserCombinator base class that provides + (concatenation) and | (alternative). Then I can define parser combinators that accept constant strings, and implement + and |: # Two kinds of errors that can be thrown by a parser combinator class UnexpectedEndOfInput(Exception): pass class ParseError(Exception): pass # Base class that provides methods for `+` and `|` syntax class ParserCombinator: def __add__(self, next): return AddCombinator(self, next) def __or__(self, other): return OrCombinator(self, other) # Literally taken string constants class Lit(ParserCombinator): def __init__(self, string): self.string = string def parse(self, tokens, pos): if pos &lt; len(tokens): t = tokens[pos] if t == self.string: return t, (pos + 1) else: raise ParseError else: raise UnexpectedEndOfInput def lit(str): return Lit(str) # Concatenation class AddCombinator(ParserCombinator): def __init__(self, first, second): self.first = first self.second = second def parse(self, tokens, pos): x, p1 = self.first.parse(tokens, pos) y, p2 = self.second.parse(tokens, p1) return (x, y), p2 # Alternative class OrCombinator(ParserCombinator): def __init__(self, first, second): self.first = fir…
accepted answer: http://stackoverflow.com/a/49675552
tagged with: python
has answer: http://stackoverflow.com/a/49675552
has title: Non-strict by-name arguments in Python?
type: AnsweredQuestion
score: 3
tagged with: callbyname
upvote count: 3
possible better answer: http://stackoverflow.com/a/49681305
downvote count: 0
has answer: http://stackoverflow.com/a/49681305
tagged with: parser-combinators

pyrfc
tags question: http://stackoverflow.com/q/49691298
tag name: pyrfc
type: Tag

http://stackoverflow.com/a/49629139
has comment: http://stackoverflow.com/comment/86266543
has comment: http://stackoverflow.com/comment/86295810
has comment: http://stackoverflow.com/comment/86267491
answers question: http://stackoverflow.com/q/49627983
has body: While your Python code is opening a pipe to a shell script that takes as argument something that looks like it's a Perl script, this question is really related to pipes in Python. This script is waiting for user input like 'i', 'm', 'c' like arguments. You can send an 'i' to the process using pi.communicate('i').
type: Answer
score: 0

http://stackoverflow.com/q/49730967
has answer: http://stackoverflow.com/a/51780519
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50501056
answer count: 3
accepted answer: http://stackoverflow.com/a/49978483
downvote count: 0
has answer: http://stackoverflow.com/a/49978483
has body: I recently started working on my very first dashboard application using dash. The tutorials are comprehensible, however, I have a hard time handling the front end details because I cannot find an API reference. Specifically, each element accepts a style argument that let's us modify some CSS details, like text alignment, fonts etc. I have seen some examples in the tutorials but I would love to have an exhaustive list of everything I can pass there. As an example, I want to create a table but the columns are too close together. I need to control the spacing between them and I imagine there should be an argument like padding, spacing, borderSize... you get the point. Where can I find these details?
possible better answer: http://stackoverflow.com/a/51780519
has title: Plotly Dash API documentation
favorite count: 0
type: Question
score: 5
tagged with: plotly-dash
upvote count: 5
tagged with: python
tagged with: css

http://stackoverflow.com/q/49631976
type: Question
has answer: http://stackoverflow.com/a/49635082
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86271231
has comment: http://stackoverflow.com/comment/86271267
tagged with: parsing
has body: I am trying to use the following line of code to get all the pathnames of files in a given directory: trainDB = [os.path.abspath(x) for x in os.listdir("C:/Users/sean/Documents/uni/ANLP/Data/Train/DrugBank")] But the ouput is like so: ['C:\\Users\\sean\\Documents\\uni\\ANLP\\Data\\19-norandrostenedione_ddi.xml', ...] Whereas I want/expect the resultant path to be: `'C:\\Users\\sean\\Documents\\uni\\ANLP\\Data\\Train\\DrugBank\\19-norandrostenedione_ddi.xml' I dont understand why the Train/DrugBank diretories are not in the path, if its any use I am runnig these commands from the ANLP directory which is one above Data
tagged with: os.path
upvote count: 0
type: UnansweredQuestion
has title: Not getting full path when using os.path.abspath in conjunction with os.listdir
answer count: 1
tagged with: directory
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49754318
type: Question
has comment: http://stackoverflow.com/comment/86551798
tagged with: pyspark
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49754523
tagged with: apache-spark
score: 1
has answer: http://stackoverflow.com/a/49754523
has body: I'm interested in a nice and clear representation of Spark RDD lineages or operator graphs for educational purposes. I tried .toDebugString() but I'm having trouble getting it pretty-printed (including line breaks etc.) What is going wrong here? Using Python version 3.6.4 (default, Mar 1 2018 18:36:42) SparkSession available as 'spark'. &gt;&gt;&gt; sc &lt;SparkContext master=local[*] appName=PySparkShell&gt; &gt;&gt;&gt; rdd = sc.parallelize(range(10000)) &gt;&gt;&gt; rdd.toDebugString() b'(4) PythonRDD[1] at RDD at PythonRDD.scala:48 []\n | ParallelCollectionRDD[0] at parallelize at PythonRDD.scala:175 []' &gt;&gt;&gt; print(rdd.toDebugString()) b'(4) PythonRDD[1] at RDD at PythonRDD.scala:48 []\n | ParallelCollectionRDD[0] at parallelize at PythonRDD.scala:175 []' &gt;&gt;&gt; Beyond the debug string, are there even better ways of visualizing the graph?
has title: Nice output of RDD lineage/Spark operator graph
favorite count: 0

http://stackoverflow.com/q/49688273
has comment: http://stackoverflow.com/comment/86388880
has title: Socket could not be created. Operation not permitted (udp)
type: UnansweredQuestion
tagged with: sockets
linked to: http://stackoverflow.com/q/6826407
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/86388985
tagged with: udp
has comment: http://stackoverflow.com/comment/86396327
has body: I'm having trouble with this line of code that would not run without sudo. try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) except socket.error, msg: print 'Socket could not be created. Error Code: ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() I get : Socket could not be created. Error Code : 1 Message Operation not permitted. Does anybody have a solution for this? Thanks in advance
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/45127645
answer count: 0

http://stackoverflow.com/comment/86299645
type: Comment
type: QuestionComment
has text: So, how can i clean that? please!
comment on: http://stackoverflow.com/q/49645135
score: 0

http://stackoverflow.com/comment/104452287
type: AnswerComment
has text: if you use `communicate()` there are things you cannot do, like reading line by line and performing actions in real-time when the process is outputting data. Simplest example: printing and logging to the console at the same time, and detecting a special line to terminate the process (specially if the process runs forever if not stopped, which forbids the use of communicate…). Also most of the time merging output & error streams are okay, and it avoids deadlocks (if output is consumed of course)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49728599

http://stackoverflow.com/comment/86491517
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49738490
has text: thanks. But of course it does not solve. See traceback. The entire booster arg in unexpected
type: Comment

http://stackoverflow.com/a/49660479
has comment: http://stackoverflow.com/comment/133876817
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49648391
has body: Have you tried following instructions from here? https://github.com/mrjbq7/ta-lib And change any sudo apt-get to just !apt. Any cd to %cd Update: try this !wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz !tar -xzvf ta-lib-0.4.0-src.tar.gz %cd ta-lib !./configure --prefix=/usr !make !make install !pip install Ta-Lib import talib Update(may 2020): for binary install (no compile) url = 'https://launchpad.net/~mario-mariomedina/+archive/ubuntu/talib/+files' ext = '0.4.0-oneiric1_amd64.deb -qO' !wget $url/libta-lib0_$ext libta.deb !wget $url/ta-lib0-dev_$ext ta.deb !dpkg -i libta.deb ta.deb !pip install ta-lib import talib Update(may 2021): even faster url = 'https://anaconda.org/conda-forge/libta-lib/0.4.0/download/linux-64/libta-lib-0.4.0-h516909a_0.tar.bz2' !curl -L $url | tar xj -C /usr/lib/x86_64-linux-gnu/ lib --strip-components=1 url = 'https://anaconda.org/conda-forge/ta-lib/0.4.19/download/linux-64/ta-lib-0.4.19-py37ha21ca33_2.tar.bz2' !curl -L $url | tar xj -C /usr/local/lib/python3.7/dist-packages/ lib/python3.7/site-packages/talib --strip-components=3 import talib Update (dec 2021): from @roborative, this is easiest to remember and take 3.8s (above is 1.2s) !pip install talib-binary Update (mar 2023): Colab is now Python 3.9, talib-binary is not updated yet, so revert to conda extraction url = 'https://anaconda.org/conda-forge/libta-lib/0.4.0/download/linux-64/libta-lib-0.4.0-h166bdaf_1.tar.bz2' !curl -L $url | tar xj -C /usr/lib/x86_64-linux-gnu/ lib --strip-components=1 url = 'https://anaconda.org/conda-forge/ta-lib/0.4.19/download/linux-64/ta-lib-0.4.19-py39hd257fcd_4.tar.bz2' !curl -L $url | tar xj -C /usr/local/lib/python3.9/dist-packages/ lib/python3.9/site-packages/talib --strip-components=3 import talib Update (apr 2023): Colab is now Python 3.10 url = 'https://anaconda.org/conda-forge/libta-lib/0.4.0/download/linux-64/libta-lib-0.4.0-h166bdaf_1.tar.bz2' !curl -L $url | tar xj -C /usr/lib/x86_64-linux-gnu/ lib --strip-components…
has comment: http://stackoverflow.com/comment/133873475
accepted answer of: http://stackoverflow.com/q/49648391
upvote count: 96
has comment: http://stackoverflow.com/comment/139971323
downvote count: 0
has comment: http://stackoverflow.com/comment/124681470
type: Answer
has comment: http://stackoverflow.com/comment/134260743
score: 96
has comment: http://stackoverflow.com/comment/139980782

http://stackoverflow.com/comment/86418493
has text: Yes, I accept your answer. Could you please expand it or explain what's happening in the function. Thank you.
comment on: http://stackoverflow.com/a/49700614
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/57705278
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49737459
score: 3
has body: Create task in build.py @task def run(project): path.append("src/main/python") from test_pack import test_app test_app.main() Try: pyb run

http://stackoverflow.com/comment/137464061
has text: The op problem also happens when writting to an excel, setting both index and header to false fix it. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49634277
type: AnswerComment

http://stackoverflow.com/comment/86354229
comment on: http://stackoverflow.com/q/49661216
score: 0
type: Comment
type: QuestionComment
has text: What happens when you use `low` and `high` for measurements? I get that the model is misspecified. What is happening is that there is no reason `early_low < early_high`, which leads you to regions with 0 probability. Even after you fix that, `measurements` being uniform means you must be sure that the generative model never allows values outside the observed ones (as it stands, you *do* allow that).

http://stackoverflow.com/q/49757674
has comment: http://stackoverflow.com/comment/86530516
downvote count: 0
answer count: 1
has title: why does sys.stdout = None work?
has comment: http://stackoverflow.com/comment/86530557
favorite count: 0
type: AnsweredQuestion
tagged with: stdout
tagged with: python
accepted answer: http://stackoverflow.com/a/49757760
score: 10
upvote count: 10
type: Question
has answer: http://stackoverflow.com/a/49757760
has body: i can silence and restore sys.stdout this way: import sys sys.stdout = None print('hello') # does not write to stdout sys.stdout = sys.__stdout__ print('hello') # writes to stdout i know i'd better be using contextlib.redirect_stdout which probably does something similar but my question is: why does the above code work? i'd have assumed python would call things like sys.stdout.write() so whatever i replace sys.stdout with should have a write method (like e.g. io.StringIO) at least.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86530393
tagged with: python-internals

http://stackoverflow.com/a/49700214
has comment: http://stackoverflow.com/comment/104895097
type: Answer
accepted answer of: http://stackoverflow.com/q/49699802
score: 3
has body: The code is working. However, when you bind to a canvas object, you have to click on part of the drawn object. Since you didn't fill the oval, that means you must click on its outline. If you fill it with the same color as the background (or any other color) you can click anywhere in the oval. self.oval = self.c.create_oval([30,50], [130,80], fill="white")
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49699802
downvote count: 0

http://stackoverflow.com/comment/86286173
has text: Ah -- right. module recursion, not datum recursion.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49639126
type: Comment

http://stackoverflow.com/comment/86261098
type: AnswerComment
has text: That seemed to do it! Thank you so much
type: Comment
comment on: http://stackoverflow.com/a/49626866
score: 0

http://stackoverflow.com/a/49671172
has comment: http://stackoverflow.com/comment/86352679
type: Answer
has comment: http://stackoverflow.com/comment/86353163
score: 0
answers question: http://stackoverflow.com/q/49670906
has comment: http://stackoverflow.com/comment/86354866
has body: you can use update: A = {'a':10, 'b': 11} B = {'a':5, 'c': 8} B.update(A) &gt;&gt; B &gt;&gt; {'a': 10, 'b': 11, 'c': 8} As you can not have a duplicate key with different value in a dict, it overrides the same keys with the key in A dictionary. read the documentation here Update or if you have to keep both values you have to create a list of dictionaries like this: l = [A, B, C]
has comment: http://stackoverflow.com/comment/86354942
has comment: http://stackoverflow.com/comment/86352775

http://stackoverflow.com/comment/86515923
has text: Thanks a lot, it's ok, I love this site :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49750537

http://stackoverflow.com/q/49610780
type: Question
has answer: http://stackoverflow.com/a/49642042
has title: Avoid Deadlocks Using Teradata and SQLAlchemy
has comment: http://stackoverflow.com/comment/86260669
tagged with: python
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/86255137
has comment: http://stackoverflow.com/comment/86254350
has comment: http://stackoverflow.com/comment/86237660
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49642042
has comment: http://stackoverflow.com/comment/86254352
has comment: http://stackoverflow.com/comment/86239146
answer count: 1
tagged with: teradata
has body: I am using sqlalchemy and sqlalchemy-teradata to query on my database. Every select statement generated by sqlalchemy would generate a table lock which impacts other concurrent users who cannot perform any insert, update or delete operation on the table while the previous user is reading it. To avoid such table locks, I need to add the following string before the SELECT statement: LOCK ROW FOR ACCESS SELECT * FROM DATABASE.TABLE; How can I override sqlalchemy select statements to add this string? Note that I have also raised the issue on GitHub here but did not find any solution so far: https://github.com/Teradata/sqlalchemy-teradata/issues/39 [Update] When connecting to Teradata, I have added the statement provided below by dnoeth: from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base, DeferredReflection from sqlalchemy.orm import scoped_session, sessionmaker [...] engine = create_engine('teradata://' + user + ':' + password + '@' + host + ':22/' + database) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) db_session.execute('SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;') # To avoid locking tables when doing select on tables Base = declarative_base(cls=DeferredReflection) Base.query = db_session.query_property() But now I have the following error message when SQLAlchemy tries to read Teradata meta data: sqlalchemy.exc.DatabaseError: (teradata.api.DatabaseError) (3932, '[25000] [Teradata][ODBC Teradata Driver][Teradata Database] Only an ET or null statement is legal after a DDL Statement. ') [SQL: 'SELECT columnname, columntype, columnlength, chartype, decimaltotaldigits, decimalfractionaldigits, columnformat, nullable, defaultvalue, idcoltype \nFROM dbc.ColumnsV \nWHERE DatabaseName=? AND TableName=?'] [parameters: ('dev_migration_tool', 'migration_object_type')]

http://stackoverflow.com/comment/86262831
has text: I don't think this question is a duplicate of https://stackoverflow.com/questions/12572362/get-a-string-after-a-specific-substring for two reasons: (a) That question is asking about getting the remainder of the string after a given word, not an identified substring, and (b) This question is specifically asking how to accomplish the task with regex; only two answers of that question use regexs, and they use them in a way that doesn't work for this question.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49621540

http://stackoverflow.com/comment/86368928
type: AnswerComment
has text: I updated selenium, chromedriver and reinstalled python and the error still comes out :(
score: 0
comment on: http://stackoverflow.com/a/49678566
type: Comment

http://stackoverflow.com/q/49617485
linked to: http://stackoverflow.com/q/68988489
has comment: http://stackoverflow.com/comment/86250769
has body: I have done some research and the consensus appears to state that this is impossible without a lot of knowledge and work. However: Would it be possible to run the same test in different tabs simultaneously? If so, how would I go about that? I'm using python and attempting to run 3-5 of the same test at once. This is not a generic test, hence I do not care if it interrupts a clean testing environment.
has title: Is it possible to run multiple instances of one selenium test at once?
tagged with: python
has answer: http://stackoverflow.com/a/49627616
tagged with: webdriver
upvote count: 14
has comment: http://stackoverflow.com/comment/86261938
has answer: http://stackoverflow.com/a/49624590
has answer: http://stackoverflow.com/a/69209465
has comment: http://stackoverflow.com/comment/86242240
has comment: http://stackoverflow.com/comment/86242081
answer count: 3
downvote count: 0
tagged with: selenium
type: UnansweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86245526
score: 14
has comment: http://stackoverflow.com/comment/130686029

http://stackoverflow.com/q/49624391
tagged with: python
has comment: http://stackoverflow.com/comment/86255824
has answer: http://stackoverflow.com/a/49624483
has body: I got an error,ModuleNotFoundError: No module named 'test2'.I made test1.py and test2.py.I wanna call test2.py's module in test1.py.So I wrote codes import test2 as test in test1.py but the error happens.I rewrote from test2 import test but same error happens.What is wrong in my code?How should I fix this?I am using IDE so I think I can install module automatically, but in this time it cannot be done.
has title: ModuleNotFoundError: No module named 'test2'
type: UnansweredQuestion
score: -2
answer count: 1
downvote count: 3
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49662409
tagged with: string
favorite count: 0
type: Question
tagged with: object
type: AnsweredQuestion
has body: Expert Pythonistas, the problem as follows: I have a mainframe AS/400 extraction made in JSON manipulated into a 'long' single string to be further sliced / sub-stringed (if that's a word). The parsing outcome create instance of a model with several attributes. Those attributes generate a OrderedDict() to be again serialized (this is because in the future, the source of data may change and I need to maintain the abstraction at this level). I learned from recent studies that the best way to maintain a attribute / data that is '' (empty string) as None to be best analyzed in the future. for i, line in enumerate(data_json): swap_string += line['data'] if data_json[i] == data_json[-1] or data_json[i+1]['data'][1] == '_': swap_list.append(swap_string) swap_string = '' And here is the raw outcome: _ D 958.860 L B NA0.000 010 N 001 U 0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 999 T00 000 99 999 -/- 001 BG/CODEBEDINGUNGEN : BG F04/F07/F20; Then, with this string, I have a 'map' or a 'header' that produces the object that can be serialized slicing and so on: slices = ['3:23', '23:24', '26:27', '29:38', '39:42', '43:46', '48:50', '51:52', '53:54', '55:58', '61:67', '72:79'] than, with this, I request the class to instantiate and create these attributes: def __init__(self, bm=None, kg=None, abm_saa=None, la=None, lt=None, bu_su=None, pos=None, hws=None, sp=None, r=None, p=None, asa=None, em_ab=None, em_bis=None, benennung=None, asb=None, t_a=None, vkfbez=None, pws1=None, qu1=None, pws2=None, qu2=None, da=None, anz=None, t_b=None, bg=None, code=None, pruef=None, add_info=None): self.bm = bm self.kg = kg self.abm_saa = abm_saa... and then comes the question: My question is: Using the list with slice delimitations, how to instantiate the object with a for loop into the correct attribute applying a list comprehension? Is also possible to do a loop with the attributes from the class? Also, apply the empty strings as None in the object with a simple if sta…
tagged with: python
has comment: http://stackoverflow.com/comment/86354929
tagged with: substring
accepted answer: http://stackoverflow.com/a/49662910
score: 1
has title: Instantiate object attributes with content of parsed/sliced substrings?
has answer: http://stackoverflow.com/a/49662910
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86231913
comment on: http://stackoverflow.com/a/49612574
score: 0
has text: Fab! You simply read my mind. This is exactly what I needed and struggled for several hours :( Many thanks!!!
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49710454
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/86434567
has body: I'm creating a Money class, and I'd like to pass the object directly to the string format() function and get the money representation with 2 decimals and the currency symbol. What method should I override to print with the string format function? Overriding str and repr did not work. from decimal import Decimal class Money(Decimal): def __str__(self): return "$" + format(self, ',.2f') def __repr__(self): return "$" + format(self, ',.2f') m = Money("123.44") print(m) # $123.44. Good. m # $123.44. Good. print("Amount: {0}".format(m)) # 123.44. Bad. I wanted $123.44 print(f"Amount: {m}") # 123.44. Bad. I wanted $123.44
has comment: http://stackoverflow.com/comment/86434596
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86434656
has comment: http://stackoverflow.com/comment/86434592
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: string-formatting
accepted answer: http://stackoverflow.com/a/49710497
tagged with: python
has answer: http://stackoverflow.com/a/49710497
has title: How to print an object's representation using the string format function?

http://stackoverflow.com/comment/86441977
comment on: http://stackoverflow.com/q/49714285
has text: Have a look at https://stackoverflow.com/questions/17530104/selenium-webdriver-submit-vs-click?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86281823
type: Comment
has text: thanks @mehul-jain this looks good. To ensure the filename is still created using the dateTime would I replace the sub process in my code with your suggested buffer and csv writer. Sorry I am not coder by trade
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49625748

http://stackoverflow.com/a/49737705
upvote count: 32
has comment: http://stackoverflow.com/comment/115326064
answers question: http://stackoverflow.com/q/49737657
has comment: http://stackoverflow.com/comment/86489667
has comment: http://stackoverflow.com/comment/115326751
downvote count: 1
has comment: http://stackoverflow.com/comment/119236917
score: 31
has comment: http://stackoverflow.com/comment/86489601
has body: Use sets: C = list(set(A) - set(B)) In case you want to mantain duplicates and/or oder: filter_set = set(B) C = [x for x in A if x not in filter_set]
has comment: http://stackoverflow.com/comment/115326122
has comment: http://stackoverflow.com/comment/115326372
type: Answer

http://stackoverflow.com/a/49745333
score: 5
type: AcceptedAnswer
downvote count: 0
has body: The command wrapped by the getCollectionInfos mongo shell command is listCollections administrative command. Administrative commands are available to run against the database. However, some mongo shell methods share similar names with administrative commands (.e.g. cloneConnection, currentOp, dropDatabase, and so on). It is easy to think that other mongo shell methods are administrative command but they aren't. Using the listCollections command e.g. # Return information for all collections in the database. db.command('listCollections') # Return information for collection `a` db.command({'listCollections': 1, 'filter': {'name': 'a'}})
answers question: http://stackoverflow.com/q/49743662
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49743662

http://stackoverflow.com/comment/138022323
type: Comment
comment on: http://stackoverflow.com/a/53250584
type: AnswerComment
has text: @gimboland I think the intent was to mimic os.walk() here, hence generator. But of course I agree otherwise.
score: 0

http://stackoverflow.com/comment/86282915
score: 1
type: Comment
has text: @Patrick. Ping me with the question URL when you write it. I'll be happy to take a look.
type: AnswerComment
comment on: http://stackoverflow.com/a/49636565

http://stackoverflow.com/q/49663396
score: 0
has answer: http://stackoverflow.com/a/49663942
linked to: http://stackoverflow.com/q/3207219
has body: I am storing the number of files in a directory in a variable and storing their names in an array. I'm unable to store file names in the array. Here is the piece of code I have written. import os temp = os.system('ls -l /home/demo/ | wc -l') no_of_files = temp - 1 command = "ls -l /home/demo/ | awk 'NR&gt;1 {print $9}'" file_list=[os.system(command)] for i in range(len(file_list)) os.system('tail -1 file_list[i]')
tagged with: shell
has title: I am trying to print the last line of every file in a directory using shell command from python script
has answer: http://stackoverflow.com/a/49663471
possible better answer: http://stackoverflow.com/a/49663471
type: Question
linked to: http://stackoverflow.com/q/6466711
has answer: http://stackoverflow.com/a/49663592
accepted answer: http://stackoverflow.com/a/49663592
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49663464
type: AnsweredQuestion

http://stackoverflow.com/q/49693803
has body: I want to use regex to get a part of the string. I want to remove the kerberos and everything after it and get the Username import re text = 'Kerberos://DME.DMS.WORLD.DMSHEN/Username' reg1 = re.compile(r"^((Kerberos?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$",text) print(reg1) Output Username I am new to regex and tried this regex but it doesn't seem to work
score: -4
has answer: http://stackoverflow.com/a/49694170
has answer: http://stackoverflow.com/a/49693903
tagged with: python
has comment: http://stackoverflow.com/comment/86400124
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/86400126
has answer: http://stackoverflow.com/a/49694281
tagged with: regex
has title: Regex to find text after linebreak in URL
has comment: http://stackoverflow.com/comment/86400201
favorite count: 0
type: Question
downvote count: 4
possible better answer: http://stackoverflow.com/a/49694170
upvote count: 0
accepted answer: http://stackoverflow.com/a/49693903

http://stackoverflow.com/a/49619896
type: Answer
has body: If you do not know which delimiter is in play for each string, you need to write some logic for this. One suggestion is to maintain a list of potential delimiters (sorted by preference / popularity) and test whether they occur in your string more than once. Below is an example. delimiters = list('-: ') test_list = ['James-Dean-Winchester', 'April:May:June', 'John Abraham Smith', 'Joe:Ambiguous-Connor'] def get_delimiter(x, delim): for sep in delim: if x.count(sep) &gt; 1: return sep else: return None result = [get_delimiter(i, delimiters) for i in test_list] # ['-', ':', ' ', None] You can then link test_list with result via zip, i.e. by iterating indices in each list sequentially. You can split a string by a delimiter using, for example, 'mystr1-mystr2-mystr3'.split('-').
answers question: http://stackoverflow.com/q/49619682
score: 0

http://stackoverflow.com/q/49647160
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49647897
tagged with: architecture
has answer: http://stackoverflow.com/a/63286014
tagged with: python
possible better answer: http://stackoverflow.com/a/58452252
favorite count: 0
has title: Visualizing your code's architecture
has answer: http://stackoverflow.com/a/58452252
tagged with: pycharm
type: Question
tagged with: production-environment
answer count: 3
downvote count: 0
tagged with: productivity-power-tools
upvote count: 40
score: 40
has body: Each weekend I'm coding on a personal project which over time has reached a certain complexity by now, where I have sequences of different functions that take my input, that I save in some class objects, chop it up, process it and then finally output it. Since I make large breaks between coding sessions I usually forget the precise structure of my code. Therefore, each time I have a bug, I have to re-familiarize myself with how the input data flows through my code, how inside some module that provides functionality things are organized etc. I'm not sure if this is due to bad code structure of my software, or simply inherent complexity. Is there a tool that, given the source code, visually shows me how the "architecture" of my code, i.e. how the classes methods and functions all work together? Ideally this would also help me understand code other people wrote faster, to get quickly an overview how the individual code pieces interact. (I'm coding in Python with Pycharm, if that helps you.)
accepted answer: http://stackoverflow.com/a/49647897

http://stackoverflow.com/a/49727272
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49727182
has comment: http://stackoverflow.com/comment/86468636
upvote count: 1
answers question: http://stackoverflow.com/q/49727182
score: 1
type: Answer
has body: What about trying something like this, class CheckCouponAPIView(viewsets.ModelViewSet): # other fields lookup_field = 'slug' From the official DRF Doc, lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to pk
has comment: http://stackoverflow.com/comment/86468747
type: AcceptedAnswer

apache-spark-sql
tags question: http://stackoverflow.com/q/49661371
tags question: http://stackoverflow.com/q/49753377
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/49710133
tags question: http://stackoverflow.com/q/49714328
tags question: http://stackoverflow.com/q/49683897
tags question: http://stackoverflow.com/q/49686275
tags question: http://stackoverflow.com/q/49603529
tags question: http://stackoverflow.com/q/49754476
tags question: http://stackoverflow.com/q/49721738
tags question: http://stackoverflow.com/q/49645139
tags question: http://stackoverflow.com/q/49634651
type: Tag
tags question: http://stackoverflow.com/q/49698111

computer-vision
tags question: http://stackoverflow.com/q/49722830
tags question: http://stackoverflow.com/q/49731759
tags question: http://stackoverflow.com/q/49653667
tags question: http://stackoverflow.com/q/49684468
tags question: http://stackoverflow.com/q/49681166
tags question: http://stackoverflow.com/q/49732469
tags question: http://stackoverflow.com/q/49740758
tags question: http://stackoverflow.com/q/49641791
tags question: http://stackoverflow.com/q/49691870
tags question: http://stackoverflow.com/q/49714258
tags question: http://stackoverflow.com/q/49708891
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/49675692
tags question: http://stackoverflow.com/q/49702795
tags question: http://stackoverflow.com/q/49610140
tags question: http://stackoverflow.com/q/49724767
tags question: http://stackoverflow.com/q/49635465
tags question: http://stackoverflow.com/q/49636870
tags question: http://stackoverflow.com/q/49711650

http://stackoverflow.com/a/49682663
downvote count: 0
has comment: http://stackoverflow.com/comment/86408203
score: 2
accepted answer of: http://stackoverflow.com/q/49682624
has comment: http://stackoverflow.com/comment/86377091
has comment: http://stackoverflow.com/comment/86408051
type: Answer
has comment: http://stackoverflow.com/comment/86414575
answers question: http://stackoverflow.com/q/49682624
upvote count: 2
has body: You can use functools.partial to create a new function object with certain parameters already passed to it: import functools def g(a, b, x): return a*x**2+b g1 = functools.partial(g, 32, 232) #placeholder values class toy: def __init__(self,x): self.x=x @property def y(self): return g1(self.x) t = toy(100) &gt;&gt;&gt;t.y &gt;&gt;&gt;320232 It is perfectly fine, however, to declare a and b outside the class and pass them to g in the property attribute: a = 100 b = 200 def g(x,a,b): return a*x**2+b class toy: def __init__(self,x): self.x=x @property def y(self): return g(self.x, a, b) Lastly, if you have variables that may or may not be used inside the class, consider implementing them as class attributes: class toy: a = 100 b = 200 def __init__(self, x): self.x = x @property def y(self): return g(self.x, toy.a, toy.b)
type: AcceptedAnswer

http://stackoverflow.com/q/49662560
has title: json_normalize() in pandas
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/49731299
has body: Python version: 2.7 I am trying to normalize below json data avaialble in MongoDB . for this i am using json_normalize. However I am not able to flatten the data within "stages" element. It is coming within collection. When I process this "stage" in a row wise it is working fine. How to do I flatten the content within stage along with rest of the data? Sample data is as below. { "_id" : ObjectId("5a8ffe8aaacee33cd21aabcb"), "niyoCustomerCompanyId" : 210068, "version" : 2, "versionDate" : ISODate("2018-02-23T17:14:10.614+05:30"), "data" : { "CustomerCompanyId" : 210068, "companyName" : "XYZ Tractors ", "mobileNo" : "***22****", "cif" : "25", "typeId" : 3, "PartnerCompanyId" : "163929", "companyDetails" : { "sectorType" : "30", "sectorSubType" : "2", "pincode" : "431602", "email" : "abcd@rediffmail.com", "stages" : [ { "name" : "Prequalification", "status" : "done" }, { "name" : "Prequalification1", "status" : "pending" } ], "currentStage" : "Pre-Qualification" } } } Code I tried with is as below. cursor_only_data_stage = customer_collection.find({}) stage_data = list(cursor_only_data_stage) stage_data_df_1 = pd.DataFrame(json_normalize(stage_data)) Expected Output is as below. id cif stage status version versiondate 5a8ffe8aaacee33cd21aabcb 25 Prequalification done 2 2018-02-23T17:14:10.614+05:30 5a8ffe8aaacee33cd21aabcb 25 Prequalification1 pending 2 2018-02-23T17:14:10.614+05:30
has answer: http://stackoverflow.com/a/49731299
type: Question
tagged with: json-normalize
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49742962
tagged with: python
downvote count: 5
has comment: http://stackoverflow.com/comment/86630190
has answer: http://stackoverflow.com/a/49986459
has comment: http://stackoverflow.com/comment/86502382
score: 12
has comment: http://stackoverflow.com/comment/86501184
has comment: http://stackoverflow.com/comment/86500822
has body: I would like to insert a string at a specific column of a specific line in a file, without reading and rewriting the entire file. Suppose I have a file file.txt How was the English test? How was the Math test? How was the Chemistry test? How was the test? I would like to change the last line to say How was the History test? by adding the string History at line 4 column 13. Currently I read in every line of the file and add the string to the specified position. with open("file.txt", "r+") as f: # Read entire file lines = f.readlines() # Update line lino = 4 - 1 colno = 13 -1 lines[lino] = lines[lino][:colno] + "History " + lines[lino][colno:] # Rewrite file f.seek(0) for line in lines: f.write(line) f.truncate() f.close() But I feel like I should be able to simply add the line to the file without having to read and rewrite the entire file.
has comment: http://stackoverflow.com/comment/86500771
has comment: http://stackoverflow.com/comment/86500733
has comment: http://stackoverflow.com/comment/86500809
has comment: http://stackoverflow.com/comment/86531300
has answer: http://stackoverflow.com/a/49961401
has comment: http://stackoverflow.com/comment/87154038
has title: How to insert text at line and column position in a file?
favorite count: 0
upvote count: 17
has comment: http://stackoverflow.com/comment/86500778
linked to: http://stackoverflow.com/q/39086
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2329417
has answer: http://stackoverflow.com/a/49978345
has answer: http://stackoverflow.com/a/49963120
linked to: http://stackoverflow.com/q/17140886
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50068789
has comment: http://stackoverflow.com/comment/86500755
has comment: http://stackoverflow.com/comment/86500975

http://stackoverflow.com/comment/86526050
has text: @kabanus because the array being printed is a numpy array which I cant upload to a sql database, so i was hoping i could upload it as a string, trying to change the numpy array i have tried :
comment on: http://stackoverflow.com/q/49755496
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86338017
comment on: http://stackoverflow.com/q/49663980
has text: yes right,can you suggest me any solution for this?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49631455
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86271888
has comment: http://stackoverflow.com/comment/86271688
score: 1
has title: Revit Dynamo gives error Data Interpolate python script
has body: Interpolate Date- Catmull I am getting the following Error: TypeError: can't multiply sequence by non-int of type 'float' Interpolate Date-Linear I am getting the following error: Unexpexted Token "v3" I am new to Python and wonder what I am doing wrong with this code. Thanks Below is the input to D and t. IN[0] -1.075000 -0.885818 -0.688475 -0.483791 -0.301645 -0.114591 0.077063 0.273042 0.473106 0.677038 1.025973 1.306626 1.592869 1.884406 2.363634 2.597338 2.833636 3.072438 3.313663 3.557232 3.803073 4.051116 4.301297 4.807834 5.069212 5.349055 5.649760 5.971703 IN[1] 0.000000 0.055556 0.111111 0.166667 0.222222 0.277778 0.333333 0.388889 0.444444 0.500000 0.555556 0.611111 0.666667 0.722222 0.777778 0.833333 0.888889 0.944444 1 0.000000 0.027778 0.055556 0.083333 0.111111 0.138889 0.166667 0.194444 0.222222 0.250000 0.277778 0.305556 0.333333 0.361111 0.388889 0.416667 0.444444 0.472222 0.500000 0.527778 0.555556 0.583333 0.611111 0.638889 0.666667 0.694444 0.722222 0.750000 0.777778 0.805556 0.833333 0.861111 0.888889 0.916667 0.944444 0.972222 1 D=IN[0] t=IN[1] a=[] def SampleLinear(v0, v1, t): value = v0 * (1.0 - t) + v1 * t return value def Interpolate (values, parameter): num = len(values) - 1 num2 = parameter * float(num) num3 = int((float(floor(num2))) v3 = values[num3] v4 = values[num3] value = SampleLinear(v3, v4, num2 - float(num3)) return value for i in t: a.append(Interpolate(D,i)) OUT = a D=IN[0] t=IN[1] a=[] def SampleCatmull(v00,v0,v1,v11,t): num = -0.5 * v00 + 1.5 * v0 - 1.5 * v1 + 0.5 * v11 num2 = v00 - 2.5 * v0 + 2.0 * v1 - 0.5 * v11 num3 = -0.5 * v00 + 0.5 * v1 value = num * (t * t * t) + num2 * (t * t) + num3 * t + v0 return value def Interpolate(values, parameter): num = len(values) - 1 num2 = parameter * float(num) num3 = float(floor(num2)) num6 = values[num3] v7 = 0 v8 = 0 num7 = values[num3] if num3 &lt;= 0: v7 = num6 - (num7 - num6) else: v7 = values[num3 - 1] if num3 &gt;= num - 1: v8 = num7 - (num6 - num7) else: v8 = values[num3 + 2] v…
has comment: http://stackoverflow.com/comment/86273835
type: Question
tagged with: interpolation
has comment: http://stackoverflow.com/comment/86270338
has comment: http://stackoverflow.com/comment/86270223
answer count: 2
has comment: http://stackoverflow.com/comment/86270197
tagged with: revit-api
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49633471
has answer: http://stackoverflow.com/a/49733419
downvote count: 0
has comment: http://stackoverflow.com/comment/86272135

http://stackoverflow.com/q/49754476
has body: Say I have a very basic Spark DataFrame that consists of a couple of columns, one of which contains a value that I want to modify. || value || lang || | 3 | en | | 4 | ua | Say, I want to have a new column per specific class where I would add a float number to the given value (this is not much relevant to the final question though, in reality I do a prediction with sklearn there, but for simplicity let's assume we are adding stuff, the idea is I am modifying the value in some way). So given a dict classes={'1':2.0, '2':3.0} I would like to have a column for each class where I add the value from DF to the value of the class and then save it to a csv: class_1.csv || value || lang || my_class | modified || | 3 | en | 1 | 5.0 | # this is 3+2.0 | 4 | ua | 1 | 6.0 | # this is 4+2.0 class_2.csv || value || lang || my_class | modified || | 3 | en | 2 | 6.0 | # this is 3+3.0 | 4 | ua | 2 | 7.0 | # this is 4+3.0 So far I have the following code that works and modifies the value for each defined class, but it is done with a for loop and I am looking for a more advanced optimization for it: import pyspark from pyspark import SparkConf, SparkContext from pyspark.sql import functions as F from pyspark.sql.types import FloatType from pyspark.sql.functions import udf from pyspark.sql.functions import lit # create session and context spark = pyspark.sql.SparkSession.builder.master("yarn").appName("SomeApp").getOrCreate() conf = SparkConf().setAppName('Some_App').setMaster("local[*]") sc = SparkContext.getOrCreate(conf) my_df = spark.read.csv("some_file.csv") # modify the value here def do_stuff_to_column(value, separate_class): # do stuff to column, let's pretend we just add a specific value per specific class that is read from a dictionary class_dict = {'1':2.0, '2':3.0} # would be loaded from somewhere return float(value+class_dict[separate_class]) # iterate over each given class later class_dict = {'1':2.0, '2':3.0} # in reality have more than 10 classes # create a udf function u…
accepted answer: http://stackoverflow.com/a/49754839
has answer: http://stackoverflow.com/a/49754839
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/86525110
tagged with: apache-spark-sql
score: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/86525200
tagged with: pyspark
has title: Applying a udf function in a distributed fashion in PySpark
tagged with: python
linked to: http://stackoverflow.com/q/38048068
has comment: http://stackoverflow.com/comment/86524236
type: AnsweredQuestion

http://stackoverflow.com/q/49743099
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86502147
possible better answer: http://stackoverflow.com/a/49743209
has comment: http://stackoverflow.com/comment/86501319
has comment: http://stackoverflow.com/comment/86501185
has answer: http://stackoverflow.com/a/49743209
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86501083
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49743114
has title: What overhead is incurred in python's reduce implementation?
tagged with: clojurescript
has comment: http://stackoverflow.com/comment/86503500
tagged with: python
has body: I have some python scripts that were taking longer than I expected, so I started investigating and found some surprises in python's performance. Mostly, it seems to revolve around reduce, but I don't understand why. To experiment, I wrote the following two modules: py.py from functools import reduce def mysum(n): return reduce(lambda acc, x: acc + x, range(n + 1)) n = int(1e8) print(mysum(n)) and clj.clj (defn mysum [n] (reduce + (range (inc n)))) (println (mysum 1e8)) I compared their performance using time: ➜ ~ time python py.py 5000000050000000 python py.py 21.90s user 0.41s system 95% cpu 23.344 total ➜ ~ time lumo clj.clj 5000000050000000 lumo clj.clj 2.44s user 0.13s system 102% cpu 2.519 total It appears that python is performing over 10x slower than the clojure implementation. But that is the opposite of what I expected. Even when running the clj file using the JVM, which incurs significant startup costs, python is beat by a mile: ➜ ~ time clj clj.clj 5000000050000000 clj clj.clj 6.01s user 0.72s system 153% cpu 4.394 total Why is python's reduce so slow here? Am I doing something wrong?
accepted answer: http://stackoverflow.com/a/49743114
tagged with: clojure

http://stackoverflow.com/comment/86328216
has text: Okay I will edit the post with code. The image of logcat is what I tried. You may disregard that image.
comment on: http://stackoverflow.com/q/49658880
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49660657
has title: Mimic Tkinter file open in Kivy
upvote count: 1
favorite count: 0
has body: I have worked mostly with Tkinter before and I used the following code to store path of file I selected. After exploring Kivy, it doesn't seem like Kivy have a simple function like this. So I tried using the filechoser instead path = filedialog.askopenfilename(initialdir="/", title="Select file") Main code is very simple class checker_ui(GridLayout): def findreport(self,path): pass class Checker(App): def build(self): return checker_ui() if __name__ == '__main__': Checker().run() Then I created a .kv file just to see what filechooser looks like. The script would just open and freeze. &lt;checker_ui&gt;: BoxLayout: FileChooserIconLayout: id:filechooser on_selection:root.select(*args) Here is the output I search all over the place and did not see anyone with a similar issue. Is there an alternative I can try to mimic the tkinter behaviour or am I stuck with this issue? I'm on a Windows machine and normal kivy widget works, ie: button,label etc.
tagged with: python
tagged with: kivy
type: Question
has answer: http://stackoverflow.com/a/49660754
has answer: http://stackoverflow.com/a/49661256
has answer: http://stackoverflow.com/a/67676493
answer count: 3
type: UnansweredQuestion
score: 1
downvote count: 0

http://stackoverflow.com/a/49732851
has body: That is just an horizontal bar plot in polar projection. Matplotlib defaults will make it look a bit different. ax = plt.subplot(projection='polar') ax.barh(0, math.radians(150)) ax.barh(1, math.radians(300)) ax.barh(2, math.radians(270)) ax.barh(3, math.radians(320)) But it can be tuned: Use set_theta_zero_location() to make the bars start at North. Use set_theta_direction() to make the bars go clockwise. Use set_rlabel_position() to move the radial labels. Use set_thetagrids() and set_rgrids() to set the ticks and labels. The result is very similar: ax.set_theta_zero_location('N') ax.set_theta_direction(-1) ax.set_rlabel_position(0) ax.set_thetagrids([0, 96, 192, 288], labels=[0, 20, 40, 60]) ax.set_rgrids([0, 1, 2, 3], labels=['a', 'b', 'c', 'd']) There must be a way to move the radial labels to the left of the bars but I could not find it. PS A more concise and maybe faster way: ax.barh([0, 1, 2, 3], np.radians([150, 300, 270, 320]), color=plt.rcParams['axes.prop_cycle'].by_key()['color'])
answers question: http://stackoverflow.com/q/49729748
score: 8
upvote count: 8
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49729748

http://stackoverflow.com/a/55924135
has comment: http://stackoverflow.com/comment/127909901
downvote count: 0
upvote count: 30
has comment: http://stackoverflow.com/comment/127912915
has comment: http://stackoverflow.com/comment/127910447
type: Answer
score: 30
answers question: http://stackoverflow.com/q/49685924
has body: To extract Google Drive zip from a Google colab notebook: import zipfile from google.colab import drive drive.mount('/content/drive/') zip_ref = zipfile.ZipFile("/content/drive/My Drive/ML/DataSet.zip", 'r') zip_ref.extractall("/tmp") zip_ref.close()

storage
tag name: storage
tags question: http://stackoverflow.com/q/49743420
type: Tag
tags question: http://stackoverflow.com/q/49724629

http://stackoverflow.com/comment/86537179
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49756839
has text: I know, but it is not my election :). Teachers' stuff...
type: Comment

http://stackoverflow.com/comment/86438304
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49712326
type: Comment
has text: @LseLibrary: Please be clearer in what you expect to happen. You could just test for `name != '0'` but that’s not a very sensible test, for example.

http://stackoverflow.com/a/49696613
answers question: http://stackoverflow.com/q/49681954
score: 0
has body: Try combining your INSERT queries into a single query: INSERT into language (language_id,name,last_update) VALUES ('1','English','2006-02-15 05:02:19.000'), ('2','Italian','2006-02-15 05:02:19.000'), ('3','Japanese','2006-02-15 05:02:19.000'), ('4','Mandarin','2006-02-15 05:02:19.000'), ... ; SQLite has a limit on the size of a single query, which is the value of SQLITE_MAX_SQL_LENGTH and defaults to 1,000,000 bytes. So you'll need to either increase this limit or split this query up into groups that fit into the limit. Doing them in groups of something like 1,000 rows will probably make a noticeable difference.
type: Answer

http://stackoverflow.com/q/49727251
downvote count: 2
tagged with: python
tagged with: string
has body: Is there a way to use the elements of a string-list first as strings and then as int? l = ['A','B','C'] for n in l: use n as string (do some operations) convert n to int(element of NG) use n as int I tried to Play around with range/len but I didnt come to a solution. Edit2: This is what I have: import pandas as pd import matplotlib.pyplot as plt NG = ['A','B','C'] l = [1,2,3,4,5,6] b = [6,5,4,3,2,1] for n in NG: print(n) dflist = [] df = pd.DataFrame(l) dflist.append(df) df2 = pd.DataFrame(b) dflist.append(df2) df = pd.concat(dflist, axis = 1) df.plot() The Output are 3 figures that look like this: But I want them to be in one figure: import pandas as pd import matplotlib.pyplot as plt NG = ['A','B','C'] l = [1,2,3,4,5,6] b = [6,5,4,3,2,1] for n in NG: print(n) dflist = [] df = pd.DataFrame(l) dflist.append(df) df2 = pd.DataFrame(b) dflist.append(df2) df = pd.concat(dflist, axis = 1) ax = plt.subplot(6, 2, n + 1) df.plot(ax = ax) This code works, but only if the list NG is made out of integers [1,2,3]. But I have it in strings. And I Need them in the Loop.
type: Question
linked to: http://stackoverflow.com/q/522563
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86469756
has answer: http://stackoverflow.com/a/49727586
score: -2
tagged with: loops
has title: Using element of list both as string and integer
possible better answer: http://stackoverflow.com/a/49727707
favorite count: 0
accepted answer: http://stackoverflow.com/a/49727842
has comment: http://stackoverflow.com/comment/86468264
tagged with: integer
has comment: http://stackoverflow.com/comment/86468526
has comment: http://stackoverflow.com/comment/86469134
has answer: http://stackoverflow.com/a/49727601
has answer: http://stackoverflow.com/a/49727707
answer count: 4
has answer: http://stackoverflow.com/a/49727842
has comment: http://stackoverflow.com/comment/86468294
upvote count: 0

numpy
tags question: http://stackoverflow.com/q/49716504
tags question: http://stackoverflow.com/q/49697958
tags question: http://stackoverflow.com/q/49606404
tags question: http://stackoverflow.com/q/49680250
tags question: http://stackoverflow.com/q/49669124
tags question: http://stackoverflow.com/q/49696818
tags question: http://stackoverflow.com/q/49729175
tags question: http://stackoverflow.com/q/49678440
tags question: http://stackoverflow.com/q/49724471
tags question: http://stackoverflow.com/q/49729340
tags question: http://stackoverflow.com/q/49691845
tags question: http://stackoverflow.com/q/49652445
tags question: http://stackoverflow.com/q/49647572
tags question: http://stackoverflow.com/q/49737192
tags question: http://stackoverflow.com/q/49684310
tags question: http://stackoverflow.com/q/49629849
tags question: http://stackoverflow.com/q/49754713
tags question: http://stackoverflow.com/q/49674212
tags question: http://stackoverflow.com/q/49721113
tags question: http://stackoverflow.com/q/49690325
tags question: http://stackoverflow.com/q/49642057
tags question: http://stackoverflow.com/q/49635573
tags question: http://stackoverflow.com/q/49605231
tags question: http://stackoverflow.com/q/49740758
tags question: http://stackoverflow.com/q/49718603
tags question: http://stackoverflow.com/q/49757871
tags question: http://stackoverflow.com/q/49613477
tags question: http://stackoverflow.com/q/49720605
tags question: http://stackoverflow.com/q/49693770
tags question: http://stackoverflow.com/q/49684379
tags question: http://stackoverflow.com/q/49683500
tags question: http://stackoverflow.com/q/49661049
tags question: http://stackoverflow.com/q/49705519
tags question: http://stackoverflow.com/q/49717999
tags question: http://stackoverflow.com/q/49628741
tags question: http://stackoverflow.com/q/49661456
tags question: http://stackoverflow.com/q/49657317
tags question: http://stackoverflow.com/q/49750470
tags question: http://stackoverflow.com/q/49675331
tags question: http://stackoverflow.com/q/49754797
tags question: http://stackoverflow.com/q/49711922
tags question: http://stackoverflow.com/q/49668314
tags question: http://stackoverflow.com/q/49647182
tags question: http://stackoverflow.com/q/49657956
tags question: http://stackoverflow.com/q/49626150
tags question: http://stackoverflow.com/q/49713611
tags question: http://stackoverflow.com/q/49635871
tags question: http://stackoverflow.com/q/49644385
tags question: http://stackoverflow.com/q/49709108
tags question: http://stackoverflow.com/q/49632200
tags question: http://stackoverflow.com/q/49624840
tags question: http://stackoverflow.com/q/49749709
tags question: http://stackoverflow.com/q/49643676
tags question: http://stackoverflow.com/q/49640315
tags question: http://stackoverflow.com/q/49662776
tags question: http://stackoverflow.com/q/49712419
tags question: http://stackoverflow.com/q/49735187
tags question: http://stackoverflow.com/q/49715547
tags question: http://stackoverflow.com/q/49755239
tags question: http://stackoverflow.com/q/49643616
tags question: http://stackoverflow.com/q/49701525
tags question: http://stackoverflow.com/q/49756264
tags question: http://stackoverflow.com/q/49744376
tags question: http://stackoverflow.com/q/49733952
tags question: http://stackoverflow.com/q/49640823
tags question: http://stackoverflow.com/q/49647836
tags question: http://stackoverflow.com/q/49694837
tags question: http://stackoverflow.com/q/49619681
tags question: http://stackoverflow.com/q/49727534
tags question: http://stackoverflow.com/q/49678660
type: Tag
tags question: http://stackoverflow.com/q/49722046
tags question: http://stackoverflow.com/q/49738489
tags question: http://stackoverflow.com/q/49684213
tags question: http://stackoverflow.com/q/49721159
tags question: http://stackoverflow.com/q/49730895
tags question: http://stackoverflow.com/q/49612061
tags question: http://stackoverflow.com/q/49742975
tags question: http://stackoverflow.com/q/49677889
tags question: http://stackoverflow.com/q/49681081

http://stackoverflow.com/q/49728012
has answer: http://stackoverflow.com/a/49730282
favorite count: 0
type: Question
tagged with: refresh
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49728491
has answer: http://stackoverflow.com/a/49730064
score: 2
upvote count: 2
downvote count: 0
answer count: 3
tagged with: pyqt
has body: i have a problem with my qt GUI. I want to update/refresh my GUI every secound, and if there is an element in a list, to add a new textline or a new button. Seen much posts about threading and qtimer but not really understand it for my GUI. So i want to update everything or just want to add the new one and if the call hang up it have to be deleted.just added the code without the trys of refreshing, because they dont work how they have to ^^. would help me alot if you can help me :) Thanks import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5 import * from PyQt5.QtCore import * import time import CTI import APIConnect class Fenster(QWidget): def __init__(self): super().__init__() self.initMe() def initMe(self): i = 1 box = QVBoxLayout(self) self.setLayout(box) Rufnummer = 0 result = APIConnect.list_users() anrufe = APIConnect.anrufe() for e in result: self.User = box.addWidget(QPushButton(e[6]+"\n"+e[7])) box.addStretch(1) self.setGeometry(50, 50, 200, 750) self.setWindowTitle("CTI") self.setWindowIcon(QIcon("telefon.png")) self.show() app = QApplication(sys.argv) w = Fenster() sys.exit(app.exec_())
has title: PyQt GUI Refresh
tagged with: pyqt5

audio
tags question: http://stackoverflow.com/q/49688815
tags question: http://stackoverflow.com/q/49632764
tags question: http://stackoverflow.com/q/49709861
tags question: http://stackoverflow.com/q/49662850
type: Tag
tags question: http://stackoverflow.com/q/49716084
tag name: audio

http://stackoverflow.com/q/49633428
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49634239
accepted answer: http://stackoverflow.com/a/49633568
has answer: http://stackoverflow.com/a/49633515
score: 5
has answer: http://stackoverflow.com/a/49633568
tagged with: python
upvote count: 6
answer count: 4
type: Question
has title: How to use context manager with lists
has body: I have a class, that has initialisation and cleaning logic: class Bird(object): def __init__(self, name): self.name = name def __enter__(self): print("enter " + self.name) return self def __exit__(self, type, value, traceback): print("exit " + self.name) I use it with context manager: with Bird("chicken") as b: print(b) But now I want use list of my objects with same behaviour, ie after working with list, its objects should be disposed: with DisposableList([Bird("A"), Bird("B")]) as list: #some ops How I can implement list or maybe another solution?
possible better answer: http://stackoverflow.com/a/49633706
has answer: http://stackoverflow.com/a/49633706
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86277129

http://stackoverflow.com/q/49681392
downvote count: 0
favorite count: 0
type: Question
upvote count: 15
has body: I am having trouble updating an Excel Sheet using pandas by writing new values in it. I already have an existing frame df1 that reads the values from MySheet1.xlsx. so this needs to either be a new dataframe or somehow to copy and overwrite the existing one. The spreadsheet is in this format: I have a python list: values_list = [12.34, 17.56, 12.45]. My goal is to insert the list values under Col_C header vertically. It is currently overwriting the entire dataframe horizontally, without preserving the current values. df2 = pd.DataFrame({'Col_C': values_list}) writer = pd.ExcelWriter('excelfile.xlsx', engine='xlsxwriter') df2.to_excel(writer, sheet_name='MySheet1') workbook = writer.book worksheet = writer.sheets['MySheet1'] How to get this end result? Thank you!
accepted answer: http://stackoverflow.com/a/49682266
tagged with: python
has title: Python Pandas - How to write in a specific column in an Excel Sheet
tagged with: excel
has answer: http://stackoverflow.com/a/49682266
possible better answer: http://stackoverflow.com/a/49681753
type: AnsweredQuestion
score: 15
answer count: 2
has answer: http://stackoverflow.com/a/49681753
tagged with: pandas

http://stackoverflow.com/comment/86392713
has text: @asimo - so groups are not important? Or grouping by `SECTOR`?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49687505

http://stackoverflow.com/a/49717771
score: 1
has body: I found the answer by myself. The solution is to use numpy's take function. You can pass the array and a vector of indices to the function and it will return the desired arrays. def calc(self,length): t = numpy.arange(0, f_s*length*6, 1/f_s) t_sin = t * f_carrier %512 t_sig = t * f_prn % 1023 self.data = (numpy.multiply(numpy.take(sinTable512, t_sin), numpy.take(self.Signal, t_sig)))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49716504
type: Answer
answers question: http://stackoverflow.com/q/49716504
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86458956
comment on: http://stackoverflow.com/q/49722754
type: QuestionComment
score: 0
type: Comment
has text: I think you're just running into the properties of PDFs here. PDFs don't have a real layout, it's just a bunch of words on a page. PDF extractors do their best to guess the layout from that but they often can't

http://stackoverflow.com/a/49656196
type: Answer
answers question: http://stackoverflow.com/q/49656116
upvote count: 3
downvote count: 0
has body: IIUC multiple index df.loc[:,pd.IndexSlice['Price']] Out[1108]: PX_FIRST PX_LAST Date 2018-03-05 1.710 -0.511 2018-03-06 1.725 -0.513 2018-03-07 1.745 -0.511 2018-03-08 1.750 -0.512
score: 3

http://stackoverflow.com/comment/86337176
comment on: http://stackoverflow.com/a/49662856
score: 0
type: Comment
type: AnswerComment
has text: The one caveat that gets me with `readlines()` is that it leaves the trailing `\n` on each line, but yeah overall, that's a bit cleaner — I just updated it to use that, and also replaced the list comprehensions with generators.

http://stackoverflow.com/q/49618953
answer count: 1
has comment: http://stackoverflow.com/comment/86244960
favorite count: 0
type: Question
type: AnsweredQuestion
score: -2
downvote count: 5
tagged with: python
has title: Function __init__ in python doesn't work
has body: i have this python code: class Tuna: def __Init__(self): print('birdie') def swim(self): print('swiminng') tuntun = Tuna() tuntun.swim() which prints out: swiminng why is the init not working?
accepted answer: http://stackoverflow.com/a/49618961
has comment: http://stackoverflow.com/comment/86244942
has answer: http://stackoverflow.com/a/49618961
upvote count: 3

http://stackoverflow.com/comment/86470956
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49728544
has text: Is this input comes from a file ?
type: Comment

http://stackoverflow.com/comment/86510526
has text: I saw this documentation before, but think maybe this is not very efficient in my program... and thank U :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49747844
type: Comment

http://stackoverflow.com/comment/86512172
type: Comment
has text: The error says it all... make you sure when you are opening the file you either 1) work in the same directory, 2) include the full file path when using `open()`
score: 2
comment on: http://stackoverflow.com/q/49748748
type: QuestionComment

http://stackoverflow.com/comment/86340646
type: AnswerComment
comment on: http://stackoverflow.com/a/49658504
type: Comment
has text: The format for the command line and Eclipse Run Config should be the same. So, no specific syntax to be followed beyond what you already do.
score: 0

http://stackoverflow.com/comment/86292234
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49642324
type: AnswerComment
has text: Note: The ability to iterate views of `OrderedDict` in reverse directly was added in Python 3.5. If you're supporting older versions, you'll need to `list`ify the items view before reversing it, which sadly necessitates a temporary.

http://stackoverflow.com/q/49714328
has comment: http://stackoverflow.com/comment/86448455
type: Question
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/86447345
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
score: 0
has title: Why my pyspark udf function will return None for me ?
answer count: 0
has body: My data have some None after join, so I want to fill them with vector. For example, my data are like id value 1 [1,2,3,4,5] 2 Null 3 [1,2,3,4,5] 4 [1,2,3,4,5] 5 [1,2,3,4,5] and my udf function is def fillVec_5(y): if y: return y else: return Vectors.dense([0 for i in range(5)]) getVector_5 = udf(lambda y: fillVec_5(y),VectorUDT()) df = df.withColumn('value',getVector_5(col('value')) df.show(5,False) But I will get error: File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main process() File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream vs = list(itertools.islice(iterator, batch)) File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 139, in load_stream yield self._read_with_length(stream) File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 164, in _read_with_length return self.loads(obj) File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 442, in loads return pickle.loads(obj) File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/sql/types.py", line 1159, in &lt;lambda&gt; return lambda *a: dataType.fromInternal(a) File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/sql/types.py", line 565, in fromInternal values = [f.fromInternal(v) for f, v in zip(self.fields, obj)] File "/opt/cloudera/parcels/CDH-5.11.2-1.cdh5.11.2.p0.4/lib/spark/python/lib/pyspark.zip/pyspark/sql/types.py", line 438, in fromInternal return self.dataType.fromInternal(obj)…
tagged with: apache-spark
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86458536

http://stackoverflow.com/q/49746668
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49746830
tagged with: deep-learning
score: 1
has title: how to create a model where optimization starts from scratch every time we change the learning rate?
answer count: 1
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: keras
favorite count: 0
type: Question
has body: Maybe someone can help me out - I am playing with learning rate in a Sequential model. I want the optimization to start from scratch every time I change the learning rate, to give a fair comparison of how each learning rate did in the results. So how to create a function in python that generates a new model to optimize the learning rate in a loop? """ optimizing learning rate""" # Create list of learning rates: lr_to_test lr_to_test = [0.000001, 0.01, 1] # Loop over learning rates for lr in lr_to_test: print('\n\nTesting model with learning rate: %f\n'%lr ) # Build new model to test, unaffected by previous models model = Sequential() # Add the layers model.add(Dense(50, activation='relu', input_shape=(n_cols,))) model.add(Dense(32, activation='relu')) model.add(Dense(1)) # Create SGD optimizer with specified learning rate: my_optimizer my_optimizer = SGD(lr=lr) # Compile the model model.compile(optimizer=my_optimizer, loss='mean_squared_error') # Fit the model model.fit(predictors, target, epochs=10) As the results I get: Testing model with learning rate: 0.000001 Epoch 1/10 534/534 [==============================] - 0s 661us/step - loss: 120.5427 Epoch 2/10 534/534 [==============================] - 0s 29us/step - loss: 111.6158 ..... Epoch 10/10 534/534 [==============================] - 0s 59us/step - loss: 65.8593 Testing model with learning rate: 0.010000 Epoch 1/10 534/534 [==============================] - 0s 693us/step - loss: nan Epoch 2/10 534/534 [==============================] - 0s 59us/step - loss: nan Epoch 3/10 534/534 [==============================] - 0s 29us/step - loss: nan ....&lt;&gt;

http://stackoverflow.com/a/49605065
downvote count: 0
answers question: http://stackoverflow.com/q/49605003
has body: Set the values of p, b, c and s to 'y'.
type: Answer
accepted answer of: http://stackoverflow.com/q/49605003
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86524410
has text: That's not the actual implementation I'm going for. Just used it for ease of explanation
score: 0
comment on: http://stackoverflow.com/q/49752905
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86368211
comment on: http://stackoverflow.com/q/49677505
score: 0
type: QuestionComment
has text: What you describe and the code don’t quite match. `sympy` is used for symbolic computation, while `scipy.optimize` will find the value of the root(s) for you. Do you want an equation for the solution or the value itself?
type: Comment

http://stackoverflow.com/a/49687757
score: 0
answers question: http://stackoverflow.com/q/49683631
type: Answer
has body: Just create a function which return True or False , now whenever you want to check pass value to that function and check : def check_token(data_): if 'token' in data_['payload']: return True else: return False Now back to your code , you can simply check by passing value to this function : if check_token(data)==True: print("GOT IT") output: GOT IT

http://stackoverflow.com/comment/106391051
comment on: http://stackoverflow.com/q/49649938
score: 0
type: Comment
type: QuestionComment
has text: In other words, I'm a time traveler ‍♂️

http://stackoverflow.com/q/49755719
has answer: http://stackoverflow.com/a/49790292
possible better answer: http://stackoverflow.com/a/49790292
tagged with: python-hypothesis
favorite count: 0
type: Question
has body: I want to generate a list of lists of integers of size 2 with the following conditions. the first element should be smaller than the second and all the data should be unique. I could generate each tuple with a custom function but don't know how to use that to satisfy the second condition. from hypothesis import strategies as st @st.composite def generate_data(draw): min_val, max_val = draw(st.lists(st.integers(1, 1e2), min_size=2, max_size=2)) st.assume(min_val &lt; max_val) return [min_val, max_val] I could generate the data by iterating over generate_date a few times in this (inefficient ?) way: &gt;&gt;&gt; [generate_data().example() for _ in range(3)] [[5, 31], [1, 12], [33, 87]] But how can I check that the data is unique? E.g, the following values are invalid: [[1, 2], [1, 5], ...] # (1 is repeated) [[1, 2], [1, 2], ...] # (repeated data) but the following is valid: [[1, 2], [3, 4], ...]
tagged with: testing
tagged with: python
has title: generating conditional data with Hypothesis Python
has answer: http://stackoverflow.com/a/49770041
accepted answer: http://stackoverflow.com/a/49770041
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: property-based-testing
downvote count: 0

http://stackoverflow.com/a/49678618
answers question: http://stackoverflow.com/q/49677505
has comment: http://stackoverflow.com/comment/86421860
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86389917
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86393497
has body: If you are looking for a numeric solution, you can use brentq from scipy.optimize import brentq f = lambda y: ((5/(1+((.0025+y)/2)))**2) + ((5/(1+((.0027+y)/2)))**4) + ((105/(1+((.003+y)/2)))**6)-104.90 res = brentq(f, 0, 1E8)
accepted answer of: http://stackoverflow.com/q/49677505
has comment: http://stackoverflow.com/comment/86389142

http://stackoverflow.com/comment/86563511
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49717205
score: 0
has text: do your helloworld MPI program make any communication ? if not, you might want to try a simple ring program. what if you print the tag right after the `MPI_Recv()` ?

http://stackoverflow.com/comment/86513812
type: Comment
has text: Where do you get the `TRN-Api-Key` header from? Do you have a link to their docs?
score: 0
comment on: http://stackoverflow.com/q/49749498
type: QuestionComment

http://stackoverflow.com/a/49601369
has body: I believe need upsample or downsample first by resample: #upsample s = s.resample('15Min').ffill() #downsample #s = s.resample('60Min').mean() #if already 30 minutes values no resample necessary Then groupby by months by DatetimeIndex.strftime converted to ordered Categorical and DatetimeIndex.time, aggregate mean and last reshape by unstack: cats = ['Jan', 'Feb', 'Mar', 'Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] months = pd.Categorical(s.index.strftime('%b'), categories=cats, ordered=True) df = s.groupby([months, s.index.time]).mean().unstack()
type: Answer
has comment: http://stackoverflow.com/comment/86210293
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49601166
has comment: http://stackoverflow.com/comment/86210299
answers question: http://stackoverflow.com/q/49601166

http://stackoverflow.com/comment/86278947
type: QuestionComment
comment on: http://stackoverflow.com/q/49615808
score: 0
has text: @SteffenUllrich I upload it manually using a different client (Cyberduck; it has a GUI). I just tried writing a different python program to just upload the index page, and it doesn't seem to have any problem.
type: Comment

http://stackoverflow.com/a/49635935
type: Answer
accepted answer of: http://stackoverflow.com/q/49635509
has comment: http://stackoverflow.com/comment/86280394
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49635509
has body: Constructing a similar structured array: In [333]: dt=[('var1', '&lt;f4'), ('var2', 'O'), ('var3', 'O'), ('var4', '&lt;i4')] In [334]: arr = np.zeros(3, dt) In [335]: arr Out[335]: array([(0., 0, 0, 0), (0., 0, 0, 0), (0., 0, 0, 0)], dtype=[('var1', '&lt;f4'), ('var2', 'O'), ('var3', 'O'), ('var4', '&lt;i4')]) Fill it with data (for now identical copies): In [336]: arr[0]=(1.2, np.array([.03]),np.array([1.8,2.1]),2) In [337]: arr[1]=(1.2, np.array([.03]),np.array([1.8,2.1]),2) In [338]: arr[2]=(1.2, np.array([.03]),np.array([1.8,2.1]),2) In [339]: arr Out[339]: array([(1.2, array([0.03]), array([1.8, 2.1]), 2), (1.2, array([0.03]), array([1.8, 2.1]), 2), (1.2, array([0.03]), array([1.8, 2.1]), 2)], dtype=[('var1', '&lt;f4'), ('var2', 'O'), ('var3', 'O'), ('var4', '&lt;i4')]) tolist doesn't remove or flatten the inner arrays: In [340]: arr.tolist() Out[340]: [(1.2000000476837158, array([0.03]), array([1.8, 2.1]), 2), (1.2000000476837158, array([0.03]), array([1.8, 2.1]), 2), (1.2000000476837158, array([0.03]), array([1.8, 2.1]), 2)] With simpler structured dtypes, np.array(arr.tolist()) often works, since np.array tries to create a multidimensional array if it can. But here the first element is a float, but the second is an array: In [341]: np.array(_) ValueError: setting an array element with a sequence. We can make an object dtype array from that list - but that still doesn't unpack the inner arrays: In [342]: np.array(arr.tolist(),object) Out[342]: array([[1.2000000476837158, array([0.03]), array([1.8, 2.1]), 2], [1.2000000476837158, array([0.03]), array([1.8, 2.1]), 2], [1.2000000476837158, array([0.03]), array([1.8, 2.1]), 2]], dtype=object) I can unpack the 'var2' field with: In [345]: arr['var2'].astype(float) Out[345]: array([0.03, 0.03, 0.03]) In [346]: arr['var2'][:] = _ In [347]: arr Out[347]: array([(1.2, 0.03, array([1.8, 2.1]), 2), (1.2, 0.03, array([1.8, 2.1]), 2), (1.2, 0.03, array([1.8, 2.1]), 2)], dtype=[('var1', '&lt;f4'), ('var2', 'O'), ('var3', '…
score: 1

http://stackoverflow.com/q/49639874
upvote count: 1
downvote count: 0
tagged with: django
has title: Missing css in Django admin
tagged with: python
accepted answer: http://stackoverflow.com/a/49640036
type: AnsweredQuestion
has body: I'm used nginx + unicorn + Django and absence css only in Django admin. I'm not understand the reason. Static is shown on all a pages besides admin. In terminal is see 200code: http://joxi.ru/KAxLRZEi4kdQYA In console missing error: http://joxi.ru/12M6KL0i4jpO9A P.S. I make collectstatic. settings INSTALLED_APPS = [ 'homepage', 'info', 'login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
score: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49640036
type: Question
tagged with: static

http://stackoverflow.com/comment/86420571
type: Comment
type: AnswerComment
has text: Thanks @user2357112 ,your solution kicks my problem away ~~
score: 0
comment on: http://stackoverflow.com/a/49703256

http://stackoverflow.com/q/49639579
downvote count: 0
linked to: http://stackoverflow.com/q/42861234
favorite count: 0
type: Question
has body: Similar unanswered question: Row by row processing of a Dask DataFrame I'm working with dataframes that are millions on rows long, and so now I'm trying to have all dataframe operations performed in parallel. One such operation I need converted to Dask is: for row in df.itertuples(): ratio = row.ratio tmpratio = row.tmpratio tmplabel = row.tmplabel if tmpratio &gt; ratio: df.loc[row.Index,'ratio'] = tmpratio df.loc[row.Index,'label'] = tmplabel What is the appropriate way to set a value by index in Dask, or conditionally set values in rows? Given that .loc doesn't support item assignment in Dask, there does not appear to be a set_value, at[], or iat[] in Dask either. I have attempted to use map_partitions with assign, but I am not seeing any ability to perform conditional assignment at the row-level.
tagged with: dask
score: 3
has title: How to do row processing and item assignment in Dask
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49639741
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49639741
tagged with: pandas
upvote count: 3
answer count: 1

http://stackoverflow.com/q/49742065
has answer: http://stackoverflow.com/a/49742176
tagged with: pyspark
has title: Py4JJavaError in spark wordcount python 3.5 on jupyter notebook
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/30518362
tagged with: spark-streaming
type: UnansweredQuestion
tagged with: python
has body: I am trying a simple network word count program on spark streaming in python with code as from pyspark import SparkContext from pyspark.streaming import StreamingContext sc = SparkContext("local[2]", "NetworkWordCount") ssc = StreamingContext(sc, 1) lines = ssc.socketTextStream("localhost", 9999) words = lines.flatMap(lambda line: line.split(" ")) pairs = words.map( lambda word : (word,1)) wordCount = pairs.reduceByKey( lambda x, y : (x+y)) wordCount.pprint() ssc.start() ssc.awaitTermination() its running all good till ssc.start() but its giving an error at ssc.awaitTermination() Py4JJavaError Traceback (most recent call last) &lt;ipython-input-2-18f3db416f1c&gt; in &lt;module&gt;() 1 ssc.start() ----&gt; 2 ssc.awaitTermination() /usr/local/lib/python3.5/dist-packages/pyspark/streaming/context.py in awaitTermination(self, timeout) 204 """ 205 if timeout is None: --&gt; 206 self._jssc.awaitTermination() 207 else: 208 self._jssc.awaitTerminationOrTimeout(int(timeout * 1000)) /usr/local/lib/python3.5/dist-packages/py4j/java_gateway.py in __call__(self, *args) 1158 answer = self.gateway_client.send_command(command) 1159 return_value = get_return_value( -&gt; 1160 answer, self.gateway_client, self.target_id, self.name) 1161 1162 for temp_arg in temp_args: /usr/local/lib/python3.5/dist-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 raise Py4JJavaError( 319 "An error occurred while calling {0}{1}{2}.\n". --&gt; 320 format(target_id, ".", name), value) 321 else: 322 raise Py4JError( Py4JJavaError: An error occurred while calling o22.awaitTermination. : org.apache.spark.SparkException: An exception was raised by Python: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pyspark/streaming/util.py", line 65, in call r = self.func(t, *rdds) File "/usr/local/lib/python3.5/dist-packages/pyspark/streaming/dstream.py", line 171, in takeAndPrint taken = rdd.take(num + 1) File "/usr/local/lib/python3.5/dist-pack…
score: 0
answer count: 2
tagged with: apache-spark
has answer: http://stackoverflow.com/a/57983252

http://stackoverflow.com/a/49736558
has comment: http://stackoverflow.com/comment/86499138
has comment: http://stackoverflow.com/comment/86498578
answers question: http://stackoverflow.com/q/49724629
type: Answer
has comment: http://stackoverflow.com/comment/86499587
accepted answer of: http://stackoverflow.com/q/49724629
has comment: http://stackoverflow.com/comment/86494750
has comment: http://stackoverflow.com/comment/86499459
score: 1
has body: I tested a bit how this can be done more efficiently and came to the point that your approach isn't bad at all for highly uncorrelated data produced by np.random.uniform. On real data this can be a bit different. I improved the speed of your functions a bit giving about 1.4GB/s compressing and 1.2GB/s decompressing, which isn't bad at all. With h5py (blosclz) I could achieve only about 450MB/s, but writing the data also to disk. Improved sparse algorithm import numpy as np import numba as nb #We can use uint16 on (4,32,32), since max. idx&lt;2**16 @nb.jit() def to_sparse_data_uint16(data): data_flat=data.reshape(-1) idx=np.empty(data.size,dtype=np.uint16) data_out=np.empty(data.size,dtype=data.dtype) ii=0 for i in range(data_flat.shape[0]): if (data_flat[i]!=0): idx[ii]=i data_out[ii]=data_flat[i] ii+=1 return idx[0:ii], data_out[0:ii], data.shape def to_dense_data(idx,data,shape): length=np.prod(shape) data_out=np.zeros(length,dtype=data.dtype) data_out[idx]=data return data_out.reshape(shape) ######################## #do you really need float64 here? images = np.array(np.random.uniform(0, 1, (100000, 4, 32, 32)),dtype=np.float32) images[images &gt; 0.05] = 0. res=[] t1=time.time() for i in range(100000): res.append(to_sparse_data_uint16(images[i,:,:,:])) print(time.time()-t1) t1=time.time() for i in range(100000): data=to_dense_data(res[i][0],res[i][1],res[i][2]) print(time.time()-t1) HDF5 Example import numpy as np import tables #register blosc import h5py as h5 import h5py_cache as h5c import time # I assume here that you don't need float64 for images.. # 1650MB Testdata images = np.array(np.random.uniform(0, 1, (100000, 4, 32, 32)),dtype=np.float32) images[images &gt; 0.05] = 0. #Write data (32,7 GB uncompressed) hdf5_path='Test.h5' f = h5c.File(hdf5_path, 'w',chunk_cache_mem_size=1024**2*100) #200 MB cache size dset_images = f.create_dataset("images", shape=(20*100000, 4, 32, 32),dtype=np.float32,chunks=(1000, 4, 32, 32),compression=32001,compression_opts=(0, …
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86499128
has comment: http://stackoverflow.com/comment/86499391

http://stackoverflow.com/comment/86550840
type: Comment
comment on: http://stackoverflow.com/a/49745530
type: AnswerComment
has text: @SiddharthSingh glad, could help! Cheers!
score: 0

http://stackoverflow.com/a/49656771
score: 0
has comment: http://stackoverflow.com/comment/86324737
has body: Your code can be simplified. It seems like you are trying to combine the 2 very different methods of collecting data below. You should choose one or the other. Individual entries n = int(input('How many numbers?\n')) res = [] for i in range(1, n+1): res.append(int(input('Enter number{0}\n'.format(i)))) Simultaneous entries n = int(input('How many numbers?\n')) in_str = input('Enter the numbers separated by space:\n') res = list(map(int, in_str.split()))
has comment: http://stackoverflow.com/comment/86324698
has comment: http://stackoverflow.com/comment/86323393
answers question: http://stackoverflow.com/q/49656317
has comment: http://stackoverflow.com/comment/86322912
type: Answer
has comment: http://stackoverflow.com/comment/86325031
has comment: http://stackoverflow.com/comment/86323379

http://stackoverflow.com/a/49629525
has body: type=text/javascript should be type="text/javascript" in line referencing jQuery.
answers question: http://stackoverflow.com/q/49629419
score: 0
type: Answer

http://stackoverflow.com/comment/86450378
score: 5
has text: Why are you doing this? Why don't you subclass my_base?
type: Comment
comment on: http://stackoverflow.com/q/49718703
type: QuestionComment

http://stackoverflow.com/q/49648719
type: Question
possible better answer: http://stackoverflow.com/a/49667467
has title: Watson Developer Cloud showing error: Microsoft Visual C++ 14.0 is required
has answer: http://stackoverflow.com/a/50036931
tagged with: python
has body: I am trying Watson visual recognition with Python, following this: https://www.ibm.com/watson/developercloud/visual-recognition/api/v3/python.html?python#introduction while tried to install the library: pip install --upgrade "watson-developer-cloud&gt;=1.2.1" I am getting following error even after installing "Microsoft Visual C++ 14.0", I have uninstalled other versions of MSVC++ too. Collecting watson-developer-cloud&gt;=1.2.1 Using cached watson-developer-cloud-1.2.1.tar.gz Requirement already up-to-date: requests&lt;3.0,&gt;=2.0 in c:\python36\lib\site-packages (from watson-developer-cloud&gt;=1.2.1) Requirement already up-to-date: python_dateutil&gt;=2.5.3 in c:\python36\lib\site-packages (from watson-developer-cloud&gt;=1.2.1) Requirement already up-to-date: autobahn&gt;=0.10.9 in c:\python36\lib\site-packages (from watson-developer-cloud&gt;=1.2.1) Collecting Twisted&gt;=13.2.0 (from watson-developer-cloud&gt;=1.2.1) Using cached Twisted-17.9.0.tar.bz2 Collecting pyOpenSSL&gt;=16.2.0 (from watson-developer-cloud&gt;=1.2.1) Using cached pyOpenSSL-17.5.0-py2.py3-none-any.whl Collecting service-identity&gt;=17.0.0 (from watson-developer-cloud&gt;=1.2.1) Using cached service_identity-17.0.0-py2.py3-none-any.whl Requirement already up-to-date: idna&lt;2.7,&gt;=2.5 in c:\python36\lib\site-packages (from requests&lt;3.0,&gt;=2.0-&gt;watson-developer-cloud&gt;=1.2.1) Requirement already up-to-date: certifi&gt;=2017.4.17 in c:\python36\lib\site-packages (from requests&lt;3.0,&gt;=2.0-&gt;watson-developer-cloud&gt;=1.2.1) Requirement already up-to-date: chardet&lt;3.1.0,&gt;=3.0.2 in c:\python36\lib\site-packages (from requests&lt;3.0,&gt;=2.0-&gt;watson-developer-cloud&gt;=1.2.1) Requirement already up-to-date: urllib3&lt;1.23,&gt;=1.21.1 in c:\python36\lib\site-packages (from requests&lt;3.0,&gt;=2.0-&gt;watson-developer-cloud&gt;=1.2.1) Requirement already up-to-date: six&gt;=1.5 in c:\python36\lib\site-packages (from python_dateutil&gt;=2.5.3-&gt;watson-developer-c…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49648847
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49667467
tagged with: twisted
tagged with: pip
tagged with: ibm-watson
accepted answer: http://stackoverflow.com/a/49648847

http://stackoverflow.com/q/49675767
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86381363
has comment: http://stackoverflow.com/comment/86375184
downvote count: 0
has comment: http://stackoverflow.com/comment/86381342
has title: Subprocess.Popen only runs second time
favorite count: 0
has comment: http://stackoverflow.com/comment/86373420
has comment: http://stackoverflow.com/comment/86375193
has body: I have a boot controller which runs a boot.py file contained in each folder of each tool i am trying to deploy. I want my boot controller to run all of these boot files simultaneously. The config file has the tool names and the versions desired, which help to generate the path to the boot.py. def run_boot(): config_file = get_config_file() parse_config_file.init(config_file) tools = parse_config_file.get_tools_to_deploy() #tools is now a list of tool names top_dir = os.getcwd() for tool in tools: ver = parse_config_file.get_tool_version(tool).strip() boot_file_path = "{0}\\Deploy\\{1}\\{2}".format(os.getcwd(),tool,ver) try: subprocess.Popen('boot.py', shell=True, cwd=boot_file_path) except: print ("{0} failed to open".format(tool)) print(tool, boot_file_path) os.chdir(top_dir) The first time i run this, the print(tool, boot_file_path) executes but the processes do not. the second time it is run the processes do open. I cannot find a reason for this.
tagged with: popen
tagged with: windows
has comment: http://stackoverflow.com/comment/86526751
tagged with: python
has comment: http://stackoverflow.com/comment/86365346
type: Question
score: 2
has comment: http://stackoverflow.com/comment/86365282
answer count: 0
tagged with: subprocess
upvote count: 2

http://stackoverflow.com/q/49600464
has body: I would like to open a file dialog with easygui but the path contains a folder with a .: C:\Users\user\.atom myfile= easygui.fileopenbox(msg="Choose a file", default=r"C:\Users\user\.atom") This opens the dialog box to C:\Users\user not C:\Users\user\.atom
has title: easygui fileopenbox: open a path with a '.' (ex C:\Users\user\.atom)
has answer: http://stackoverflow.com/a/67024300
tagged with: path
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/67024300
answer count: 2
has answer: http://stackoverflow.com/a/49601624
score: 0
accepted answer: http://stackoverflow.com/a/49601624
type: Question
tagged with: easygui

http://stackoverflow.com/comment/86369597
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49678975
has text: This is probably because you ran pip as root which it advises you not to do. Try removing that package and then doing `pip install fedex --user` as a normal user.
type: Comment

http://stackoverflow.com/q/49712632
type: Question
has comment: http://stackoverflow.com/comment/86439186
has title: H2O - savefig with "performance.plot()" ROC
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49712644
tagged with: python
has comment: http://stackoverflow.com/comment/86439606
has answer: http://stackoverflow.com/a/49712644
has body: When I use H2O 3.19, I want to save the training data's performance matplotlib.pyplot graphic (ROC) at server side, how can I do it? Here we can see the source code of plot() in h2o/model/metrics_base.py: def plot(self, type="roc", server=False): """ Produce the desired metric plot. :param type: the type of metric plot (currently, only ROC supported). :param server: if True, generate plot inline using matplotlib's "Agg" backend. :returns: None """ # TODO: add more types (i.e. cutoffs) assert_is_type(type, "roc") # check for matplotlib. exit if absent. try: imp.find_module('matplotlib') import matplotlib if server: matplotlib.use('Agg', warn=False) import matplotlib.pyplot as plt except ImportError: print("matplotlib is required for this function!") return if type == "roc": plt.xlabel('False Positive Rate (FPR)') plt.ylabel('True Positive Rate (TPR)') plt.title('ROC Curve') plt.text(0.5, 0.5, r'AUC={0:.4f}'.format(self._metric_json["AUC"])) plt.plot(self.fprs, self.tprs, 'b--') plt.axis([0, 1, 0, 1]) if not server: plt.show() plot(type="roc", server=False) just examines the existence of matplotlib.pyplot and does not return the plt object, so I cannot call plt.savefig(). What can I do?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86446388
tagged with: h2o
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86514541
favorite count: 0

http://stackoverflow.com/q/49740960
has comment: http://stackoverflow.com/comment/86496623
has title: Python-Pandas While loop
favorite count: 0
type: Question
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49813461
upvote count: 0
has answer: http://stackoverflow.com/a/49813030
has body: I am having some trouble with the DataFrame and while loop: A B 5 10 5 10 10 5 I am trying to have a while loop that: while (Column A &lt; Column B): Column A = Column A + (Column B / 2) Column B = Column B / 2 Any ideas how to do this.
answer count: 2
downvote count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/86641389

http://stackoverflow.com/q/49726193
tagged with: python
has title: 'User' object has no attribute 'ValidationError'
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49726341
has answer: http://stackoverflow.com/a/51259798
has comment: http://stackoverflow.com/comment/86466272
type: Question
score: 0
tagged with: django-forms
has comment: http://stackoverflow.com/comment/86466153
has body: I'm trying to create a registration form. Everything works fine until I try to raise a validation error in case email already exists. It says, 'User' object has no attribute 'ValidationError' Here's what I did, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) mail = form.cleaned_data['email'] if User.objects.filter(email=mail).exists(): raise new_form.ValidationError('Looks like email already exists') else: new_form.save() username = request.POST.get('username') password = request.POST.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect(reverse('accounts:profile')) else: form = RegistrationForm() How can we fix that?
has answer: http://stackoverflow.com/a/49730722
has answer: http://stackoverflow.com/a/49726519
has comment: http://stackoverflow.com/comment/86466622
has answer: http://stackoverflow.com/a/51255552
answer count: 5
tagged with: django

http://stackoverflow.com/a/49729052
type: Answer
accepted answer of: http://stackoverflow.com/q/49728926
has body: since thisdir[i] is not converted to its value during execution, so the error No such file or directory Replace os.system('py pdf2txt.py -o text_path thisdir[i]') with os.system("python ./pdf2txt.py -o {0} {1}".format(text_path,thisdir[i]))
has comment: http://stackoverflow.com/comment/86472314
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86472129
has comment: http://stackoverflow.com/comment/86471844
answers question: http://stackoverflow.com/q/49728926
has comment: http://stackoverflow.com/comment/86472417

http://stackoverflow.com/q/49744674
linked to: http://stackoverflow.com/q/49722640
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
has body: This question in reference with question - how to create edges for nodes? I used the suggestions and wrote a code but I am getting n error - ValueError: Can only tuple-index with a MultiIndex Code: import pandas as pd import networkx as nx df = pd.read_csv('file.txt',sep='\s+') df.columns = ['a', 'b'] df = df.dropna(axis=0) #distinct values to create nodes distinct = pd.concat([df['a'], df['b']]).unique() G=nx.Graph() for i in distinct: node=G.add_node(1) for i in df.iterrows(): A = df['a'][i] B = df['b'][i] G.add_edge(A,B) I am getting the error in the loop for creating edges but I do not understand what is the error and how to solve it.
answer count: 1
has comment: http://stackoverflow.com/comment/86504116
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86503961
tagged with: networkx
has title: Error in creating the edges python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86504018
has comment: http://stackoverflow.com/comment/86504094
has answer: http://stackoverflow.com/a/49744851
has comment: http://stackoverflow.com/comment/86504005

http://stackoverflow.com/comment/86385865
type: Comment
comment on: http://stackoverflow.com/q/49687358
type: QuestionComment
has text: No matter how much i train the network it just gets closer and closer to 0.5
score: 0

http://stackoverflow.com/comment/86528854
comment on: http://stackoverflow.com/q/49756765
type: Comment
type: QuestionComment
has text: Pretty much a duplicate of [this](https://stackoverflow.com/questions/19906224/redirection-opeartors-and-in-os-systemcmd). TD;DR: use subprocess instead of os.system, as mentioned in the [docs](https://docs.python.org/2/library/os.html#os.system).
score: 0

http://stackoverflow.com/comment/86345499
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49648392
has text: now i got your point! Thanks. Yes, if i have the index,I of course also have the value. Ah! klaro!

http://stackoverflow.com/q/49724113
tagged with: nested
has answer: http://stackoverflow.com/a/49724189
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86462405
linked to: http://stackoverflow.com/q/8023306
possible better answer: http://stackoverflow.com/a/49724189
tagged with: python
score: -1
has body: In Python, is there a good way (programmatically) to get the value of ["win"]["amount"] from the subset of data where the most recent date exists? To provide a more concrete example of what I'm asking, I'd like the amount for win from April 2, 2018 (2018-04-02), which would be 199.51. This is the source JSON (I convert this to a Python dict using json.loads): { "numbers": [{ "lose": { "amount": "122.50" }, "win": { "amount": "232.50" }, "date": "2018-01-08" }, { "lose": { "amount": "233.75" }, "win": { "amount": "216.25" }, "date": "2018-03-05" }, { "lose": { "amount": "123.50" }, "win": { "amount": "543.00" }, "date": "2018-03-12" }, { "lose": { "amount": "213.31" }, "win": { "amount": "253.33" }, "date": "2018-03-19" }, { "lose": { "amount": "217.00" }, "win": { "amount": "199.51" }, "date": "2018-04-02" }] } This seems like a very simple solution is in order, but I cannot quite nail down what that solution is, or if there is a Pythonic way of accomplishing this. I did write some logic to calculate the largest date by putting all of the dates into a list called datelist and doing a max(datelist), but I'm not sure how to relate that back to get ["amount"]["win"].
has comment: http://stackoverflow.com/comment/86462242
tagged with: dictionary
tagged with: date
accepted answer: http://stackoverflow.com/a/49724192
type: AnsweredQuestion
has title: Get the most currently dated subset of data from a Python dict with multiple dated dicts within
answer count: 2
has answer: http://stackoverflow.com/a/49724192
upvote count: 0
tagged with: max
has comment: http://stackoverflow.com/comment/86462167

http://stackoverflow.com/q/49628338
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/86263856
type: Question
accepted answer: http://stackoverflow.com/a/49629002
has answer: http://stackoverflow.com/a/49628515
has comment: http://stackoverflow.com/comment/86263898
has body: I recently was asked to deliver a python project as part of an interview process. I tested my project on Windows and MacOSX, with Pycharm, Spyder, jupyter notebook and command line and everything works fine. However, the reviewer was unable to make the project work on his side, because of module import issues according to him. My modules are organized like this: my_project/ my_module.py main_module.py my_package/ __init__.py my_submodule_1.py my_submodule_2.py my_submodule_1.py: import my_module import my_submodule_2 I haven't added any path related to this project in PYTHONPATH. The project main function is located in main_module.py. The reviewer seem to have problems with the modules imported in my_submodule_1.py. Could anyone shed some light on possible mistakes here and why it would work on my side and not on his?
has answer: http://stackoverflow.com/a/49629002
has title: Python import modules issue
tagged with: python-module
tagged with: python
possible better answer: http://stackoverflow.com/a/49628515
type: AnsweredQuestion
tagged with: python-import

http://stackoverflow.com/comment/86340624
comment on: http://stackoverflow.com/a/49665220
score: 0
type: AnswerComment
has text: @DyZ Do you think the answer needs to explain any of that? My thought was that it will just be unnecessary information, and possibly overwhelming, to the OP, or to someone else with the same question, but I could easily be wrong on that.
type: Comment

http://stackoverflow.com/comment/86266134
score: 0
type: AnswerComment
has text: it seems that is the issue, I switched from 2.7 to 3.5 and indeed I have import issues
type: Comment
comment on: http://stackoverflow.com/a/49629002

http://stackoverflow.com/comment/86481576
type: QuestionComment
comment on: http://stackoverflow.com/q/49733850
has text: Can you provide code?
score: 3
type: Comment

http://stackoverflow.com/q/49673677
has comment: http://stackoverflow.com/comment/86358036
has title: python change the loop variable in function body
has comment: http://stackoverflow.com/comment/86358446
possible better answer: http://stackoverflow.com/a/49673868
type: AnsweredQuestion
score: 0
has body: I found a behaviour in Python which is slightly counter-intuitive (or rather not what I am used to!). So, I have some code as follows: for c in range(10): c += 1 print(c) This prints 1 2 3 4 5 6 7 8 9 10 Even doing something like: c = 0 for c in range(10): ... Does not change the output? I guess the scoping rules are different than C++. My question is if someone needs to change the loop index within the function body, how could one do it?
tagged with: python
accepted answer: http://stackoverflow.com/a/49673788
has comment: http://stackoverflow.com/comment/86358225
type: Question
has answer: http://stackoverflow.com/a/49673788
has answer: http://stackoverflow.com/a/49673868
answer count: 2

http://stackoverflow.com/comment/87776830
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49683770
has text: Would you mind accepting an answer, if it helped you solve the problem?
score: 0

http://stackoverflow.com/q/49713113
answer count: 2
has comment: http://stackoverflow.com/comment/86440311
has answer: http://stackoverflow.com/a/69373638
downvote count: 0
accepted answer: http://stackoverflow.com/a/49713446
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49713446
has comment: http://stackoverflow.com/comment/86439792
has comment: http://stackoverflow.com/comment/86439954
tagged with: pandas
upvote count: 3
has body: I am getting performance warning from Pandas /usr/local/lib/python3.4/dist-packages/pandas/core/generic.py:1471: PerformanceWarning: your performance may suffer as PyTables will pickle object types that it cannot map directly to c-types [inferred_type-&gt;mixed-integer,key-&gt;block0_values] [items-&gt;['int', 'str']] I've read several issues on github and questions here, and all of them say this is because I mix types in one column, but I definetely not. The simple example is follows: import pandas as pd df = pd.DataFrame(columns=['int', 'str']) df = df.append({ 'int': 0, 'str': '0'}, ignore_index=True) df = df.append({ 'int': 1, 'str': '1'}, ignore_index=True) for _, row in df.iterrows(): print(type(row['int']), type(row['str'])) # &lt;class 'int'&gt; &lt;class 'str'&gt; # &lt;class 'int'&gt; &lt;class 'str'&gt; # however df.dtypes # int object # str object # dtype: object # the following causes the warning df.to_hdf('table.h5', 'table') What can this be about and what can I do?
has title: DataFrame performance warning
tagged with: hdf5
tagged with: python
tagged with: pytables
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/69373638

http://stackoverflow.com/comment/86432749
has text: @Kubuntuer82 Yes, your answer is pretty similar now that you've incorporated my suggestion. I found it preferable to post my own answer instead of repeatedly giving you improvement suggestions.
comment on: http://stackoverflow.com/a/49709607
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49649917
tagged with: date
has body: So this is one columns in my dataframe. i want to replace whole string with the time only. So from above string , i only want to extract 20:30:02 in long format. I know, how to convert into long, but how to extract time is i am not getting in python.
has comment: http://stackoverflow.com/comment/86308171
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/49650130
has comment: http://stackoverflow.com/comment/86308001
has answer: http://stackoverflow.com/a/49650340
type: Question
has answer: http://stackoverflow.com/a/49650130
accepted answer: http://stackoverflow.com/a/49650098
has comment: http://stackoverflow.com/comment/86307956
has title: How to take only time from this 2018-01-25T20:30:02.533+0000?
tagged with: datetime
has answer: http://stackoverflow.com/a/49650098
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/49722608
has title: String Formatting: Iterate the row values from a csv file
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/86458627
type: Question
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/49722851
downvote count: 0
has body: I have a csv file. I want to iterate the rows and produce sql string. I tried the solutions in stackoverflow but could not manage to fix it. csv file rating,product_type,upc,title Three,Books,a897fe39b1053632,A Light in the Attic One,Books,6957f44c3847a760,Soumission python file starts with the following code path = r'C:\Users\HP\PycharmProjects\book_crawler\books\items.csv' file = open(path, 'rt') I tried different version for string formatting. Some of the errors I get: IndexError: tuple index out of range for row in file: print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({},{},{},{})'.format(row)) TypeError: not all arguments converted during string formatting for row in file: print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % row) TypeError: not all arguments converted during string formatting for row in file: print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % (row,)) TypeError: not all arguments converted during string formatting for row in file: print ('INSERT IGNORE INTO books_table(rating, product_type, upc, title) VALUES({0},{1},{2},{3})' % tuple(row))
tagged with: python
has answer: http://stackoverflow.com/a/49722851
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86458626
has comment: http://stackoverflow.com/comment/86458646
has comment: http://stackoverflow.com/comment/86458635
tagged with: sql
has comment: http://stackoverflow.com/comment/86458647
answer count: 1
tagged with: mysql

http://stackoverflow.com/q/49630745
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86269141
score: 0
linked to: http://stackoverflow.com/q/46721954
has body: I'm new to Python/QML and I can't seem to figure out how to add new ListElements to the ListModel directly from Python. here is the code: Python file: import sys from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtGui import QGuiApplication from PyQt5.QtCore import QObject app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine('tutorial.qml') sys.exit(app.exec_()) and the qml file: import QtQuick 2.0 import QtQuick.Controls 2.3 import QtQuick.Layouts 1.3 ApplicationWindow { visible: true title: qsTr("Window Title") ListModel { id: listmodelid objectName: "listmodelobject" ListElement { name: "Oliver A" student:false credits:2 } ListElement { name: "Rick Liam" student:true credits:4 } } ListView { model: listmodelid height: 200 delegate: ItemDelegate{ text: name } } } And I want to add new elements from a list that looks like this in python; some_list=[{"name":"John Doe","credits":3,"student":True},{"name":"John Deer","credits":7,"student":True},{"name":"John Cena","credits":0,"student":False}] I've tried getting the ListModel Object and using .setProperty('model',some_list) but didn't seem to do anything.
answer count: 0
tagged with: pyqt
upvote count: 1
downvote count: 1
has title: How to add new elements to ListModel in QML directly from Python
tagged with: pyqt5
duplicate of: http://stackoverflow.com/q/46721954
has comment: http://stackoverflow.com/comment/86269304
favorite count: 0
type: Question
tagged with: qml

http://stackoverflow.com/comment/86390707
comment on: http://stackoverflow.com/q/49689173
has text: Do not start learning Python 2 in 2018.
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/comment/86459113
has text: Because in between batches I am running url/domain filters on the queue to remove urls (spam, blacklisted sites, duplicates, etc), and then running it through another set of functions to prioritize and resort the queue as it grows beyond the batch size. I am converting the queue to a list between batches, filtering/resorting it, and then creating a new queue from the list.
comment on: http://stackoverflow.com/a/49717630
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49740741
type: AnsweredQuestion
score: 0
has body: I am trying to write a little program, which reads out MPR121's status with Adafruit MPR121 python library (capacitive touch with Raspberry PI 2), and this status can be get via a simple GET method. The problem is that, I can't manage to create its reading thread: as example of the MPR121 shows, I have to use at least a while loop - or just do one measurement. Example: import time from flask import Flask import Adafruit_MPR121.MPR121 as MPR121 #you have to give the static URL path and physical path on your machine #after then you can reach some static files # this is essential!! app = Flask(__name__,static_url_path="/client", static_folder="/home/pi/asd/client") cap = MPR121.MPR121() #enabling some test issues TEST = False @app.route('/read') def read(): if TEST: return "asd" else: current_touched = cap.touched() return current_touched @app.route('/') def root(): #This is the root path, just sent back a static webpage return app.send_static_file('index.html') As you see, I'd get the status of the MPR121 with a standard get method (flask answers errorCode 500). How can I solve this problem? Answer: * Serving Flask app "flask_main" * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) asd [2018-04-09 21:48:02,189] ERROR in app: Exception on /read [GET] Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/pi/alapitvany/flask_m…
tagged with: raspberry-pi
answer count: 1
has answer: http://stackoverflow.com/a/49746526
type: Question
has title: python Flask and MPR121 reading on raspberry PI
tagged with: python
accepted answer: http://stackoverflow.com/a/49746526
tagged with: flask

sentiment-analysis
tags question: http://stackoverflow.com/q/49614798
tags question: http://stackoverflow.com/q/49629678
tags question: http://stackoverflow.com/q/49731478
type: Tag
tag name: sentiment-analysis

http://stackoverflow.com/q/49713848
linked to: http://stackoverflow.com/q/41860817
has comment: http://stackoverflow.com/comment/95321415
tagged with: python
has body: I am doing hyperparameter optimization using Bayesian Optimization in Tensorflow for my Convolutional Neural Network (CNN). And I am getting this error: ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[4136,1,180,432] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc I optimized these hyperparameters: dim_batch_size = Integer(low=1, high=50, name='batch_size') dim_kernel_size1 = Integer(low=1, high=75, name='kernel_size1') dim_kernel_size2 = Integer(low=1, high=50, name='kernel_size2') dim_depth = Integer(low=1, high=100, name='depth') dim_num_hidden = Integer(low=5, high=1500, name='num_hidden') dim_num_dense_layers = Integer(low=1, high=5, name='num_dense_layers') dim_learning_rate = Real(low=1e-6, high=1e-2, prior='log-uniform', name='learning_rate') dim_activation = Categorical(categories=['relu', 'sigmoid'], name='activation') dim_max_pool = Integer(low=1, high=100, name='max_pool') dimensions = [dim_batch_size, dim_kernel_size1, dim_kernel_size2, dim_depth, dim_num_hidden, dim_num_dense_layers, dim_learning_rate, dim_activation, dim_max_pool] It says resource is exhausted. Why is this? Is it because I optimized too many hyperparameters? Or there is some dimension mismatch? Or did I assign a hyperparameter range that is beyond the allowed range for correct operation?
has comment: http://stackoverflow.com/comment/93115368
tagged with: deep-learning
upvote count: 3
accepted answer: http://stackoverflow.com/a/49763025
answer count: 1
downvote count: 0
tagged with: bayesian
has answer: http://stackoverflow.com/a/49763025
has comment: http://stackoverflow.com/comment/95283700
tagged with: hyperparameters
tagged with: tensorflow
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
has title: Hyperparameter Optimization in Tensorflow

http://stackoverflow.com/q/49629782
tagged with: python
linked to: http://stackoverflow.com/q/11709079
has answer: http://stackoverflow.com/a/49630060
has body: I've got the following python code; links = [] links.append(re.findall(b'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body)) return simplejson.dumps({"link": links}) When ran it returns an undefined value within the HTML page Any help explaining why this happens would be great
has comment: http://stackoverflow.com/comment/86266314
linked to: http://stackoverflow.com/q/1732348
linked to: http://stackoverflow.com/q/3075550
tagged with: http://stackoverflow.com/tag/json
tagged with: http://stackoverflow.com/tag/html
answer count: 1
score: -1
downvote count: 1
favorite count: 0
type: Question
has title: python regular expressions to json
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86266296
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86266529

http://stackoverflow.com/comment/86497047
score: 0
type: Comment
type: QuestionComment
has text: Then use the folder you just created. Your code calls `mkdir` a second time, when you *know* it already exists. That's guaranteed to raise an exception. You already *have* the folder name; use it.
comment on: http://stackoverflow.com/q/49740849

http://stackoverflow.com/comment/86305639
type: QuestionComment
has text: @FlyingTeller I didn't feel like it was a complete answer (and I didn't really want to write one) but it gives enough of an explanation to be helpful. And yeah they're not the same, I didn't phrase that well but what I was trying to show was in this scenario they will achieve the same things. `l, = something` will fail if `something` is a sequence of more than one element. Also you're right that `plt.plot` returns a list, that's my mistake when I typed that, but my point was just I don't like this kind of `l, = ...` usage.
comment on: http://stackoverflow.com/q/49647761
score: 0
type: Comment

http://stackoverflow.com/q/49712244
has title: Training GANs on GPUs with Keras: All layer names should be unique for discriminator
has comment: http://stackoverflow.com/comment/86488821
downvote count: 0
tagged with: gpu
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
score: 5
upvote count: 5
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
has body: I'm trying to train a simple GAN on GPU with Keras. I verified that the code runs with CPU on my laptop. Then, I added multi_gpu_model as per below to enable it to run on a set of GPUs. However, I am getting the following error: RuntimeError: ('The name "Discriminator" is used 2 times in the model. All layer names should be unique. Layer names: ', ['input_3', 'input_4', 'lambda_3', 'lambda_4', 'lambda_5', 'lambda_6', 'model_3', 'Discriminator', 'Discriminator']) The error seems to suggest that because I'm calling the Discriminator model multiple times, the name of the layers overlap. However, it is unclear to me how I can get around this problem. For your convenience, the full code is provided below: from __future__ import print_function, division from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.merge import _Merge from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampling2D, Conv2D, Convolution2D, Conv2DTranspose from keras.models import Sequential, Model from keras.optimizers import Adam, RMSprop from keras.utils import multi_gpu_model import keras.backend as K from optimizer import optimAdam from functools import partial # import inception_score import _pickle as cPickle import matplotlib.pyplot as plt import os import sys import tensorflow as tf import numpy as np from PIL import Image BATCH_SIZE = 128 GRADIENT_PENALTY_WEIGHT = 10 class RandomWeightedAverage(_Merge): """Takes a randomly-weighted average of two tensors. In geometric terms, this outputs a random point on the line between each pair of input points. Inheriting from _Merge is a little messy but it was the quickest solution I could think of. Improvements appreciated.""" def _merge_function(self, inputs): weights = K.random_uniform((BATCH_SIZE, 1, 1, 1)) return (weights * inputs[0]) + ((1 - weights) * inputs[1]) class GA…
has answer: http://stackoverflow.com/a/49715079

http://stackoverflow.com/comment/86452052
score: 0
comment on: http://stackoverflow.com/q/49719404
type: QuestionComment
has text: post the code also
type: Comment

http://stackoverflow.com/q/49703095
answer count: 4
upvote count: 4
tagged with: list
has answer: http://stackoverflow.com/a/49703108
has answer: http://stackoverflow.com/a/49708021
has body: I have two lists: listA = ['a1', 'a2', 'a3', 'a4'] listB = ['b2', 'b4'] and I want to pair items in the format any string same number, like so: listC = [('a1', None),('a2', 'b2'),('a3', None),('a4', 'b4')] I´ve tried itertools.zip_longest but I couldn´t get what I need: &gt;&gt;&gt;list(itertools.zip_longest(listA, listB) [('a1', 'b2'), ('a2', 'b4'), ('a3', None), ('a4', None)] Any suggestions how to get listC?
score: 1
has answer: http://stackoverflow.com/a/49703253
linked to: http://stackoverflow.com/q/5967500
downvote count: 3
linked to: http://stackoverflow.com/q/3438756
has title: Pair elements from two different lists
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49710609
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/773
tagged with: python

http://stackoverflow.com/comment/86449240
type: AnswerComment
comment on: http://stackoverflow.com/a/49714573
score: 0
type: Comment
has text: Ohh.. that's perfect, that makes sense, thank you very much.

http://stackoverflow.com/q/49639986
has comment: http://stackoverflow.com/comment/86287656
tagged with: visual-studio-code
has body: I need help with running a python file in VSCode. At the moment I can right-click the file and choose "Run Python File in Terminal" and it works for the simple things like: v = "Hello World" print(v) However, I want to run a function with user input and I just can't get it to work. Can someone tell me how it's done? Example of a function: def userInput(): v = input("What do you want to print? ") print(v)
tagged with: function
has comment: http://stackoverflow.com/comment/86343049
tagged with: python
accepted answer: http://stackoverflow.com/a/49678594
has comment: http://stackoverflow.com/comment/86342917
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86343307
score: 0
has comment: http://stackoverflow.com/comment/86342785
has comment: http://stackoverflow.com/comment/86343708
answer count: 1
has title: Python functions in VSCode
has answer: http://stackoverflow.com/a/49678594
type: Question
has comment: http://stackoverflow.com/comment/86287680

http://stackoverflow.com/q/49642103
type: Question
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/86291939
has comment: http://stackoverflow.com/comment/86291906
tagged with: python
has title: Create list of values from kwargs keys
score: 0
has answer: http://stackoverflow.com/a/49642154
answer count: 2
accepted answer: http://stackoverflow.com/a/49642283
tagged with: keyword-argument
upvote count: 1
has answer: http://stackoverflow.com/a/49642283
downvote count: 1
has comment: http://stackoverflow.com/comment/86291907
has body: How can I get a list of values from kwargs (see example below), I am able to get keys but not the values Kwargs: {'description_9': u' HVAC Ductwork Upgrade ', 'state_9': u'NSW', 'hours_6': u'2', 'hours_5': u'1', 'hours_4': u'1', 'hours_3': u'1', 'hours_2': u'8', 'hours_1': u'5', 'state_1': u'NSW', 'state_3': u'NSW', 'state_2': u'NSW', 'state_5': u'NSW', 'state_4': u'NSW', 'state_7': u'NSW', 'state_6': u'NSW', 'nbn_2': u' No ', 'nbn_3': u' Yes ', 'nbn_1': u' No ', 'nbn_6': u' Yes ', 'nbn_7': u' Yes ', 'nbn_4': u' No ', 'nbn_5': u' Yes ', 'nbn_8': u' Yes ', 'nbn_9': u' Yes ', 'site_8': u'Dee Why ', 'site_9': u'Sefton ', 'hours_9': u'4', 'site_2': u'Paddington ', 'site_3': u'Lidcombe ', 'site_1': u'Paddington ', 'site_6': u'St Marys ', 'site_7': u'Various ', 'site_4': u'Parramatta ', 'site_5': u'Kingsgrove ', 'spwo_8': u' SP30073989-2 ', 'spwo_9': u' SP30074031-1 ', 'spwo_4': u' SP30071948-1 ', 'spwo_5': u' SP30073129-1 ', 'spwo_6': u' SP30073989-1 ', 'spwo_7': u' SP30073989-3 ', 'spwo_1': u' SP30063647-1 ', 'spwo_2': u' SP30066349-1 ', 'spwo_3': u' SP30071798-1 ', 'hours_8': u'2', 'hours_7': u'3', 'description_2': u' Lvl 5 CHW PCU Upgrade ', 'description_3': u' Ductwork Upgrade ', 'description_1': u' Chilled Water Riser Upgrade ', 'description_6': u' HVAC Dropper Upgrade ', 'description_7' : u' HVAC Dropper Upgrade ', 'project_manager': u'Ossama Rihani', 'state_8': u'NSW', 'description_8': u' HVAC Dropper Upgrade ', 'description_5': u' HVAC and SGP Upgrade ', 'description_4': u' Main Distribution Board LCR Automatic Transfer Switches Design &amp; Construction P2 '} Code to extract keys with a filter: state_keys = [key for key in kwargs if key.startswith("state_")] Code i am trying to get the key values - not complete: state_values = [value for key, value in kwargs if key.startswith("state_")]
has comment: http://stackoverflow.com/comment/86291831
possible better answer: http://stackoverflow.com/a/49642154
favorite count: 0

http://stackoverflow.com/q/49755450
score: 1
tagged with: python
has title: Can I get the gradient of a tensor with respect to the input without applying the input?
tagged with: tensorflow
has body: For example, I need to compute the gradient of the cross_entropy with respect to x, but I need to apply another value to the gradient function. That is: f'(x)|x = x_t I think tf.gradients() function will only give the gradient at x = x. So does tensorflow provide any of this feature?
has answer: http://stackoverflow.com/a/49756883
tagged with: tensor
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: machine-learning
upvote count: 1
favorite count: 0
type: Question
tagged with: tensorflow-gradient

http://stackoverflow.com/q/49693264
has comment: http://stackoverflow.com/comment/86399065
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: The program is saying Process finished with exit code 0 but i am not getting any output. I am using Python version 2.7 and the program's job is to detect free parking slots in a car park. It also has pedestrian detection. Any help will be very much appreciated please i badly need this code to work. Thanks Here is the link to the source code, along with a video link of how it works https://github.com/ankit1khare/ComputerVision DESIRED OUTPUT: The program should open the input video and draw the parking overlay on top of the video. Here are the codes for the main program import yaml import numpy as np import cv2 # path references fn = "Khare_testvideo_01.mp4" #3 #fn = "datasets\parkinglot_1_720p.mp4" #fn = "datasets\street_high_360p.mp4" fn_yaml = "Khare_yml_01.yml" fn_out = "Khare_outputvideo_01.avi" cascade_src = 'Khare_classifier_02.xml' car_cascade = cv2.CascadeClassifier(cascade_src) global_str = "Last change at: " change_pos = 0.00 dict = { 'text_overlay': True, 'parking_overlay': True, 'parking_id_overlay': True, 'parking_detection': True, 'motion_detection': True, 'pedestrian_detection': False, # takes a lot of processing power 'min_area_motion_contour': 500, # area given to detect motion 'park_laplacian_th': 2.8, 'park_sec_to_wait': 1, # 4 wait time for changing the status of a region 'start_frame': 0, # begin frame from specific frame number 'show_ids': True, # shows id on each region 'classifier_used': True, 'save_video': True } # Set from video cap = cv2.VideoCapture(fn) print("video found") video_info = { 'fps': cap.get(cv2.CAP_PROP_FPS), 'width': int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)*0.6), 'height': int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)*0.6), 'fourcc': cap.get(cv2.CAP_PROP_FOURCC), 'num_of_frames': int(cap.get(cv2.CAP_PROP_FRAME_COUNT))} cap.set(cv2.CAP_PROP_POS_FRAMES, dict['start_frame']) # jump to frame number specified def run_classifier(img, id): # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cars = car_cascade.detectMultiScale(img, 1.1, 1) if cars…
tagged with: opencv
has answer: http://stackoverflow.com/a/49697762
score: 1
answer count: 1
tagged with: python
has title: OpenCV code in PyCharm: Process finished with exit code 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86398905
has comment: http://stackoverflow.com/comment/86409719

http://stackoverflow.com/a/49729239
accepted answer of: http://stackoverflow.com/q/49729099
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86472794
type: Answer
has body: Not sure, why but I would try to get rid of the "noise" around your command &amp; check return code: check_call(["dos2unix",file1], stdout=f_null , stderr=subprocess.STDOUT) pass as list of args, not command line (support for files with spaces in it!) remove shell=True as dos2unix isn't a built-in shell command use check_call so it raises an exception instead of failing silently At any rate, it is possible that dos2unix detects that the output isn't a tty anymore and decides to dump the output in it instead (dos2unix can work from standard input &amp; to standard output). I'd go with that explanation. You could check it by redirecting to a real file instead of os.devnull and check if the result is there. But I would do a pure python solution instead (with a backup for safety), which is portable and doesn't need dos2unix command (so it works on Windows as well): with open(file1,"rb") as f: contents = f.read().replace(b"\r\n",b"\n") with open(file1+".bak","wb") as f: f.write(contents) os.remove(file1) os.rename(file1+".bak",file1) reading the file fully is fast, but could choke on really big files. A line-by-line solution is also possible (still using the binary mode): with open(file1,"rb") as fr, open(file1+".bak","wb") as fw: for l in fr: fw.write(l.replace(b"\r\n",b"\n")) os.remove(file1) os.rename(file1+".bak",file1)
answers question: http://stackoverflow.com/q/49729099
score: 3
has comment: http://stackoverflow.com/comment/86472726

http://stackoverflow.com/comment/86483455
type: Comment
type: AnswerComment
has text: The 2nd one is better
score: 3
comment on: http://stackoverflow.com/a/49734782

http://stackoverflow.com/comment/86267086
type: QuestionComment
has text: yeah, I think you have to refresh for that. Annoying isn't it? have a good read.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49629722

pygobject
type: Tag
tag name: pygobject
tags question: http://stackoverflow.com/q/49756058

http://stackoverflow.com/q/49630868
has answer: http://stackoverflow.com/a/49631067
tagged with: if-statement
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has title: Hour of Python Trinket Number of Things challenge
has body: I was doing the "Number of Things" challenge on the Hour of Python Trinket website (https://hourofpython.trinket.io/python-challenges#/string-challenges/number-of-things-challenge) and was able to follow a tutorial on The Clever Programmer youtube channel to help. The challenge creates a sentence which pluralizes depending on the [0] int in the list. In the [1] slot, the string "trinket" would be returned as "trinkets" adding an 's' at the end. To take it a step further, I wanted to add a line that would see a word that ends in 's' (in my example 'boss') and add 'es' instead of 's'. I tried using an elif statement after the first if statement but it keeps appending "s". I would like the first statement to say "There are 5 bosses" I'm a novice learning Python now. Please be gentle haha. # Make a function how_many that, given a list of a number # and a thing name, returns a grmmatically correct sentence # describing the number of things. # # &gt;&gt;&gt; how_many([5, "trinket"]) # There are 5 trinkets. # &gt;&gt;&gt;&gt; how_many([1, "king"]) # There is 1 king. def how_many(the_list): # Add code here that returns the answer dg = str(the_list[1]) if the_list[0] &gt; 1: return "There are " + str(the_list[0]) + ' ' + the_list[1] + 's' elif dg[-1] == "s": return "There are " + str(the_list[0]) + ' ' + the_list[1] + 'es' else: return "There is " + str(the_list[0]) + ' ' + the_list[1] # Add print statements here to test what your code does:""" print how_many([5, "boss"]) print how_many([1, "king"]) ______ Prints: There are 5 bosss There is 1 king
accepted answer: http://stackoverflow.com/a/49630944
possible better answer: http://stackoverflow.com/a/49631067
has answer: http://stackoverflow.com/a/49630944
type: Question

http://stackoverflow.com/comment/86333750
score: 1
comment on: http://stackoverflow.com/q/49661827
type: Comment
type: QuestionComment
has text: Are you looking to get the closure cells, or the values in those cells?

http://stackoverflow.com/a/49681823
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49681731
has body: I would suggest comparing the list of files in the directory before and after archive extracting. Additional files and folders will be those from tar file.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86525240
type: QuestionComment
comment on: http://stackoverflow.com/q/49754385
type: Comment
score: 2
has text: Your question seems to boil down to: "Why doesn't the progress bar update when it's called from the main GUI?" What exactly do you mean when you say "call" it? I suspect you mean "call the class" which implies that `Tk.__init__()` gets called as a result. That could be the problem if it occurs from after another part of the program has also already called it because you can't have two `Tk` instances running at the same time—they don't play well together. There _are_ ways of creating more than one top-level window though, just not the way you [may] be doing it.

http://stackoverflow.com/comment/86466449
comment on: http://stackoverflow.com/a/49726341
score: 0
type: Comment
has text: Sir, again it's raising a similar error, `'RegistrationForm' object has no attribute 'ValidationError'`
type: AnswerComment

http://stackoverflow.com/q/49724128
has comment: http://stackoverflow.com/comment/86468587
answer count: 1
has body: When I press an inline button, handler button_pressed invokes multiple times. How to fix it? I need only one invocation. def button_pressed(bot, update): query = update.callback_query keyboard = [] for article in nn: keyboard.append([ InlineKeyboardButton(article.title, callback_data=article.pageid) ]) reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text('text_here', reply_markup=reply_markup, chat_id=query.message.chat_id, message_id=query.message.message_id) def main(): updater = Updater(TOKEN) dp = updater.dispatcher dp.add_handler(CallbackQueryHandler(button_pressed)) updater.start_polling(clean=True) updater.idle() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/86462921
score: 0
tagged with: python-telegram-bot
tagged with: bots
has title: Python-telegram-bot buttons handler invokes multiple times
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49730912
tagged with: telegram
type: UnansweredQuestion

http://stackoverflow.com/comment/86207118
comment on: http://stackoverflow.com/a/49599998
score: 0
type: Comment
has text: It should be noted that creating d from s alone would take linear time.
type: AnswerComment

http://stackoverflow.com/q/49683892
type: Question
accepted answer: http://stackoverflow.com/a/49684962
tagged with: python
upvote count: 4
tagged with: flask
has body: I want to pass a value from html link to my function in flask: the police man name has a button next to it if it is clicked i should take its id and send it to the python function here is the html code : &lt;ul class="list-group"&gt; {% for p in policemen %} &lt;li class="list-group-item"&gt;{{ " "~ p.rank ~" "}} &lt;div class="col-md-2 text-center"&gt; &lt;a href='/deletepolice/{{p.id}}' class="btn btn-primary btn-lg" &gt; &lt;/div&gt; Delete ? &lt;/a&gt; &lt;/li&gt; {% endfor %} here is the python function : @app.route('/deletepolice/&lt;string:id&gt;', methods=['GET','POST']) def deletepolice(id): # Create cursor cur = mysql.connection.cursor() # Execute cur.execute("DELETE FROM police WHERE id = %s", [id]) # Commit to DB mysql.connection.commit() #Close connection cur.close() flash('Police man deleted', 'success') return redirect(url_for('policemen'))
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49684962
answer count: 1
downvote count: 1
has title: pass a value from html link to my function in flask
tagged with: jinja2
favorite count: 0

http://stackoverflow.com/q/49660432
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86330502
has body: I have a list in which I am trying to replace empty strings with 0. Is there a way to do this other than iterating through each item in the list? Here's a smaller example of what my list is like: testlist=['',18.0,'','',0,15,8.0] In Matlab, I know I could do something like this: testlist[testlist=='']=0 but this only seems to change the first value (even if its something other than an empty string).
has answer: http://stackoverflow.com/a/49660500
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86330533
upvote count: 1
tagged with: python
has title: Using logical to index list and convert values
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/1540049
has answer: http://stackoverflow.com/a/49660665

http://stackoverflow.com/q/49707881
favorite count: 0
type: Question
tagged with: statistics
tagged with: anova
tagged with: p-value
score: 1
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: I did anova test b/w 'density' : continuous, 'quality':catagorical, but got different F-statics and p-value. now I am confused which one should i use to reject or support null hypothesis. import statsmodels.formula.api as smf import patsy formula = 'density ~ C(quality)' y,x = patsy.dmatrices(formula, wine_train, return_type='dataframe') smf.OLS(y,x).fit().summary() F-statistic: 9.093 Prob (F-statistic): 1.73e-08 ols result: image But anova test{f_oneway} is giving differnt F and p-value. wine_train'density','quality'.groupby('quality').groups stats.f_oneway(wine_train'density','quality'.groupby('quality').groups[3], wine_train'density','quality'.groupby('quality').groups[4], wine_train'density','quality'.groupby('quality').groups[5], wine_train'density','quality'.groupby('quality').groups[6], wine_train'density','quality'.groupby('quality').groups[7], wine_train'density','quality'.groupby('quality').groups[8]) **F_onewayResult(statistic=3.2489023202821761, pvalue=0.0064318288153747899)** may you give me idea that OLS and f_oneway are different or sthing.
downvote count: 0
has title: difference between OLS and f_oneway (Anova)
tagged with: machine-learning
upvote count: 1

http://stackoverflow.com/comment/86503802
score: 0
has text: Your code doesn't specify what `s` is in `xy2 = s+xy1`. If you used the `+` operator to add the values of `xy1` (which is type `xyData`) to `s` (which I'm guessing is a NumPy array), then the sum `s+xy1` will be converted into a NumPy array, which does not have an attribute `setValues`. You need to convert `s` into an `xyData` object first for this code to work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49743363

http://stackoverflow.com/q/49681124
has answer: http://stackoverflow.com/a/49682247
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86374573
possible better answer: http://stackoverflow.com/a/75358177
has answer: http://stackoverflow.com/a/75358177
has title: Vectorized implementation for `numpy.random.multivariate_normal`
tagged with: python
upvote count: 6
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has body: I am trying to use numpy.random.multivariate_normal to generate multiple samples where each sample is drawn from a multivariate Normal distribution with a different mean and cov. For example, if I would like to draw 2 samples, I tried from numpy import random as rand means = np.array([[-1., 0.], [1., 0.]]) covs = np.array([np.identity(2) for k in xrange(2)]) rand.multivariate_normal(means, covs) but this results in ValueError: mean must be 1 dimensional. Do I have to do a for loop for this? I thought that for functions like rand.binomial this is possible.
has comment: http://stackoverflow.com/comment/86374606
accepted answer: http://stackoverflow.com/a/49682247
score: 6
downvote count: 0

http://stackoverflow.com/q/49688722
has comment: http://stackoverflow.com/comment/86515737
has title: How can I merge these two functions into a single one ? [python 3.]
has comment: http://stackoverflow.com/comment/86389279
tagged with: python
tagged with: mouse
tagged with: image
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86389866
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86389629
favorite count: 0
type: Question
has body: It has been several weeks since I started learning python (via anaconda). I have started to develop my personal code for some applications for my work. So the question is the next one, I have this two function draw_rectangle and magnification which each one uses a different mouse_handler. As you can see in the code, both functions are the same, so what I want to do is to merge them into just one function (trying to make a better code structure). Finally, I call these functions in another script via: data['image_right'], rectangle['right'] = draw_rectangle(data['image_right']) magnification = magnification(data['image_left']) Here are the functions : def mouse_handler(action, x, y, flags,img) : # Action to be taken when left mouse button is pressed if action==cv2.EVENT_LBUTTONDOWN: rectangle.append([x,y]) # Action to be taken when left mouse button is released elif action==cv2.EVENT_LBUTTONUP: rectangle.append([x,y]) def draw_rectangle(img): global rectangle rectangle = [] #Create the window to show image cv2.namedWindow("Image",cv2.WINDOW_NORMAL) cv2.setMouseCallback("Image", mouse_handler, img) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows() img = img[rectangle[0][1]:rectangle[1][1],rectangle[0][0]:rectangle[1][0]] return img, rectangle def mouse_handler2(action, x, y, flags,img) : # Action to be taken when left mouse button is pressed if action==cv2.EVENT_LBUTTONDOWN: coordinates.append([x,y]) # Action to be taken when left mouse button is released elif action==cv2.EVENT_LBUTTONUP: coordinates.append([x,y]) def magnification(img): global coordinates coordinates = [] imgcopy = img.copy() #Create the window to show image cv2.namedWindow("Image",cv2.WINDOW_NORMAL) cv2.setMouseCallback("Image", mouse_handler2, imgcopy) cv2.putText(imgcopy, "Click/unclick", (int(imgcopy.shape[1]/4), int(imgcopy.shape[0]/2)), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 0), 3) cv2.imshow("Image", imgcopy) cv2.waitKey(0) cv2.destroyAllWindows() magnification = 10/np.sqrt( np.power…
tagged with: python-3.x
tagged with: opencv

http://stackoverflow.com/q/49730837
has title: Distinct command in django
type: AnsweredQuestion
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49730897
has body: what will be the ORM queries for the following situation: Count of child accounts(account_child_id) Count the number of accounts won(stage=Won). Count the number of distinct accounts with potential=’HP’ Count the number of distinct accounts with pipeline=’HP’
has answer: http://stackoverflow.com/a/49730897
score: 0
answer count: 1
tagged with: orm
type: Question

http://stackoverflow.com/comment/86263118
comment on: http://stackoverflow.com/q/49628097
type: Comment
type: QuestionComment
has text: @VasilisG. it's important to stress that these results are not "wrong". These are the expected results when sorting strings.
score: 1

http://stackoverflow.com/comment/86492041
comment on: http://stackoverflow.com/q/49738790
score: 6
has text: Use a loop to iterate over your list. Inside that list use the condition.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49680893
type: AcceptedAnswer
downvote count: 0
has body: Let's try: df[df['Diff'] == df['A'].map(df[df.Diff &gt; pd.Timedelta('2 days')] .groupby('A')['Diff'].min())] Output: A B C Diff 1 2002-01-16 2002-01-30 DX 14 days 3 2002-01-16 2002-01-30 FY 14 days 5 2002-04-28 2002-05-25 CO 27 days 7 2002-04-28 2002-05-25 DS 27 days
accepted answer of: http://stackoverflow.com/q/49680627
score: 3
answers question: http://stackoverflow.com/q/49680627
type: Answer
upvote count: 3

http://stackoverflow.com/q/49643616
has title: multiple image stitching in python
has comment: http://stackoverflow.com/comment/86296102
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86384830
has body: I am trying to run a code on image stitching using opencv Stitcher module on Windows. Here is a code: import cv2 import numpy as np import glob images = [] for file in glob.glob("path_to_images/*.png"): n= cv2.imread(file) images.append(n) result = images[0] for i in images: stitcher = cv2.createStitcher(False) result = stitcher.stitch(result, images[i]) cv2.imwrite("C:/Users/user/Desktop/mosaicing/island/out1.jpg", result[1]) I receive an error: TypeError: only integer scalar arrays can be converted to a scalar index I would appreciate any hints on how to solve it. TIA
has comment: http://stackoverflow.com/comment/86294881
tagged with: python
has comment: http://stackoverflow.com/comment/86384086
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/86384049
tagged with: image-stitching
type: Question
tagged with: numpy

http://stackoverflow.com/comment/86527929
has text: Hmmm yes, perhaps that should of been clearer in the description, but given the various [threads](https://stackoverflow.com/questions/26358281/convert-pdf-to-doc-python-bash?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) I've seen on the topic-- it should be working. Another [link](https://gist.github.com/eyecatchup/8ceed7aaa6694078d7c8)
score: 0
comment on: http://stackoverflow.com/q/49739245
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86512419
type: AnswerComment
comment on: http://stackoverflow.com/a/49747985
type: Comment
has text: @HassanALi As per that code snippet, if we did not specify path then it'll be saved in the same directory of `odoo`. If you want that newly created file at different place then specify path..... `with open("/home/flash/Downloads/imageToSave.jpg", "wb") as imgFile:` with this that file will be created in the `Downloads` directory!
score: 0

http://stackoverflow.com/comment/86299885
type: QuestionComment
has text: Yes it is possible, to do so I suggest you document yourself on Regular Expressions and how they can help you place the description string at the desired place of your html code
score: 0
comment on: http://stackoverflow.com/q/49645306
type: Comment

http://stackoverflow.com/comment/86226040
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49606484
has text: If you weren't trying to interface with PyQt, what would the signature for `ReceiveProcDataArr` actually be? I ask because PyQt5 `QVariant` support is different to PyQt4 and it's not clear to me that you actually should be using `QVariant` (see [docs](http://pyqt.sourceforge.net/Docs/PyQt5/pyqt_qvariant.html)). Unfortunately I can't find any information on what your trying to do, so it's a bit hard for me to get any further than this.

http://stackoverflow.com/q/49712577
has answer: http://stackoverflow.com/a/49712760
accepted answer: http://stackoverflow.com/a/49712760
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49712646
possible better answer: http://stackoverflow.com/a/49712646
favorite count: 0
type: Question
has body: I have a pandas dataframe that looks like this: from to a b b a c d c d d c I want to find the count of the combination of from and to regardless of the order so I'll end up with something like: places count [a,b] 2 [c,d] 3 I'm struggling to find a effective way of achieving this. Any help would be much appreciated.
has answer: http://stackoverflow.com/a/49713293
has title: Count of combination of columns regardless of order
tagged with: python
type: AnsweredQuestion
upvote count: 3
score: 3

http://stackoverflow.com/a/49664041
score: 2
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49663796
has body: ValueError: contamination must be in (0, 0.5] This means that contamination must be strictly larger than 0.0 and less than or equal to 0.5. (What does this square bracket and parenthesis bracket notation mean [first1,last1)? is a good question on the brackets notation) As you have commented, print(outlier_fraction) outputs 0.0, the problem lies in the first 6 lines of the code you posted.

http://stackoverflow.com/comment/86252715
has text: yeah, this method can't make sure each number to be unique in its row or column, thanks for pointing it out.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49606621

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/49614540
tags question: http://stackoverflow.com/q/49716147
tags question: http://stackoverflow.com/q/49715779
tags question: http://stackoverflow.com/q/49756839
tags question: http://stackoverflow.com/q/49642129
tags question: http://stackoverflow.com/q/49623986
tags question: http://stackoverflow.com/q/49663541
type: Tag
tags question: http://stackoverflow.com/q/49709753
tags question: http://stackoverflow.com/q/49732721
tags question: http://stackoverflow.com/q/49735392
tags question: http://stackoverflow.com/q/49647437

string
tags question: http://stackoverflow.com/q/49714254
tags question: http://stackoverflow.com/q/49629443
tags question: http://stackoverflow.com/q/49668140
tags question: http://stackoverflow.com/q/49624130
type: Tag
tags question: http://stackoverflow.com/q/49663106
tags question: http://stackoverflow.com/q/49629916
tags question: http://stackoverflow.com/q/49745889
tags question: http://stackoverflow.com/q/49740784
tags question: http://stackoverflow.com/q/49662174
tags question: http://stackoverflow.com/q/49634108
tags question: http://stackoverflow.com/q/49658698
tags question: http://stackoverflow.com/q/49691923
tags question: http://stackoverflow.com/q/49603557
tags question: http://stackoverflow.com/q/49619443
tags question: http://stackoverflow.com/q/49660209
tags question: http://stackoverflow.com/q/49602396
tags question: http://stackoverflow.com/q/49701989
tags question: http://stackoverflow.com/q/49730750
tags question: http://stackoverflow.com/q/49676597
tags question: http://stackoverflow.com/q/49684663
tags question: http://stackoverflow.com/q/49695477
tags question: http://stackoverflow.com/q/49686160
tags question: http://stackoverflow.com/q/49685426
tags question: http://stackoverflow.com/q/49599735
tags question: http://stackoverflow.com/q/49620011
tags question: http://stackoverflow.com/q/49630581
tags question: http://stackoverflow.com/q/49615816
tags question: http://stackoverflow.com/q/49705106
tags question: http://stackoverflow.com/q/49662409
tags question: http://stackoverflow.com/q/49624212
tags question: http://stackoverflow.com/q/49656922
tags question: http://stackoverflow.com/q/49706231
tags question: http://stackoverflow.com/q/49731023
tags question: http://stackoverflow.com/q/49694090
tags question: http://stackoverflow.com/q/49756717
tags question: http://stackoverflow.com/q/49681951
tags question: http://stackoverflow.com/q/49756350
tags question: http://stackoverflow.com/q/49643369
tags question: http://stackoverflow.com/q/49720530
tags question: http://stackoverflow.com/q/49727037
tags question: http://stackoverflow.com/q/49714068
tags question: http://stackoverflow.com/q/49638176
tags question: http://stackoverflow.com/q/49620178
tags question: http://stackoverflow.com/q/49715287
tags question: http://stackoverflow.com/q/49692151
tags question: http://stackoverflow.com/q/49702536
tags question: http://stackoverflow.com/q/49638761
tags question: http://stackoverflow.com/q/49724953
tags question: http://stackoverflow.com/q/49698551
tags question: http://stackoverflow.com/q/49666050
tags question: http://stackoverflow.com/q/49747499
tags question: http://stackoverflow.com/q/49730257
tags question: http://stackoverflow.com/q/49727251
tags question: http://stackoverflow.com/q/49666036
tags question: http://stackoverflow.com/q/49692297
tags question: http://stackoverflow.com/q/49661621
tags question: http://stackoverflow.com/q/49612207
tags question: http://stackoverflow.com/q/49703045
tags question: http://stackoverflow.com/q/49666331
tags question: http://stackoverflow.com/q/49756824
tags question: http://stackoverflow.com/q/49663348
tags question: http://stackoverflow.com/q/49663950
tags question: http://stackoverflow.com/q/49716552
tags question: http://stackoverflow.com/q/49728132
tags question: http://stackoverflow.com/q/49637751
tags question: http://stackoverflow.com/q/49724789
tags question: http://stackoverflow.com/q/49606792
tags question: http://stackoverflow.com/q/49630010
tags question: http://stackoverflow.com/q/49600700
tags question: http://stackoverflow.com/q/49659606
tags question: http://stackoverflow.com/q/49719353
tags question: http://stackoverflow.com/q/49711722
tag name: string
tags question: http://stackoverflow.com/q/49685310
tags question: http://stackoverflow.com/q/49606909
tags question: http://stackoverflow.com/q/49635591
tags question: http://stackoverflow.com/q/49683215
tags question: http://stackoverflow.com/q/49619281
tags question: http://stackoverflow.com/q/49621503

http://stackoverflow.com/q/49713333
favorite count: 0
type: Question
upvote count: 2
tagged with: function
downvote count: 0
tagged with: python
tagged with: variables
accepted answer: http://stackoverflow.com/a/49713363
has answer: http://stackoverflow.com/a/49713363
score: 2
has title: Python Declare Variables in Function Call?
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/49713367
has answer: http://stackoverflow.com/a/49713377
has body: Sorry if this has already been asked, I'm not sure exactly how to describe my question in a sentence anyway. I'm doing some work for my bioinformatics course, and I've begun to see variables declared when functions are called, instead of just passing the argument (see line 5 below). def sobelFilter(pixmap): matrix = array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) grey = pixmap.mean(axis=2) #&lt;---here edgeX = convolveMatrix2D(grey, matrix) edgeY = convolveMatrix2D(grey, matrix.T) pixmap2 = sqrt(edgeX * edgeX + edgeY * edgeY) normalisePixmap(pixmap2) return pixmap2 What is the purpose of grey = pixmap.mean(axis=2) when axis is never used again? Why not just say grey = pixmap.mean(2)? If it's necessary for my question, this is just code we were given to use, not written by myself. Pixmap refers to this code: def imageToPixmapRGB(img): img2 = img.convert("RGB") w,h = img2.size data = img2.getdata() pixmap = array(data, float) pixmap = pixmap.reshape((h,w,3)) return pixmap
has answer: http://stackoverflow.com/a/49713367

python-requests
tags question: http://stackoverflow.com/q/49625798
tags question: http://stackoverflow.com/q/49701183
tags question: http://stackoverflow.com/q/49749498
tags question: http://stackoverflow.com/q/49615277
tags question: http://stackoverflow.com/q/49749959
tags question: http://stackoverflow.com/q/49678261
tags question: http://stackoverflow.com/q/49724965
type: Tag
tags question: http://stackoverflow.com/q/49721695
tags question: http://stackoverflow.com/q/49751339
tags question: http://stackoverflow.com/q/49744164
tags question: http://stackoverflow.com/q/49752560
tags question: http://stackoverflow.com/q/49738635
tags question: http://stackoverflow.com/q/49601155
tags question: http://stackoverflow.com/q/49709753
tags question: http://stackoverflow.com/q/49700726
tags question: http://stackoverflow.com/q/49757135
tag name: python-requests
tags question: http://stackoverflow.com/q/49709434
tags question: http://stackoverflow.com/q/49703512
tags question: http://stackoverflow.com/q/49710169
tags question: http://stackoverflow.com/q/49684133
tags question: http://stackoverflow.com/q/49691395
tags question: http://stackoverflow.com/q/49694126
tags question: http://stackoverflow.com/q/49712430
tags question: http://stackoverflow.com/q/49623406
tags question: http://stackoverflow.com/q/49626286
tags question: http://stackoverflow.com/q/49615041
tags question: http://stackoverflow.com/q/49712525
tags question: http://stackoverflow.com/q/49646424
tags question: http://stackoverflow.com/q/49659163
tags question: http://stackoverflow.com/q/49659733
tags question: http://stackoverflow.com/q/49668721
tags question: http://stackoverflow.com/q/49728262
tags question: http://stackoverflow.com/q/49696580
tags question: http://stackoverflow.com/q/49622811
tags question: http://stackoverflow.com/q/49708525
tags question: http://stackoverflow.com/q/49663091
tags question: http://stackoverflow.com/q/49680816
tags question: http://stackoverflow.com/q/49600779
tags question: http://stackoverflow.com/q/49681501
tags question: http://stackoverflow.com/q/49635758
tags question: http://stackoverflow.com/q/49745973

http://stackoverflow.com/q/49671345
possible better answer: http://stackoverflow.com/a/49672861
type: Question
has body: I've been setting up a couple of IDE for Python. I'm surprised that IDE (used e.g. Spyder or VS Code) do not highlight error if an argument is missing. Is this is not expected? def say(what): print(what) say() # no error?
answer count: 2
has comment: http://stackoverflow.com/comment/124257595
has answer: http://stackoverflow.com/a/49671643
tagged with: ide
tagged with: python
has title: Missing arguments to Python function - error detection in IDE
has comment: http://stackoverflow.com/comment/86352867
accepted answer: http://stackoverflow.com/a/49671643
has answer: http://stackoverflow.com/a/49672861
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49726653
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49723540
has body: You could hide the actual compiling in a custom FunctionElement: from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import FunctionElement, column from sqlalchemy.sql.base import ColumnCollection from sqlalchemy.types import TEXT, INTEGER class ts_stat(FunctionElement): name = "ts_stat" @property def columns(self): # Using (undocumented) `_selectable=self` would allow # omitting the explicit `select_from(ts_stat_obj)` in # every query using `ts_stat`. return ColumnCollection( column("word", TEXT), column("ndoc", INTEGER), column("nentry", INTEGER)) @compiles(ts_stat, 'postgresql') def pg_ts_stat(element, compiler, **kw): kw.pop("asfrom", None) # Ignore and set explicitly arg1, = element.clauses # arg1 is a FromGrouping, which would force parens around the SELECT. stmt = compiler.process( arg1.element, asfrom=False, literal_binds=True, **kw) # TODO: Choose a random tag for dollar quoting. Another option # would be to wrap the stmt in `literal()`, compiling that, and # letting the driver worry about quoting. return f"ts_stat($${stmt}$$)" Usage is straightforward: you pass a Select or a Query as the sole argument: from sqlalchemy import select, column, literal from sqlalchemy.dialects import postgresql from sqlalchemy.orm import sessionmaker d = postgresql.dialect() s = select([1]) f = ts_stat(s) stmt = select([f.c.word, f.c.ndoc, f.c.nentry]).\ select_from(f).\ order_by(f.c.nentry.desc(), f.c.ndoc.desc(), f.c.word).\ compile(dialect=d) print(stmt) # SELECT word, ndoc, nentry # FROM ts_stat($$SELECT 1$$) ORDER BY nentry DESC, ndoc DESC, word Session = sessionmaker() session = Session() q = session.query(literal(1)) f2 = ts_stat(q) stmt2 = select(['*']).\ select_from(f2).\ order_by(f2.c.nentry.desc(), f2.c.ndoc.desc(), f2.c.word).\ compile(dialect=d) print(stmt2) # SELECT * # FROM ts_stat($$SELECT 1 AS param_1$$) ORDER BY nentry DESC, ndoc DESC, word Note that using literal_binds=True limits what you can pass as parameters to the inner select, a…
type: Answer
has comment: http://stackoverflow.com/comment/86482089
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49723540

http://stackoverflow.com/a/49616982
type: Answer
has body: You should probably use the json package and json.dumps your dictionary. That will create a json string with your dictionary that you can store in dynamoDB as a JSON document or directly as a string if you are so inclined. In this case you can later read it and json.loads it back into a python dictionary. Using JSON also means you'll have less compatibility problems in the future if you need to interface with other products or applications.
has comment: http://stackoverflow.com/comment/86298158
answers question: http://stackoverflow.com/q/49616659
score: 0
has comment: http://stackoverflow.com/comment/86294837

http://stackoverflow.com/comment/86361560
type: Comment
type: QuestionComment
has text: Please post the complete Traceack when asking about code that throws an exception - format it as code.
score: 0
comment on: http://stackoverflow.com/q/49675279

http://stackoverflow.com/q/49705937
has comment: http://stackoverflow.com/comment/86508089
tagged with: praw
type: Question
answer count: 0
tagged with: reddit
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86443203
has comment: http://stackoverflow.com/comment/86443075
has title: Having trouble installing praw
has body: So I'm trying to make a Reddit bot so I have to install praw. the problem is I keep getting this error message: matplotlib 1.3.1 requires nose, which is not installed. matplotlib 1.3.1 requires tornado, which is not installed. matplotlib 1.3.1 has requirement numpy&gt;=1.5, but you'll have numpy 1.8.0rc1 which is incompatible. When I try to install nose and tornado they also fail, so what am I supposed to do or should I just give up?
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86425386
tagged with: bots
has comment: http://stackoverflow.com/comment/86459454

http://stackoverflow.com/comment/86480847
type: Comment
type: AnswerComment
has text: @DeltaIV, no, that's not necessary. The dictionaries already contain all the items from your lists by construction. Also, lists have no `items` method.
score: 0
comment on: http://stackoverflow.com/a/49733212

http://stackoverflow.com/comment/86507655
score: 0
type: Comment
type: QuestionComment
has text: If you want to refer to other StackOverflow questions, please put links to them.
comment on: http://stackoverflow.com/q/49746712

http://stackoverflow.com/q/49637751
type: Question
has answer: http://stackoverflow.com/a/49651052
answer count: 2
type: UnansweredQuestion
has title: Removing substrings from a string in Python?
tagged with: string
score: 0
tagged with: numbers
has answer: http://stackoverflow.com/a/49637796
has body: I´m currently facing the problem that I have a string (deeplink) of which I want to extract one certain substring: https://www.jsox.de/tokyo-l200/tokio-skytree-ticket-fuer-einlass-ohne-anstehen-t107728/?partner_id=M1 https://www.jsox.de/tokyo-l201/ganztaegige-bustour-zum-fuji-ab-tokio-t65554/?partner_id=M1 I expect to get extract the following information from the strings above: t107728 t65554 How can I only extract for example the substring t107728 from the the first string above? I tried it with the split and sub function but it does not work out Can you guys help me out? Any feedback is appreciated
tagged with: python
tagged with: web-crawler

http://stackoverflow.com/a/49655113
type: Answer
accepted answer of: http://stackoverflow.com/q/49649014
type: AcceptedAnswer
downvote count: 0
has body: I'm not sure what ntp is in your code but this should work: brand = ntp.xpath('.//b[.="Marca e Modello:"]/following-sibling::text()[1]').extract_first()
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49649014
has comment: http://stackoverflow.com/comment/86342069

http://stackoverflow.com/q/49702440
has comment: http://stackoverflow.com/comment/86424535
has comment: http://stackoverflow.com/comment/86419065
accepted answer: http://stackoverflow.com/a/49706677
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49706596
answer count: 2
has answer: http://stackoverflow.com/a/49706677
tagged with: pandas
upvote count: 2
has answer: http://stackoverflow.com/a/49706596
downvote count: 0
favorite count: 0
has title: How can I apply a format to a groupby function?
type: Question
has body: I have the following DataFrame: High counts Total 11 1.2492 2 2.4984 1 1.2466 2 2.4932 20 1.2574 1 1.2574 19 1.2547 1 1.2547 18 1.2523 1 1.2523 I have used following line to groupby hg = grps.groupby("High").size().reset_index(name='counts') I am trying to group by this DataFrame in the following format. But values of High must not change. {:.3f} # 1.249, 1.246, 1.257 ... Is it possible to do this or shall i create a new DataFrame? EDIT: Here is the expected output High counts Total New 11 1.2492 2 2.4984 1.249 1 1.2466 2 2.4932 1.246 20 1.2574 1 1.2574 1.257 19 1.2547 1 1.2547 1.254 18 1.2523 1 1.2523 1.252
linked to: http://stackoverflow.com/q/27592456
tagged with: rounding
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86424276
linked to: http://stackoverflow.com/q/11950819

http://stackoverflow.com/comment/86496636
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49740628
has text: `pip install --upgrade pip; pip install --upgrade django`
score: 0

http://stackoverflow.com/a/49757973
type: Answer
has comment: http://stackoverflow.com/comment/86531297
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49757409
has comment: http://stackoverflow.com/comment/86531185
answers question: http://stackoverflow.com/q/49757409
has body: It looks as if you are hitting this issue. It looks as if it has been fixed, but there hasn't been a release since then. You could try installing the master branch. This might be a good idea anyway, since 0.9.7 was released in 2015. Alternatively, or you could try setting LANG, as suggested in this similar issue for a different project. LANG=en_US.UTF8 pip3 install django-nvd3

http://stackoverflow.com/q/49753793
downvote count: 0
has title: Tensorflow CPU RAM allocation
has comment: http://stackoverflow.com/comment/86555943
has comment: http://stackoverflow.com/comment/86555960
upvote count: 7
has comment: http://stackoverflow.com/comment/86544809
has comment: http://stackoverflow.com/comment/86523360
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/123784081
has comment: http://stackoverflow.com/comment/86623249
has body: I experience an incredibly high amount of (CPU) RAM usage with Tensorflow while about every variable is allocated on the GPU device, and all computation runs there. Even then, RAM usage exceeds the VRAM usage by a factor of 2 at least. I'm trying to understand why so as to see if it can be remedied or if it's inevitable. Question So my main question is: Does Tensorflow allocate and maintain a copy of all GPU variables on (CPU) RAM? If yes, what is allocated when (in which phase, see below)? And why is it useful to allocate this in CPU memory? More info I have 3 phases in which I see RAM increasing dramatically. First, when defining the graph (I append VGG-19 with quite large loss functions that iterate over many translated activation maps). This adds 2 GB to RAM usage. Second, defining the optimizer (I use Adam) adds 250MB. Initialize global variables adds 750MB. And then it remains stable and runs very fast (all on GPU). (Amounts of data mentioned here are when I input tiny images of size 8x8x3, batch size of 1. If I do more than 1x16x16x3, the process gets killed because it overflows my 8GB RAM+6GB swap limit). Note that I recorded variable placement with tf.ConfigProto(log_device_placement=True), and GPU usage using tf.RunMetadata and visualization on tensorboard. Thank you for any help. System information Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes OS Platform and Distribution: Linux Ubuntu 17.10 TensorFlow installed from (source or binary): binary TensorFlow version (use command below): 1.7 Python version: 3.6.3 GCC/Compiler version (if compiling from source): 6.4.0 CUDA/cuDNN version: 9.0 GPU model and memory: NVidia GeForce Titan Xp
score: 7
tagged with: python
has comment: http://stackoverflow.com/comment/86555796
has comment: http://stackoverflow.com/comment/86565820
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/86522709
type: UnansweredQuestion

shutil
tags question: http://stackoverflow.com/q/49696136
tags question: http://stackoverflow.com/q/49699933
tags question: http://stackoverflow.com/q/49657054
tags question: http://stackoverflow.com/q/49676876
tags question: http://stackoverflow.com/q/49673036
tags question: http://stackoverflow.com/q/49607990
tags question: http://stackoverflow.com/q/49610870
type: Tag
tags question: http://stackoverflow.com/q/49672411
tag name: shutil

http://stackoverflow.com/comment/86390685
score: 0
has text: @Vivek Kumar I'm calling ``gp.kernel_.get_params()`` :)
comment on: http://stackoverflow.com/q/49688564
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86268970
comment on: http://stackoverflow.com/a/49630946
type: Comment
has text: Thanks, @ely. I changed the backend to "tensorflow" in the keras.json file and the error is resolved now. I am able to import the modules successfully. thanks again :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86299686
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49645763
has text: There is no magic involved. You need to search your whole structure until you find a matching keyname, then insert your values there. SO is about fixing _your_ Code, show it to us.If you have specifiic questions provide your code as [mvce](https://stackoverflow.com/help/mcve). If you encounter errors, copy and paste the error message verbatim ( word for word) into your question. Avoid using screenshots unless you need to convey layout errors. We can NOT copy and paste your image into our IDEs to fix your code.

http://stackoverflow.com/comment/86471280
type: QuestionComment
comment on: http://stackoverflow.com/q/49728460
score: 2
has text: I think you are going to the wrong direction.Network bottleneck usually do no depend on such small compression. Network go with packets, so a lot overhead. It is ok to compress large files/data (and compression take CPU and memory bandwidth). Before to optimize, start to measure and understand where are the problems. Guesses are near always wrong (but if you have a lot (really a lot) of experience, but than you will fail often anyway).
type: Comment

http://stackoverflow.com/a/49625469
has body: Simply use a loop to do that: result=[] for i in your_array: result.append(vars[i]) or one linear [vars[i] for i in your_array]
has comment: http://stackoverflow.com/comment/86261951
type: Answer
score: 17
downvote count: 0
upvote count: 17
answers question: http://stackoverflow.com/q/49625407

http://stackoverflow.com/comment/86252639
type: QuestionComment
score: 0
has text: Then use : docs.python.org/2/library/xml.etree.elementtree.html
comment on: http://stackoverflow.com/q/49622811
type: Comment

http://stackoverflow.com/a/49661466
has comment: http://stackoverflow.com/comment/86634045
type: Answer
has comment: http://stackoverflow.com/comment/86333699
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/86332936
accepted answer of: http://stackoverflow.com/q/49661380
has comment: http://stackoverflow.com/comment/86333307
downvote count: 0
has body: You can read your file line by line, split on whitespace and use the elements in reverse to create a dictionary: with open("your_file", "r") as f: # open the file for reading # read it line by line, split and invert the fields to use as k:v for your dict data = dict(reversed(line.split()) for line in f) # {'trendmar': '+41G', 'ttpsenet': '1.4G', 'tyibahco': '3.6G', # 'uberhelp': '+19M', 'umljgate': '+9.2G'} Beware that dict is essentially a hash map so it cannot have duplicate keys - values of duplicate keys will be overwritten with the latest value if they occur in the file. UPDATE: If you want to preserve all the values you'll have to store them as lists, something like: import collections data = collections.defaultdict(list) # initiate all fields as lists with open("your_file", "r") as f: # open the file for reading for line in f: # read the file line by line value, key = line.split() # split the line to value and key data[key].append(value) # append the value to the list for its key And now your data will look like: {'trendmar': ['-34G', '+41G'], 'ttpsenet': ['1.4G'], 'tyibahco': ['3.6G'], 'uberhelp': ['-13M', '+19M'], 'umljgate': ['-8.9G', '+9.2G']} UPDATE 2: If you want to sum the values instead you'll first need to convert them to floats, then use regular arithmetic operations to reach the final value, so first write a function to convert from the SI shorthand notation to native float: QUANTIFIER_MAP = {"p": 1e15, "t": 1e12, "g": 1e9, "m": 1e6, "k": 1e3} def si_to_float(number): try: last_char = number[-1].lower() if last_char in QUANTIFIER_MAP: return float(number[:-1]) * QUANTIFIER_MAP[last_char] return float(number) except ValueError: return 0.0 Now you can substitute list for a float when creating data and sum the values instead of appending: import collections data = collections.defaultdict(float) # initiate all fields as integers with open("your_file", "r") as f: # open the file for reading # read it line by line, split and invert the fields to use as k…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86628205
has comment: http://stackoverflow.com/comment/86334775
answers question: http://stackoverflow.com/q/49661380

http://stackoverflow.com/a/49679220
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49677096
type: Answer
answers question: http://stackoverflow.com/q/49677096
score: 0
has body: This should help. df["Entity"].str.extract('"([-0-9"]*)"').str.strip() Output: 0 196609 1 -1140719616 2 196609 3 196609 4 196609 5 10000227 6 196609 7 -1140719616 Name: Entity, dtype: object

http://stackoverflow.com/q/49708926
downvote count: 1
has answer: http://stackoverflow.com/a/49709132
favorite count: 0
type: Question
tagged with: digits
has body: I want to build a simple digit prediction model. Therefore I: load in the sklearn dataset Use the DecisionTreeClassifier() Fit to the data Predict the new image import matplotlib.pyplot as plt from sklearn import datasets from sklearn import tree digits = datasets.load_digits() clf = tree.DecisionTreeClassifier() clf = clf.fit(digits.data, digits.target) clf.predict(digits.data[-1]) What did I do wrong? ValueError Traceback (most recent call last) &lt;ipython-input-9-b58a2a08d39b&gt; in &lt;module&gt;() ----&gt; 1 clf.predict(digits.data[-1])
has answer: http://stackoverflow.com/a/49709887
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49709363
score: 0
has title: Predicting numbers using sklearn digits dataset - error
possible better answer: http://stackoverflow.com/a/49709265
accepted answer: http://stackoverflow.com/a/49709132
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49709265

http://stackoverflow.com/a/49719120
score: 0
has comment: http://stackoverflow.com/comment/86453085
has comment: http://stackoverflow.com/comment/86453375
type: Answer
has body: The problem with your current approach is mostly based on words.count(word) inside a for loop. This means that you iterate the entire list for every unique word in set(words), and only count a single word... instead, you can use Counter and make a single pass of your list. The Counter object is a dictionary, which you can use for your key in sorting, with frequency lookups of O(1). Even for 1000 "words" in my example, the speed-up is dramatic... for longer inputs, I got bored waiting for timeit to finish :) import string from collections import Counter import numpy as np # Just to create fake data # Create some fake data letters = list(string.ascii_lowercase) new_words = [''.join(list(np.random.choice(letters, 3, replace=True))) for x in range(1000)] def original(search_list): """ Your current approach """ for i, pair in enumerate(sorted( ((word, search_list.count(word)) for word in set(search_list)), key=lambda p: p[1], reverse=True)): pass def new_approach(search_list): freq = Counter(search_list) search_list = sorted(search_list, key=lambda x: freq[x], reverse=True) new_list = [] checked = set() for item in search_list: if item not in checked: new_list.append(item) checked.add(item) For a list of 1000 "words": %timeit original(new_words) 26.6 ms ± 289 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit new_approach(new_words) 833 µs ± 30 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) You should see whether this new approach is suitable for your needs before trying to use something like multiprocessing as that may be adding extra code complexity that isn't necessary once you fix your time complexity issue. EDIT: As pointed out by the OP, we can skip the intermediate list and set by simply sorting the Counter object: def new_approach(search_list): freq = Counter(search_list) search_list = enumerate(sorted(freq, key=lambda x: freq[x], reverse=True)) New timing: %timeit new_approach(new_words) 438 µs ± 6.31 µs per loop (mean ± std. dev. of 7 ru…
has comment: http://stackoverflow.com/comment/86453279
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49717183
answers question: http://stackoverflow.com/q/49717183
has comment: http://stackoverflow.com/comment/86452935
has comment: http://stackoverflow.com/comment/86453015

http://stackoverflow.com/q/49743824
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86503727
downvote count: 0
tagged with: matrix
answer count: 1
accepted answer: http://stackoverflow.com/a/49744696
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86503123
has comment: http://stackoverflow.com/comment/86503371
has title: How to use Numpy Matrix operation to calculate multiple samples at once?
tagged with: python
has body: How do I use Numpy matrix operations to calculate over multiple vector samples at once? Please see below the code I came up with, 'd' is the outcome I'm trying to get. But this is only one sample. How do I calculate the output without doing something like repeat the code for every sample OR looping through every sample? a = np.array([[1, 2, 3]]) b = np.array([[1, 2, 3]]) c = np.array([[1, 2, 3]]) d = ((a.T * b).flatten() * c.T) a1 = np.array([[2, 3, 4]]) b1 = np.array([[2, 3, 4]]) c1 = np.array([[2, 3, 4]]) d1 = ((a1.T * b1).flatten() * c1.T) a2 = np.array([[3, 4, 5]]) b2 = np.array([[3, 4, 5]]) c2 = np.array([[3, 4, 5]]) d2 = ((a2.T * b2).flatten() * c2.T)
has answer: http://stackoverflow.com/a/49744696
tagged with: vectorization
has comment: http://stackoverflow.com/comment/86503351
score: 2
upvote count: 2
tagged with: numpy

http://stackoverflow.com/comment/86255815
type: AnswerComment
has text: Thank you, but my spark version is 1.6.0, which does not have VectorUDT, this's why I asked this question
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49624396

http://stackoverflow.com/a/49701263
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
has body: IIUC: See my post on pd.concat for more information Or the documentation pd.concat(C, keys=list(zip(A, B)), axis=1) Jan Feb Mar location1 location2 location3 A B C A B C A B C 0 -0.519821 -1.820451 -0.645732 -0.519821 -1.820451 -0.645732 -0.519821 -1.820451 -0.645732 1 1.043477 -0.666565 -0.298504 1.043477 -0.666565 -0.298504 1.043477 -0.666565 -0.298504 Alternatively pd.concat(dict(zip(zip(A, B), C)), axis=1)
type: Answer
accepted answer of: http://stackoverflow.com/q/49700457
has comment: http://stackoverflow.com/comment/86416229
answers question: http://stackoverflow.com/q/49700457

http://stackoverflow.com/comment/86245155
has text: I believe that's still true but see here for the usual alternatives https://stackoverflow.com/questions/9348264/does-tkinter-have-a-table-widget
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49618110
score: 1

http://stackoverflow.com/comment/86397849
type: AnswerComment
score: 0
type: Comment
has text: P.S This isn't the most efficient solution and can be quite resource hungry as the rows to process is the number of rows in the table * the number of rows in the table.
comment on: http://stackoverflow.com/a/49682779

http://stackoverflow.com/comment/86296724
comment on: http://stackoverflow.com/q/49644482
has text: Add a sample case?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86355063
has text: Or make a copy of the original list by using `for i in myList[:]` instead.
score: 0
comment on: http://stackoverflow.com/q/49672100
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49803943
answers question: http://stackoverflow.com/q/49736503
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49736503
has body: Thanks for trying to help. After looking around on SO for days, I found a similar question where someone said I should include another path path('sale/', views.laptop_sale, name = "sale") in addition to my existing path('sale/&lt;str:laptopname&gt;', views.laptop_sale, name = "sale") which seems to have solved the problem. Again, thanks for trying to help.

http://stackoverflow.com/a/49696579
upvote count: 1
answers question: http://stackoverflow.com/q/49695188
score: 0
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86469337
has body: import pandas as pd ... new_frame=pd.merge(dataframe1,dataframe2,on condition) in case of more advanced merge we can specify the column names as well dataframe'column1','column2',...

http://stackoverflow.com/q/49649308
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49650108
has title: What is the name of local server use to run django App?
upvote count: 1
has body: Django server name which is use to run app locally. As php use apache server to run app locally.
score: -6
accepted answer: http://stackoverflow.com/a/49650108
downvote count: 7
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49649342
has comment: http://stackoverflow.com/comment/86306596
answer count: 2
has answer: http://stackoverflow.com/a/49649342
tagged with: django
tagged with: python

http://stackoverflow.com/q/49730861
answer count: 1
favorite count: 0
type: Question
has title: psycopg2.extras.execute_values to insert multiple rows for geometry data
tagged with: python
tagged with: psycopg2
tagged with: postgis
has body: This is my insert query sql = "INSERT INTO sightings (run_id, geometry, properties) VALUES(%s, ST_MakePoint(%s, %s), %s);" 1) run_id is an internal uuid 2) geometry - this is geopoint object 3) properties is a JSON object On running psycopg2.extras.execute_values(cur, sql, listOfTuples) I get an error that says: the query contains more than one '%s' placeholder' I realize my mistake around this, but how can I get around it. Is there a way the template parameter can be of any help.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50409648
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50409648
downvote count: 0

kivy
tags question: http://stackoverflow.com/q/49640585
tags question: http://stackoverflow.com/q/49707807
type: Tag
tags question: http://stackoverflow.com/q/49656343
tag name: kivy
tags question: http://stackoverflow.com/q/49706669
tags question: http://stackoverflow.com/q/49722275
tags question: http://stackoverflow.com/q/49727200
tags question: http://stackoverflow.com/q/49681973
tags question: http://stackoverflow.com/q/49737339
tags question: http://stackoverflow.com/q/49741076
tags question: http://stackoverflow.com/q/49641386
tags question: http://stackoverflow.com/q/49705758
tags question: http://stackoverflow.com/q/49641307
tags question: http://stackoverflow.com/q/49637981
tags question: http://stackoverflow.com/q/49654664
tags question: http://stackoverflow.com/q/49698979
tags question: http://stackoverflow.com/q/49663837
tags question: http://stackoverflow.com/q/49713682
tags question: http://stackoverflow.com/q/49660657
tags question: http://stackoverflow.com/q/49711968
tags question: http://stackoverflow.com/q/49650213
tags question: http://stackoverflow.com/q/49656005
tags question: http://stackoverflow.com/q/49652081
tags question: http://stackoverflow.com/q/49723274

http://stackoverflow.com/q/49642651
upvote count: 4
score: 4
type: Question
accepted answer: http://stackoverflow.com/a/49642826
has answer: http://stackoverflow.com/a/49642744
possible better answer: http://stackoverflow.com/a/49642744
answer count: 2
tagged with: raspberry-pi
downvote count: 0
tagged with: robotics
tagged with: callback
favorite count: 0
has answer: http://stackoverflow.com/a/49642826
type: AnsweredQuestion
has body: Can I pass class A into class B so that B can run a callback using A's member function? I am trying to write a Python leg class for a robot I am building. I am using a Raspberry Pi as the main computer, and Martin O'Hanlon's KY040 rotary encoder library KY040 to detect each 1/4 rotation of the leg. To this end, I watch for the first of several clicks, sleep for a short time, stop the servo, and now a 1/4 rotation has been achieved. In standalone, unthreaded code this works fine, but creating a class has been a challenge. Details: A threaded sentinel loop watches a boolean (quarterTurn) to signal that a rotation must be carried out. def run(self): print "leg running" while self._running: sleep(.0001) if self.quarterTurn: print "quarterTurn is: " + str(self.quarterTurn) self.qTurn(self.quarterCount) qTurn accesses a pwm controller to activate the motors, and reset quarterTurn to false. def qTurn(self, quarters): count = 0 while count < quarters: sleep(.0001) self.setMotor(self.maxPulse) if self.ClickedOnce: count = count + 1 sleep(.17) self.parkMotor() sleep(.04) self.clickedOnce = False self.quarterTurn = False The trick is that O'Hanlon's class is already threaded. On one hand, it is convenient, on the other, it makes my class more complex. The KY040 makes use of a callback function to provide feedback, but using this within my class is the source of my trouble. I need the callback to modify a a boolean in my leg class, but this function is only called by the KY040 class, which tries to pass itself into the function. def rotaryChange(self, pin): self.clickedOnce = True Since the code is open source (thank you, O'Hanlon), I thought I could modify the constructor of the KY040 to let me pass my leg class into it, so that I could modify the correct data. O'Hanlon's Original Constructor: def __init__(self, clockPin, dataPin, switchPin=None, rotaryCallback=None, switchCallback=None,rotaryBouncetime=250, switchBouncetime=300): # persist values self.clockPin = clockPin self…
has title: Python: Passing a class member function to another class's callback
tagged with: python

http://stackoverflow.com/q/49638674
accepted answer: http://stackoverflow.com/a/49638751
tagged with: strip
score: 1
duplicate of: http://stackoverflow.com/q/20306223
tagged with: python
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/86285084
answer count: 4
tagged with: substring
type: Question
has answer: http://stackoverflow.com/a/49638741
downvote count: 0
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49638734
has title: Unexpected result when removing substring from a string
linked to: http://stackoverflow.com/q/20306223
possible better answer: http://stackoverflow.com/a/49638741
has body: I have a string s, and I want to remove '.mainlog' from it. I tried: &gt;&gt;&gt; s = 'ntm_MonMar26_16_59_41_2018.mainlog' &gt;&gt;&gt; s.strip('.mainlog') 'tm_MonMar26_16_59_41_2018' Why did the n get removed from 'ntm...'? Similarly, I had another issue: &gt;&gt;&gt; s = 'MonMar26_16_59_41_2018_rerun.mainlog' &gt;&gt;&gt; s.strip('.mainlog') 'MonMar26_16_59_41_2018_reru' Why does python insist on removing n's from my strings? How I can properly remove .mainlog from my strings?
has answer: http://stackoverflow.com/a/49638776
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49638751

http://stackoverflow.com/comment/86379513
comment on: http://stackoverflow.com/q/49680972
type: Comment
type: QuestionComment
has text: Oh wait, I see that @umläute's answer has the correct magic - `make build_all`
score: 0

http://stackoverflow.com/a/49670942
upvote count: 1
score: 1
has body: First, filter out the falsy (empty) elements, then join the elements of the remaining elements: &gt;&gt;&gt; l = [[], ['A'], ['B'], ['A', 'B']] &gt;&gt;&gt; list(map(''.join, filter(bool, l))) ['A', 'B', 'AB'] Equivalent list-comprehensiony way: &gt;&gt;&gt; l = [[], ['A'], ['B'], ['A', 'B']] &gt;&gt;&gt; [''.join(e) for e in l if e] ['A', 'B', 'AB'] To do this five times, do it five times: start = ["A", "B"] for _ in range(5): start = [''.join(e) for e in powerset(start) if e]
has comment: http://stackoverflow.com/comment/86352232
has comment: http://stackoverflow.com/comment/86353186
type: Answer
has comment: http://stackoverflow.com/comment/86354262
downvote count: 0
answers question: http://stackoverflow.com/q/49670868

http://stackoverflow.com/q/49677568
has comment: http://stackoverflow.com/comment/86366523
tagged with: nan
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/76596935
tagged with: time-series
accepted answer: http://stackoverflow.com/a/49677695
has answer: http://stackoverflow.com/a/76596935
has answer: http://stackoverflow.com/a/49677695
tagged with: python
upvote count: 6
score: 6
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has body: For a time series sales forecasting task I want to create a feature that represents the average sales over the last 3 days. I have a problem when I want to predict the sales for days in the future, since these data points do not have sales data (NaN values). Pandas offers rolling_mean(), but that function results in a NaN ouput when any data point in the window is NaN. My data: Date Sales 02-01-2013 100.0 03-01-2013 200.0 04-01-2013 300.0 05-01-2013 200.0 06-01-2013 NaN Result after using pd.rolling_mean() with window of 2: Date Rolling_Sales 02-01-2013 NaN 03-01-2013 150.0 04-01-2013 250.0 05-01-2013 250.0 06-01-2013 NaN Desired result: Date Rolling_Sales 02-01-2013 NaN 03-01-2013 150.0 04-01-2013 250.0 05-01-2013 250.0 06-01-2013 200.0 So in case the a NaN is included, I want to ignore it and take the average of all the other data points in the window.
downvote count: 0
has title: How to ignore NaN in rolling average calculation in Python

http://stackoverflow.com/q/49664780
type: Question
score: 0
answer count: 0
tagged with: pyqt
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86339416
has comment: http://stackoverflow.com/comment/86339440
has title: Wrong argument type, PySide
has body: I am working from a book, learning python with raspberry pi and I'm a bit stumped on this because I receive this type error. My IDE is spitting this message out below and I am unsure if it's a constructor type issue control_window = TurtleControl(babbage) TypeError: 'PySide.QtGui.QWidget' called with wrong argument types: PySide.QtGui.QWidget(Turtle) Supported signatures: PySide.QtGui.QWidget(PySide.QtGui.QWidget = None, PySide.QtCore.Qt.WindowFlags = 0) import turtle import sys from PySide.QtCore import * from PySide.QtGui import * class TurtleControl (QWidget): def __init_(self, turtle): super(TurtleControl, self) .__init__() self.turtle = turtle self.left_btn = QPushButton("Left", self) self.right_btn = QPushButton("Right", self) self.move_btn = QPushButton("Move", self) self.distance_spin = QSpinBox() self.controlsLayout = QGridLayout() self.controlsLayout.addWidget(self.left_btn, 0, 0) self.controlsLayout.addWidget(self.right_btn, 0, 1) self.controlsLayout.addWidget(self.distance_spin,1, 0) self.controlsLayout.addWidget(self.move_btn,1, 1) self.setLayout(self.controlsLayout) self.distance_spin.setRange(0, 100) self.distance_spin.setSingleStep(5) self.distance_spin.setValue(20) self.move_btn.clicked.connect(self.move_turtle) self.move_btn.clicked.connect(self.move_turtle_right) self.move_btn.clicked.connect(self.move_turtle_left) # set up turtle window = turtle.Screen() babbage = turtle.Turtle() # Create a QT application app = QApplication(sys.argv) control_window = TurtleControl(babbage) control_window.show() # Enter QT application main loop app.exec_() sys.exit()
tagged with: pyside
tagged with: python
has comment: http://stackoverflow.com/comment/86339459
has comment: http://stackoverflow.com/comment/86339333

http://stackoverflow.com/comment/86359223
has text: sorry, @tobias_k I did not understand your suggestion until running.t spelled it out
comment on: http://stackoverflow.com/q/49674084
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49712339
has body: Use zip to iterate over both lists at the same time and enumerate to get the indices during iteration, and write a list comprehension that filters out the indices where the list values don't match: &gt;&gt;&gt; [i for i, (x, y) in enumerate(zip(a, b)) if x != y] [4, 8]
has comment: http://stackoverflow.com/comment/86438347
has comment: http://stackoverflow.com/comment/86438327
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86438694
has comment: http://stackoverflow.com/comment/86438666
answers question: http://stackoverflow.com/q/49712308
type: Answer

http://stackoverflow.com/comment/86478784
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49732469
has text: Are you by any chance using OpenCV to load your images ?

http://stackoverflow.com/comment/86330351
has text: What is the error message that is being displayed?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49660379
type: Comment

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/49644992
tags question: http://stackoverflow.com/q/49623051
tags question: http://stackoverflow.com/q/49685677
tags question: http://stackoverflow.com/q/49701323
tags question: http://stackoverflow.com/q/49722754
tags question: http://stackoverflow.com/q/49666015
type: Tag
tags question: http://stackoverflow.com/q/49716523
tag name: pdf
tags question: http://stackoverflow.com/q/49647703

http://stackoverflow.com/q/49657500
has body: I'm trying to make a program that will work as an "infomercial" in a separate window. What i have are two integers (x and y) that both increase at the same time, in this case every 5 seconds. With the increasing values i need a timer displayed at the same time, that can show the elapsed time of how long the program has been running. I want to be albe to start and pause the program So far i have an infinite while loop running where the values are increased every 5 seconds with time.sleep(5). I have tried implementing a timer in the form of a time.time(), and get it to work with the increments. I have also added buttons but don't work. I'm using tkinter as gui obtion. How am i supposed to make it work? with threading? import time from tkinter import * import math usage = 0 yearly = 0 cubik = 0 price = 0 root = Tk() root.title("Usage of fluid") root.geometry("300x400") var = IntVar() var1 = IntVar() var2 = StringVar() var3 = StringVar() var4 = StringVar() def update_timeText(): current= time.strftime("%H:%M:%S") timeText.configure(text=current) root.after(1000, update_timeText) def start(): global state state = True def pause(): global state state = False def exist(): root.destroy() frame = LabelFrame(root, text="Liter", font=30) frame.pack(fill = "both", expand="yes") l = Label(frame, textvariable=var, font=20) l.pack(pady = 3) frame2 = LabelFrame(root, text="price from use", font=30) frame2.pack(fill = "both", expand= "yes") l2 = Label(frame2, textvariable=var1, font=16) l2.pack(side = LEFT) l3 = Label(frame2, text="dollars", font=16) l3.pack(side=LEFT) frame3 = LabelFrame(root, text="yearly", font=30) frame3.pack(fill = "both", expand="yes") m3 = Label(frame3, textvariable=var2, font=16, wraplength=0) m3.pack(side=TOP) l4 = Label(frame3, text="Liter", font=16) l4.pack(side=TOP) l5 = Label(frame3, text="m3", font=16) l5.pack(side=BOTTOM, fill="both") m4 = Label(frame3, textvariable=var3, font=16, wraplength=0) m4.pack(side=BOTTOM) frame4 = LabelFrame(root, text='runt…
has comment: http://stackoverflow.com/comment/86324083
has comment: http://stackoverflow.com/comment/86329021
type: Question
has comment: http://stackoverflow.com/comment/86324887
tagged with: python
has comment: http://stackoverflow.com/comment/86328987
has comment: http://stackoverflow.com/comment/86324079
has title: Increasing integers at specific time with elapsed time
score: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86346577
has text: Have you tried any methods to get it ? If yes, please include those here
type: Comment
comment on: http://stackoverflow.com/q/49668147
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89973151
score: 0
comment on: http://stackoverflow.com/q/49615401
type: Comment
has text: Please post some code: I am fairly sure there is something wrong in your code (looks like you are using stateful RNNs or something like that) that is causing wrong evaluation
type: QuestionComment

http://stackoverflow.com/q/49695072
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49695124
has answer: http://stackoverflow.com/a/49695124
tagged with: python
favorite count: 0
type: Question
answer count: 2
score: 2
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49695141
has title: Preserving type (int or float) of entry when extracting rows
has body: I have a dataframe that I append several rows to containing elements of different type (either float or integer): df = pd.DataFrame() df = df.append( pd.DataFrame({'i': [0], 'j': [0.3]}), ignore_index=True) df = df.append( pd.DataFrame({'i': [1], 'j': [0.6]}), ignore_index=True) df = df.append( pd.DataFrame({'i': [9], 'j': [0.9]}), ignore_index=True) Now, I want to extract the row that contains the smallest value of, say, i: df.iloc[df['i'].argmin()] This gives me i 0.0 j 0.3 Name: 0, dtype: float64 where i has now been converted to a float. This is very undesirable for me ad I would like for it to stay an integer. Is there a way to perform the iloc such that the type is unchanged? Or a way to define df initially such that it respects the type of each column? Note that I would prefer a solution that does not assume I know in advance which columns will be interger and which will be float. All I know is that columns will exist of those two types. EDIT: Say I now want to convert the result to a dictionary: df = pd.DataFrame() df = df.append( pd.DataFrame({'i': [0], 'j': [0.3]}), ignore_index=True) df = df.append( pd.DataFrame({'i': [0], 'j': [0.3]}), ignore_index=True) df = df.iloc[df['i'].idxmin()].astype(object) df.astype(object).to_dict() This gives me {'i': 0.0, 'j': 0.3}. The form of the dictionary is as desired, however, the integer has now turned into a float. Is it possible to preserve the int-format?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49695141

http://stackoverflow.com/comment/86284548
type: AnswerComment
has text: I'm actaully just running everything on a very secure local network with no internet connection. So this idea might be very difficult to accomplish, but i'll look into it.
type: Comment
comment on: http://stackoverflow.com/a/49638153
score: 0

http://stackoverflow.com/a/49653854
has comment: http://stackoverflow.com/comment/86317145
has body: In your project directory, you should have a .elasticbeanstalk folder, you must have another one .ebextensions. If you don't have it, add it. Then you must create the files to run some stuff on the instances that EBT will fire for you. For example, add a file like 10_packages.config the number is important because will keep the order. The file content is something like that: # 10_packages.config # Add the packages needed to run the application and some other tools packages: yum: git: [] postgresql94-devel: [] gcc: [] gcc-c++: [] make: [] libffi-devel: [] libmemcached-devel: [] vim-enhanced: [] Then you need to install django and all the packages you need for your app. Create a file called 20_pip_requirements.config # 20_pip_requirements.config # Update pip in the venv commands: 01_upgrade_pip_for_venv: command: "sudo /opt/python/run/venv/bin/pip install --upgrade pip" Eventually, you must migrate the database, this must be run just one time. Let's fire another file 30_migrate.config # 30_migrate.config container_commands: 01_migrate_database: command: "./manage.py migrate" leader_only: true This is just an example, but give you an idea about what you have to do. Read the docs for more info.
score: 0
answers question: http://stackoverflow.com/q/49652460
has comment: http://stackoverflow.com/comment/86330777
has comment: http://stackoverflow.com/comment/86359522
has comment: http://stackoverflow.com/comment/86317687
has comment: http://stackoverflow.com/comment/86316961
has comment: http://stackoverflow.com/comment/86330722
has comment: http://stackoverflow.com/comment/86316704
type: Answer

http://stackoverflow.com/comment/86285468
comment on: http://stackoverflow.com/a/49635422
has text: Yeah, the links both have some psuedocode and explanations that should get you started. Sorry about the bluntness, some people on SO expect others to write their code for them, and I wasn’t sure if you were one of those people.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49660174
tagged with: matplotlib
has answer: http://stackoverflow.com/a/54251127
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49662571
tagged with: python
has answer: http://stackoverflow.com/a/49662391
possible better answer: http://stackoverflow.com/a/49662391
linked to: http://stackoverflow.com/q/64106682
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 3
downvote count: 0
has body: I'm aware of this answer, Is it possible to control matplotlib marker orientation?, and the marker documentation, but is it possible to take an existing matplotlib marker symbol (nonregular polygon) and rotate it? Specifically, I would like to rotate the thin diamond symbol ("d") 90 degrees, such that its long axis is horizontal.
linked to: http://stackoverflow.com/q/23345565
has answer: http://stackoverflow.com/a/49662571
has title: Rotate existing matplotlib markers?

http://stackoverflow.com/comment/86298614
score: 1
type: Comment
type: QuestionComment
has text: I don't know what WifiRadar is for but there are no alternatives? Otherwise, you can copy [jethro recipe](http://cgit.openembedded.org/openembedded-core/tree/meta/recipes-devtools/python/python-pygtk_2.24.0.bb?h=jethro) into your layer and adapt it to work on rocko. Or, you can also port wifi-radar to up-to-date GTK3.
comment on: http://stackoverflow.com/q/49643443

http://stackoverflow.com/q/49720109
has answer: http://stackoverflow.com/a/49720202
possible better answer: http://stackoverflow.com/a/49720202
tagged with: python
favorite count: 0
type: Question
answer count: 2
tagged with: deep-learning
tagged with: neural-network
upvote count: 1
tagged with: machine-learning
has body: In tensorflow we used variables in two ways: a = tf.constant(12) b = tf.constant(10) #NOW SAY I WANT TO ADD THESE TWO #1st method ans = tf.Variable(tf.add(a, b)) # Initialize the variable init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) print(sess.run(ans)) #2nd method ans1 = tf.add(a, b) sess = tf.Session() sess.run(ans1) So as we all know that for using 1st method we have to initialize the variable or it will throw an error of "uninitialised variable". But their is no need to do initialization for 2nd method. So my question is why are we using 1st method or tf.Variable in tensorflow? Is their any specific use of this?
has title: Why we use tf.Variable in tensorflow if we can directly use a variable without initialisation?
downvote count: 1
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49720236
score: 0
accepted answer: http://stackoverflow.com/a/49720236

http://stackoverflow.com/q/49702471
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49702597
has answer: http://stackoverflow.com/a/49702597
has title: Can warnings warn without returning out of a function?
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: Is there anyway for the warnings.warn() function to be caught be a caller while still executing the rest of the code after the warn() call? The problem I am having is that function b will warnings.warn() if something happens, and then I want the rest of that function to finish its job and return a list of what it actually did. If a warning was thrown, I want to catch it, email it to someone, and continue on when I call that function from another module, but that isn't happening. here is what it looks like in code: import warnings def warn_function(arg_1): if arg_1 &gt; 10: warnings.warn("Your argument was greater than 10.") return arg_1 - 5 with warnings.catch_warnings(): warnings.filterwarnings("error") try: answer = warn_function(20) except Warning: print("A warning was thrown") finally: print(answer)
score: 1

http://stackoverflow.com/comment/86479817
comment on: http://stackoverflow.com/q/49730763
type: Comment
type: QuestionComment
has text: Well it's like 30 records from few millions that I want to copy. Already managed via `expunge_all()`
score: 0

http://stackoverflow.com/q/49741823
has title: Is there a way to reincarnate Python process from previous execution (stack and code)?
type: Question
has body: I quick-sort a 1GB file using Python. The problem is that this sort process is interrupted in predefined intervals of 120 sec (Python terminates). So every time I'm reaching 120 sec limit I pickle that half-sorted data and let Python exit. On next invocation I un-pickle previous dump and restart quicksort from the beginning. Question: Is there a way to dump memory and code in such a way that upon next Python invocation that memory/code dump can be loaded and quick-sort just starts where it left off without the need to restart the sort from the beginning of the pickled file?
score: 0
has comment: http://stackoverflow.com/comment/86498230
has comment: http://stackoverflow.com/comment/86498268
tagged with: python
has comment: http://stackoverflow.com/comment/86498281
has comment: http://stackoverflow.com/comment/86498267
answer count: 0
has comment: http://stackoverflow.com/comment/86498466
type: UnansweredQuestion

http://stackoverflow.com/comment/86518238
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49751339
has text: That web has a "Spanish" server so since every single country has "name" as a class which is annoying, I thought about searching inside the web instead of searching with the tags since all of them are exactly the same and the program won't know which one to get What I wanted to get was the "status" - if it is operational, so that is why I was trying to start by getting the server

http://stackoverflow.com/comment/86216591
has text: Well in that case yes. Sometimes with pandas, you have an `inplace` parameter that let you modify the current object but not for `append` apparently.
comment on: http://stackoverflow.com/a/49604304
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49650962
has comment: http://stackoverflow.com/comment/86310544
has comment: http://stackoverflow.com/comment/86310084
has comment: http://stackoverflow.com/comment/86310712
has comment: http://stackoverflow.com/comment/86331235
has comment: http://stackoverflow.com/comment/86310763
has body: I'm not sure why I'm having easier time string searching in program I wrote in python faster than a program I wrote in C++. Is there a trick I'm missing? Generating Use Case This is for a single line use case, however in the real use case I care about multiple lines. #include "tchar.h" #include "stdio.h" #include "stdlib.h" #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;ctime&gt; using namespace std; void main(void){ ofstream testfile; unsigned int line_idx = 0; testfile.open("testfile.txt"); for(line_idx = 0; line_idx &lt; 50000u; line_idx++) { if(line_idx != 43268u ) { testfile &lt;&lt; line_idx &lt;&lt; " dontcare" &lt;&lt; std::endl; } else { testfile &lt;&lt; line_idx &lt;&lt; " care" &lt;&lt; std::endl; } } testfile.close(); } The regular expression Using regular expression ^(\d*)\s(care)$ The C++ Program takes 13.954 seconds #include "tchar.h" #include "stdio.h" #include "stdlib.h" #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;ctime&gt; using namespace std; void main(void){ double duration; std::clock_t start; ifstream testfile("testfile.txt", ios_base::in); unsigned int line_idx = 0; bool found = false; string line; regex ptrn("^(\\d*)\\s(care)$"); start = std::clock(); /* Debug time */ while (getline(testfile, line)) { std::smatch matches; if(regex_search(line, matches, ptrn)) { found = true; } } testfile.close(); duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout &lt;&lt; "Found? " &lt;&lt; (found ? "yes" : "no") &lt;&lt; std::endl; std::cout &lt;&lt; " Total time: " &lt;&lt; duration &lt;&lt; std::endl; } Python Program takes 0.02200 seconds import sys, os # to navigate and open files import re # to search file import time # to benchmark ptrn = re.compile(r'^(\d*)\s(care)$', re.MULTILINE) start = time.time() with open('testfile.txt','r') as testfile: filetext = testfile.read() matches = re.findall(ptrn,…
has comment: http://stackoverflow.com/comment/86324169
has comment: http://stackoverflow.com/comment/86310425
type: AnsweredQuestion
score: 2
tagged with: string-search
has comment: http://stackoverflow.com/comment/86310127
linked to: http://stackoverflow.com/q/14205096
upvote count: 5
has comment: http://stackoverflow.com/comment/86310042
downvote count: 3
has comment: http://stackoverflow.com/comment/86310807
tagged with: python
has title: Can C++ program string search as fast as and/or faster than python?
tagged with: regex
accepted answer: http://stackoverflow.com/a/49662237
favorite count: 0
has comment: http://stackoverflow.com/comment/86310772
type: Question
tagged with: c++
has answer: http://stackoverflow.com/a/49662237
linked to: http://stackoverflow.com/q/2602013
has comment: http://stackoverflow.com/comment/86310059
has comment: http://stackoverflow.com/comment/86310185
has comment: http://stackoverflow.com/comment/86311660
tagged with: benchmarking
has comment: http://stackoverflow.com/comment/86311491
has comment: http://stackoverflow.com/comment/86310014
answer count: 1
has comment: http://stackoverflow.com/comment/86316443
linked to: http://stackoverflow.com/q/1269795

http://stackoverflow.com/comment/86380581
comment on: http://stackoverflow.com/q/49684590
type: Comment
type: QuestionComment
score: 1
has text: What is the data you have access to? Do you have the coordinates of all these parks? Can you show us a sample of the data please.

http://stackoverflow.com/q/49688826
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: python
has title: Passing variables between different classes and definition in tkinter
score: -2
linked to: http://stackoverflow.com/q/33646605
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have a problem with my code. I am unable to pass a variable to another class once a submit button is pressed in my tkinter frame. I have followed the advice from a post already (How to access variables from different classes in tkinter?), which has helped but I still have issues. From where to where I need these variables is commented on the code below: import tkinter as tk from tkinter import StringVar LARGE_FONT = ("Verdana", 12) class Club(tk.Tk): def get_page(self, page_class): return self.frames[page_class] def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.shared_data = { "username": tk.StringVar(), "password": tk.StringVar(), } self.frames = {} for F in (Terminal, newUser, newUserSubmitButton, delUser): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(Terminal) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class Terminal(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Welcome to the club terminal. Click the options below", font=LARGE_FONT) label.grid(columnspan=3) button = tk.Button(self, text="Visit new User", command=lambda: controller.show_frame(newUser)) button.grid(row=1, column=0) button2 = tk.Button(self, text="Visit del User", command=lambda: controller.show_frame(delUser)) button2.grid(row=1, column=1) class newUser(tk.Frame): def __init__(self, parent, controller): def submitButton(): username = self.controller.shared_data["username"].get() print(username) controller.show_frame(newUserSubmitButton) ##username variable from here to... tk.Frame.__init__(self, parent) welcomelabel = tk.Label(self, text="Add New User/s", font=LARGE_FONT) welcomelabel.grid(columnspan=2, sticky="ew") userNameLabel = tk.Label(self, tex…
has comment: http://stackoverflow.com/comment/86396679
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86391559
has answer: http://stackoverflow.com/a/49690928

http://stackoverflow.com/a/49701585
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: It depends what you want to do with it, but you can use pd.to_numeric() with errors = 'coerce'. For example: df = pd.DataFrame({'Spd of Max Gust (km/h)':[75, 80.2, 12, '&lt;32']}) Spd of Max Gust (km/h) 0 75 1 80.2 2 12 3 &lt;32 &gt;&gt;&gt; pd.to_numeric(df['Spd of Max Gust (km/h)'], errors='coerce') 0 75.0 1 80.2 2 12.0 3 NaN So to apply your filter: df[(pd.to_numeric(df['Spd of Max Gust (km/h)'], errors='coerce').astype(float) &gt;= 50.0)] Gives you this: Spd of Max Gust (km/h) 0 75 1 80.2
answers question: http://stackoverflow.com/q/49701468

http://stackoverflow.com/comment/86442022
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49713530
score: 0
has text: If all you care about are the parameter estimates, then just using scipy is enough. If you want standard errors and inference, then writing a few extra lines to make a subclass with statsmodels is still a lot less than handcoding everything with scipy.

http://stackoverflow.com/comment/86298935
has text: Updated the question please check!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49645323

http://stackoverflow.com/q/49704142
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49704750
tagged with: django-rest-framework
linked to: http://stackoverflow.com/q/36414804
favorite count: 0
type: Question
has body: I am trying to make a rest application to communicate with my android application but it is stopping me the validation of the password. I use the User model by default of django and I would like to try to make the server validate the password I found some other interesting answers but the truth is that django is not my strong point (my specialty is android) and they do not explain well how to implement them in my view restapp/views.py class postRegister(APIView): def post(self,request): data = JSONParser().parse(request) cencripM=CriptoMovil(KEY_ENC_M) data['username'] = cencripM.decrypt(data['username']) data['email'] = cencripM.decrypt(data['email']) data['password'] = cencripM.decrypt(data['password']) serializer = RegistSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({"message":"save","state":"1"}) return Response({"message":serializer.errors,"state":"2"}) maybe it helps some of the articles that I found but I did not understand how to implement them in the view (I repeat my specialty is android) many options but I did not know how to implement interesting but I did not understand how to implement the view
has comment: http://stackoverflow.com/comment/86431326
has comment: http://stackoverflow.com/comment/86422627
has comment: http://stackoverflow.com/comment/86422679
accepted answer: http://stackoverflow.com/a/49704750
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86422289
has title: How to validate the password django rest
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/86282530
has text: @J.Taylor: Whoever's calling `Queue.join` needs to know.
comment on: http://stackoverflow.com/a/49637357
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/86219019
score: 0
type: AnswerComment
has text: No worries, it's not like it was creating a confusion. It's the same principle no matter what the dir name would be.
comment on: http://stackoverflow.com/a/49601624
type: Comment

http://stackoverflow.com/q/49685065
has title: How to implement app communication port
tagged with: python
has body: Saving the code below as application.py allows me to run a process that when started shows a simple QDialog with a QLabel: python application.py While the process is running and dialog shown I would like to change the default title "somewhere over the rainbow" to something else. How to achieve it? from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * app = QApplication([]) class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setLayout(QVBoxLayout()) self.label = QLabel('somewhere over the rainbow') self.layout().addWidget(self.label) self.show() dialog = Dialog() app.exec_() edited: Below is an example of QLabel's text set to a new string value "01011001001001110100100110":
has comment: http://stackoverflow.com/comment/86381979
has comment: http://stackoverflow.com/comment/86381945
type: AnsweredQuestion
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/86384378
has comment: http://stackoverflow.com/comment/86381583
answer count: 1
has comment: http://stackoverflow.com/comment/86381879
accepted answer: http://stackoverflow.com/a/49724660
has comment: http://stackoverflow.com/comment/86384172
type: Question
tagged with: qt
has comment: http://stackoverflow.com/comment/86381804
has answer: http://stackoverflow.com/a/49724660

http://stackoverflow.com/q/49647703
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86305321
downvote count: 2
upvote count: 1
answer count: 1
tagged with: file
has body: I am trying to read numerical data from a table as a string in python. (I have tried many different ways to convert the table to CSV, Excel and so on but nothing seems to work perfectly. Therefore I wanna try the string approach) Each line looks basically like this: "ebit 34 894 38 445 28 013 26 356 12 387 -8 680 -2 760 838" Here we have 8 columns. The last digits to the right: 838 belongs to one column, -2 760 belongs to one column, 12 387 belongs to one column, and so on. Does anyone have a smart approach on how to know which numbers belong to which column?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49648321
accepted answer: http://stackoverflow.com/a/49648321
has title: Reading tabular data from pdf file
has comment: http://stackoverflow.com/comment/86303925
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86304095
has comment: http://stackoverflow.com/comment/86304020
has comment: http://stackoverflow.com/comment/86303660

http://stackoverflow.com/q/49731420
tagged with: swi-prolog
has comment: http://stackoverflow.com/comment/86480569
has comment: http://stackoverflow.com/comment/86479619
type: UnansweredQuestion
score: 1
answer count: 1
has title: error about libpl (shared) when using pyswip (mac)
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86479425
has comment: http://stackoverflow.com/comment/86501580
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86484877
has answer: http://stackoverflow.com/a/56101194
has comment: http://stackoverflow.com/comment/86479722
has comment: http://stackoverflow.com/comment/86479833
has comment: http://stackoverflow.com/comment/86479983
tagged with: python
has body: I got the error libpl (shared) not found.(see below for details) when using pyswip (mac). I know there is a question about it posted several years ago, but it is not solved. I installed swiprolog(>7.0.0) with homebrew and run 2to3 for pyswip. Help me. PS: I am learning logic programming, I need it. libpl (shared) not found. Possible reasons: 1) SWI-Prolog not installed as a shared library. Install SWI-Prolog (5.6.34 works just fine) An exception has occurred, use %tb to see the full traceback. The error is thrown here. # UNIX-like try: _lib = CDLL("libpl.dylib") except IndexError: # let's try the cwd _lib = CDLL("./libpl.so")

http://stackoverflow.com/comment/86389865
has text: @IvanKalchev I think that was a bad decision in the case of `Event`, `Condition`, etc., which were otherwise written to closely model their `threading` counterparts, but for what it's worth, the decision was intentional, it's not a mere oversight. Someone sufficiently interested in the matter should argue on the bug tracker that the _timeout_ arguments be implemented for `Event.wait` and others that have them.
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/49632779
type: Comment

http://stackoverflow.com/a/58651634
has body: You must obtain a Kerberos ticket for this to work. Your example doesn't specify whether your Linux system is set up to authenticate via Kerberos or whether you have previously obtained a Kerberos ticket before your code hits your connection string. If your Linux system is set up to authenticate via Kerberos, then as a proof of concept you can obtain a Kerberos ticket using kinit from the command line. Here's what works for me in python3 running in Ubuntu on Windows via the WSL. The python code: #!/usr/bin/env python # minimal example using Kerberos auth import sys import re import pyodbc driver='{ODBC Driver 17 for SQL Server}' server = sys.argv[1] database = sys.argv[2] # trusted_connection uses kerberos ticket and ignores UID and PASSWORD in connection string # https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/using-integrated-authentication?view=sql-server-ver15 try: cnxn = pyodbc.connect(driver=driver, server=server, database=database, trusted_connection='yes') cursor = cnxn.cursor() except pyodbc.Error as ex: msg = ex.args[1] if re.search('No Kerberos', msg): print('You must login using kinit before using this script.') exit(1) else: raise # Sample select query cursor.execute("SELECT @@version;") row = cursor.fetchone() while row: print(row[0]) row = cursor.fetchone() print('success') This tells you if you don't have a ticket. Since it uses a ticket you don't have to specify a user or password in the script. It will ignore both. Now we run it: user@localhost:~# kdestroy # make sure there are no active tickets kdestroy: No credentials cache found while destroying cache user@localhost:~# python pyodbc_sql_server_test.py tcp:dbserver.example.com mydatabase You must login using kinit before using this script. user@localhost:~# kinit Password for user@DOMAIN.LOCAL: user@localhost:~# python pyodbc_sql_server_test.py tcp:dbserver.example.com mydatabase Microsoft SQL Server 2016 (SP2-GDR) (KB4505220) - 13.0.5101.9 (X64) Jun 15 2019 23:15:58 Copyright (c) Mi…
has comment: http://stackoverflow.com/comment/111522931
downvote count: 0
upvote count: 17
has comment: http://stackoverflow.com/comment/128906566
has comment: http://stackoverflow.com/comment/111523956
type: Answer
answers question: http://stackoverflow.com/q/49695990
score: 17

http://stackoverflow.com/q/49624967
tagged with: random
accepted answer: http://stackoverflow.com/a/49625104
upvote count: 0
downvote count: 2
has title: Generating duplicates with weights (python)
has answer: http://stackoverflow.com/a/49625104
duplicate of: http://stackoverflow.com/q/3679694
has answer: http://stackoverflow.com/a/49625088
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3679694
score: -2
has comment: http://stackoverflow.com/comment/86256947
has body: I have the following list: priority=['Emergency','High','Normal','Low'] I need to generate a list of 15000 values in the list above, with frequency of each of them being 10%,20%,30%,40%. Can somebody show me how to do it?
possible better answer: http://stackoverflow.com/a/49625088
tagged with: duplicates
tagged with: python
type: Question
tagged with: list
answer count: 2

http://stackoverflow.com/a/49628258
has comment: http://stackoverflow.com/comment/86263422
score: 0
has body: Change user_setup() to User.user_setup() in main(), since user_setup() is a method of the User class, python won't find it as a normal function. You would also want to change login() to User.login() However, classes are rather used in another way, for example a new user would more often be made by combining your user_setup() and __init__() and then creating a user this way: user1 = User(...)
has comment: http://stackoverflow.com/comment/86263500
answers question: http://stackoverflow.com/q/49628193
type: Answer

http://stackoverflow.com/comment/86415758
score: 0
has text: If the probability of each number isn't 5% regardless of what came before, then they're not random. And Python uses a good random number generator.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49691972

http://stackoverflow.com/q/49672750
upvote count: 1
accepted answer: http://stackoverflow.com/a/49672966
answer count: 1
has comment: http://stackoverflow.com/comment/86388206
has body: I have a dataframe with a few columns Client ID, Prd No, Prd Weight. I made Client ID an index column as part of the process of transforming the data from wide to long using the wide_to_long method. When I apply the sort_values method to the Prd No column, the arrangement is weird. It arranges it as 1, 10, 100, 101, 2, 20, 200....etc. How I want the data arranged is 1, 2, 3, 4... I've tried all sorts of things, including explicitly changing the Prd No to an integer type using the astype() method, but no luck. What could I be doing wrong? Is it a setting or version of Pandas I am using? Help, anyone? import pandas as pd df = pd.read_csv("new_export.csv") df1 = pd.wide_to_long(df,['diameterbh', 'base_diam_1', 'length_1', 'top_diam_1', 'base_diam_2', 'length_2', 'top_diam_2', 'base_diam_3', 'length_3', 'top_diam_3', 'x_product'], i='uniqueID', j='Tree Number', sep='_') df3 = df2[df2['diameterbh'].notnull()].fillna(value=0)sort_values(by="Tree Number")
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: sort_values arranging values wrong
has answer: http://stackoverflow.com/a/49672966
has comment: http://stackoverflow.com/comment/86356201
tagged with: python
type: Question

http://stackoverflow.com/q/49688481
has answer: http://stackoverflow.com/a/49735597
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/86413178
upvote count: 6
has comment: http://stackoverflow.com/comment/87572975
has title: Using context managers for recovering from celery's SoftTimeLimitExceeded
answer count: 1
has comment: http://stackoverflow.com/comment/86483529
downvote count: 0
tagged with: celery
favorite count: 0
type: Question
has body: I am trying to set a maximum run time for my celery jobs. I am currently recovering from exceptions with a context manager. I ended up with code very similar to this snippet: from celery.exceptions import SoftTimeLimitExceeded class Manager: def __enter__(self): return self def __exit__(self, error_type, error, tb): if error_type == SoftTimeLimitExceeded: logger.info('job killed.') # swallow the exception return True @task def do_foo(): with Manager(): run_task1() run_task2() run_task3() What I expected: If do_foo times out in run_task1, the logger logs, the SoftTimeLimitExceeded exception is swallowed, the body of the manager is skipped, the job ends without running run_task2 and run_task3. What I observe: do_foo times out in run_task1, SoftTimeLimitExceeded is raised, the logger logs, the SoftTimeLimitExceeded exception is swallowed but run_task2 and run_task3 are running nevertheless. I am looking for an answer to following two questions: Why is run_task2 still executed when SoftTimeLimitExceeded is raised in run_task1 in this setting? Is there an easy way to transform my code so that it can performs as expected?
type: UnansweredQuestion

http://stackoverflow.com/q/49755568
has title: I've converted Python code to .exe and I get error when I execute it
type: UnansweredQuestion
tagged with: cx-freeze
tagged with: opencv
tagged with: pyinstaller
tagged with: python
linked to: http://stackoverflow.com/q/27284050
has body: I've used Pyinstaller and cx_freeze to convert a Python code to .exe and with both of them, I get an error when I run the executable. It's a CLI OpenCV program and works properly from source code. I'm using Windows 10 and the version of Python is 3.6.4. I've tried this in Linux and there it works. Output: 1. Generate Dataset. (No data has been generated yet.) 2. Exit 3. Enter Camera Address Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\imi_4\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\imi_4\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\imi_4\AppData\Local\Programs\Python\Python36\lib\site-packages\keyboard\__init__.py", line 296, in listen _os_keyboard.listen(self.direct_callback) File "C:\Users\imi_4\AppData\Local\Programs\Python\Python36\lib\site-packages\keyboard\_winkeyboard.py", line 562, in listen prepare_intercept(callback) File "C:\Users\imi_4\AppData\Local\Programs\Python\Python36\lib\site-packages\keyboard\_winkeyboard.py", line 555, in prepare_intercept keyboard_hook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_callback, GetModuleHandleW(NULL), NULL) ctypes.ArgumentError: argument 3: &lt;class 'OverflowError'&gt;: int too long to convert
has comment: http://stackoverflow.com/comment/86526283
has comment: http://stackoverflow.com/comment/86533193
tagged with: ctypes
type: Question
linked to: http://stackoverflow.com/q/48788549
score: 0
has comment: http://stackoverflow.com/comment/86526082
answer count: 0

pytest
tags question: http://stackoverflow.com/q/49691959
tags question: http://stackoverflow.com/q/49617551
tag name: pytest
tags question: http://stackoverflow.com/q/49605830
tags question: http://stackoverflow.com/q/49736577
tags question: http://stackoverflow.com/q/49670686
tags question: http://stackoverflow.com/q/49659306
tags question: http://stackoverflow.com/q/49749695
tags question: http://stackoverflow.com/q/49600379
tags question: http://stackoverflow.com/q/49610498
tags question: http://stackoverflow.com/q/49738081
tags question: http://stackoverflow.com/q/49687072
tags question: http://stackoverflow.com/q/49656808
tags question: http://stackoverflow.com/q/49723266
tags question: http://stackoverflow.com/q/49699477
tags question: http://stackoverflow.com/q/49677311
type: Tag

http://stackoverflow.com/a/49655134
has comment: http://stackoverflow.com/comment/86319447
has comment: http://stackoverflow.com/comment/86319137
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86319173
accepted answer of: http://stackoverflow.com/q/49654772
has comment: http://stackoverflow.com/comment/86335619
downvote count: 0
has comment: http://stackoverflow.com/comment/86329413
has body: Django templates let you check 'where you are' in the for loop, so all you have to do is open and close your rows appropriately: {% for user in user_list %} {% if forloop.counter0|divisibleby:"3" %} {% endif %} {{user.id}} {% if forloop.last or forloop.counter|divisibleby:"3" %} {% endif %} {% endfor %}
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49654772
has comment: http://stackoverflow.com/comment/86319242
has comment: http://stackoverflow.com/comment/86329661
type: Answer
has comment: http://stackoverflow.com/comment/86319160
has comment: http://stackoverflow.com/comment/86328913

http://stackoverflow.com/a/49724148
downvote count: 0
has comment: http://stackoverflow.com/comment/109809254
has comment: http://stackoverflow.com/comment/86462253
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86462441
type: Answer
accepted answer of: http://stackoverflow.com/q/49724085
has comment: http://stackoverflow.com/comment/86462372
has body: PEP-484 has been updated since the original answer was written. In modern python-type-checking, it is preferred to make the Optional explicit. To quote the PEP: A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code: def handle_employee(e: Employee = None): ... This would have been treated as equivalent to: def handle_employee(e: Optional[Employee] = None) -&gt; None: ... This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.
score: 19
upvote count: 19
answers question: http://stackoverflow.com/q/49724085

indexing
tags question: http://stackoverflow.com/q/49742418
tags question: http://stackoverflow.com/q/49734812
tags question: http://stackoverflow.com/q/49716504
tags question: http://stackoverflow.com/q/49729175
tags question: http://stackoverflow.com/q/49748748
tags question: http://stackoverflow.com/q/49713951
tag name: indexing
tags question: http://stackoverflow.com/q/49697844
tags question: http://stackoverflow.com/q/49643676
tags question: http://stackoverflow.com/q/49673859
tags question: http://stackoverflow.com/q/49678660
type: Tag
tags question: http://stackoverflow.com/q/49716841
tags question: http://stackoverflow.com/q/49713204
tags question: http://stackoverflow.com/q/49702766
tags question: http://stackoverflow.com/q/49619868
tags question: http://stackoverflow.com/q/49738053
tags question: http://stackoverflow.com/q/49722520
tags question: http://stackoverflow.com/q/49735683
tags question: http://stackoverflow.com/q/49704687
tags question: http://stackoverflow.com/q/49620130
tags question: http://stackoverflow.com/q/49653397
tags question: http://stackoverflow.com/q/49754041
tags question: http://stackoverflow.com/q/49608461

http://stackoverflow.com/comment/86395538
type: Comment
type: QuestionComment
has text: If you run your code, what happens? I'm looking at your code but can't figure out why that wouldn't work.
score: 0
comment on: http://stackoverflow.com/q/49691737

http://stackoverflow.com/q/49711706
type: UnansweredQuestion
upvote count: 1
has title: How to change CSV file into 2 lists
downvote count: 1
favorite count: 0
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86437185
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: midi
has comment: http://stackoverflow.com/comment/86437348
has body: I used this MIDI-CSV converter on a MIDI file and now I need to change the whole file into 2 lists so I can use them for my application. Basically, I need to take each pair of lines like this... 2, 960, Note_on_c, 0, 76, 71 2, 1200, Note_off_c, 0, 76, 0 2, 1200, Note_on_c, 0, 75, 38 2, 1440, Note_off_c, 0, 75, 0 and turn them into one item for each list. NoteList=[56, 55] NoteTypeList=['EthNote', 'EthNote'] If you're wondering why its 56 not 76 it's because I minus 20 to make the keyboard input 1-88 instead of 21-108 or whatever it is.
has comment: http://stackoverflow.com/comment/86436976
answer count: 0

http://stackoverflow.com/q/49638471
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86288917
tagged with: django
has comment: http://stackoverflow.com/comment/86285411
tagged with: python
has comment: http://stackoverflow.com/comment/86284618
has answer: http://stackoverflow.com/a/49640880
has title: Formatting date 2018-04-03T14:10:00-07:00 to any readable date/time in Python
has answer: http://stackoverflow.com/a/49640603
score: 0
answer count: 3
has body: 2018-04-03T14:10:00-07:00 is there a built in python method? Or something in Django? I am only used to working with javascript/node and I can't figure this out
tagged with: date
has comment: http://stackoverflow.com/comment/86284654
type: Question
linked to: http://stackoverflow.com/q/466345
has answer: http://stackoverflow.com/a/49642669

http://stackoverflow.com/q/49604549
downvote count: 2
has answer: http://stackoverflow.com/a/71044856
linked to: http://stackoverflow.com/q/538346
has body: Square Every Digit of a Number in Python? if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. write a code but this not working. def sq(num): words = num.split() # split the text for word in words: # for each word in the line: print(word**2) # print the word num = 9119 sq(num)
has comment: http://stackoverflow.com/comment/86216216
has comment: http://stackoverflow.com/comment/86216489
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/493386
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86216272
has answer: http://stackoverflow.com/a/74656705
accepted answer: http://stackoverflow.com/a/49604694
has answer: http://stackoverflow.com/a/67385940
has comment: http://stackoverflow.com/comment/86216263
has answer: http://stackoverflow.com/a/62336978
has title: Square Every Digit of a Number in Python?
tagged with: python
answer count: 6
possible better answer: http://stackoverflow.com/a/50968802
duplicate of: http://stackoverflow.com/q/1906717
has comment: http://stackoverflow.com/comment/86216641
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50968802
has comment: http://stackoverflow.com/comment/86216270
has answer: http://stackoverflow.com/a/49604694
score: 0
has comment: http://stackoverflow.com/comment/86216289
tagged with: numbers

http://stackoverflow.com/comment/86440322
score: 0
type: Comment
type: QuestionComment
has text: I included all the files, every section in that code is separated with asterisk saying which file it is
comment on: http://stackoverflow.com/q/49708302

http://stackoverflow.com/comment/86285030
has text: I'm using a jupyter notebook
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49638494

http://stackoverflow.com/q/49682311
type: UnansweredQuestion
tagged with: boto3
has body: I want to fetch all metadata for a bucket with a prefix via Boto. There are a few SO questions that imply this isn't possible via the AWS API. So, two questions: Is there a good reason this shouldn't be possible via the AWS API? Although I can't find one in docs, Is there a convenience method for this in Boto? I'm currently doing this using multithreading, but that seems like overkill, and I'd really rather avoid it if at all possible.
has title: How to get s3 metadata for all keys in a bucket via boto3
score: 2
upvote count: 2
downvote count: 0
tagged with: amazon-web-services
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49682459
type: Question
linked to: http://stackoverflow.com/q/47879347
tagged with: amazon-s3
tagged with: python

http://stackoverflow.com/comment/137870672
type: Comment
comment on: http://stackoverflow.com/a/49693363
has text: what was the docker command you used to run your container? Did you specify --network bridge in your case?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86459156
has text: That isnt how `del` works. `del` deletes *variables* not objects. IOW consider, `x = 42; y = []; y.append(x); del x; print(y)`
score: 4
type: Comment
comment on: http://stackoverflow.com/q/49722785
type: QuestionComment

http://stackoverflow.com/q/49684468
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49702076
upvote count: 4
score: 0
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/49702076
has answer: http://stackoverflow.com/a/50226115
has answer: http://stackoverflow.com/a/52042615
tagged with: machine-learning
has title: Mask R-CNN for object detection and segmentation [Train for a custom dataset]
favorite count: 0
has body: I'm doing a research on "Mask R-CNN for Object Detection and Segmentation". So I have read the original research paper which presents Mask R-CNN for object detection, and also I found few implementations of Mask R-CNN, here and here (by Facebook AI research team called detectron). But they all have used coco datasets for testing. But I'm quite a bit of confusing for training above implementations with custom data-set which has a large set of images and for each image there is a subset of masks images for marking the objects in the corresponding image. So I'm pleasure if anyone can post useful resources or code samples for this task. Note: My dataset has following structure, It consists with a large number of images and for each image, there are separate image files highlighting the object as a white patch in a black image. Here is an example image and it's masks: Image; Masks;
type: Question
accepted answer: http://stackoverflow.com/a/50226115
tagged with: semantic-segmentation
tagged with: python
tagged with: computer-vision
tagged with: object-detection

http://stackoverflow.com/q/49692183
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49692943
tagged with: import
favorite count: 0
has answer: http://stackoverflow.com/a/49692943
tagged with: python-3.x
has title: Package import failure in Python 3.5
accepted answer: http://stackoverflow.com/a/49692407
type: Question
has answer: http://stackoverflow.com/a/49692407
score: 5
upvote count: 5
tagged with: python
has body: I have the following folder structure: /main main.py /io __init__.py foo.py In Python 2.7 I would write the following in main.py: import io.foo or from io.foo import * wheareas in Python 3.5 I get an import error: Traceback (most recent call last): File "./main.py", line 6, in &lt;module&gt; import io.foo ImportError: No module named 'io.foo'; 'io' is not a package I couldn't find any help so far.

http://stackoverflow.com/q/49757409
has body: I have the following error when executing the following command pip3 install django-nvd3 Collecting django-nvd3 Using cached django-nvd3-0.9.7.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 "/private/var/folders/rs/30thcgbd2334t5kfx1n3fj5w0000gn/T/pip-build-g97vw973/django-nvd3/setup.py", line 7, in &lt;module&gt; readme = readme_file.read() File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 2070: ordinal not in range(128) ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/rs/30thcgbd2334t5kfx1n3fj5w0000gn/T/pip-build-g97vw973/django-nvd3/ Why is this happening?
tagged with: pip
has answer: http://stackoverflow.com/a/49757973
type: Question
possible better answer: http://stackoverflow.com/a/49757961
has title: Error installing django-nvd3
tagged with: python-nvd3
accepted answer: http://stackoverflow.com/a/49757973
has answer: http://stackoverflow.com/a/49757961
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/20101834
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/q/49658148
answer count: 1
has comment: http://stackoverflow.com/comment/86326025
type: Question
has comment: http://stackoverflow.com/comment/86325986
tagged with: reverse
has answer: http://stackoverflow.com/a/49658392
accepted answer: http://stackoverflow.com/a/49658392
has body: I was doing the reverse a linked list leetcode problem: Reverse a singly linked list. However my code only returns the head although I think the head is linked with its next node by: pre = curr.next Below is my code. I'm having difficulty figuring out where the problem is. Any help is appreciated!! class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return head pre, curr, post = None, head, head.next while post: pre = curr.next pre, curr, post = curr, post, post.next pre = curr.next return curr
tagged with: python
has title: Why does my reverse linked list only return head?
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: linked-list

http://stackoverflow.com/a/49685142
upvote count: 8
type: Answer
has body: In python 3, when you open a file in text mode, e.g., "r", there is a decoder between you and the raw file. In this case, its the UTF-8 decoder. "file position" doesn't really make sense because a character index at the text level is different than a byte index in the file. In addition, python does caching in the background to aid with decode. The solution is to read in binary and do the decode later f = open('myfile.txt', 'rb') f.seek(start) text = f.read(length).decode(encoding='utf-8') f.close()
score: 8
accepted answer of: http://stackoverflow.com/q/49684881
answers question: http://stackoverflow.com/q/49684881
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86281334
comment on: http://stackoverflow.com/q/49636813
score: 0
type: Comment
type: QuestionComment
has text: How do those pixels create that size image? That's not even a perfect square. You should have a 2304 length array

http://stackoverflow.com/q/49637186
answer count: 1
downvote count: 0
tagged with: bokeh
favorite count: 0
type: Question
upvote count: 2
tagged with: google-maps
type: UnansweredQuestion
has body: I can only set zooms but I need to have a very specific position so I can overlay it over another plot. How I get a view just from the limits I specified below? Right now I can only set a zoom which is difficult for overlaying on another plot. from bokeh.io import output_file, show from bokeh.models import ColumnDataSource, GMapOptions from bokeh.plotting import gmap output_file("gmap.html") lat_lims = (42.418574999999997, 42.420059000000002) lon_lims = (-70.907111, -70.904135999999994) map_options = GMapOptions(lat=np.mean(lat_lims), lng=np.mean(lon_lims), map_type="satellite", zoom=18) # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: p = gmap(googlemaps_api_key, map_options) show(p)
tagged with: python
has answer: http://stackoverflow.com/a/49640980
tagged with: google-maps-api-3
score: 2
tagged with: satellite
has title: How to set longitude and latitude ranges for Bokeh Google Maps plot in Python?

http://stackoverflow.com/comment/86244784
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49618485
score: 0
has text: if you download the script, then you can just say `system("python path/to/script.py")`

http://stackoverflow.com/comment/86265517
has text: Please show HTML you get into the browser
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49629419
type: Comment

http://stackoverflow.com/comment/86286025
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49634456
has text: Ah, I figured you could probably use the descriptor itself. But hash function would be even better :)
type: Comment

http://stackoverflow.com/comment/86363777
comment on: http://stackoverflow.com/q/49675751
score: 0
type: Comment
has text: @JWeezy it doesn't make sense to duplicate procedures for each user.
type: QuestionComment

http://stackoverflow.com/a/49752540
has comment: http://stackoverflow.com/comment/86524893
has body: You can add all of your columns as as a list in list: l = [] for file in [your_files]: with open(file, 'r') as f: for line in f.readlines() l.appned(line.split(" ")) Now you have list of lists, so just sort them with length of sublists then put it in a new file: l.sort(key=len) with open(outputfile, 'w'): # Write lines here as you want
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49752293
has comment: http://stackoverflow.com/comment/86520477
downvote count: 0

http://stackoverflow.com/comment/86408264
type: QuestionComment
has text: I don't see what's your problem with `with` blocks but yes, if you insist doing it this way, there nothing wrong with the approach. You could open the file once in `a+` mode and then `fhandle.seek(0)` to get back to the beginning but you won't gain much from that.
score: 2
comment on: http://stackoverflow.com/q/49696956
type: Comment

http://stackoverflow.com/comment/86479696
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49732940
has text: What is the issue you are facing? We need more information
type: Comment

http://stackoverflow.com/a/49711109
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49696980
has body: Thank you @JeanRostan for your help, I was able to output correct output with the following code (even though it is very primitive one): user_input = [] translate = {} for line in open('dictionary.txt'): english, aboriginal = line.split(',') translate[english] = aboriginal while user_input != "": user_input = input("English: ") if user_input == "": break else: tempList = [] for word in user_input.split(): tempList.append(translate[word]) A = ("".join(tempList)) B = (A.replace('\n',' ')) B = B.rstrip() print(B)
accepted answer of: http://stackoverflow.com/q/49696980
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49705020
tagged with: artificial-intelligence
tagged with: google-assistant-sdk
favorite count: 0
type: Question
tagged with: raspberry-pi
tagged with: google-api
downvote count: 0
has title: Raspberry Pi Google Assistant Issues
upvote count: 1
has body: I followed this tutorial recently and have had an issue. I can't seem to get it working but when i run the command sudo /home/pi/google-assistant-init.sh to start it, I get this error: /home/pi/main.py:16: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. GPIO.setup(25, GPIO.OUT) Traceback (most recent call last): File "/home/pi/main.py", line 58, in &lt;module&gt; main() File "/home/pi/main.py", line 52, in main with Assistant(credentials) as assistant: TypeError: __init__() missing 1 required positional argument: 'device_model_id' and I can't seem to get it working. Any help would be appreciated. I have completed all the steps too.
has answer: http://stackoverflow.com/a/49711239
type: AnsweredQuestion
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49711239
tagged with: python

http://stackoverflow.com/q/49723357
has body: from sympy import * x = Symbol('x') f = (2*x) + 1 fprime = f.diff() f = lambdify(x, f) fprime = lambdify(x, fprime) newtons_expr = lambdify(x, x - (f(x) / fprime(x)) ) def newtons_method(guess): approx = newtons_expr(guess) if Abs(approx - guess) &lt; 0.001: print(approx) # &lt;-- returns a float (-0.5) print(type(approx)) # &lt;-- returns "&lt;class 'float'&gt;" return approx # &lt;-- returns a None else: newtons_method(approx) print(newtons_method(1)) I built this function using SymPy to evaluate one of the solutions to an equation using Newton's method. For some reason, however, its returning a None instead of a float, even though it explicitly prints a float before it returns the value of approx. What's wrong here? I've never seen this before.
has comment: http://stackoverflow.com/comment/86478237
has title: Using SymPy, recursive function returning "None" value
has comment: http://stackoverflow.com/comment/86462496
duplicate of: http://stackoverflow.com/q/17778372
type: Question
has comment: http://stackoverflow.com/comment/86460708
has comment: http://stackoverflow.com/comment/86461574
has comment: http://stackoverflow.com/comment/86460426
has answer: http://stackoverflow.com/a/49723984
linked to: http://stackoverflow.com/q/17778372
tagged with: python
has comment: http://stackoverflow.com/comment/86460564
score: 0
tagged with: sympy
has comment: http://stackoverflow.com/comment/86460498
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86460811
answer count: 1

http://stackoverflow.com/a/49734401
has comment: http://stackoverflow.com/comment/86483151
answers question: http://stackoverflow.com/q/49734284
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/86482809
score: 2
has body: Multiple file is not possible but all the multiple files share the single app = Flask(__name__) right ? You can use this app to start the flask run. file1.py =&gt; app = Flask(__name__) file2.py =&gt; from file import app file3.py =&gt; from file import app export FLASK_APP=file1.py flask run
downvote count: 0

http://stackoverflow.com/q/49744164
has comment: http://stackoverflow.com/comment/86503109
has comment: http://stackoverflow.com/comment/86503136
type: Question
has body: UPDATE: As DyZ commented below, my problem turned out to be that the source code did not have the necessary information. So, I started using Selenium and it worked!!! I am trying to web scrape and obtain the price of products from a website. I am using the lxml and requests module. So far what I have is: import requests from xml.etree import ElementTree as html page = requests.get(myUrl) tree = html.fromstring(page.content) prices = tree.xpath('//div[@class="product-pricing"]/text()') This should give me the list of prices but what I get instead when I print prices is: ['\n\t\t\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t\t\t'] Does anyone know why this is happening/ how I could fix this?
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: web-scraping
upvote count: 1
tagged with: python-requests
favorite count: 0
has title: Data being hidden when webscraping
has comment: http://stackoverflow.com/comment/86503224
tagged with: lxml
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86526705

http://stackoverflow.com/comment/86440664
score: 0
comment on: http://stackoverflow.com/q/49713281
type: Comment
has text: Just a style note, the Python convention is to name classes in UpperCamelCase (so Work) and functions in lowercase_separated_by_underscores (so main).
type: QuestionComment

http://stackoverflow.com/q/49739356
has body: I can not build CNN for 1D input vector. Example of input value: df_x.iloc[300] Out[33]: 0 0.571429 1 1.000000 2 0.971429 3 0.800000 4 1.000000 5 0.142857 6 0.657143 7 0.857143 8 0.971429 9 0.000000 10 0.000000 11 0.000000 12 0.000000 13 0.000000 14 0.000000 15 0.000000 Name: 300, dtype: float64 Example of output value: df_y.iloc[300] Out[34]: 0 0.571429 1 0.914286 2 1.000000 3 0.971429 4 0.800000 5 1.000000 6 0.914286 7 0.942857 8 0.800000 9 0.657143 10 0.857143 11 0.971429 12 0.000000 13 0.000000 14 0.000000 15 0.000000 16 0.000000 17 0.000000 18 0.000000 19 0.000000 20 0.000000 21 0.000000 22 0.000000 I have 15k traing examples. df_x.shape Out[28]: (15772, 16) df_y.shape Out[29]: (15772, 23) My current model: model = Sequential() model.add(Conv2D(5, df_x.shape[1], input_shape=(5, 1))) model.add(Dense(46, activation='relu')) model.add(Dense(56, activation='relu')) model.add(Dense(66, activation='relu')) model.add(Dense(56, activation='relu')) model.add(Dense(46, activation='relu')) model.add(Dense(df_y.shape[1], activation='relu')) # compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(df_x, df_y, epochs=5, batch_size=10) I want to build model where first layer will be conv size (5,1), 5 filters and input shape df_x.shape[1], 1. I have an error: ValueError: Input 0 is incompatible with layer conv2d_10: expected ndim=4, found ndim=3 Can you explain me how can I build CNN for 1D input values?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49758312
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49758312
upvote count: 2
answer count: 1
downvote count: 0
tagged with: machine-learning
has title: Keras: convolutional layer for 1D input
tagged with: keras
type: AnsweredQuestion
score: 2
tagged with: conv-neural-network
tagged with: python

http://stackoverflow.com/comment/86323150
type: Comment
has text: You have some spacing issues. Can you fix them?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49657011

http://stackoverflow.com/a/49685704
has body: If you access a function directly from the class object, then it is not actually a method, it is merely a function and you have to pass the arguments you specified in the signature of your function definition, or else, like any other function, it will raise an error. Only if you access the function through the instance will the descriptor protocol be initiated, binding the instance to the method, essentially returning a new partially applied function, a bound-method-object. So, you need to do: items = self.getAll()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49685563
score: 0
accepted answer of: http://stackoverflow.com/q/49685563
type: Answer

mime-mail
type: Tag
tag name: mime-mail
tags question: http://stackoverflow.com/q/49605212

http://stackoverflow.com/a/49744547
answers question: http://stackoverflow.com/q/49744326
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Let's say this is a fragment of your dictionary: doc = {'N8:EntityList': {'N8:Entity': [{'N1:Director': [{'@xsi:type': 'Foo'}]}]}} I assume that you have a list of keys for each item of interest: path = ['N8:EntityList', 'N8:Entity', 'N1:Director', '@xsi:type'] Iterate through the keys, one level at a time, checking if the next keyed object is a list or not. In the former case, take its first element: e = doc for key in path: e = e[key][0] if isinstance(e[key], list) else e[key] print(e) #Foo
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49744326

http://stackoverflow.com/q/49610336
has title: Python Lambda function usage
has body: I have come across this line of code. loss={'ctc': lambda y_true, y_pred: y_pred} 1. What is the function of lambda here? 2. What is the use of 'ctc' here?
score: 1
downvote count: 0
upvote count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/49610469
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86227174
has answer: http://stackoverflow.com/a/49610390
answer count: 3
type: UnansweredQuestion
tagged with: loss-function
tagged with: python
tagged with: lambda
has answer: http://stackoverflow.com/a/49610534
has comment: http://stackoverflow.com/comment/86238588

http://stackoverflow.com/comment/86500213
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49742766
type: QuestionComment
has text: But either way, the answer will be similar: instead of a dict comprehension over `sorted(d.items(), key=whatever)` you'd do a dict comprehension over `some_quicksort_function_you_wrote_or_found(d.items(), key=whatever)`.

http://stackoverflow.com/a/56249512
score: 23
has comment: http://stackoverflow.com/comment/133036190
upvote count: 23
answers question: http://stackoverflow.com/q/49635436
has comment: http://stackoverflow.com/comment/120132931
type: Answer
has comment: http://stackoverflow.com/comment/126263626
has body: Without having to iterate over the Dataframe, you can do the following: df['lon'] = df['geometry'].x df['lat'] = df['geometry'].y
downvote count: 0

http://stackoverflow.com/q/49694394
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86401508
accepted answer: http://stackoverflow.com/a/49694566
has answer: http://stackoverflow.com/a/49694566
tagged with: sequence
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86401359
has title: A better way to create a timeline of repeated event at a given frequency
upvote count: 2
downvote count: 0
has body: I have a square (pulse) signal which has a frequency fq, and is played between t0 and tf. To create the timeline, I simply do: import numpy as np t0 = 0 tf = 200 fq = 20 timeline = np.round(np.arange(t0, tf, 1/fq*1000), 3) A frequency of 20 Hz means a pulse is delivered every 50 ms. The timeline outputted is: timeline Out[284]: array([ 0., 50., 100., 150.]) Now, I would like the same think, but with a burst of n_pulse at frequency fq_burst repeated at the frequency fq. Example: A burst of 4 pulses at 500 Hz repeated at 20 Hz should give me the timeline: timeline Out[282]: array([ 0., 2., 4., 6., 50., 52., 54., 56., 100., 102., 104., 106., 150., 152., 154., 156.]) My current solution works but is far from being nice and optimal: start_burst = np.round(np.arange(t0, tf, 1/fq*1000), 3) timing = list() for t in start_burst: for n in range(n_pulse): timing.append(t + n*(1/fq_burst*1000)) timeline = np.round(np.asarray(timing), 3) Any suggestion on how to improve this timeline generation? I'm thinking of a way to create directly the values in a numpy array and then to reshape it, but I can't figure out how to do it. Thanks!
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86401407
score: 2

http://stackoverflow.com/comment/104782972
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49748494
has text: If your problem still persist even though you have latest pip installed, probably try to upgrade these other packages too: `pip install pyOpenSSL backports.ssl requests`

http://stackoverflow.com/comment/86225116
score: 0
type: Comment
type: QuestionComment
has text: remove `df = pd.DataFrame(df)`, and check `df[0]`, you would find the problem.
comment on: http://stackoverflow.com/q/49607418

http://stackoverflow.com/a/49710468
type: Answer
has comment: http://stackoverflow.com/comment/86434653
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86434580
has body: Please try code below: with open('output.json') as file: data = json.load(file) with open('roleassign.csv', 'wt') as file: file.write('Role,Policy\n') for element in data['RoleDetailList']: if 'RoleName' in element.keys(): s= element['RoleName'] for policy in element['AttachedManagedPolicies']: c = s + ',' + policy['PolicyName'] file.write(c + '\n') Your File writer is being opened in the loop and every time it was overwriting the file with only the headers. Simply moved it out.
answers question: http://stackoverflow.com/q/49710351

http://stackoverflow.com/q/49731417
tagged with: pandas
has comment: http://stackoverflow.com/comment/86477334
has comment: http://stackoverflow.com/comment/86477474
type: Question
linked to: http://stackoverflow.com/q/28766133
type: UnansweredQuestion
has body: I am using a dataset of 60,000. Which is taking 6.4 seconds to read the xlsx file and then convert it into a CSV. How to reduce the time? My code : import pandas as pd import time def read_xlsx(path): df = pd.read_excel(path) return df def convert_to_csv(df): df.to_csv('orders_csv_file.csv') if __name__ == '__main__': start = time.clock() df = read_xlsx("/home/arima/sublime_workspace/orders.xlsx") print(time.clock() - start) start = time.clock() convert_to_csv(df) print(time.clock() - start) Time taken for reading the excel is high(6 sec), converting it into csv taking(.30) sec.
duplicate of: http://stackoverflow.com/q/28766133
tagged with: python
has comment: http://stackoverflow.com/comment/86477009
has title: How to reduce the time taken to read a xlsx and convert it to a csv in pandas on a large dataset?
has comment: http://stackoverflow.com/comment/86477181
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86476874

http://stackoverflow.com/comment/86487277
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49736079
type: AnswerComment
has text: HoudaF: It shouldn't matter based on the results you show in your question, but try using `float(str(row['longitude']))` and `float(str(row['latitude']))` instead. As Orphamiel said, it looks like you have some invalid data which we can't help you with unless you edit your question to include some actual sample data from the csv input file.

http://stackoverflow.com/q/49662022
tagged with: python
has title: how to install openCV_python with no import cv2 error?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/41972261
has answer: http://stackoverflow.com/a/49662269
has comment: http://stackoverflow.com/comment/86334082
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86334419
tagged with: opencv
type: AnsweredQuestion
has body: I am trying to install the OpenCV-python on my mac and i have used the following: $pip install opencv-python which gave me the following error: $pip install opencv-python Collecting opencv-python Using cached opencv_python-3.4.0.12-cp27-cp27m macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Collecting numpy&gt;=1.11.1 (from opencv-python) Using cached numpy-1.14.2-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl matplotlib 1.3.1 requires nose, which is not installed. matplotlib 1.3.1 requires tornado, which is not installed. Installing collected packages: numpy, opencv-python Found existing installation: numpy 1.8.0rc1 Cannot uninstall 'numpy'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. Then i did try the pip install --upgrade matplotlib which didnot change anything. It just show me: matplotlib 2.2.2 requires backports.functools-lru-cache, which is not installed. matplotlib 2.2.2 has requirement numpy&gt;=1.7.1, but you'll have numpy 1.8.0rc1 which is incompatible. As I found many ways to install the openCV-python in the internet like: https://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/ and I installed on my other mac but i got import cv2 problem alot in my codes. I will be more than happy if anyone have a good solution or recommendation to install the openCV-python. Thanks
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49662269
has comment: http://stackoverflow.com/comment/86334264
score: 1

http://stackoverflow.com/comment/86278956
comment on: http://stackoverflow.com/a/49635595
type: AnswerComment
has text: I mean that you call `tup` here is one of many tuples inside a numpy array. Can I just manipulate each tuple as an index of the array? or is there something to be done with iterators?
score: 0
type: Comment

http://stackoverflow.com/a/49758916
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49636443
answers question: http://stackoverflow.com/q/49636443
has body: Aside from the issue with this code's overuse of topic.get_producer (addressed in my answer here), the reason that the first example runs much faster than the second is that the second is effectively running in synchronous mode. That is, every single message produced results in a wait for delivery confirmation before the next message can be produced. If you're interested in writing an application that produces asynchronously, you're probably more interested in something closer to the first example. The correct way to do this is laid out in the pykafka readme: with topic.get_producer(delivery_reports=True) as producer: count = 0 while True: count += 1 producer.produce('test msg', partition_key='{}'.format(count)) if count % 10 ** 5 == 0: # adjust this or bring lots of RAM ;) while True: try: msg, exc = producer.get_delivery_report(block=False) if exc is not None: print 'Failed to deliver msg {}: {}'.format( msg.partition_key, repr(exc)) else: print 'Successfully delivered msg {}'.format( msg.partition_key) except Queue.Empty: break This code produces 10 ** 5 messages asynchronously, then stops producing to consume the delivery report queue, which contains one report per message produced. It prints any reported delivery errors and allows production to resume once the entire queue has been consumed. The 10 ** 5 number can be adjusted depending on your memory limitations - it effectively functions as a bound on the size of the delivery reports queue.
type: Answer

http://stackoverflow.com/a/49665346
has comment: http://stackoverflow.com/comment/86340534
answers question: http://stackoverflow.com/q/49665291
type: Answer
has body: try this! it's from memory but it should work :) # Print Your code here print('Hello in console window') list1 = ['home', 'school', 'bus', 'football'] list2 = ['yesterday I went to home', 'I am busy', 385723, 'I feel like playing football', 'I was tired last week' , 'I go to school by bus' ,' there is a bus stop near my home', 'I am hungry'] theList = [] i = 0 for item in list2: item1 = str(item).split(" ") if len(item1) &gt;= 1: is_in = [x for x in item1 if x.lower() in list1] else: is_in = item if item.lower() == list1 else 0 if len(is_in) &gt; 0: theList.append(item) for item in theList: print(item) Let me know if it errs,
score: 0

http://stackoverflow.com/comment/86414827
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49700290
has text: Do you know how to use either WMI or Win32 API? If so, there's a WMI events for process launch that you can wait on, or you can install a Windows hook that catches every new window and see which window class name it's for. But neither one is trivial to learn, so you're going to have to do some research before you can do anything with an answer.

http://stackoverflow.com/q/49628474
answer count: 0
has body: I'm trying to insert some rows into a database table using SQLAlchemy, but some of the rows contain strings that SQLAlchemy interprets as parameters. That causes errors, even though I just want to insert the strings exactly as they are. For example, one entry is like: abc, \“depth\“:0, The query it is supposed to execute is: INSERT INTO schema.table VALUES ( 'abc, \“depth\“:0,') (I realize that I need to change the \" into double-backslashes for the database to interpret it correctly.) Which causes the error: sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter '0' [SQL: "INSERT INTO schema.table VALUES ( 'abc, \“depth\“%(0)s,')\n"] [parameters: [{}]] (Background on this error at: http://sqlalche.me/e/cd3x) Is there a way to have SQLAlchemy insert the string as-is (without modifying it or trying to interpret it)? Thanks. Essentially, the code is: engine = create_engine(...) session = sqlalchemy.orm.sessionmaker(bind=engine) query = """INSERT INTO schema.table VALUES ( 'abc, \“depth\“:0,')""" session.execute(query) session.commit() session.close() But the query is created programmatically in a loop of thousands of strings (and there will be new strings every day), so I don't have pre-existing knowledge of what every string is.
has comment: http://stackoverflow.com/comment/86263931
downvote count: 0
tagged with: sqlalchemy
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has title: sqlalchemy - Execute plain text (don't bind parameters)
tagged with: python
has comment: http://stackoverflow.com/comment/86281797
score: 2

http://stackoverflow.com/comment/86462227
type: AnswerComment
type: Comment
has text: @Primusa, how many observations should I train the model with to get meaningful predictions?
comment on: http://stackoverflow.com/a/49712177
score: 0

http://stackoverflow.com/a/55661266
type: Answer
upvote count: 1
has body: I believe the following better demonstrates the bullet class used to sole Problem 12- 5 of the "Python Crash Course". import pygame # The name used to create the .py where settings are stored from problem123settings import Settings ai_settings = Settings() # Allow the grouping of related elements of the game and act on all the # grouped elements of the game at once with Sprite. from pygame.sprite import Sprite class Bullet(Sprite): """A class to manage bullets fired from the ship.""" def __init__(self, ai_settings, screen, ship): """Create a bullet object at the ship's current position.""" # Super is called to inherit properly from Sprite. super().__init__() self.screen = screen # Create a bullet rect at (0, 0) [x and y coordinates at the top left # corner of the screen] and then set the correct position. self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) # Set bullet's centerx at the center of the ship. self.rect.centerx = ship.rect.centerx # Set the bullet height at the center of the ship, therefore # making it appear that the bullet comes from the front of the ship. self.rect.center = ship.rect.center # Store the bullet's position as a decimal value. self.x = float(self.rect.x) self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): """Move the bullet across the screen.""" ''' The update() method manages the bullets position. When a bullet is fired, it moves across the screen, which corresponds to an increasing x-coordinate value; so to update the position, we add the amount stored in self.speed_factor to self.x. We then use the value of self.x to set the value of self.rect.x. Once fired the bullets y-coordinate value never changes. ''' self.x += self.speed_factor # Update the rect position of the bullet. self.rect.x = self.x def draw_bullet(self): """Draw the bullet to the screen.""" pygame.draw.rect(self.screen, self.color, self.rect)
answers question: http://stackoverflow.com/q/49719322
downvote count: 0
score: 1

http://stackoverflow.com/a/72525657
has body: Necroposting. I ran into the same situation investigating another issue (using Python 3). Listing: [Python.Docs]: ctypes - A foreign function library for Python [Python.Docs]: pickle - Python object serialization A pointer is a (starting) memory address where data (a number of bytes) may (or may not) be stored. Typically, when used in structure members, a pointer is used to store an array of elements (element represents the pointed type) just like in your example because: Avoids array limitations Flexibility: possibility to use the same structure (instance) for multiple numbers of elements (partially overlaps with #1.) But, a pointer doesn't hold / have information about how much memory the stored data occupies (some could argue it's the pointed type's sizeof, but that is more like a hint). So, in order to be able to get the right amount of bytes (in order to pickle (or do whatever with) it) from the pointer address, the data size must also be retrieved from an external (current pointer wise) source (in our case from another structure member). If the size is not available, the fallback would be (as stated above) the pointed type's sizeof, but there might be cases when that wouldn't be correct. Things get even more complicated when structures are nested (which is pretty often). Also, data size might be expressed in bytes or elements. So, there is no generic way of knowing how many bytes are stored at one address, and that's precisely why (CTypes) pointers can't be pickled by default (otherwise there might be cases of accessing "forbidden" memory which is Undefined Behavior and might trigger SegFault (Access Violation)). As a consequence, structures (unions, or any other container types) containing pointers should define their own pickling strategy (depending on how they store / interpret data). I created a small example. code00.py: #!/usr/bin/env python import ctypes as ct import pickle import sys def __reduce__(self): #print("__reduce__") state = [] ptr_size = None …
downvote count: 0
answers question: http://stackoverflow.com/q/49694832
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/49774934
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49722791
has body: Adjust the following line: p.add_tools(HoverTool(tooltips=[("LOCATION", "@x"), ("TOTAL", "@counts")])) See the documentation: Field names that begin with @ are associated with columns in a ColumnDataSource. For instance the field name "@price" will display values from the "price" column whenever a hover is triggered. If the hover is for the 17th glyph, then the hover tooltip will correspondingly display the 17th price value.
answers question: http://stackoverflow.com/q/49722791
score: 7
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86502558
type: AnswerComment
comment on: http://stackoverflow.com/a/49724759
score: 0
has text: Yes. It's working perfectly now- the problem was wrong column numbers in this line "for col in range(2, Data.max_column + 1):". My data is in the first column. Thank you so much for such a elegant program- I hope to learn enough to help someone else like this some day- you have been very patient. Thank you!
type: Comment

http://stackoverflow.com/comment/86474651
has text: Welcome to SO. Please provide a **[mcve]**. In this example, it's not clear what types your variables are.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49730540
type: QuestionComment

http://stackoverflow.com/q/49749215
upvote count: 3
linked to: http://stackoverflow.com/q/14143284
has title: Pycode style E501 line too long (118 > 79 characters)
downvote count: 3
tagged with: python
favorite count: 0
type: Question
tagged with: pycodestyle
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49749497
has comment: http://stackoverflow.com/comment/86513097
score: 0
has body: charr_prob = float(self.char_freq(kgram, char) * 1.0 / (self.kgram_freq(kgram) * 1.0)) How can I fix this?

http://stackoverflow.com/q/49753231
has comment: http://stackoverflow.com/comment/86523572
has comment: http://stackoverflow.com/comment/86523287
has body: repost of my question here: https://github.com/ageitgey/face_recognition/issues/441 I would like to load an opencv image object into face_recognition library. https://github.com/ageitgey/face_recognition I am using Django Python, I have used opencv to crop and do some face quality checks. Here is what something I did: im_obj = request.data['image_file'] im_cv = cv2.imdecode(np.fromstring(im_obj.read(), np.uint8), cv2.IMREAD_UNCHANGED) result, checked_cv_image = process(im_cv) &lt;-- this does some stuff like crop, etc unknown_image = face_recognition.load_image_file(checked_cv_image) &lt;-- this doesnt work it has this error: AttributeError: 'numpy.ndarray' object has no attribute 'read' My Question: I would like to know is it possible to figure a way how to load an opencv object into face_recognition object. UPDATE: I tried to use, this: ret, buf_checked_cv_image = cv2.imencode( '.png', checked_cv_image ) unknown_image = face_recognition.load_image_file(buf_checked_cv_image) this doesnt work as well, same error: AttributeError: 'numpy.ndarray' object has no attribute 'read'
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/99933739
has comment: http://stackoverflow.com/comment/86524161
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86522832
tagged with: opencv
has comment: http://stackoverflow.com/comment/86524306
tagged with: dlib
has title: how to load opencv object to face_recognition. load_image_file() api does not work for this
score: 1
has comment: http://stackoverflow.com/comment/86523052
downvote count: 0
has comment: http://stackoverflow.com/comment/86523485
tagged with: face-recognition
favorite count: 0
type: Question

http://stackoverflow.com/a/49660449
answers question: http://stackoverflow.com/q/49660350
has body: While loops repeat when the statement is True, in this case when either a != c orb != devaluates to False, so will the while loop argument. You want to alter the logic, change: a != c and b !=d to: not (a == c and b == d) or: a != c or b != d This will achieve what you are after.
score: 0
type: Answer

http://stackoverflow.com/comment/86214677
type: Comment
comment on: http://stackoverflow.com/a/49603551
score: 0
has text: I just saw now @user8212173 previous comment in the original question! Now i got it, thanks! (im pissed of with my pc right now haha)
type: AnswerComment

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/49685681
tags question: http://stackoverflow.com/q/49742866
tags question: http://stackoverflow.com/q/49667831
tags question: http://stackoverflow.com/q/49647008
tags question: http://stackoverflow.com/q/49623585
tag name: xml
tags question: http://stackoverflow.com/q/49738907
tags question: http://stackoverflow.com/q/49666015
tags question: http://stackoverflow.com/q/49674363
tags question: http://stackoverflow.com/q/49624797
tags question: http://stackoverflow.com/q/49682016
tags question: http://stackoverflow.com/q/49630662
tags question: http://stackoverflow.com/q/49683956
tags question: http://stackoverflow.com/q/49724045
type: Tag
tags question: http://stackoverflow.com/q/49614725
tags question: http://stackoverflow.com/q/49633355
tags question: http://stackoverflow.com/q/49623360
tags question: http://stackoverflow.com/q/49657796
tags question: http://stackoverflow.com/q/49735880
tags question: http://stackoverflow.com/q/49699823
tags question: http://stackoverflow.com/q/49724220
tags question: http://stackoverflow.com/q/49613298
tags question: http://stackoverflow.com/q/49623765
tags question: http://stackoverflow.com/q/49628478
tags question: http://stackoverflow.com/q/49742721
tags question: http://stackoverflow.com/q/49738661
tags question: http://stackoverflow.com/q/49680816
tags question: http://stackoverflow.com/q/49626277

http://stackoverflow.com/q/49633500
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: deal with many2many field in odoo
has body: I have two models skills and res_users. I want that each user can have many skills and also each skill can have many users on it. I tried to do that but without success. This is my skills: class technicians_skills(osv.osv): _name = 'skills' _description = 'Technicians Skills' _columns = { 'name': fields.char(string='name', size=50), 'description': fields.text(string="description"), 'member_ids': fields.many2many('res.users', 'skill', string='Technicians') } and this is the users : class res_users(osv.osv): _inherit = 'res.users' _columns = { 'skill': fields.many2many('skills', relation='skills.rel', column1='name', column2='skill', string='Skill'), } and I want to know the skills of each user, but when I call this : test = http.request.env['skills.rel'].search([]) It shows me this error KeyError: 'skills.rel'
type: UnansweredQuestion
tagged with: odoo
has answer: http://stackoverflow.com/a/49636688
tagged with: python
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86210451
has text: Fair enough. I'll leave the ansewr here as an example of what not to do.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49601411
type: Comment

filesaver.js
tag name: filesaver.js
type: Tag
tags question: http://stackoverflow.com/q/49723499

http://stackoverflow.com/comment/139942624
has text: This seems like two different questions: one about the dict behaviour and one about the list behaviour. If both are understood then it's trivial to see why they aren't the same.
comment on: http://stackoverflow.com/q/49646583
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86434580
has text: Cheers no worries :) Glad it helped , Yes i Liked the above solution as well.
comment on: http://stackoverflow.com/a/49710468
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86497429
has text: Thank you very much. I have tried to rewrite my code using the hints you have given me, but I haven't been able to write a working code. Could you please elaborate a little? I believe I understand the general idea you imply, but I am failing at the execution. I am sorry, I am very new at this. For example, I tried loading the 2nd sheet into memory and printing it out. It prints a disordered list- how then, if the string is present in 'rest_of_second_sheet', take the value in the corresponding first column- as in how do I identify the string's location?
type: Comment
comment on: http://stackoverflow.com/a/49724759
score: 0
type: AnswerComment

http://stackoverflow.com/a/49671723
score: 15
upvote count: 15
type: AcceptedAnswer
downvote count: 0
has body: Marginals To show the lines of a kde plot with a different linestyle you can use the linestyle argument, which is passed on to matplotlib's corresponding plot function. sns.kdeplot(setosa.sepal_width, color="r", ax=g.ax_marg_x, linestyle="--") To provide this argument to the kde plot which is produced via distplot you may use the kde_kws argument. sns.distplot(..., kde_kws={"linestyle":"--"}) However, there does not seem to be any reason to use a distplot here. Joint KDE For the 2D case, the linestyle argument has no effect. A 2D kdeplot is a contour plot. Hence you need to use the contour's linestyles (note the s) argument. sns.kdeplot(, linestyles="--") Complete code import matplotlib.pyplot as plt import seaborn as sns iris = sns.load_dataset("iris") setosa = iris.loc[iris.species == "setosa"] virginica = iris.loc[iris.species == "virginica"] g = sns.JointGrid(x="sepal_width", y="petal_length", data=iris) sns.kdeplot(setosa.sepal_width, setosa.sepal_length, cmap="Reds", shade=False, shade_lowest=False, ax=g.ax_joint, linestyles="--") sns.kdeplot(virginica.sepal_width, virginica.sepal_length, cmap="Blues", shade=False, shade_lowest=False, ax=g.ax_joint, linestyles=":") sns.kdeplot(setosa.sepal_width, color="r", legend=False, ax=g.ax_marg_x, linestyle="--") sns.kdeplot(virginica.sepal_width, color="b", legend=False, ax=g.ax_marg_x, linestyle=":") sns.kdeplot(setosa.sepal_length, color="r", legend=False, ax=g.ax_marg_y, vertical=True, linestyle="--") sns.kdeplot(virginica.sepal_length, color="b", legend=False, ax=g.ax_marg_y, vertical=True, linestyle=":") plt.show()
answers question: http://stackoverflow.com/q/49671053
accepted answer of: http://stackoverflow.com/q/49671053
type: Answer

http://stackoverflow.com/comment/86361092
comment on: http://stackoverflow.com/q/49674883
type: Comment
type: QuestionComment
has text: Possible duplicate of [Find closest row of DataFrame to given time in Pandas](https://stackoverflow.com/questions/15115547/find-closest-row-of-dataframe-to-given-time-in-pandas)
score: 0

http://stackoverflow.com/comment/86243605
type: Comment
has text: Accoording to Atom, test.txt uses utf8-encoding. Adding "encoding="utf-8"" in both, test and test2, solved the problem, thanks alot!
type: AnswerComment
comment on: http://stackoverflow.com/a/49618253
score: 0

http://stackoverflow.com/a/49734531
has comment: http://stackoverflow.com/comment/88233787
accepted answer of: http://stackoverflow.com/q/49734441
type: AcceptedAnswer
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/88165750
has body: Use df.to_records() to convert your dataframe to a structured array. You can pass index=False to remove index from your result. import numpy as np df = pd.DataFrame(np.random.rand(10,3),columns=['Acol','Ccol','Bcol']) res = df.to_records(index=False) # rec.array([(0.12448699852020828, 0.7621451848466592, 0.0958529943831431), # (0.14534869167076214, 0.695297214355628, 0.3753874117495527), # (0.09890006207909052, 0.46364777245941025, 0.10216301104094272), # (0.3467673672203968, 0.4264108141950761, 0.1475998692158026), # (0.9272619907467186, 0.3116253419608288, 0.5681628329642517), # (0.34509767424461246, 0.5533523959180552, 0.02145207648054681), # (0.7982313824847291, 0.563383955627413, 0.35286630304880684), # (0.9574060540226251, 0.21296949881671157, 0.8882413119348652), # (0.0892793829627454, 0.6157843461905468, 0.8310360916075473), # (0.4691016244437851, 0.7007146447236033, 0.6672404967622088)], # dtype=[('Acol', '&lt;f8'), ('Ccol', '&lt;f8'), ('Bcol', '&lt;f8')]) A structured array will always have one dimension. That can't be changed. But you can get the shape via: res.view(np.float64).reshape(len(res), -1).shape # (10, 3) For performance, if you are manipulating data, you are better off using numpy.array via df.to_numpy() and recording your column names in a dictionary with integer keys.
answers question: http://stackoverflow.com/q/49734441
has comment: http://stackoverflow.com/comment/86509826
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86419915
comment on: http://stackoverflow.com/a/49701349
type: Comment
has text: Thanks for your response.I am actually looking to plot a 3 different line charts for each year showing me the txns in y axis and months in x axis
score: 0
type: AnswerComment

http://stackoverflow.com/q/49744560
has answer: http://stackoverflow.com/a/49806467
has comment: http://stackoverflow.com/comment/86509690
score: 0
has comment: http://stackoverflow.com/comment/86531042
has title: Mysqldb problems copying django site to new server
answer count: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/86504557
type: Question
tagged with: python
has body: I'm stuck. I'm trying to replicate my fedora setup on a second server. I've got problems. My environment: - mysql (mariadb) - python3 - django - apache with mod_wsgi I'm getting a 500 Internal server error. When I zoom in on the httpd error_log I see this: [Mon Apr 09 22:44:14.119939 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] mod_wsgi (pid=2728): Exception occurred processing WSGI script '/var/www/html/at/at/wsgi.py'. [Mon Apr 09 22:44:14.120097 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] Traceback (most recent call last): [Mon Apr 09 22:44:14.120178 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/var/www/html/at/at/wsgi.py", line 16, in &lt;module&gt; [Mon Apr 09 22:44:14.120190 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] application = get_wsgi_application() [Mon Apr 09 22:44:14.120206 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/usr/local/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Apr 09 22:44:14.120214 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] django.setup(set_prefix=False) [Mon Apr 09 22:44:14.120228 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/usr/local/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup [Mon Apr 09 22:44:14.120236 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] apps.populate(settings.INSTALLED_APPS) [Mon Apr 09 22:44:14.120250 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/usr/local/lib64/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Mon Apr 09 22:44:14.120258 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] raise RuntimeError("populate() isn't reentrant") [Mon Apr 09 22:44:14.120285 2018] [wsgi:err…
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/49601585
has answer: http://stackoverflow.com/a/49601630
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to understand: "the collection of objects directly referenced by an immutable object cannot change"?
tagged with: python
tagged with: immutability
score: 3
answer count: 2
upvote count: 3
has body: From the Python documentation: An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.) While the first part of the original quote is understandable, I don't quite get the last sentence. How can I understand the phrase: "directly referenced by an immutable object"?
has answer: http://stackoverflow.com/a/49601629
downvote count: 0

http://stackoverflow.com/q/49620487
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
answer count: 1
score: 16
upvote count: 16
has comment: http://stackoverflow.com/comment/86248395
has body: I am able to run a background function using multiprocessing.Process with the start method fork. For some reason, I need this child process to start a new environment when running. So I set the start method to spawn via multiprocessing.set_start_method('spawn') and run the job via job.start() I get the following error: Can't pickle &lt;class 'module'&gt;: attribute lookup module on builtins failed However, I do not use pickle for anything within the function that I am calling. What could I be doing wrong? Is there a general rule of thumb that I should have followed when running processes in spawn mode? FYI: I am on a machine with Ubuntu 16.04
favorite count: 0
has title: Why changing start method to 'spawn' from 'fork' in Python multiprocessing does not allow me run my job anymore?
tagged with: multiprocessing
type: Question
tagged with: spawn
has comment: http://stackoverflow.com/comment/86248132
tagged with: python
has answer: http://stackoverflow.com/a/49620642
accepted answer: http://stackoverflow.com/a/49620642
tagged with: python-multiprocessing

ctypes
tags question: http://stackoverflow.com/q/49694832
tags question: http://stackoverflow.com/q/49635105
tags question: http://stackoverflow.com/q/49755568
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/49707878
tags question: http://stackoverflow.com/q/49744870
tags question: http://stackoverflow.com/q/49690898
tags question: http://stackoverflow.com/q/49633964

http://stackoverflow.com/q/49656955
answer count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51621020
favorite count: 0
has title: Apriori Algorithm shows lots of result even for small amount of data
tagged with: python
has body: I am trying out apriori algorithm which takes more than the expected time, this is the code. import pandas as pd dataset = pd.read_csv("data.csv", header=None) transactions = [] for i in range(0, 10): temp = [] for j in range(0, 20): temp.append(str(dataset.values[i,j])) transactions.append(temp) from apyori import apriori associations = apriori(transactions, min_support=0.03, min_confidence=0.7, min_lift=3, min_length=2) result = list(associations) it's working fine upto the point of creating apriori object. But when I tried to run the last line (conversion to list) it's taking huge amount of time. As you can see above I have only inputted 10 transactions, but it has output more than a million rules, so I couldn't find the error in the code. pls help me to find the issue. The below image shows my variable values in anaconda spyder ide. Thank you.....
type: Question
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: apriori
has comment: http://stackoverflow.com/comment/86323502

http://stackoverflow.com/comment/86480165
type: Comment
type: QuestionComment
has text: Perhaps you need a parser for that. Language models, at least the ngram models, are not capable of capturing grammatical correctness. However, recurrent neural language models have shown some interesting properties in this direction.
comment on: http://stackoverflow.com/q/49605248
score: 0

http://stackoverflow.com/q/49609353
has title: pandas.DataFrame.to_csv not exporting all rows
has comment: http://stackoverflow.com/comment/86225314
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86225882
has body: does anyone have an idea what could be causing pandas.DataFrame.to_csv not to export the complete dataframe? print(len(df)) [77814 rows x 42 columns] df.to_csv('filename.csv')) The resulting csv files has 54470 lines and is missing block of data around 1/3 down the file. My data is time stamped to I can tell that the missing data is one large chunk and not random points throughout the file. I'm working in python 3.6.5 and pandas is 0.22.0. Thanks a lot for your help
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/86225235
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56460130
tagged with: missing-data
has comment: http://stackoverflow.com/comment/86240163
tagged with: python
has comment: http://stackoverflow.com/comment/86225623
tagged with: export-to-csv
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/53606044
downvote count: 0

http://stackoverflow.com/comment/86507382
comment on: http://stackoverflow.com/q/49746552
type: Comment
type: QuestionComment
score: 0
has text: you said it - "but `returns none`"

http://stackoverflow.com/comment/86335894
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49643492
type: Comment
has text: @Paral, the `command` parameter points to a function. In this case, I pointed it at the `res` function. Sometimes there's a mismatch between the parameters that `command` wants to pass and what the function expects. This is a situation where a `lambda` can be used to overcome that mismatch by appearing to accept one parameter list but calling the function with another. There are likely other reasons, for using a `lambda` in this situation.

http://stackoverflow.com/q/49637222
has answer: http://stackoverflow.com/a/49638169
type: UnansweredQuestion
has body: #!/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("Arial",10,QtGui.QFont.Bold,False) username = QtGui.QLabel('Username',self) username.move(10,40) username.setFont(font); usernameEdit = QtGui.QLineEdit(self) usernameEdit.move(100,35) usernameEdit.textChanged[str].connect(self.onChangedusername) usernameEdit.setFocus() btn = QtGui.QPushButton('Login', self) btn.move(10, 80) btn.setFixedWidth(130) btn.setFixedHeight(50) btn.setStyleSheet("background-color: #FF0000") #red color btn.clicked.connect(self.begin) btn.setFont(font) self.setGeometry(5, 30, 600, 300) self.setWindowTitle('CSCI237') #Update window title to CSCI237 self.show() def onChangedusername(self, text): global username username = str(text) def begin(self): print username def main(): app = QtGui.QApplication(sys.argv) ex = Home() sys.exit(app.exec_()) if __name__ == '__main__': main() Update the window title to CSCI237 - Course Registration Change the Login button color. Hint: Use hex color codes Update the code to print ‘Hello –username-’ when the Login button is clicked. Add a new button called Logout that prints ‘Goodbye’ when clicked.
answer count: 1
has title: Add a new button called logout that prints 'Goodbye' when clicked
has comment: http://stackoverflow.com/comment/86282112
tagged with: python
has comment: http://stackoverflow.com/comment/86286990
tagged with: codio
has comment: http://stackoverflow.com/comment/86283195
score: 0
has comment: http://stackoverflow.com/comment/86286965
has comment: http://stackoverflow.com/comment/86282978
type: Question

http://stackoverflow.com/comment/86468769
comment on: http://stackoverflow.com/q/49649938
has text: I'm voting to close this question as off-topic because this is better asked of the Python developer(s) (mailing list).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49656004
tagged with: python
has answer: http://stackoverflow.com/a/49656288
has comment: http://stackoverflow.com/comment/86323742
upvote count: 0
has comment: http://stackoverflow.com/comment/86321468
has answer: http://stackoverflow.com/a/49657402
has body: I have a list that I want to use to populate an option menu in tkinter. I have searched far and wide and cannot find a solution that works... any help is appreciated! from tkinter import * from tkinter.ttk import * from tkinter import messagebox import tkinter as tk from tkinter import ttk class TestGUI(Frame): def __init__(self, root): Frame.__init__(self, root) self.root = root self.pack() self.mylist = ['test','test2','test3'] self.emailDropDown= OptionMenu(root,self.mylist) self.emailDropDown.pack() root = Tk() gui = TestGUI(root) root.mainloop()
has comment: http://stackoverflow.com/comment/86322245
has comment: http://stackoverflow.com/comment/86323778
favorite count: 0
type: Question
tagged with: tkinter
answer count: 2
downvote count: 2
type: UnansweredQuestion
score: -2
has title: Populate tkinter optionmenu using a list

http://stackoverflow.com/comment/86533193
score: 0
comment on: http://stackoverflow.com/q/49755568
type: Comment
type: QuestionComment
has text: Probably you didn't define `argtypes` and `restype` for the function. Check https://stackoverflow.com/questions/48788549/python-ctypes-oserror-exception-access-violation-writing-0xfffffffffa1c001/48811895#48811895 for more details defining them. But, without the code it's just a wild guess.

http://stackoverflow.com/a/49720968
answers question: http://stackoverflow.com/q/49720930
has body: You are not actually changing the value of var. Replace var + 1 with var +=1. var = 0 def recursion_function(n): global var if(n &gt; 0): var += 1 print(var) recursion_function(n-1) recursion_function(6) &gt;&gt;&gt;1 &gt;&gt;&gt;2 &gt;&gt;&gt;3 &gt;&gt;&gt;4 &gt;&gt;&gt;5 &gt;&gt;&gt;6
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49623249
answer count: 2
has comment: http://stackoverflow.com/comment/86254097
tagged with: pandas
has answer: http://stackoverflow.com/a/49623629
has comment: http://stackoverflow.com/comment/86253572
upvote count: 3
downvote count: 2
accepted answer: http://stackoverflow.com/a/49623739
has comment: http://stackoverflow.com/comment/86254110
score: 1
has answer: http://stackoverflow.com/a/49623739
favorite count: 0
has comment: http://stackoverflow.com/comment/86253484
has title: Compare values from two pandas data frames, order-independent
type: Question
tagged with: python-3.x
tagged with: unordered
has comment: http://stackoverflow.com/comment/86254294
has comment: http://stackoverflow.com/comment/86253829
has comment: http://stackoverflow.com/comment/86253665
has comment: http://stackoverflow.com/comment/101421795
has comment: http://stackoverflow.com/comment/86253759
tagged with: python
has comment: http://stackoverflow.com/comment/86253741
has comment: http://stackoverflow.com/comment/86253981
has body: I am new to data science. I want to check which elements from one data frame exist in another data frame, e.g. df1 = [1,2,8,6] df2 = [5,2,6,9] # for 1 output should be False # for 2 output should be True # for 6 output should be True etc. Note: I have matrix not vector. I have tried using the following code: import pandas as pd import numpy as np priority_dataframe = pd.read_excel(prioritylist_file_path, sheet_name='Sheet1', index=None) priority_dict = {column: np.array(priority_dataframe[column].dropna(axis=0, how='all').str.lower()) for column in priority_dataframe.columns} keys_found_per_sheet = [] if file_path.lower().endswith(('.csv')): file_dataframe = pd.read_csv(file_path) else: file_dataframe = pd.read_excel(file_path, sheet_name=sheet, index=None) file_cell_array = list() for column in file_dataframe.columns: for file_cell in np.array(file_dataframe[column].dropna(axis=0, how='all')): if isinstance(file_cell, str) == 'str': file_cell_array.append(file_cell) else: file_cell_array.append(str(file_cell)) converted_file_cell_array = np.array(file_cell_array) for key, values in priority_dict.items(): for priority_cell in values: if priority_cell in converted_file_cell_array[:]: keys_found_per_sheet.append(key) break I am doing something wrong in if priority_cell in converted_file_cell_array[:] ? Is there any other efficient way to do that?
linked to: http://stackoverflow.com/q/38212697
possible better answer: http://stackoverflow.com/a/49623629
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86253874

http://stackoverflow.com/a/49640478
type: Answer
score: 1
has body: Your temperature range is inappropriate - 1000 K is not usually considered to be "low" temperature. Try something like 10 K or 1 K instead. This Wikipedia article explains why the behaviour you saw was linear. (The article also says the low-temperature relation is cubic instead of quadratic, but this is not too important for the purpose of this question.)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49640101

http://stackoverflow.com/comment/86391296
has text: Thank you JussiV, but other errors are still going on
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49689239
score: 0

http://stackoverflow.com/comment/86493770
type: QuestionComment
comment on: http://stackoverflow.com/q/49739412
score: 0
has text: I don't fully understand what you're trying to do, but if you have `queryset_list = fp.objects.all()` as the last line of that `if query:`, the previous line is pointless. `queryset_list` will always have all the `fp` objects. You are also returning from within the `for` loop, so only the first iteration will run, after skipping the header.
type: Comment

http://stackoverflow.com/a/63844121
score: 4
has body: Although a long time have passed since I asked this question(and probably duplicate but I can't find similar ones), let me don't leave it unanswered. select .py file which is supposed to be executed from top right corner of program window and select "edit configurations" then check 'run with python console' enabled. I don't know which pycharm version added this option to run a code in console for the first time(maybe from its first release!) but that is all should be done!
type: Answer
accepted answer of: http://stackoverflow.com/q/49601425
downvote count: 0
answers question: http://stackoverflow.com/q/49601425
type: AcceptedAnswer
upvote count: 4

http://stackoverflow.com/comment/86434950
type: QuestionComment
comment on: http://stackoverflow.com/q/49710109
score: 0
type: Comment
has text: Anyway, there are dozens of SQL parsing libraries out there (although picking one that's actually correct can be hard from among the toy versions that work 98% of the time but are fundamentally flawed and can't be fixed for the other 2%). That's the obvious right solution here if you need to parse a sequence of arbitrary SQL statements with semicolon terminators.

http://stackoverflow.com/q/49619281
tagged with: tkinter
has answer: http://stackoverflow.com/a/49619629
possible better answer: http://stackoverflow.com/a/49619625
tagged with: photoimage
has comment: http://stackoverflow.com/comment/86246190
has answer: http://stackoverflow.com/a/49619625
tagged with: base64
tagged with: python
has body: I am fairly new to Python and am attempting to compile a text (.txt) document that acts as a save file and can be loaded later. I would like it to be a standalone document that holds all attributes the user is working with (including some images that I would like to be saved in the file as encoded base64 binary strings). I have written the program and it saves everything to the text file correctly (although I did have to pass the encoded values through a str()) but I am unable to access the images later for decoding. Here is an example of my creation of the text information: if os.path.isfile("example.png"): #if the user has created this type of image.. with open("example.png", "rb") as image_file: image_data_base64_encoded_string = base64.b64encode(image_file.read()) f = open("example_save.txt",'a+') f.write("str(image_data_base64_encoded_string)+"\n") f.close() #save its information to the text doc And here is an example of one of my many attempts to re-access this information. master.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = ((".txt files","*.txt"),("all files","*.*"))) with open(master.filename) as f: image_import = ((f.readlines()[3]))#pulling the specific line the data string is in image_imported = tk.PhotoImage(data=image_import) This is only my most recent attempt of many - and still returns an error. I tried decoding the encoded information before passing to the tkinter PhotoImage function but I think that Python may be seeing the encoded information as a string (since I made it one when I saved the information) but I do not know how to change it back without altering the information. Any help would be appreciated.
tagged with: string
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86248477
score: 0
has comment: http://stackoverflow.com/comment/86246312
has title: Decode Base64 after it has been saved as a string object?
has comment: http://stackoverflow.com/comment/86245660
has comment: http://stackoverflow.com/comment/86245789
accepted answer: http://stackoverflow.com/a/49619629
type: Question
answer count: 2

keras-2
tags question: http://stackoverflow.com/q/49737772
tags question: http://stackoverflow.com/q/49604079
tags question: http://stackoverflow.com/q/49630178
tag name: keras-2
type: Tag

http://stackoverflow.com/q/49750691
type: Question
has title: Python check for corrupted video file (catch OpenCV error)
type: UnansweredQuestion
score: 10
has answer: http://stackoverflow.com/a/49751695
tagged with: python
linked to: http://stackoverflow.com/q/49602465
tagged with: opencv
linked to: http://stackoverflow.com/q/8873657
tagged with: video
has comment: http://stackoverflow.com/comment/86517682
has body: I'm searching for a way to check if a video file is corrupted. I'm using cv2 (OpenCV for python) to load the video. If the video file is corrupt, I would like to skip the file and move on to the next one. I found this stackoverflow question and therefore tried this: try: vid = cv2.VideoCapture(corrupt_video_file) except cv2.error as e: print(e) except: print('error') but I still receive the following error: [mov,mp4,m4a,3gp,3g2,mj2 @ 0x1b2d000] moov atom not found Unable to stop the stream: Inappropriate ioctl for device OpenCV Error: Unspecified error (GStreamer: unable to start pipeline ) in cvCaptureFromCAM_GStreamer, file /home/student/programs/opencv-3.4.0/modules/videoio/src/cap_gstreamer.cpp, line 890 VIDEOIO(cvCreateCapture_GStreamer (CV_CAP_GSTREAMER_FILE, filename)): raised OpenCV exception: /home/student/programs/opencv-3.4.0/modules/videoio/src/cap_gstreamer.cpp:890: error: (-2) GStreamer: unable to start pipeline in function cvCaptureFromCAM_GStreamer It appears that a cpp error is raised and not a python error. (I compiled opencv from source, was needed for an other project) Is it possible to also catch those cpp errors? Or is there an other way to check for corrupted video files in python? Or does the problem lie with that I compiled openCV myself, and not just installed the python-cv2? Any help or suggestions would be welcome!
answer count: 1
downvote count: 0
upvote count: 10
favorite count: 0

http://stackoverflow.com/a/49715522
answers question: http://stackoverflow.com/q/49714439
type: Answer
has body: You can try translate method : import unicodedata import sys data1=['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?'] data=dict.fromkeys([i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')]) def remove_punctuation(sentence): return sentence.translate(data) for i in data1: print(remove_punctuation(i)) output: The first time you see The Second Renaissance it may look boring Look at it at least twice and definitely watch part 2 It will change your view of the matrix Are the human people the ones who started the war Is AI a bad thing
score: 0

http://stackoverflow.com/comment/86403338
has text: @jarmod Can you please give me an example, many thanks
comment on: http://stackoverflow.com/q/49695050
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86510365
has text: @pascalwhoop, feedback on the new answer?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49630662
type: QuestionComment

http://stackoverflow.com/q/49617543
has answer: http://stackoverflow.com/a/49617629
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49617801
tagged with: python
has comment: http://stackoverflow.com/comment/86244360
has comment: http://stackoverflow.com/comment/86244091
has answer: http://stackoverflow.com/a/49617901
score: 0
has title: Python: why are lists defined inside while loops recycled but not variables that are assigned lists inside same loop?
answer count: 3
has comment: http://stackoverflow.com/comment/86244110
has comment: http://stackoverflow.com/comment/86242086
has comment: http://stackoverflow.com/comment/86242126
tagged with: append
has body: Still new, I searched google but I didn't really find an explanation so thank you in advance. When writing Python, why is is that during a while loop, a variable that is assigned a list outside of the while loop can be modified and retain it's modifications with each iteration, but a variable that is assigned a list during the loop will revert back to it's original assignment with each iteration? Here is an example code: x = [1,1,1] while True: a = [1,1,1] b = x a.append(1) b.append(2) print(a) print(b) why does variable a stay the same, while variable b can be appended with each iteration and maintain its modifications? Thanks.
type: Question
has comment: http://stackoverflow.com/comment/86242102

http://stackoverflow.com/a/49610905
type: Answer
answers question: http://stackoverflow.com/q/49600700
downvote count: 0
has comment: http://stackoverflow.com/comment/112872072
score: 9
upvote count: 9
has body: All answers are correct, but in case your sentence is quite long and the mapping-dictionary rather small, you should think of iterating over the items (key-value pairs) of the dictionary and apply str.replace to the original sentence. The code as suggested by the others. It takes 6.35 µs per loop. %%timeit search = "you don't need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?" mapping = {"don't": "do not" } search = ' '.join([mapping.get(i, i) for i in search.split()]) Let's try using str.replace instead. It takes 633 ns per loop. %%timeit search = "you don't need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?" mapping = {"don't": "do not" } for key, value in mapping.items(): search = search.replace(key, value) And let's use Python3 list comprehension. So we get the fastest version that takes 1.09 µs per loop. %%timeit search = "you don't need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?" mapping = {"don't": "do not" } search = [search.replace(key, value) for key, value in mapping.items()][0] You see the difference? For your short sentence the first and the third code are about the same speed. But the longer the sentence (search string) gets, the more obvious the difference in performance is. Result string is: 'you do not need a dog. but if you like dogs, you should think of getting one for your own. Or a cat?' Remark: str.replace would also replace occurrences within long concatenated words. One needs to ensure that replacement is done for full words only. I guess there are options for str.replace. Another idea is using regular expressions as explained in this posting as they also take care of lower and upper cases. Trailing white spaces in your lookup dictionary won’t work since you won’t find occurrences at the beginning or on the end of a sentence.

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/49731391
type: Tag

http://stackoverflow.com/comment/86223718
type: Comment
comment on: http://stackoverflow.com/q/49608523
has text: Stackoverflow is not a code writing service. @phil
score: 2
type: QuestionComment

http://stackoverflow.com/a/49745120
type: Answer
answers question: http://stackoverflow.com/q/49744989
has body: You don't need a loop. Python has a sum function total = sum(integers)
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86438584
score: 0
type: Comment
type: QuestionComment
has text: What you listed as your data doesn’t look like a dict ... please provide a better example.
comment on: http://stackoverflow.com/q/49712491

http://stackoverflow.com/q/49643012
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49643547
has comment: http://stackoverflow.com/comment/86294313
type: Question
has comment: http://stackoverflow.com/comment/86293679
has body: Is there some function which can converts a context manager to a decorator? i.e. I can quickly write the following, but I hope don't miss the common wheel.. Thanks! def context_manager_to_decorator(context_manager: ContextManager): def decorator(func): if context_manager is None: return func @functools.wraps(func) def decorated(*args, **kwargs): with context_manager: return func(*args, **kwargs) return decorated return decorator
has title: Is there library function to convert context manager to decorator
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86294297
has comment: http://stackoverflow.com/comment/86294671
tagged with: python

http://stackoverflow.com/comment/86380612
comment on: http://stackoverflow.com/a/49684143
type: Comment
score: 0
type: AnswerComment
has text: I moved l=[] in while and now I am getting something like this, if I print l but nothing on text. ['\x02'] ['9'] ['L'] ['0'] ['0'] ['1'] ['2'] ['5'] ['0'] ['0'] ['1'] ['\x03'] ['\x02'] ['9'] ['H'] ['1'] ['1'] ['0'] ['5'] ['9'] ['0'] ['0'] ['1'] ['\x03']

http://stackoverflow.com/a/49665704
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49665655
has body: Go to Pycharm File -> Project Settings -> find Project Interpreter In the topright you'll find a plus sign. Click that, search for pygame in the list, install it from there. You should now have a properly installed pygame usable in PyCharm. You may want to clean up your Desktop, too.

http://stackoverflow.com/q/49695723
has answer: http://stackoverflow.com/a/49700146
type: AnsweredQuestion
has title: sqlalchemy update value via resultproxy-object
tagged with: sqlite
answer count: 1
downvote count: 1
tagged with: sqlalchemy
has body: I have a large table with a lot of textual data. The code snippet below is a minimal example from a larger textcorpus-reader that i am writing at the moment. from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.orm import sessionmaker engine = create_engine("sqlite:///corpus.db") meta = MetaData(bind=engine) Session = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, autocommit=False) data_table = Table("data", meta, autoload=True, autoload_with=engine) def computationally_heavy(raw_text): """ This does a lot of text-processing and needs a lot of RAM and CPU. For the sake of this example it does just this: """ return raw_text.split("\n") session = Session() query = session.query(data_table).yield_every(10) for i, row in enumerate(query): result = computationally_heavy(row.raw_text) # This is, what is not working - column 'processed_text' does already exist: row.processed_text = result if i % 250 == 0: s.flush() session.commit() session.close() My problem is that i would like to update single rows in the for loop, but i get: AttributeError: can't set attribute. I read that this way of assigning to rows was possible in sqlalchemy versions prior to 0.9 or something. (I have 1.2.0, but downgrading seems like a silly option, since there must be a way to do this.) And i know this way of assigning to single rows based on query results is possible in sqlsoup, but would rather not use another package, since there sure is a way to do this from sqlalchemy. My question: How do i have to do the row.processed_text = result to get the desired update of the single row going? Since this is supposed to work with different databases, where the column may be named differently i would like to avoid a hardcoded Query(data_table).where(data_table.primary_key == row.primary_key).update() because i do not necessarily know the name of the primary key column. PS.: Performance of the database is not the focus here, since i have time, this is only supposed to r…
favorite count: 0
type: Question
upvote count: 0
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49700146

featuretools
tag name: featuretools
tags question: http://stackoverflow.com/q/49711987
type: Tag

http://stackoverflow.com/q/49702173
has comment: http://stackoverflow.com/comment/86418053
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49703336
has answer: http://stackoverflow.com/a/76611052
tagged with: python
has answer: http://stackoverflow.com/a/49702190
has comment: http://stackoverflow.com/comment/86418054
upvote count: 2
has comment: http://stackoverflow.com/comment/86418060
score: 1
has answer: http://stackoverflow.com/a/63447732
has answer: http://stackoverflow.com/a/49702208
has title: How can I print list of items from multiple lines into a single line in Python?
downvote count: 1
favorite count: 0
has body: I am trying to convert items list from multiple lines to a single line string and vice-versa. I am able to convert items from a single line string to multiple line vertical item list with following code: Items = ["Apple","Ball","Cat"] A = ("\n".join(Items)) print (A) Which prints item list as follows: Apple Ball Cat I am all set with above code My Question is regarding second code (which I can't figure out) down below: However, I am unable to convert vertical list from multiple lines to a single line string. I have following items in multiple lines; Apple Ball Cat and I want to print them in a single line as: Apple Ball Cat I appreciate any kind of advice.
type: Question
tagged with: python-3.x

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/49697958
type: Tag

http://stackoverflow.com/comment/86515784
comment on: http://stackoverflow.com/q/49748482
type: QuestionComment
score: 0
has text: Looks like a candidate for an Observer-Pattern or Model-View-Pattern.
type: Comment

http://stackoverflow.com/q/49642780
tagged with: python
has answer: http://stackoverflow.com/a/49643637
has comment: http://stackoverflow.com/comment/86293114
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86293706
has body: [H6-4] (gene.py) Write a program that reads a string from the user. This string represents a DNA molecule as a sequence of letters A, C, G, and T, each letter representing a different base. Then determine whether it represents a potential gene, if it satisfies the following 4-part codon criteria: • It begins with the start codon ATG. • Its length is a multiple of 3. • It ends with one of the stop codons TAG, TAA, or TGA. • It has no intervening stop codons, anywhere in the codon sequence between the first and last codons. Do so by defining a Boolean function is_gene(dna) that returns True when dna is valid DNA and it satisfies each of the codon criteria. Also define a Boolean function is_valid_DNA(seq) that returns True if each character in seq is one of A, C, G, or T. Otherwise return False. Then complete your program: use your is_valid_DNA(seq) function to validate the input string seq's contents, printing Not valid DNA if it contains any characters other than one of A, C, G, and T. Otherwise, check it via your is_gene() function and print Is potential gene if it satisfies the previous 4-part codon criteria, and Is NOT potential gene otherwise. Finally, if the input string is not valid DNA or violates the 4-part codon criteria, print out some kind of diagnostic information that describes details on why it's not valid. This information might describe why the contents are invalid DNA, such as which bases are illegal and at what sequence position they occur. For the 4-part codon criteria, it might be a description such as "Doesn't start with ATG" or "Length isn't a multiple of 3", and so forth. I will award up to 1 point of Extra Credit for diagnostic output that is so detailed and nicely formatted.
answer count: 1
downvote count: 3
favorite count: 0
type: Question
has title: what is functions for this DNA to solve this problems python
upvote count: 0
accepted answer: http://stackoverflow.com/a/49643637
score: -3

heroku
tags question: http://stackoverflow.com/q/49729234
type: Tag
tags question: http://stackoverflow.com/q/49636036
tag name: heroku

http://stackoverflow.com/a/49756763
has body: The grid doesn't store the number of columns anywhere, so it's not easy to retrieve. Internally, the grid simply associates a left-attach and a width property with each child widget. The easiest way to calculate the number of columns in the grid is to iterate over all its children and find the maximum of left-attach + width: def get_grid_columns(grid): cols = 0 for child in grid.get_children(): x = grid.child_get_property(child, 'left-attach') width = grid.child_get_property(child, 'width') cols = max(cols, x+width) return cols Another option would be to subclass Gtk.Grid and override all methods that add, remove, or move child widgets: class Grid(Gtk.Grid): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.columns = 0 def add(self, child): super().add(child) self.columns = max(self.columns, 1) def attach(self, child, left, top, width, height): super().attach(child, left, top, width, height) self.columns = max(self.columns, left+width) # etc... The problem with this is the sheer number of methods that you have to override: add, attach, attach_next_to, insert_column, remove_column, insert_next_to, remove, and possibly a few more that I've missed. It's a lot of work and prone to errors. There are events for when child widgets are added or removed from a container, but that doesn't really help - what you really need to intercept is when a child widget's properties are modified, and as far as I know there's no way to do that. I tried to override the child_set_property method, but it never gets called.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49756058
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86528972
has comment: http://stackoverflow.com/comment/86528950
upvote count: 1
answers question: http://stackoverflow.com/q/49756058
has comment: http://stackoverflow.com/comment/86528637

http://stackoverflow.com/a/49700496
upvote count: 1
has comment: http://stackoverflow.com/comment/86414666
answers question: http://stackoverflow.com/q/49700368
type: Answer
has body: You can't do what you ask for, but you can do something similar. Set the default value to some other sentinel value, then add a check in your function. None is often a good choice. def fun_func(x=None): if x is None: x = something print(x+x) # lots of lines of code ... something = 21 fun_func() This way, the evaluation of something is deferred until fun_func() is actually called. If None is actually a legitimate value of x, then you might prefer this slightly more convoluted method: _sentinel = object() def fun_func(x=_sentinel): if x is _sentinel: x = something print(x+x)
score: 1
downvote count: 0

http://stackoverflow.com/a/49723716
has body: The as_numer_denom method will recursively find the numerator and denominator of a rational expression: &gt;&gt;&gt; a.as_numer_denom() (x, x + 1) The functions fraction, numer and denom just give you the literal numerator and denominator of an expression without doing denesting.
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/49658716
downvote count: 0

http://stackoverflow.com/q/49649706
has answer: http://stackoverflow.com/a/49649849
favorite count: 0
accepted answer: http://stackoverflow.com/a/49649849
type: Question
has title: Creating a list of documents using if-else in python
tagged with: python-3.x
tagged with: if-statement
tagged with: python
has body: I have a data set which contains keywords,rank_organic and document column. For every keyword there are documents for rank_organic = 1,2,3,4 or 5. But for some keywords I have some rank_organic field missing. For example: For keyword A, I have rank_organic = 1,2,4,5 and 3 is missing. I want to create a list of documents of length 5 where for rank_organic=3, null or space should come and for rest rank the documents should come. Below is the code which I am using but it giving error. Please help me how to achieve it. def key_doc(data): lis=[] for i in pd.unique(data['keyword']): a = data.loc[data['keyword'].isin([i])] j = i.replace(" ","_") j = Node(i, parent= Testing, documents=[(a.loc[(a['rank_organic']==1)])['vocab'].tolist()[0] ,(a.loc[(a['rank_organic']==2)])['vocab'].tolist()[0] ,(a.loc[(a['rank_organic']==3)])['vocab'].tolist()[0] ,(a.loc[(a['rank_organic']==4)])['vocab'].tolist()[0] ,(a.loc[(a['rank_organic']==5)])['vocab'].tolist()[0]]) # print j.name, len(j.documents) lis.append(j) return lis ERROR: ,(a.loc[(a['rank_organic']==3)])['vocab'].tolist()[0] IndexError: list index out of range
type: AnsweredQuestion
score: 0
tagged with: for-loop
tagged with: pandas
upvote count: 1
downvote count: 1
answer count: 1

http://stackoverflow.com/a/49711197
type: Answer
answers question: http://stackoverflow.com/q/49711113
has comment: http://stackoverflow.com/comment/86436254
has body: There are 4 changes to be made: datetime.strptime throws a ValueError if no date can be parsed, so you have to replace your if i == datetime.strptime(i, '%d %b %Y'): with a try: ... except: block: for n, i in enumerate(mylist): try: mylist[n] = datetime.strptime(i, '%d %b %Y') except ValueError: pass Your date format is incorrect. %b means "abbreviated month name", but your month names aren't abbreviated. You have to use %B instead: for n, i in enumerate(mylist): try: mylist[n] = datetime.strptime(i, '%d %B %Y') except ValueError: pass If you want the dates in your list formatted like "2018-04-13 00:00:00", you have to format them with datetime.strftime: for n, i in enumerate(mylist): try: mylist[n] = datetime.strptime(i, '%d %B %Y').strftime('%Y-%m-%d 00:00:00') except ValueError: pass If a string starts with "Expected in", replace it with "01": for n, i in enumerate(mylist): if i.startswith('Expected in '): i = '01' + i[11:] try: mylist[n] = datetime.strptime(i, '%d %B %Y').strftime('%Y-%m-%d 00:00:00') except ValueError: pass Result: ['2018-04-13 00:00:00', 'Mercury', '0', '2018-04-13 00:00:00', 'October', '59', '2018-04-27 00:00:00', 'Kaala', '0', '2018-04-27 00:00:00', 'Adityam', '34', '2018-05-01 00:00:00', 'XXX', '99']
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86437029
accepted answer of: http://stackoverflow.com/q/49711113
upvote count: 2
downvote count: 0

web-scraping
tags question: http://stackoverflow.com/q/49600779
tags question: http://stackoverflow.com/q/49649090
tags question: http://stackoverflow.com/q/49741201
tags question: http://stackoverflow.com/q/49620571
tags question: http://stackoverflow.com/q/49705523
tags question: http://stackoverflow.com/q/49709377
tags question: http://stackoverflow.com/q/49631055
tags question: http://stackoverflow.com/q/49715966
tags question: http://stackoverflow.com/q/49659261
tags question: http://stackoverflow.com/q/49709434
tags question: http://stackoverflow.com/q/49690100
tags question: http://stackoverflow.com/q/49653274
tag name: web-scraping
tags question: http://stackoverflow.com/q/49673886
tags question: http://stackoverflow.com/q/49748736
tags question: http://stackoverflow.com/q/49603462
tags question: http://stackoverflow.com/q/49650369
tags question: http://stackoverflow.com/q/49732587
tags question: http://stackoverflow.com/q/49684432
tags question: http://stackoverflow.com/q/49751398
tags question: http://stackoverflow.com/q/49739132
tags question: http://stackoverflow.com/q/49612510
tags question: http://stackoverflow.com/q/49699973
type: Tag
tags question: http://stackoverflow.com/q/49668206
tags question: http://stackoverflow.com/q/49750183
tags question: http://stackoverflow.com/q/49615664
tags question: http://stackoverflow.com/q/49739994
tags question: http://stackoverflow.com/q/49714216
tags question: http://stackoverflow.com/q/49674105
tags question: http://stackoverflow.com/q/49625751
tags question: http://stackoverflow.com/q/49617989
tags question: http://stackoverflow.com/q/49682135
tags question: http://stackoverflow.com/q/49684990
tags question: http://stackoverflow.com/q/49734915
tags question: http://stackoverflow.com/q/49636099
tags question: http://stackoverflow.com/q/49746928
tags question: http://stackoverflow.com/q/49661168
tags question: http://stackoverflow.com/q/49703521
tags question: http://stackoverflow.com/q/49694649
tags question: http://stackoverflow.com/q/49699767
tags question: http://stackoverflow.com/q/49711153
tags question: http://stackoverflow.com/q/49665316
tags question: http://stackoverflow.com/q/49684095
tags question: http://stackoverflow.com/q/49601120
tags question: http://stackoverflow.com/q/49732518
tags question: http://stackoverflow.com/q/49684290
tags question: http://stackoverflow.com/q/49744164
tags question: http://stackoverflow.com/q/49638285
tags question: http://stackoverflow.com/q/49701840
tags question: http://stackoverflow.com/q/49708525
tags question: http://stackoverflow.com/q/49726034

http://stackoverflow.com/comment/86285834
comment on: http://stackoverflow.com/q/49639075
has text: Why can't you create a view for this?
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/comment/86332025
type: Comment
comment on: http://stackoverflow.com/q/49661027
score: 0
has text: because i need to extract hrefs inside div class "search_col_2" , i dont want to extract any other links and there are other links which are under but i dont need them
type: QuestionComment

http://stackoverflow.com/a/52531355
has body: Upgrading ipykernel worked for me conda upgrade ipykernel
score: 5
downvote count: 0
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49603097

http://stackoverflow.com/q/49612619
possible better answer: http://stackoverflow.com/a/49612845
has answer: http://stackoverflow.com/a/49614687
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: neural-network
upvote count: 6
tagged with: python
has comment: http://stackoverflow.com/comment/86231828
tagged with: artificial-intelligence
has title: I am getting an accuracy of 1.0 every time in neural network
accepted answer: http://stackoverflow.com/a/49614687
has answer: http://stackoverflow.com/a/49612845
has comment: http://stackoverflow.com/comment/86235078
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86232093
answer count: 2
downvote count: 0
has body: I am doing binary classification using multilayer perceptron with numpy and tensorflow. input matrix is of shape = (9578,18) labels has the shape = (9578,1) Here's the code: #preprocessing input = np.loadtxt("input.csv", delimiter=",", ndmin=2).astype(np.float32) labels = np.loadtxt("label.csv", delimiter=",", ndmin=2).astype(np.float32) train_size = 0.9 train_cnt = floor(inp.shape[0] * train_size) x_train = input[0:train_cnt] y_train = labels[0:train_cnt] x_test = input[train_cnt:] y_test = labels[train_cnt:] #defining parameters learning_rate = 0.01 training_epochs = 100 batch_size = 50 n_classes = labels.shape[1] n_samples = 9578 n_inputs = input.shape[1] n_hidden_1 = 20 n_hidden_2 = 20 def multilayer_network(X,weights,biases,keep_prob): ''' X: Placeholder for data inputs weights: dictionary of weights biases: dictionary of bias values ''' #first hidden layer with sigmoid activation # sigmoid(X*W+b) layer_1 = tf.add(tf.matmul(X,weights['h1']),biases['h1']) layer_1 = tf.nn.sigmoid(layer_1) layer_1 = tf.nn.dropout(layer_1,keep_prob) #second hidden layer layer_2 = tf.add(tf.matmul(layer_1,weights['h2']),biases['h2']) layer_2 = tf.nn.sigmoid(layer_2) layer_2 = tf.nn.dropout(layer_2,keep_prob) #output layer out_layer = tf.matmul(layer_2,weights['out']) + biases['out'] return out_layer #defining the weights and biases dictionary weights = { 'h1': tf.Variable(tf.random_normal([n_inputs,n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2,n_classes])) } biases = { 'h1': tf.Variable(tf.random_normal([n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } keep_prob = tf.placeholder("float") X = tf.placeholder(tf.float32,[None,n_inputs]) Y = tf.placeholder(tf.float32,[None,n_classes]) predictions = multilayer_network(X,weights,biases,keep_prob) #cost function(loss) and optimizer function cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with…
score: 6
tagged with: machine-learning

http://stackoverflow.com/q/49731765
has body: I have a sorted list of datetime objects as follows: X = [datetime.date(2017, 1, 14), datetime.date(2017, 1, 14), datetime.date(2017, 1, 16), datetime.date(2017, 1, 16), datetime.date(2017, 1, 18), datetime.date(2017, 1, 22), datetime.date(2017, 1, 24), datetime.date(2017, 1, 24), datetime.date(2017, 1, 29), datetime.date(2017, 2, 4), datetime.date(2017, 2, 10), datetime.date(2017, 2, 22), datetime.date(2017, 2, 28), datetime.date(2017, 3, 8), datetime.date(2017, 3, 28), datetime.date(2017, 4, 17), datetime.date(2017, 4, 20), datetime.date(2017, 4, 20), datetime.date(2017, 5, 16), datetime.date(2017, 5, 26), datetime.date(2017, 6, 12), datetime.date(2017, 6, 23), datetime.date(2017, 6, 28), datetime.date(2017, 7, 28), datetime.date(2017, 8, 14), datetime.date(2017, 8, 29), datetime.date(2017, 8, 29), datetime.date(2017, 9, 26), datetime.date(2017, 10, 4), datetime.date(2017, 10, 5), datetime.date(2017, 10, 8), datetime.date(2017, 11, 20), datetime.date(2017, 12, 2), datetime.date(2017, 12, 11), datetime.date(2017, 12, 11), datetime.date(2018, 2, 14), datetime.date(2018, 2, 16), datetime.date(2018, 3, 2), datetime.date(2018, 3, 5), datetime.date(2018, 3, 28)] The goal is to plot a line chart with X-axis as date, and Y-axis as the no. of times each of the dates appears in the list. I understand that the lamest way to get the line chart is to remove duplicates from X, and generate another list Y which contains the frequency of each datetime object in X, and do a plt.plot(X,Y) But is there a smarter / more pythonic way of doing this? I've already read Plotting time in Python with Matplotlib, but that doesn't help.
tagged with: python
has comment: http://stackoverflow.com/comment/86477171
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1574088
has title: Plotting list of datetime objects as a line chart in matplotlib
score: 3
upvote count: 3
tagged with: matplotlib
tagged with: python-datetime
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49732175
has answer: http://stackoverflow.com/a/49732175
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86477499

http://stackoverflow.com/q/49650449
has comment: http://stackoverflow.com/comment/86309029
has body: Hello everyone and thanks in advance. I'm trying to extract the not matching column strings from two different csv files and write the results in a new cvs file. As far as now, I've written this code: import csv with open(r'C:\Users\DataAnalyst\Desktop\phonesdata\sms_03.csv', 'r') as sms: sms_indices = dict((r[1], i) for i, r in enumerate(csv.reader(sms))) with open(r'C:\Users\DataAnalyst\Desktop\phonesdata\marketing.csv', 'r') as marketing: reader = csv.reader(marketing) f3 = open('results.csv', 'w') c3 = csv.writer(f3) sms_mark = list(marketing) for sms_03_row in sms: row = 1 found = False results_row = sms_03_row #Moved out from nested loop for marketing_row in sms_mark: x = marketing[0] if sms_03_row[1] != marketing_row[0]: results_row.append(x) found = True break row += 1 if not found: results_row.append('Not found') c3.writerow(results_row) sms.close() marketing.close() f3.close() However, I got this: Traceback (most recent call last): File "&lt;ipython-input-5-bc26b28cdf70&gt;", line 1, in &lt;module&gt; sms_mark = list(marketing) ValueError: I/O operation on closed file. How can I solved it? Having this code, will I get just the not matching strings? Thank you!
has comment: http://stackoverflow.com/comment/86325608
has title: ValueError issue and how to extract not matching strings from two files?
has comment: http://stackoverflow.com/comment/86326811
type: AnsweredQuestion
score: 0
tagged with: spyder
has answer: http://stackoverflow.com/a/49659414
tagged with: python
accepted answer: http://stackoverflow.com/a/49659414
tagged with: valueerror
type: Question
answer count: 1

http://stackoverflow.com/comment/86492074
has text: @abarnert can you recommend me another? maybe more easier to use?
comment on: http://stackoverflow.com/q/49738661
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86530520
score: 0
has text: The directory gets new txt files that are parsed.
comment on: http://stackoverflow.com/q/49757610
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49652884
tagged with: django
tagged with: python
has title: my Django DayArchiveView is not detected in urls.py
type: AnsweredQuestion
score: 0
tagged with: django-views
has answer: http://stackoverflow.com/a/49652947
answer count: 1
type: Question
has body: I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get /balance/2018/, or /balance/2018/04/ the views will be displayed, while /balance/2018/04/02 will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results. my urls.py file from django.urls import path, re_path from .views import ArticleYearArchiveView, ArticleMonthArchiveView, ArticleDayArchiveView from . import views urlpatterns = [ path('', views.index, name='index'), path(r'&lt;int:year&gt;/&lt;int:month:&gt;/&lt;int:day&gt;/', views.ArticleDayArchiveView.as_view(day_format='%d'), name='show_day'), path(r'&lt;int:year&gt;/&lt;int:month&gt;/', views.ArticleMonthArchiveView.as_view(month_format='%m'), name='show_month'), path(r'&lt;int:year&gt;/', views.ArticleYearArchiveView.as_view(), name='show_year'), ] my views.py file from django.shortcuts import render from django.views.generic.dates import YearArchiveView, MonthArchiveView, DayArchiveView from django.http import HttpResponse from django.db.models import Sum from .models import Category, Article import datetime # Create your views here. def index(request): num_of_articles = Article.objects.all().count() num_of_categories = Category.objects.all().count() return render(request, 'index.html', context = { 'num_of_articles':num_of_articles, 'num_of_categories':num_of_categories}) class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.all() date_field = 'financial_day' make_object_list = True def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['summation'] = Article.objects.all().filter(financial_day__year=kwargs['year'].year).aggregate(Sum('amount_of_money'))['amount_of_money__sum'] return context class ArticleMonthArchiveView(MonthArchiveView): queryse…
accepted answer: http://stackoverflow.com/a/49652947

http://stackoverflow.com/comment/86442206
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49714322
type: QuestionComment
has text: Which type of tensorflow you've installed, with or without GPU support? [This answer](https://github.com/tensorflow/tensorflow/issues/11571#issuecomment-316126312) provides a script which may help you identify missing DLLs.

http://stackoverflow.com/a/49629319
accepted answer of: http://stackoverflow.com/q/49626724
has body: Here is one way. def adjacentElementsProduct(l): for x, y in zip(l,l[1:]): yield x*y print(max(adjacentElementsProduct([2,5,10,5,2]))) # 50 This can be written more succinctly without the need to define a function: lst = [2,5,10,5,2] print(max(x*y for x, y in zip(lst, lst[1:]))) Explanation Indentation is crucial in Python. Make sure you indent correctly. Your function should return or yield values. In this case yield is appropriate if you call max outside the function. Vectorised approach You can also use numpy for this: import numpy as np x = np.array([2,5,10,5,2]) (x[:-1]*x[1:]).max() # 50
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49626724

http://stackoverflow.com/q/49628086
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: tuples
has answer: http://stackoverflow.com/a/49628507
has title: Compare List of Tuples and Return Indices of Matched Values
tagged with: python
has comment: http://stackoverflow.com/comment/86263052
has answer: http://stackoverflow.com/a/49629060
score: 0
has answer: http://stackoverflow.com/a/49628191
answer count: 3
type: UnansweredQuestion
has body: I'm new to programming and am having some trouble with this exercise. The goal is to write a function that returns a list of matching items. Items are defined by a tuple with a letter and a number and we consider item 1 to match item 2 if: Both their letters are vowels (aeiou), or both are consonants AND The sum of their numbers is a multiple of 3 NOTE: The return list should not include duplicate matches --> (1,2) contains the same information as (2,1), the output list should only contain one of them. Here's an example: ***input:*** [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)] ***output:*** [(0,4), (1,2), (3,5)] Any help would be much appreciated!

http://stackoverflow.com/comment/86572399
has text: Thank you by your comment and suggestion Paul. Yes, my data is about 98% sparse, but only in one single axis. Maybe is more easy to think the data with dimension (12000, 10000, 750), because in this way, all (x,y) have values, but in the z-axis it does not have all 750 values, but only 20 nonzero (2%).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49740518
score: 0

http://stackoverflow.com/comment/86240563
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49616430
type: Comment
has text: Thanks! It's not a typo but I don't know `read()` would change `html1` since I thought I was just extracting its contents. For `html3`, I tried `html3.__repr__()` and noted that the memory address of it is same as `html1`. Is there a way to copy the object only but not share the same address?

http://stackoverflow.com/comment/86392515
has text: Is it possible to compile these as static libraries (**.a**) instead of dynamic libraries (the end product will still be dynamic)?
comment on: http://stackoverflow.com/q/49690321
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49756981
answer count: 1
downvote count: 0
favorite count: 0
has body: With xarray, I'm using ds.to_zarr() to write a dataset to S3 and then xr.open_zarr() to see if I get the same dataset back. My dataset in xarray looks like: &lt;xarray.Dataset&gt; Dimensions: (nv: 2, reference_time: 11, time: 11, x: 4608, y: 3840) Coordinates: * reference_time (reference_time) datetime64[ns] 2018-04-01T18:00:00 ... * x (x) float64 -2.304e+06 -2.303e+06 -2.302e+06 ... * y (y) float64 -1.92e+06 -1.919e+06 -1.918e+06 ... * time (time) datetime64[ns] 2018-04-01T19:00:00 ... Dimensions without coordinates: nv Data variables: time_bounds (time, nv) datetime64[ns] dask.array&lt;shape=(11, 2), chunksize=(1, 2)&gt; ProjectionCoordinateSystem (time) |S64 b'' b'' b'' b'' b'' b'' b'' b'' ... T2D (time, y, x) float64 dask.array&lt;shape=(11, 3840, 4608), chunksize=(1, 3840, 4608)&gt; and I write it to zarr using: fs = s3fs.S3FileSystem(anon=False) d = s3fs.S3Map(f_zarr, s3=fs) ds.to_zarr(store=d, mode='w') when I try to read it back in using: ds2 = xr.open_zarr(d) I get back: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-17-8198db1c8578&gt; in &lt;module&gt;() ----&gt; 1 ds2 = xr.open_zarr(d) /opt/conda/lib/python3.6/site-packages/xarray/backends/zarr.py in open_zarr(store, group, synchronizer, auto_chunk, decode_cf, mask_and_scale, decode_times, concat_characters, decode_coords, drop_variables) 476 477 variables = OrderedDict([(k, maybe_chunk(k, v)) --&gt; 478 for k, v in ds.variables.items()]) 479 return ds._replace_vars_and_dims(variables) 480 else: /opt/conda/lib/python3.6/site-packages/xarray/backends/zarr.py in &lt;listcomp&gt;(.0) 476 477 variables = OrderedDict([(k, maybe_chunk(k, v)) --&gt; 478 for k, v in ds.variables.items()]) 479 return ds._replace_vars_and_dims(variables) 480 else: /opt/conda/lib/python3.6/site-packages/xarray/backends/zarr.py in maybe_chunk(name, var) 471 token2 = tokenize(name, var._data) 472 name2 = 'zarr-%s' % token2 --&gt; 473 return va…
type: Question
tagged with: dask
has comment: http://stackoverflow.com/comment/86529235
has answer: http://stackoverflow.com/a/49831196
tagged with: amazon-s3
tagged with: zarr
has comment: http://stackoverflow.com/comment/86530338
tagged with: python
tagged with: python-xarray
has title: Round-tripping Zarr data from Xarray
upvote count: 1
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/86207569
type: QuestionComment
type: Comment
score: 0
has text: So you want an"invisible" char?
comment on: http://stackoverflow.com/q/49600250

http://stackoverflow.com/comment/86268038
score: 0
type: Comment
has text: check out Martijn Pieters♦ answer [here](https://stackoverflow.com/questions/1867861/python-dictionary-how-to-keep-keys-values-in-same-order-as-declared)
comment on: http://stackoverflow.com/a/49630567
type: AnswerComment

http://stackoverflow.com/comment/97826442
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49726068
has text: Were you able to solve the issue?I am facing similar issue

http://stackoverflow.com/comment/86378208
type: QuestionComment
comment on: http://stackoverflow.com/q/49683171
has text: Thanks heaps. i didn't realize that.
score: 0
type: Comment

http://stackoverflow.com/comment/86500888
comment on: http://stackoverflow.com/q/49742418
type: Comment
score: 0
has text: @COLDSPEED - Thank you so much for the help. that certainly helped.
type: QuestionComment

http://stackoverflow.com/comment/86403331
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49683473
has text: I was talking about the cpu usage on the MVP. cpu_count() is returning 4. With my actual program I can see 4 processes open using htop but only one of those processes is at 100%. I looked into pools but they seemed to be overcomplicated. The pickling issue seems like it could be the problem. The only difference between the code is the size of the object so I'll try to add a larger object to the MVP

http://stackoverflow.com/comment/86495658
has text: accepting a string as an input and make two tests on its length, and in each case we will have an output but it must be an integer
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49740566

http://stackoverflow.com/a/49706144
answers question: http://stackoverflow.com/q/49703045
has body: You are checking if apple is in the list but you want to check if any string in the list contains apple list5 = ['apple', 'mango', 'sherbet'] list6 = ['I ate an apple', 'I ate two apples', 'I love mango'] [x for x in list5 if any(x in item for item in list6)] #['apple', 'mango'] EDIT This creates a list of list in which contain the indexes of the sentence in the second list, which contain the word from the first list list5 = ['apple', 'mango', 'sherbet'] list6 = ['I ate an apple', 'I ate two apples', 'I love mango', '2 apple', 'big apple', 'big mango'] [[i for i, sentence in enumerate(list6) if x in sentence] for x in list5] #[[0, 1, 3, 4], [2, 5], []] As I said in my comment a dictionary would be better in this situation {x:[i for i,sen in enumerate(list6) if x in sen] for x in list5} #{'apple': [0, 1, 3, 4], 'mango': [2, 5], 'sherbet': []} And if only exact matches should be stored you can use this, but this does not work if the first list does not only contain words, for example if list5 contains "an apple" this does NOT work {x:[i for i,sen in enumerate(list6) if any(x==item for item in sen.split())] for x in list5} #{'apple': [0, 3, 4], 'mango': [2, 5], 'sherbet': []}
has comment: http://stackoverflow.com/comment/86436262
has comment: http://stackoverflow.com/comment/86435176
has comment: http://stackoverflow.com/comment/86435246
has comment: http://stackoverflow.com/comment/86437879
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86436176
accepted answer of: http://stackoverflow.com/q/49703045
upvote count: 8
score: 8
has comment: http://stackoverflow.com/comment/86437916
has comment: http://stackoverflow.com/comment/86434839
type: Answer

image-processing
tags question: http://stackoverflow.com/q/49601934
tags question: http://stackoverflow.com/q/49701525
type: Tag
tags question: http://stackoverflow.com/q/49656522
tags question: http://stackoverflow.com/q/49711408
tags question: http://stackoverflow.com/q/49620855
tags question: http://stackoverflow.com/q/49640744
tags question: http://stackoverflow.com/q/49610140
tags question: http://stackoverflow.com/q/49726941
tags question: http://stackoverflow.com/q/49684815
tags question: http://stackoverflow.com/q/49690962
tags question: http://stackoverflow.com/q/49656671
tags question: http://stackoverflow.com/q/49618427
tags question: http://stackoverflow.com/q/49630501
tags question: http://stackoverflow.com/q/49713201
tags question: http://stackoverflow.com/q/49636870
tags question: http://stackoverflow.com/q/49754454
tags question: http://stackoverflow.com/q/49653146
tags question: http://stackoverflow.com/q/49667248
tags question: http://stackoverflow.com/q/49706062
tags question: http://stackoverflow.com/q/49730325
tags question: http://stackoverflow.com/q/49731759
tags question: http://stackoverflow.com/q/49656244
tags question: http://stackoverflow.com/q/49732726
tags question: http://stackoverflow.com/q/49631518
tags question: http://stackoverflow.com/q/49686635
tags question: http://stackoverflow.com/q/49738602
tags question: http://stackoverflow.com/q/49653554
tag name: image-processing
tags question: http://stackoverflow.com/q/49660153
tags question: http://stackoverflow.com/q/49710734
tags question: http://stackoverflow.com/q/49643631
tags question: http://stackoverflow.com/q/49706803
tags question: http://stackoverflow.com/q/49669049
tags question: http://stackoverflow.com/q/49671039
tags question: http://stackoverflow.com/q/49701626
tags question: http://stackoverflow.com/q/49716853

http://stackoverflow.com/comment/86260502
type: QuestionComment
comment on: http://stackoverflow.com/q/49626599
has text: @Nathan But how to use?
score: 0
type: Comment

http://stackoverflow.com/q/49610183
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49610234
has body: Sorry for being not clear in question title, so I will describe on dataset Id Item 1 North 1 South 1 West 1 Central 2 North 2 South 2 East 3 North 3 East I want to filter, for example never West Id Item 2 North 2 South 2 East 3 North 3 East This is only display data from Id that don't have West there.
answer count: 2
has answer: http://stackoverflow.com/a/49610234
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/49610249
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49610249
favorite count: 0
type: Question
tagged with: python
has title: How do I make a "never" filter in pandas dataframe

http://stackoverflow.com/comment/86366105
comment on: http://stackoverflow.com/q/49675629
type: QuestionComment
score: 0
has text: Because you simply don't need two. A single call to `mainloop` is global, and works for all widgets that are children of the same root window. `mainloop` is the _main_ loop, not a _window_ loop.
type: Comment

http://stackoverflow.com/comment/86442424
has text: Why do you read the shapefile twice? Could you make your shapefile available somehow, so that your code is runnable?
comment on: http://stackoverflow.com/q/49713433
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49750922
has comment: http://stackoverflow.com/comment/86518215
type: Answer
answers question: http://stackoverflow.com/q/49750470
has comment: http://stackoverflow.com/comment/86517905
upvote count: 1
score: 1
downvote count: 0
has body: If the rest of the picture is one colour you can compare each pixel and find a different colour indicating the start of the picture like this please pay attention that I assume the top right hand corner to be the background colour, if this is not always the case, use a different approach (counting mode pixel colour for instance)!: import numpy as np from PIL import Image import pprint def get_y_top(pix, width, height, background, difference): back_np = np.array(background) for y in range(0, height): for x in range(0, width): if max(np.abs(np.array(pix[x, y]) - back_np)) &gt; difference: return y def get_y_bot(pix, width, height, background, difference): back_np = np.array(background) for y in range(height-1, -1, -1): for x in range(0, width): if max(np.abs(np.array(pix[x, y]) - back_np)) &gt; difference: return y def get_x_left(pix, width, height, background, difference): back_np = np.array(background) for x in range(0, width): for y in range(0, height): if max(np.abs(np.array(pix[x, y]) - back_np)) &gt; difference: return x def get_x_right(pix, width, height, background, difference): back_np = np.array(background) for x in range(width-1, -1, -1): for y in range(0, height): if max(np.abs(np.array(pix[x, y]) - back_np)) &gt; difference: return x img = Image.open('test.jpg') width, height = img.size pix = img.load() background = pix[0,0] difference = 20 #or whatever works for you here, use trial and error to establish this number y_top = get_y_top(pix, width, height, background, difference) y_bot = get_y_bot(pix, width, height, background, difference) x_left = get_x_left(pix, width, height, background, difference) x_right = get_x_right(pix, width, height, background, difference) Using this information you can crop your image and save: img = img.crop((x_left,y_top,x_right,y_bot)) img.save('test3.jpg') Resulting in this:

django-allauth
tags question: http://stackoverflow.com/q/49619817
type: Tag
tag name: django-allauth
tags question: http://stackoverflow.com/q/49655402
tags question: http://stackoverflow.com/q/49608669

http://stackoverflow.com/comment/86366127
score: 1
type: Comment
type: QuestionComment
has text: Note the date on that answer -- it was true for BS3.
comment on: http://stackoverflow.com/q/49676954

http://stackoverflow.com/q/49625006
tagged with: raspberry-pi
tagged with: pubnub
answer count: 2
downvote count: 0
tagged with: javascript
upvote count: 1
tagged with: python
type: UnansweredQuestion
type: Question
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49635552
has comment: http://stackoverflow.com/comment/86278370
score: 1
has answer: http://stackoverflow.com/a/49641346
has title: Display picture(located on computer) on webpage(not localhost) in real time
favorite count: 0
has body: So,i am stuck in my IoT project where i have to display a picture taken with my picam in real time on my webpage(hosted on 000webhost) as soon as it is taken. Here is what i have tried: on my raspberrry pi i have a python code converting the image into Base64(use pubnub to publish) and to use Pubnub javascript sdk which recieves the base64 string and use it to decode back and display the image. Problem is: Pubnub only allows almost 35kb data to send at a time is there a way where i can take the picture with my picam in the backend and update my webpage by displaying the very picture taken at that moment. (i am using pubnub to send a message(trigger) from my webpage to the python script on my raspberry pi to take the picture)

http://stackoverflow.com/comment/86381544
score: 0
type: QuestionComment
has text: You need to have zlib1g-dev installed which without root access won't be possible, kind of stuck... Cant you pip3 install pip--user
comment on: http://stackoverflow.com/q/49685085
type: Comment

http://stackoverflow.com/comment/86279114
comment on: http://stackoverflow.com/q/49635801
has text: If you do stick with regex, go to: https://regex101.com/ They've got a tool that shows exactly what your regex is doing live. I owe everything I've ever accomplished with regular expressions to that site.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86232016
type: Comment
has text: @JMZhou: Then just throw in a `Reshape((100, 1))(outputs)`.
comment on: http://stackoverflow.com/a/49611960
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86355681
score: 0
comment on: http://stackoverflow.com/q/49672553
type: QuestionComment
type: Comment
has text: on windows, that's not the way to get the lines. On `MSYS` `LINES` exists, `ROWS` doesn't. you probably need windows API to get the values. I'm not sure. the answer linked seems to be OK on windows.

http://stackoverflow.com/q/49726689
has comment: http://stackoverflow.com/comment/86467404
downvote count: 1
has body: Hello I have my python file which shows the sell value of bittrex: import requests import time import hashlib print("---------------------------new program --------------------------------") r = requests.get(url='https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-XRP&type=both') print(r.json()["result"]["sell"][0]["Rate"]) The python above executed correctly and show the value when execute in console. And I have a php page to execute and show the result of the price of XRP from bittrex <?php ob_start(); $output = shell_exec('python3 /home/dramasea/Desktop/mypython.py'); echo " $output "; ob_end_flush(); ?> Can I know why it only shows -------new program------- on the webpage but not the value of the price as it shown when executed in console
has comment: http://stackoverflow.com/comment/86468365
has comment: http://stackoverflow.com/comment/86467743
score: 0
has comment: http://stackoverflow.com/comment/86468353
has title: php to execute python which requests to a https link fails
tagged with: exec
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86468941
has answer: http://stackoverflow.com/a/49726993
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/86469807

http://stackoverflow.com/a/49722726
score: 0
has body: Consider just one of your lists: ['Hello', 'Hi']. This produces two "pairs" in your output (Hi -&gt; Hello) and (Hello -&gt; Hi). To process one of the lists we're looking at something like: for x in l: for y in l: if x != y: [update the count of x -&gt; y] (You could use itertools.combinations or itertools.permutations (depending on preference) to turn this into one loop.) So how should we store the counts? As noted, the inner dictionaries are calling out to be instances of Counter, since it's basically a dictionary which defaults to 0 if the key is missing (meaning you don't have to check for the presence of the key, you can just increment the value). It would be convenient if your outer dictionary could be a dictionary that defaults to an empty Counter, which you can accomplish with defaultdict. I'll leave it to you to write the code to update the counts and process all the lists, but hopefully this is enough to put you on the right path. (Both defaultdict and Counter are in collections. I initially found the defaultdict documentation kind of confusion--you'd create one with counts = defaultdict(Counter).)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86459067
accepted answer of: http://stackoverflow.com/q/49722338
type: Answer
answers question: http://stackoverflow.com/q/49722338

http://stackoverflow.com/q/49681166
has title: resizing images based on distance between 2 objects in the image
type: Question
tagged with: opencv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86377459
has comment: http://stackoverflow.com/comment/86374420
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/86374612
score: 0
has comment: http://stackoverflow.com/comment/86374228
answer count: 0
has body: I have multiple images, each image has 2 objects,but the camera capturing those images has been moving forward and backward, I want to resize all the images so that the distance between the 2 objects can be the same in all the images. Can it be done in python and opencv. currently I'm trying to get the ratio between the distances of 2 images, and then resize, but I can't get the right answer code: resize_factor = default_dist_bet_objects / current_image_distance res = cv2.resize(image, fx = resize_facor, fy= resize_factor, interpolation=cv2.INTER_CUBIC) then i either crop or paste on another image so that all sizes (300,400)
has comment: http://stackoverflow.com/comment/86374810

http://stackoverflow.com/q/49696701
possible better answer: http://stackoverflow.com/a/49696742
upvote count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/49696742
has title: Should I ever directly call object.__str__()?
type: AnsweredQuestion
has body: I'm writing a class in Python and I'm writing a __str__() function so my print statements can print string representations of instances of that class. Is there ever a reason to directly do something like this: myObj = Foo(params) doSomething(myObj.__str__()) It feels like since there are other neater ways to do this, it would be a bad idea (or at least, not proper style) to directly call __str__(). That said, I can't find a website specifically saying not to.
tagged with: oop
answer count: 3
score: 7
tagged with: python
has answer: http://stackoverflow.com/a/49696737
type: Question
accepted answer: http://stackoverflow.com/a/49697053
downvote count: 0
has answer: http://stackoverflow.com/a/49697053

http://stackoverflow.com/comment/86382634
comment on: http://stackoverflow.com/a/49685739
score: 0
type: AnswerComment
has text: This is nice idea, but it only works for the first case.
type: Comment

http://stackoverflow.com/comment/86273020
score: 0
type: Comment
type: QuestionComment
has text: Can you post first 20 lines of the csv file, because what you are saying is your line 13, you have the same value in line 1 as well
comment on: http://stackoverflow.com/q/49632641

http://stackoverflow.com/q/49659985
has answer: http://stackoverflow.com/a/49660061
has comment: http://stackoverflow.com/comment/86329638
tagged with: python
has title: Insert 2D array into 3D array in python
has comment: http://stackoverflow.com/comment/86329594
tagged with: numpy
type: AnsweredQuestion
answer count: 3
score: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/49660059
possible better answer: http://stackoverflow.com/a/61255921
has body: Lets say I make the following arrays: &gt;&gt;&gt; a = zeros((2,2,2)) &gt;&gt;&gt; b = ones((2,2)) How can I insert b into the middle of a? So my resulting array will look like array([[[ 0., 0.], [ 0., 0.]], [[ 1., 1.], [ 1., 1.]], [[ 0., 0.], [ 0., 0.]]])
downvote count: 1
has answer: http://stackoverflow.com/a/49660059
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61255921

http://stackoverflow.com/q/49699499
has title: matplotlib graph embedded in wxPython panel does not display entire graph
tagged with: python
accepted answer: http://stackoverflow.com/a/49714049
type: AnsweredQuestion
score: 0
tagged with: matplotlib
answer count: 1
tagged with: wxpython
linked to: http://stackoverflow.com/q/49723026
type: Question
tagged with: graph
has answer: http://stackoverflow.com/a/49714049
has body: My goal is to have multiple relatively small graphs being generated in the same wxPython panel. Additionally, I would like to manually resize the graphs and place them where I want. This causes issues because my graphs are displayed incorrectly. Changing the size of the graph does not change the graph itself, it only cuts off parts of the graph. It's easier to see what I mean if you run my code. As you can see, the graph on the right is fully displayed, but it is too big and I want to make it a bit smaller. However, the smaller graph on the left is missing half of the graph! Does anyone have an idea as to how this can be fixed? import wx import matplotlib as mpl mpl.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import Figure class MainFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, None, size=(1200,900)) self.panel_1 = Panel_one(self) class Panel_one(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER) self.temp_graph = Graph(self, position=(50, 100), size=(400,400)) self.temp_graph = Graph(self, position=(550, 100), size=(700, 700)) class Graph(wx.Panel): def __init__(self, parent, position, size): wx.Panel.__init__(self, parent, pos=position, size=size) self.figure = Figure(None) self.canvas = Canvas(self, -1, self.figure) self.axes = self.figure.add_subplot(111) if __name__ == "__main__": app = wx.App(redirect=False) frame = MainFrame(None) frame.Show() app.MainLoop() I have found another thread with a similar problem, but the thread's solution did not work correctly and the graphs were still displayed incorrectly.

http://stackoverflow.com/q/49696658
answer count: 1
has comment: http://stackoverflow.com/comment/86406470
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53632534
upvote count: 2
type: UnansweredQuestion
tagged with: function
tagged with: sockets
has body: I am programming a client-server TCP connection in Python, and the client is asked to choose something from a list of functions, one of which is Fibonacci. So after the client picks Fibonacci I want him to be asked to enter a number, and that number to be sent to the Fibonacci function parameter and then return the value from the server to the client. def FIBONACCI(n): if n == 0: return 0 elif n == 1: return 1 else: return (FIBONACCI(n-1)+FIBONACCI(n-2)) I worked with functions without parameters and they work but I haven't seen anything with parameters. Should the input be written in the client side and also how is it sent to the server and all that? P.S I have sent the input FIBONACCI with a sendall and I tried to do it again for the parameter but it doesn't seem to work... I hope I was clear. This is how the function is called: def requests (keyword): if (keyword == "FIBONACCI"): return FIBONACCI(n)
has title: Getting input from client in python
tagged with: python
tagged with: parameter-passing
has comment: http://stackoverflow.com/comment/86406639
score: 2

http://stackoverflow.com/a/49735045
downvote count: 0
type: AcceptedAnswer
has body: Yes, here is a vectorized approach: col = df.column # This is based on your code and is assumed to to return # a column but I think you should use indexing to get a column like df['colname'] cond1 = col &gt; 0 cond2 = ~cond1 col[cond1] = col[cond1] * -1 col[cond2] = col[cond2] * 10
accepted answer of: http://stackoverflow.com/q/49734856
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49734856
score: 5

http://stackoverflow.com/a/49692129
score: 1
has body: Try the below way to get the prices you wish to have. Instead of using this: quote.xpath('.//div[@class="buy-box-container"]/p[2]/text()').extract_first() Try using this: quote.xpath('.//div[@class="buy-box-container"]//p[@class="price"]/text()').extract()[-1]
type: Answer
answers question: http://stackoverflow.com/q/49682449
downvote count: 0
upvote count: 1

file-conversion
tags question: http://stackoverflow.com/q/49739245
tag name: file-conversion
type: Tag

http://stackoverflow.com/q/49738962
score: 2
downvote count: 0
answer count: 1
has title: Python - Cell type 'NoneType' while value inside. How to transform that?
has body: I have been struggling with this for the last couple of hours. I am writing a script for a one-time usage that I hope will save me a lot of time. The purpose of the script is as follow: #In a certain directory, loop through all the .xlsx files #From each .xlsx file, select a whole column based on the column header (user input) (in this case, a year) #Copy these columns successively into a new workbook. I have beforehand transformed .tsv files into a .xlsx files using pandas as follow: # Read tsvfile into dataframe in using panda df = pandas.read_table(tsvfile) # New excelfile writer = ExcelWriter(tsvfile + '.xlsx') # Write dataframe to excel df.to_excel(writer, header = True) writer.save() This worked perfectly, and I now have multiple .xlsx files that can be opened with no change in the data. The issue is that according to excel, the cell values have been saved in textformat. When trying to use the content of these cells in my python script, I often get the following error message: AttributeError: 'NoneType' object has no attribute ‘……’ The strange thing is, that I am able to put these cells into a list, and I can read the value from the cells that way: [… '2005 ', '2006 ', '2007 ', '2008 ', '2009 ', '2010 ', '2011 ', '2012 ', '2013 ', '2014 '….] But I still cannot match it with '2015'. I also cannot delete the spaces after each year, because the type is still 'NoneType'. This is the function I use to find the column number (the one with the list): def checkvalue(x, y, z): """Check if userinput (y) can be found in the row (z), return column number if found""" print(z) values = [] for j, cells in enumerate(range(1, x.max_column + 1), 1): #Cursor cursor = x.cell(row = z, column = cells) values.append(cursor.value) if y in values: return y else: return 999999 I have uploaded one dataset as example (it is data from Eurostat): https://ufile.io/fut70 My whole script (incomplete, work in progress): https://pastebin.com/tdmEynUm What I’d like to know is, what can I do to e…
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49739315
upvote count: 2
has answer: http://stackoverflow.com/a/49739315
tagged with: python
has comment: http://stackoverflow.com/comment/86492717
has comment: http://stackoverflow.com/comment/86493027
tagged with: excel
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/86244437
has text: `print("token: ", bson.BSON.decode(resume_token))` results in a "TypeError: argument to _bson_to_dict must be a bytes object"
score: 0
comment on: http://stackoverflow.com/q/49617127
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49673692
has answer: http://stackoverflow.com/a/49674331
accepted answer: http://stackoverflow.com/a/49674331
has comment: http://stackoverflow.com/comment/86358318
type: Question
possible better answer: http://stackoverflow.com/a/49674054
has title: Print rows containing word from all words in txt file
has answer: http://stackoverflow.com/a/49674054
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86358202
has comment: http://stackoverflow.com/comment/86358266
has answer: http://stackoverflow.com/a/49674175
score: 0
answer count: 3
has body: I have tab separated file with 57k rows and 23 columns containing words. I want to print all rows from my large file which they contain word from my txt file. My file with words: with open('file.txt', 'r') as file: for l in file: lines = l.strip().split('\t') Example output from file above: ['aaa', 'bbb', 'ccc'] Now I want print all rows from my large .txt file with sentences such as: Here aaa is a good day. Your bbb is very good. Here ccc. How to do it? Best

http://stackoverflow.com/comment/86458153
comment on: http://stackoverflow.com/q/49722338
score: 0
type: Comment
type: QuestionComment
has text: @Nick Sorry I did not get you. But the keys should be all the words I have. The values should be the count of other words that appear in the same list with the key. Hope I explained it in a good way

http://stackoverflow.com/comment/86498182
score: 0
type: Comment
has text: Also, aren't there libraries for this on PyPI already? It seems like a common enough thing that there would be.
type: QuestionComment
comment on: http://stackoverflow.com/q/49741733

http://stackoverflow.com/q/49651397
type: UnansweredQuestion
has title: How do you use logging in package which by default falls back to print in Python?
tagged with: python
tagged with: logging
downvote count: 0
has answer: http://stackoverflow.com/a/49652657
upvote count: 1
score: 1
answer count: 1
has body: I want to change my print statements of my package to using logging. So I will write my scripts like import logging logger = logging.getLogger(__name__) def func(): logger.info("Calling func") which is the recommended way? However, many users do not initialize logging and hence will not see the output. Is there a recommended way so that users who do not initialize logging can see info output, and those who explicitly set up logging do not get their specific configuration tampered with by my package?
favorite count: 0
type: Question

http://stackoverflow.com/q/49610858
type: UnansweredQuestion
score: 0
answer count: 1
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/49611269
has body: When I import tensorflow in Python 3.5.3, it gives me following: ERROR: No module named _pywrap_tensorflow Unless you are using bazel, you should not try to import tensorflow from its source directory; please exit the tensorflow source tree, and relaunch your python interpreter from there. I installed tensorflow-0.12.0 using the following command: python -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl
has comment: http://stackoverflow.com/comment/86228696
has title: Importing issue with tensorflow in Python 3.5.3
tagged with: tensorflow
type: Question
tagged with: python-3.x
tagged with: python-import
has comment: http://stackoverflow.com/comment/86229010

http://stackoverflow.com/q/49623137
score: 0
tagged with: apache-pig
has comment: http://stackoverflow.com/comment/86277270
answer count: 1
has title: Call Python function from Pig script
tagged with: putty
type: Question
accepted answer: http://stackoverflow.com/a/49635572
has body: I am new to Pig and would like to call a local python file from Pig after I have connected to the server via PuTTy. Below are the codes I have tried and the error message I received: REGISTER ‘myudf.py’ using jython as my_udf The error message is below and I don't know how to tell Pig the path to the py file. File myudf.py does not exist Another code i tried is: DEFINE mycommand `python myudf.py` ship(‘C:\Users\myname\Documents\code\myudf.py’)； The error message is unexpected character ’S’ This may sound super easy but I have spent hours on it and failed. Any advice will be highly appreciated.
has answer: http://stackoverflow.com/a/49635572
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/86430421
type: QuestionComment
score: 0
has text: you can also use: `if ana.parent.name == "tr" and 'tabindex' in ana.parent and ana.parent['tabindex'] == '0':`
comment on: http://stackoverflow.com/q/49708392
type: Comment

http://stackoverflow.com/a/49735295
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86484878
accepted answer of: http://stackoverflow.com/q/49735028
has body: This is one way using numpy.nanmean. avg = np.nanmean([df1.values, df2.values, df3.values], axis=0) for df in [df1, df2, df3]: df[df.isnull()] = avg df = df.astype(int) Note: since np.nan is float, we convert explicitly back to int.
answers question: http://stackoverflow.com/q/49735028
has comment: http://stackoverflow.com/comment/86484990
has comment: http://stackoverflow.com/comment/86485017
type: Answer
has comment: http://stackoverflow.com/comment/86484833
downvote count: 0

http://stackoverflow.com/comment/86406444
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49620757
has text: @Fourier, I did not know of `panchor` and `anchor`

http://stackoverflow.com/q/49751135
has comment: http://stackoverflow.com/comment/115781517
has comment: http://stackoverflow.com/comment/86640236
score: 21
tagged with: recaptcha
tagged with: incapsula
tagged with: scrapy
linked to: http://stackoverflow.com/q/30286293
favorite count: 0
has comment: http://stackoverflow.com/comment/86619483
has comment: http://stackoverflow.com/comment/86628259
has body: I use Scrapy and I try to scrape this site that uses Incapsula I had already asked a Question about this issue 2 years ago, but this method (Incapsula-Cracker) does not work anymore. I tried to understand How Incapsula works and I tried this for bypass it def start_requests(self): yield Request('https://courses-en-ligne.carrefour.fr', cookies={'store': 92}, dont_filter=True, callback = self.init_shop) def init_shop(self,response) : result_content = response.body RE_ENCODED_FUNCTION = re.compile('var b="(.*?)"', re.DOTALL) RE_INCAPSULA = re.compile('(_Incapsula_Resource\?SWHANEDL=.*?)"') INCAPSULA_URL = 'https://courses-en-ligne.carrefour.fr/%s' encoded_func = RE_ENCODED_FUNCTION.search(result_content).group(1) decoded_func = ''.join([chr(int(encoded_func[i:i+2], 16)) for i in xrange(0, len(encoded_func), 2)]) incapsula_params = RE_INCAPSULA.search(decoded_func).group(1) incap_url = INCAPSULA_URL % incapsula_params yield Request(incap_url) def parse(self): print response.body But i'm redirected to RE-Captcha Page Request unsuccessful. Incapsula incident ID: 459000960022408474-41333502566401539
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/86726774
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86626461
upvote count: 23
has title: How to bypass Incapsula with Python
type: Question
has comment: http://stackoverflow.com/comment/86619246
has answer: http://stackoverflow.com/a/49880089
has comment: http://stackoverflow.com/comment/86619158
has answer: http://stackoverflow.com/a/49864687
linked to: http://stackoverflow.com/q/39354465

http://stackoverflow.com/comment/86260383
comment on: http://stackoverflow.com/a/49626353
has text: Can I perfom the same coding in a list within a list?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86526640
type: QuestionComment
comment on: http://stackoverflow.com/q/49755480
score: 0
type: Comment
has text: Question wise it is a dupe. I will use the answer proposed over there unless someone has a better one. Although it seems clear that ConfigParser only intended one to be able to change the matching, and not modify it.

http://stackoverflow.com/comment/86223578
comment on: http://stackoverflow.com/q/49608352
type: Comment
type: QuestionComment
score: 0
has text: You call `make_reset_password` in the test itself so why do you want to mock it?

http://stackoverflow.com/q/49679643
tagged with: python-3.x
score: 0
accepted answer: http://stackoverflow.com/a/49679723
has comment: http://stackoverflow.com/comment/86371210
linked to: http://stackoverflow.com/q/4527454
has comment: http://stackoverflow.com/comment/86371039
has answer: http://stackoverflow.com/a/49679723
answer count: 1
has title: Python Dictionary contains List as Value - How to update based on some other input
upvote count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86375721
tagged with: python
has body: I have a python dictionary where the value is a 2 item list. The first item is a count of how many times I have seen the key. The 2nd item is another integer which I need to update based on some input. dictionary = { 'key1' : [1, 200] 'key2' : [1, 100] } Suppose, I encounter key1 again and the input is 150. So the update operation should yield dictionary = { 'key1' : [2, 350] 'key2' : [1, 100] } How do I do it? I saw this post but doesn't help. Please suggest. I am using Python 3. EDIT: Before posting this, I tried below: data = defaultdict(list) key = requestTokens[1] # one of the input that works as a key data[key][0] +=1 data[key][1] += int(statusTokens[1]) #another input is statusTokens[1] a string But I am getting error data[key][0] +=1 IndexError: list index out of range
type: Question
has comment: http://stackoverflow.com/comment/86375715

xml-namespaces
type: Tag
tags question: http://stackoverflow.com/q/49699823
tag name: xml-namespaces

http://stackoverflow.com/a/49618527
answers question: http://stackoverflow.com/q/49616151
has comment: http://stackoverflow.com/comment/86261953
has comment: http://stackoverflow.com/comment/86261004
has comment: http://stackoverflow.com/comment/86261323
has comment: http://stackoverflow.com/comment/86262054
has comment: http://stackoverflow.com/comment/86265493
score: 0
has body: In &lt;input&gt; tags the text is in the value attribute. Setting it with JavaScript should work upload_button = el_id('FileNameUpload') browser.execute_script("arguments[0].value = 'arguments[1]';", upload_button, path_to_my_image)
has comment: http://stackoverflow.com/comment/86263795
has comment: http://stackoverflow.com/comment/86261407
has comment: http://stackoverflow.com/comment/86261771
type: Answer

http://stackoverflow.com/a/49622227
score: 1
has body: A simple suggestion would be to create a class that describes a player, their attributes and any functions associated with the player. For example: class Player: def __init__(self, id): self.money = 0 self.items = [] self.level = 1 # Initialize other player attributes here def add_money(self, amount_added): self.money += amount_added def main(): player_1 = Player(id=1) player_1.add_money(100) player_2 = Player(id=2) This is a very generic example, but defining a class for a player will allow you to easily create an object for which you can associate each player. If you add 100 to player 1's money then that will be completely independent of player 2's money. I suggest searching up tutorials/examples on classes and you'll get a feel!
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49622075
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49622075

http://stackoverflow.com/comment/86464239
type: QuestionComment
comment on: http://stackoverflow.com/q/49725147
score: 0
type: Comment
has text: I guess your file `CourseInstructor.txt` don't contain enough data.

http://stackoverflow.com/comment/86513124
comment on: http://stackoverflow.com/q/49748378
score: 0
type: Comment
type: QuestionComment
has text: You posted this question after @JhonKey posted the same, so should be a duplicate, but this is better quality, and a can't vote for duplicate since JhonKey's doesn't have accepted/upvoted answers.

http://stackoverflow.com/comment/86398958
has text: I did thought of this also, Now suppose that, while in training. one of my column was having categorical variable with 5 class. so it will generate 4 dummies columns for that class. But while predicting on client side, he passed only one row of course which will have one class only in that row. In this way even if i used pipline, it will not able to create that extra 4 dummies columns for me.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49693138

http://stackoverflow.com/comment/110210346
type: AnswerComment
has text: Note that `usecols` accept the columns letters as parameter: usecols = "A,C:AA"
comment on: http://stackoverflow.com/a/56252452
score: 2
type: Comment

http://stackoverflow.com/q/49697577
score: 2
tagged with: numpy
tagged with: python-3.x
linked to: http://stackoverflow.com/q/40807475
upvote count: 2
accepted answer: http://stackoverflow.com/a/49697820
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/49697852
has answer: http://stackoverflow.com/a/49697820
duplicate of: http://stackoverflow.com/q/40807475
favorite count: 0
linked to: http://stackoverflow.com/q/44265572
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47276494
answer count: 3
possible better answer: http://stackoverflow.com/a/49697632
tagged with: python
has body: I'd like to find what values exist in an array 'A' that also exist in array 'B'. However, the arrays are of different size and I'd like to introduce a tolerance as there is likely to be a systematic error between the two datasets. I'm aware of 'np.isclose', but this is for arrays of the same size.
has title: Compare elements in two 1D arrays of different size, with tolerance
has answer: http://stackoverflow.com/a/49697632
type: Question

http://stackoverflow.com/comment/86296147
comment on: http://stackoverflow.com/q/49643760
type: QuestionComment
has text: Thanks for helping! I tried, and the result was like this. [response header: {'date': 'Wed, 04 Apr 2018 06:22:50 GMT', 'status': '400', 'content-length': '1555', 'referrer-policy': 'no-referrer', 'content-type': 'text/html; charset=UTF-8'}]
type: Comment
score: 0

http://stackoverflow.com/a/49676383
downvote count: 0
has body: Solution If you print the button's id at method show_load, it will display None, therefore you will have to save the button's text and use it in the load method. Referencing Widgets The Kv Language provides a way to do this using id’s. Think of them as class level variables that can only be used in the Kv language. In Python code, to reference the id, one can use self.ids.id-name.text or self.ids['id-name'].text or self.obj-name.text whereby obj-name is an ObjectProperty and hooked up to the id-name defined in the Kv file. When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in this self.ids dictionary type property. Example Snippets - main.py class checker_ui(GridLayout): btn_text = StringProperty('') # the on_release function def show_load(self, instance): # save the button's text because button's id is None self.btn_text = instance.text content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() # store the path def load(self, path, filename): global newfilepath global oldfilepath if self.btn_text == newfile: newfilepath = os.path.join(path, filename[0]) else: oldfilepath = os.path.join(path, filename[0]) self.dismiss_popup()
accepted answer of: http://stackoverflow.com/q/49663837
answers question: http://stackoverflow.com/q/49663837
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/86373829
score: 0
comment on: http://stackoverflow.com/q/49665919
type: QuestionComment
type: Comment
has text: I get it. Probably I should stick to the REST API for a while. Will try to contribute to the SDK as this is my line of work currently.

mnist
tags question: http://stackoverflow.com/q/49619542
tags question: http://stackoverflow.com/q/49732573
tags question: http://stackoverflow.com/q/49688680
tags question: http://stackoverflow.com/q/49713164
tags question: http://stackoverflow.com/q/49615689
type: Tag
tags question: http://stackoverflow.com/q/49702795
tags question: http://stackoverflow.com/q/49688880
tags question: http://stackoverflow.com/q/49740247
tags question: http://stackoverflow.com/q/49614340
tag name: mnist

http://stackoverflow.com/comment/136479066
type: AnswerComment
has text: Is there a method chaining way to change path?
type: Comment
comment on: http://stackoverflow.com/a/49798311
score: 0

http://stackoverflow.com/comment/86214647
has text: @AndreyTyukin, Yes - shouldn't confuse pandas `groupby` on dataframe with itertools `groupby` on list. The `itertools` method requires explicit sorting first.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49603706
type: Comment

http://stackoverflow.com/comment/86237780
score: 0
type: Comment
type: AnswerComment
has text: just encounted another error, when the file is empty it returns File "tronio.py", line 28, in get_proxy return proxy_manager.random_proxy().proxy_string File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\proxymanager\manager.py", line 45, in random_proxy return random.choice(self.proxies) File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\random.py", line 258, in choice raise IndexError('Cannot choose from an empty sequence') from None IndexError: Cannot choose from an empty sequence
comment on: http://stackoverflow.com/a/49614907

http://stackoverflow.com/comment/86512097
comment on: http://stackoverflow.com/q/49740758
type: QuestionComment
has text: If you know the approximate position, you should really trim the video to that region. Also, you can probably get away with not doing the matching, e.g. by looking at spikes in total pixel intensity in that region (maybe normalised by total pixel intensity in the frame, depending on if the background/lighting changes a lot).
score: 0
type: Comment

http://stackoverflow.com/comment/86501926
comment on: http://stackoverflow.com/q/49743363
has text: Please make it a part of the question where it belongs and where it could be formatted.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86241770
score: 0
has text: why have you tagged both `python-2.7` and `python-3.x`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49617199

http://stackoverflow.com/comment/86441762
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49705406
score: 0
has text: That timing is also loading the same file over and over.

http://stackoverflow.com/comment/86471339
has text: What if I want to save this to a file or write to a text file in python
comment on: http://stackoverflow.com/a/49728737
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49663292
duplicate of: http://stackoverflow.com/q/18510403
tagged with: python
has title: How can I pass object-specific values to a function from objects created in a loop?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49663377
upvote count: 0
possible better answer: http://stackoverflow.com/a/49663377
downvote count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/49663407
answer count: 2
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/49663407
has body: I have searched deeply for a solution to this problem, but, being new to Python and tkinter, it is difficult to find solutions to problems in a language you are largely unfamiliar with. I hope this is not a repeat question. Suppose I create a series of buttons in tkinter, each of which will sequentially display a letter of the alphabet, defined as such: from string import ascii_uppercase as alphabet from tkinter import Button blockLetterButtons = [] for i in range(0,26): blockLetterButtons.append(Button(competitorSelectionFrame, text=alphabet[i], command=some_function(alphabet[i]))) Somewhere below this in the for loop is a .grid(...) for all of these. The function that is being referenced in the command attribute is as the following: def some_function(letter): print(letter) So I recognize two problems with my code: The function in the command attribute is executing immediately upon running the code, because I am specifying a function call rather than a function name. Even if that was the proper way to call the function with a parameter, using alphabet[i] wouldn't work, because it would pass whatever the value of i is upon click, and not whatever i was upon execution of the for loop. So my questions are the following: How can I specify a function in the command attribute and pass to that function with a parameter? How can I specify that parameter to be the letter of the alphabet specific to that button, without defining a button explicitly for every letter? I am fairly certain I could use a list comprehension to solve the second problem, perhaps a dictionary with the key equal to the letter and the value equal to the button, but then I still wouldn't know how to get the key value from the button on its own.
tagged with: function
has comment: http://stackoverflow.com/comment/86336618
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86336699
has comment: http://stackoverflow.com/comment/86337273
linked to: http://stackoverflow.com/q/18510403
score: -2

http://stackoverflow.com/a/49615606
type: Answer
answers question: http://stackoverflow.com/q/49615548
has body: if you can use numpy A = np.array([a,c,b]).transpose() np.savetxt('output.txt',A)
has comment: http://stackoverflow.com/comment/86238068
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49740061
has title: How the child process can act as a daemon after the main process is finished
linked to: http://stackoverflow.com/q/49604997
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86507936
tagged with: python-daemon
tagged with: python
tagged with: python-multiprocessing
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86510370
has body: I want to know that even main process is existing, How can I make child processes to keep running? And pool case also can do this? import os import time from multiprocessing import Process, current_process def doubler(number): result = number * 2 proc_name = current_process().name print('{0} doubled to {1} by: {2}'.format( number, result, proc_name)) time.sleep(2) print('eixt{0}'.format(proc_name)) def doubler1(): print("manse!!!") if __name__ == '__main__': numbers = [5, 10, 15, 20, 25] procs = [] for index, number in enumerate(numbers): proc = Process(target=doubler, args=(number,)) #proc.daemon = True procs.append(proc) proc.start() proc = Process(target=doubler1) procs.append(proc) proc.start() print('main process exit') # for proc in procs: # proc.join()
has comment: http://stackoverflow.com/comment/86509587
type: Question

http://stackoverflow.com/comment/86249181
comment on: http://stackoverflow.com/q/49621105
score: 0
has text: It's not `search`. What else are you trying to call?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86433836
type: AnswerComment
has text: I tried and it was still the same error message... could it be because the cursor had already been there at the input box when I looked at the controlled screen, in which case do I still have to switch to it?
type: Comment
comment on: http://stackoverflow.com/a/49705186
score: 0

http://stackoverflow.com/q/49633071
accepted answer: http://stackoverflow.com/a/49633123
has comment: http://stackoverflow.com/comment/86273966
duplicate of: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/49633123
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has title: I am making a password system thing, how can I make the first IF statement run again without making it into a function?
linked to: http://stackoverflow.com/q/23294658
has body: if userInput != userPassword: print("I'm sorry, that is wrong please try again. Try to remember capitals!") elif userInput == userPassword: print("That is correct you may now find out your mobile phone costs!") mobile_phone() When that runs and I enter the wrong password it just repeats the first print statement (I'm sorry, that is wrong please try again. Try to remember capitals!) how can I make it just run it again ONCE and if it is wrong then maybe another time until it is answered with the right password. Debut Post
score: -2
tagged with: python

http://stackoverflow.com/q/49697876
has body: I am currently trying to extract product data from a JSON feed that contains nested data. The nested structure is looking as follows: http://live.icecat.biz/api/?shopname=openIcecat-live&amp;lang=en&amp;content=featuregroups&amp;icecat_id=1334921 I basically want to extract basic datasheet information for products in the database. Each product has different feature categories at the "top-level" and varying features below that in a nested structure. My code looks like this so far: import requests url2 = 'http://live.icecat.biz/api/?shopname=openIcecat-live&amp;lang=de&amp;content=featuregroups&amp;icecat_id=1334921' content = requests.get(url).content j = json.loads(content) for each in j['data']['FeaturesGroups']: print each ['FeatureGroup']['Name']['Value'] It works fine and prints the headlines of each feature category. But I am unable to parse the individual features. How can I do this ? My attempt was to use a second loop to iterate over j['data']['FeaturesGroups']['Features'] (see below) but no success :/ for each in j['data']['FeaturesGroups']: for each in ['Features']: print ['Feature']['ID'] Thanks a lot!
tagged with: nested-lists
tagged with: arrays
has comment: http://stackoverflow.com/comment/86408839
tagged with: python
has comment: http://stackoverflow.com/comment/86408932
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/49698043
answer count: 2
possible better answer: http://stackoverflow.com/a/49698102
has title: How to parse/extract nested JSON data with Python?
upvote count: 2
has answer: http://stackoverflow.com/a/49698043
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has answer: http://stackoverflow.com/a/49698102
favorite count: 0
tagged with: parsing
type: Question

http://stackoverflow.com/comment/86691392
score: 0
type: AnswerComment
has text: you can check all the output shapes of each layer by doing `model.summary()`
comment on: http://stackoverflow.com/a/49744176
type: Comment

http://stackoverflow.com/a/49755354
accepted answer of: http://stackoverflow.com/q/49752100
upvote count: 15
has comment: http://stackoverflow.com/comment/102881546
answers question: http://stackoverflow.com/q/49752100
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/120148295
has comment: http://stackoverflow.com/comment/105518710
has body: Well... the solution was quite easy, just reading the correct docs page I figured out how to solve my problem. Just create a new class which extends from fields. Field and override the _validate method as follows: class BytesField(fields.Field): def _validate(self, value): if not isinstance(value, bytes): raise ValidationError('Invalid input type.') if value is None or value == b'': raise ValidationError('Invalid value') And here's the marshmallow schema: class MySchema(Schema): // ... field = BytesField(required=True) // ... That's all. Sorry for wasting your time.
type: Answer
score: 15

http://stackoverflow.com/comment/86444776
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49715880
has text: @Axioms if you want it to be available for all functions in a class you can make it a class variable. Other than that nothing much to do but to write it in every function needed

http://stackoverflow.com/a/49720904
answers question: http://stackoverflow.com/q/49671889
score: 0
accepted answer of: http://stackoverflow.com/q/49671889
type: Answer
has body: Code: from bs4 import BeautifulSoup with open('/path/to/some.html') as f: soup = BeautifulSoup(f.read(), 'html.parser') service = soup.find('div', style='box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;').get_text(strip=True) cve_ids = [cve_elem.text for cve_elem in soup.select('table &gt; tbody &gt; tr &gt; td &gt; a')] protocol, port = soup.select_one('table &gt; h2').text.split('/') print('{}, {}/{}, CVE-IDs: {}'.format(service, protocol, port, cve_ids)) Output: 42263 - Unencrypted Telnet Server, tcp/23, CVE-IDs: ['CVE-2013-2566', 'CVE-2015-2808'] Notice usage of select() that works with CSS selectors. I also used &gt;, which is a child combinator. The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the children of elements matched by the first.
type: AcceptedAnswer

http://stackoverflow.com/a/49601455
downvote count: 0
has body: You can get all column names from cursor.description and use zip() function to construct a list of dicts: # prepare cursor and execute procedure conn = ... cursor = conn.cursor() cursor.callproc(...) # get only column names from cursor description column_names_list = [x[0] for x in cursor.description] # construct a list of dict objects (&lt;one table row&gt;=&lt;one dict&gt;) result_dicts = [dict(zip(column_names_list, row)) for row in cursor.fetchall()] Should be valid on SELECT statements as well.
answers question: http://stackoverflow.com/q/49601005
type: AcceptedAnswer
upvote count: 10
score: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/49601005

http://stackoverflow.com/q/49606909
tagged with: file
has comment: http://stackoverflow.com/comment/86220472
has comment: http://stackoverflow.com/comment/86220820
has answer: http://stackoverflow.com/a/49606931
has answer: http://stackoverflow.com/a/49606993
answer count: 4
duplicate of: http://stackoverflow.com/q/27805919
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49599623
type: UnansweredQuestion
downvote count: 0
has body: I am trying to extract specific information from a .txt file. I have figured out a way to isolate the lines I need; however, printing them has proven to be problematic. with open('RCSV.txt','r') as RCSV: for line in RCSV.read().splitlines(): if line.startswith(' THETA'): print(line.next()) When I use line.next() it gives me this error: "AttributeError: 'str' object has no attribute 'next'" Here is a link to the .txt file Here is a link to the area of the file in question What I'm trying to do is extract the line following the line that starts with 'THETA PHI' etc.
has answer: http://stackoverflow.com/a/49606943
upvote count: 1
tagged with: python
tagged with: string
has title: Extracting next line of text file
has comment: http://stackoverflow.com/comment/86220497
linked to: http://stackoverflow.com/q/27805919
score: 1
has answer: http://stackoverflow.com/a/49606998

http://stackoverflow.com/a/49678291
has body: The problem is that you have not established the QScrollArea as centralWidget. class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("My Awesome App") size = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) layout = QVBoxLayout() layout2 = QVBoxLayout() brw = Color2('brown') brw.setSizePolicy(size) layout2.addWidget(brw) layout2.addWidget(Color('black')) layout2.setStretch(1,2) layout2.addWidget(Color('cyan')) layout2.setStretch(2, 1) layout.addWidget(Color('red')) layout.addWidget(Color('blue')) layout.addWidget(Color('green')) self.scrollArea = QScrollArea() # set CentralWidget self.setCentralWidget(self.scrollArea) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget(self.scrollArea) self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 600, 500)) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.scrollAreaWidgetContents.setMinimumSize(QSize(500, 500)) self.scrollLayout = QVBoxLayout(self.scrollAreaWidgetContents) #self.scrollLayout.setSizeConstraint(QLayout.SetMinimumSize) #2 self.mainLayout = QHBoxLayout() self.mainLayout.addWidget(Color('purple')) self.mainLayout.addWidget(Color('yellow')) self.mainLayout.addWidget(Color('orange')) self.mainLayout.addLayout(layout2) self.mainLayout.addLayout(layout) self.scrollLayout.addLayout(self.mainLayout) self.show()
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49677073
has comment: http://stackoverflow.com/comment/86380249
has comment: http://stackoverflow.com/comment/86401331
answers question: http://stackoverflow.com/q/49677073
type: Answer
has comment: http://stackoverflow.com/comment/86380284

http://stackoverflow.com/a/49712268
score: 0
has comment: http://stackoverflow.com/comment/86439480
has comment: http://stackoverflow.com/comment/86453633
has comment: http://stackoverflow.com/comment/86453707
answers question: http://stackoverflow.com/q/49712191
has body: You can group by month-start ('MS') using resample: df.set_index('last_payout').resample('MS').sum().plot(kind='bar')
type: Answer
has comment: http://stackoverflow.com/comment/86438261

http://stackoverflow.com/q/49745153
has title: One to many queryset in django
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49752504
has body: I have 2 tables, Item and UserDetail. In table Item, I have item_id and item_name like this: My UserDetail table like this: I need to get user's username, and their most recent updated(e.g, Tina's education level was BSc on 05/01/2015 and changed to MSc on 05/01/2017. So I have to pick MSc for her education level), email, home phone, cellphone and education information. For any missing info, I leave it as blank. So my result would be: [{'username':John, 'email':'john@abs.com', 'homePhone':'', 'cellPhone':'', 'education':''}, {'username':Jade, 'email': jade@email.com, 'homePhone':111 456-7890, 'cellPhone':'','education':''}, {'username':Tina, 'email':'', 'homePhone':'', 'cellPhone':'211 234-5678', 'education':'Msc'},] Currently, I have queryset like this in my view.py: items=Item.objects.filter(Q(item_id__in=(2, 3, 4, 6))).values('item_name').order_by('item_id') users=[username1, username2, ...] for user in users: users_data = UserDetail.objects.filter(username=username)\ .filter(Q(id__in=(2,3, 4, 6)).values('id','record')\ .order_by('id').latest(DateRecorded) qs1=[user] for item in items: for value in users_data: user_data='' if item['item_id']== value['id']: user_data=value['record'] break qs1.append(data) qs2.append(qs1) This works OK. However, the format of qs2 is not exactly the one I expected. I am getting qs2 like this: [[u'John', u'john@abs.com', u'', u'', u''], [u'Jade', u'jade@email.com', u'111 456-7890',u'',u''], [u'Tina', u'', u'', u'211 234-5678', u'mac'],] Also, it takes more time to get the result back. Does anyone have good suggestion on this? Add more comments on this: Right now, I have data like this: users_data= &lt;QuerySet [{u'username': u'john', u'id': u'2', u'record': u'joh@abc.com'}, {u'username': u'jade', u'id': u'2', u'record': u'jade@email.com'}, {u'username': u'jade', u'id': u'3', u'record': u'111 456-7890'}....] Would prefer to construct the final data like: by_username = [{u'username': u'john', u'email': u'joh@abc.com'}, {u'username': u'…
score: 0
answer count: 2
tagged with: django
has answer: http://stackoverflow.com/a/49746307

http://stackoverflow.com/q/49608160
tagged with: list
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/86223091
has title: Python List of Strings
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x
has body: Given a list of strings, return a list with the strings in sorted order, except group all the strings that begin with 'x' first. For instance: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] Hint: this can be done by making 2 lists and sorting each of them before combining them.
has answer: http://stackoverflow.com/a/49608234
accepted answer: http://stackoverflow.com/a/49608327
has answer: http://stackoverflow.com/a/49608166
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/49608327
possible better answer: http://stackoverflow.com/a/49608206
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49608206

http://stackoverflow.com/comment/86400211
score: 0
comment on: http://stackoverflow.com/q/49690321
type: QuestionComment
has text: @DanD.: Python allows only one module per `.so` _name_—you can use multiple links to one file as one module each.
type: Comment

generator
type: Tag
tags question: http://stackoverflow.com/q/49696421
tags question: http://stackoverflow.com/q/49749033
tag name: generator
tags question: http://stackoverflow.com/q/49710035
tags question: http://stackoverflow.com/q/49654085
tags question: http://stackoverflow.com/q/49752452
tags question: http://stackoverflow.com/q/49631008
tags question: http://stackoverflow.com/q/49617233
tags question: http://stackoverflow.com/q/49609811
tags question: http://stackoverflow.com/q/49618352
tags question: http://stackoverflow.com/q/49642607

http://stackoverflow.com/q/49706503
type: UnansweredQuestion
has body: I successfully processed a video and had the algorithm detect faces, but I am attempting to detect faces in real-time, capturing images from the screen (such as when I'm playing games, etc.) This is the bit of the code I used to process a captured video: capture = cv2.VideoCapture('source_video.avi') How can I change this to capture images from the screen in real-time? Please give me some code examples if possible.
downvote count: 2
answer count: 1
favorite count: 0
tagged with: opencv
has title: Real-time screen capture and feature detection using OpenCV
tagged with: python
has answer: http://stackoverflow.com/a/49706555
type: Question
score: 0
tagged with: yolo
upvote count: 2

http://stackoverflow.com/comment/86251012
comment on: http://stackoverflow.com/q/49622024
type: Comment
score: 0
has text: My version is Python 3.6
type: QuestionComment

http://stackoverflow.com/a/49630954
type: Answer
answers question: http://stackoverflow.com/q/49630802
score: 5
downvote count: 0
type: AcceptedAnswer
has body: From Django's source code below, it is almost the same. Both methods call the _chain method. With filter, you create a Q object without any children, but the overhead is not much. Using all is nonetheless preferable as it is avoiding unnecessary code to be executed. def all(self): """ Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._chain() def filter(self, *args, **kwargs): """ Return a new QuerySet instance with the args ANDed to the existing set. """ return self._filter_or_exclude(False, *args, **kwargs) def _filter_or_exclude(self, negate, *args, **kwargs): if args or kwargs: assert self.query.can_filter(), \ "Cannot filter a query once a slice has been taken." clone = self._chain() if negate: clone.query.add_q(~Q(*args, **kwargs)) else: clone.query.add_q(Q(*args, **kwargs)) return clone
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49630802

http://stackoverflow.com/comment/86419791
comment on: http://stackoverflow.com/a/49699160
type: Comment
score: 0
type: AnswerComment
has text: I also tried this, but got only 14 items printed. I guess this is because the table component that I want to retrieve has 14 items initially when not scrolled. How can I retrieve total items including scrolled down items.

http://stackoverflow.com/comment/86730973
comment on: http://stackoverflow.com/a/49855617
type: Comment
score: 0
type: AnswerComment
has text: I just run it on my end with np.random.seed(7), I got: [array([ 0.46554423]), array([ 0.53445577])] 5.32693337325

http://stackoverflow.com/comment/95480543
comment on: http://stackoverflow.com/q/49683697
score: 0
type: QuestionComment
has text: Also, try creating a virtualenv and install dask in it.
type: Comment

http://stackoverflow.com/comment/121996476
type: Comment
type: AnswerComment
has text: @levsa: This PEP is meant for Python 3.9 and newer, if you want to try this for older Python versions (from 3.7) you have to use `from __future__ import annotations` to be forward-compatible.
comment on: http://stackoverflow.com/a/68097210
score: 1

http://stackoverflow.com/comment/86523766
score: 1
type: QuestionComment
has text: What's your code so far?
type: Comment
comment on: http://stackoverflow.com/q/49754529

http://stackoverflow.com/comment/86331200
type: QuestionComment
score: 0
has text: @Alasdair i've updated my base.html again to show the full content of what i have. I dont understand what youre asking in regards to "is 'question' set in a loop?" from what i've understood from the tutorials i've followed, the html pulls question.user.username from my model in models.py or views.py. Could you please direct me to an example of what you mean? is there a better location to place this url? i was trying to do something similar to how stackoverflow has their 'user activity' button that is to the right of the search bar.
type: Comment
comment on: http://stackoverflow.com/q/49654973

http://stackoverflow.com/comment/86404226
comment on: http://stackoverflow.com/q/49694832
has text: Do you mean when pickling? My `__getstate__` has no problems (if I call it, I get the correct results). The problem is that the pickling method is not calling my custom method at all, instead throwing this exception.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/120661843
comment on: http://stackoverflow.com/a/49712185
score: 0
type: Comment
has text: Thanks, m8. That's exactly what was wrong with mine, at least.
type: AnswerComment

http://stackoverflow.com/comment/86325494
type: Comment
comment on: http://stackoverflow.com/a/49657988
score: 0
type: AnswerComment
has text: How would I get the output to show the students ID number and print the highest score out of the the total attempts. Something like:

http://stackoverflow.com/comment/86351369
has text: If I reduced the list to say cats = ["ronny"] and age = ["5"] how could I still use this but without experiencing an out of range error
type: AnswerComment
comment on: http://stackoverflow.com/a/49670375
score: 0
type: Comment

visual-studio
tags question: http://stackoverflow.com/q/49618052
type: Tag
tags question: http://stackoverflow.com/q/49668165
tags question: http://stackoverflow.com/q/49722928
tag name: visual-studio
tags question: http://stackoverflow.com/q/49653161

http://stackoverflow.com/comment/86419969
type: Comment
type: QuestionComment
has text: You must have a (C-level) stack trace? If not, attach a debugger to Python before calling this function.
score: 0
comment on: http://stackoverflow.com/q/49703186

http://stackoverflow.com/comment/86530925
comment on: http://stackoverflow.com/q/49757979
type: QuestionComment
has text: Your desired output is not valid python
type: Comment
score: 4

min
type: Tag
tags question: http://stackoverflow.com/q/49640751
tags question: http://stackoverflow.com/q/49754041
tag name: min

http://stackoverflow.com/comment/86317148
comment on: http://stackoverflow.com/q/49639586
type: Comment
type: QuestionComment
score: 0
has text: @abarnert I can't provide a minimal complete verifiable example since I don't know how to do what I want to do, and that is what I am asking: How can I pass arguments to `__init__` method in `MyPipeline` **without** using the `@classmehod def from_crawler` as suggested in the [docs](https://doc.scrapy.org/en/latest/topics/item-pipeline.html)

http://stackoverflow.com/q/49732911
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86479616
tagged with: machine-learning
tagged with: scikit-learn
tagged with: text-classification
score: 0
tagged with: pandas
has body: I am working on text classification problem. Here is my dataset Narration | Category _________________________________________________________ clg cr: ten plus |transfer to ten plus At Sydney, Garment payment BY Mr.Haj |Transfer From Mr.Haj RTGS-CPU Wales-Steven |Transfer from Steven NEFT-Payment-Amy Adams/12march/XXXX4567 |Transfer from Amy Adams KFC Chicken Burger |Food Trent Wines and Rum |Alcohol CD-Payment-2345XXX78 Imran |Transfer from Imran . . . . . . The problem is I have huge volume of data-set to train, (around 3 million entries) as a result there are lot of categories formed (around 500k categories) It is not possible for me to train the machine with so many categories. The problem is with the individual transfer, Example in the dataset: (Transfer From Mr.Haj, Transfer from Steven, ......) I don't want to loose significance of narrations too as a result I dont want to generalise as "Transfer to XX" instead of party name. My two questions are: 1. How do I train the data with so many categories. 2. How Do I handle the party name while testing (Example: Mr.Haj, Steven) with similar kind of test narration data and get the categorized output as Transfer to Customer. part of my script: from sklearn.model_selection import train_test_split data= pd.read_csv('file.txt', delimiter='\t',usecols=['Narration','Category'],encoding=("utf-8")) target_one=data['Category'] test_data= pd.read_csv('test_file.txt', delimiter='\t',usecols=['Narration','Category'],encoding=("utf-8")) x_train, y_train = (data.Narration, data.Category ) x_test, y_test = (test_data.details, test_data.category) from nltk.corpus import stopwords vect = CountVectorizer(ngram_range=(1,2),stop_words='english') X_train = vect.fit_transform(x_train) X_test = vect.transform(x_test) mnb = MultinomialNB(alpha =0.13) mnb.fit(X_train,y_train)
has title: Memory Error due to a lot of Categories
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86479824

http://stackoverflow.com/a/49756684
downvote count: 0
has body: In the link you have included sets num words to a miximum. Apply a small maximum to overcome your memory issues. max_words=100000 tokenizer = Tokenizer(num_words=max_words) ...
upvote count: 1
answers question: http://stackoverflow.com/q/49731355
type: Answer
accepted answer of: http://stackoverflow.com/q/49731355
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49723810
has body: For canonical reference I'm adding this solution for those who prefer an explicitly arithmetic solution. element_result = tf.cast(1.5 - tf.abs(label-prediction), tf.int8) # 1.5 due to floor rounding row_result = tf.reduce_all(tf.cast(element_result, tf.bool), axis=1) # AND 'em together accuracy = tf.reduce_mean(tf.cast(row_result, tf.float32))
score: 0
answers question: http://stackoverflow.com/q/49712104
type: Answer

http://stackoverflow.com/comment/86295831
comment on: http://stackoverflow.com/a/49613177
type: AnswerComment
score: 0
has text: I didn't check it but I think it is a unix timestamp
type: Comment

http://stackoverflow.com/comment/86262826
comment on: http://stackoverflow.com/a/49616812
type: AnswerComment
has text: Please include JavaScript callbacks example too.
score: 1
type: Comment

http://stackoverflow.com/a/49684836
score: 56
has body: List comprehension inside Spark's array a = [1,2,3,4,5,6,7,8,9,10] df = spark.createDataFrame([['a b c d e f g h i j '],], ['col1']) df = df.withColumn("NewColumn", F.array([F.lit(x) for x in a])) df.show(truncate=False) df.printSchema() # +--------------------+-------------------------------+ # |col1 |NewColumn | # +--------------------+-------------------------------+ # |a b c d e f g h i j |[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]| # +--------------------+-------------------------------+ # root # |-- col1: string (nullable = true) # |-- NewColumn: array (nullable = false) # | |-- element: integer (containsNull = false) @pault commented (Python 2.7): You can hide the loop using map: df.withColumn("NewColumn", F.array(map(F.lit, a))) @ abegehr added Python 3 version: df.withColumn("NewColumn", F.array(*map(F.lit, a))) Spark's udf # Defining UDF def arrayUdf(): return a callArrayUdf = F.udf(arrayUdf, T.ArrayType(T.IntegerType())) # Calling UDF df = df.withColumn("NewColumn", callArrayUdf()) Output is the same.
type: Answer
has comment: http://stackoverflow.com/comment/113879430
has comment: http://stackoverflow.com/comment/116723717
has comment: http://stackoverflow.com/comment/86381600
has comment: http://stackoverflow.com/comment/86407141
downvote count: 0
answers question: http://stackoverflow.com/q/49683897
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86381486
has comment: http://stackoverflow.com/comment/116725007
accepted answer of: http://stackoverflow.com/q/49683897
has comment: http://stackoverflow.com/comment/113880643
upvote count: 56

http://stackoverflow.com/a/49756486
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49755066
has body: What do you have as your default charset in settings.py? This is what I have in my settings.py: DEFAULT_CHARSET = 'UTF-8' Anyways mysql and charsets can be a bit of a pain in the behind sometimes. See this reddit thread: https://www.reddit.com/r/programming/comments/6mksng/how_we_almost_lost_an_important_client_because_of/ Which links to this article: https://www.eversql.com/mysql-utf8-vs-utf8mb4-whats-the-difference-between-utf8-and-utf8mb4/

http://stackoverflow.com/a/50068575
type: Answer
has body: When you use readlines, you get linefeed/newline characters. If you do a print(repr(image_path)) You'll see newlines (\n) in the output. Use strip() to remove whitespace (spaces, tabs, newlines, carriage returns) a the beginning and end of strings. So your code becomes: import os import cv2 PATH_IN = 'D:\\user\\data\\Augmentation' path_out = 'D:\\user\\data\\Augmentation\\images_90t' try: if not os.path.exists('images_90t'): os.makedirs('images_90t') except OSError: print ('Error: Creating directory of data') with open('filelist.txt', 'r') as f: for image_path in f.readlines(): print(repr(image_path)) # will show the newlines \n in image_path image_path = image_path.strip() image = cv2.imread(image_path) print("The type of image is: " , type(image)) # OUTPUT: The type of image is: &lt;class 'NoneType'&gt; (h, w) = image.shape[:2] center = (w / 2, h / 2) M = cv2.getRotationMatrix2D(center, 90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) #cv2.imshow("rotated", rotated) path_out = os.path.join(path_out, os.path.basename(image_path)) cv2.imwrite(path_out, rotated) cv2.waitKey(0) I also fixed up your path_out assignment to put all of the output files in the right place.
has comment: http://stackoverflow.com/comment/87161475
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49606213
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49606213

http://stackoverflow.com/q/49663567
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86337479
has comment: http://stackoverflow.com/comment/86353451
has comment: http://stackoverflow.com/comment/86337802
has comment: http://stackoverflow.com/comment/86337081
has comment: http://stackoverflow.com/comment/86386949
type: Question
accepted answer: http://stackoverflow.com/a/49692421
has title: Python multiprocess seems not working
has comment: http://stackoverflow.com/comment/86362314
answer count: 1
has comment: http://stackoverflow.com/comment/86337439
downvote count: 0
has comment: http://stackoverflow.com/comment/86363414
upvote count: 1
has comment: http://stackoverflow.com/comment/86389989
has comment: http://stackoverflow.com/comment/86362169
favorite count: 0
has comment: http://stackoverflow.com/comment/86361960
tagged with: multiprocessing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49692421
has body: I am learning Python multiprocessing, this is my code: import multiprocessing as mp import time def cube(list_i, result_i): for i in list_i: result_i[i]=i**3 return def test(): result_i=list(range(10000000)) list_i=list(range(10000000)) single=mp.Process(target=cube, args=(range(10000000),result_i)) t=time.time() single.start() single.join() print(time.time()-t) multiple=[mp.Process(target=cube, args=(i, result_i)) for i in [range(i*2500000, i*2500000+2500000) for i in range(4)]] t=time.time() for process in multiple: process.start() for process in multiple: process.join() print(time.time()-t) return if __name__=='__main__': test() output: 12.0096 32.0467 It seems that single process is faster? My computer's cpu is i5-5200 with 4 cores.

http://stackoverflow.com/q/49675618
duplicate of: http://stackoverflow.com/q/1132941
type: Question
linked to: http://stackoverflow.com/q/1132941
has body: I was tring to build a trie tree base on a word list, below is the node class defintion, self.next_trees for children of the node. class Node(object): def __init__(self, charactor, tree_dict={}): self.charactor = charactor self.next_trees = tree_dict self.is_end = False and build the tree use this function def build_tree(words): root = Node(None) for word in words: trace = root.next_trees for i,c in enumerate(word): if c not in trace: trace[c] = Node(charactor=c) pdb.set_trace() if i == len(word)-1: trace[c].is_end = True else: trace = trace[c].next_trees else: trace = trace[c].next_trees return root each time when the codes run to the break point, the object "trace" refers to is exactly the same object "trace[c].next_trees" refer to,rather than a empty dict"{}" enter image description here and I copy similiar codes to a new .py file and run, it won't happen again.why it happens here?(python version 2.7.12)
tagged with: python
accepted answer: http://stackoverflow.com/a/49675763
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49675763
has title: python object member refer to itself incorrectly
answer count: 1

http://stackoverflow.com/comment/86221850
score: 1
type: Comment
type: QuestionComment
has text: When you turn a **list** into a **set**, you lose any duplicates.
comment on: http://stackoverflow.com/q/49607601

http://stackoverflow.com/q/49636061
tagged with: python
has comment: http://stackoverflow.com/comment/86280050
has comment: http://stackoverflow.com/comment/86310587
has title: multiprocessing on python on windows server
type: Question
has comment: http://stackoverflow.com/comment/86284288
answer count: 0
type: UnansweredQuestion
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/86279635
has comment: http://stackoverflow.com/comment/86316931
score: 0
has body: I am trying to run my code on a Windows server with 56 cores, but it seems very slow. I am using a multiprocessing package on python 3. Here is part of my code. iterable = chunks pool = multiprocessing.Pool(processes=num_processes) func = partial(functions.Calcualtion, df2, df1) res = pool.map(func, iterable) pool.close() I have a DF that I divided it into chunks and two other dfs, df1, df2 that are the same for all calculations. I have defined functions that do the calculation. When it was running on my machine with 4 core it was faster than the server. Any idea what is the possible problem?

http://stackoverflow.com/comment/86455275
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49711216
type: Comment
has text: I thought the same.but this is 24 .OP wants 24*12

pyad
tag name: pyad
tags question: http://stackoverflow.com/q/49632933
type: Tag

http://stackoverflow.com/q/49631870
tagged with: python-2.7
downvote count: 0
has title: python pandas csv to html UnicodeEncodeError
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86270782
favorite count: 0
has answer: http://stackoverflow.com/a/49632124
type: Question
tagged with: pandas
tagged with: python
type: UnansweredQuestion
has body: I was trying to convert a csv data to html using Pandas. But i was getting the below error UnicodeEncodeError('ascii', u'', 10305, 10306, 'ordinal not in range(128)') How to resolve this issue

http://stackoverflow.com/a/49740864
has body: As discussed for instance here, it is not supported out-of-the-box (same is true for Decision Tree). So as mentioned there, you would have to implement a custom Criterion in Cython here, as Python would be too slow. Or more specifically here, where the Median is calculated, in the tree package and add it to the dictionary CRITERIA_REG, here.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49739047
answers question: http://stackoverflow.com/q/49739047
type: Answer
score: 0

xcode
tag name: xcode
type: Tag
tags question: http://stackoverflow.com/q/49688197

http://stackoverflow.com/q/49756030
has body: The input data I have is basically a step and hold ramp function. The output data spikes at the start each of these hold regions. Here is the data in a figure, input in green, output in blue I would like to take the average of the regions just after the spikes (Essentially the red regions in the plot) It seems like the binned_statistics method in the scipy package would work great for this, but I don't see how I could remove the spikes from the averaging. What I've got so far: avg_in, avg_out = stats.binned_statistic(input, [input, output], 'mean', bins=12)[0] Ideally I would ignore the first 10% of each bin or something. Here is some sample data. Im using pandas to read it in.
has comment: http://stackoverflow.com/comment/86530294
has answer: http://stackoverflow.com/a/49758652
has comment: http://stackoverflow.com/comment/86528276
tagged with: pandas
has title: Ignoring x% of front part of each bin in scipy.stats.binned_statistic
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86531327
has comment: http://stackoverflow.com/comment/86531118
tagged with: scipy
accepted answer: http://stackoverflow.com/a/49758652
type: Question
has comment: http://stackoverflow.com/comment/86529853
tagged with: numpy
has comment: http://stackoverflow.com/comment/86529816
has comment: http://stackoverflow.com/comment/86528825
tagged with: python
has comment: http://stackoverflow.com/comment/86530227
tagged with: statistics
type: AnsweredQuestion

http://stackoverflow.com/comment/86246381
has text: check this [Zip in Python](https://medium.com/@happymishra66/zip-in-python-48cb4f70d013)
comment on: http://stackoverflow.com/q/49619662
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86486035
type: QuestionComment
score: 0
has text: Okay so i tried running the above command and it shows a pop up that tesseract.exe has stopped working. I already reinstalled the Tesseract-OCR engine.
comment on: http://stackoverflow.com/q/49734789
type: Comment

http://stackoverflow.com/comment/86442200
type: Comment
type: QuestionComment
has text: Do you want to convert the `str` to `bytes`?
comment on: http://stackoverflow.com/q/49714520
score: 0

http://stackoverflow.com/q/49710683
downvote count: 1
has answer: http://stackoverflow.com/a/49710728
has comment: http://stackoverflow.com/comment/86435282
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86435415
has body: How do you get the very next list within a nested list in python? I have a few lists: charLimit = [101100,114502,124602] conditionalNextQ = [101101, 101200, 114503, 114504, 124603, 124604]` response = [[100100,4] ,[100300,99] ,[1100500,6] ,[1100501,04] ,[100700,12] ,[100800,67] ,[100100,64] ,[100300,26] ,[100500,2] ,[100501,035] ,[100700,9] ,[100800,8] ,[101100,"hello"] ,[101101,"twenty"] ... ] for question in charLimit: for limitQuestion in response: limitNumber = limitQuestion[0] if question == limitNumber: print(limitQuestion) The above code is doing what I want, i.e. printing the list instances in response when it contains one of the numbers in charlimit. However, I also want it to print the immediate next value in response also. For example the second-to-last value in response contains 101100 (a value thats in charlimit) so I want it to not only print 101100,"hello" (as the code does at the moment) but the very next list also (and only the next) 101100,"hello" 101101,"twenty" Thank is advance for any help here. Please note that response is a verrrrry long list and so I'm looking to make things fairly efficient if possible, although its not crucial in the context of this work. I'm probably missing something very simple but cant find examples of anyone doing this without using specific indexes in very small lists.
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/49710932
tagged with: nested-lists
has answer: http://stackoverflow.com/a/49710932
type: Question
upvote count: 2
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/49710728
has title: Get just the very next list within a nested list in python

http://stackoverflow.com/comment/86311338
comment on: http://stackoverflow.com/a/49651569
type: Comment
score: 0
type: AnswerComment
has text: `arrivaltime <= logtime and logtime <= begintime` can be written `arrivaltime <= logtime <= begintime` in Python. Means the same thing.

http://stackoverflow.com/comment/86474878
comment on: http://stackoverflow.com/a/49730494
type: AnswerComment
has text: thankyou,but this one works for the second case. What about this "JAN07" ?
score: 0
type: Comment

http://stackoverflow.com/comment/86618250
comment on: http://stackoverflow.com/a/49770041
type: Comment
type: AnswerComment
has text: Ah, as Zac mentions, I had missed your requirement that *each* integer should be unique. I'll update the answer to take that into account.
score: 0

http://stackoverflow.com/comment/86244675
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49618232
type: Comment
has text: Ah you hero thank you. Ofc it happens below it and that's why it can run once

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/49748640
tags question: http://stackoverflow.com/q/49715435
tag name: countvectorizer
tags question: http://stackoverflow.com/q/49618950

http://stackoverflow.com/comment/86213213
has text: It does makes sense in the pyhton side. I do believe that my implementation of passing the arguments in VB are incorrect. If is write this: .StartInfo.Arguments = "HelloWorld.py" the python code works as expected. But if I write this: .StartInfo.Arguments = ("HelloWorld.py" & arg1) then the python code does not work at all.
comment on: http://stackoverflow.com/a/49602647
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49731193
type: Question
linked to: http://stackoverflow.com/q/11089850
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49731300
has title: Django Form Does Not Find Right ID int Increment on Production vs LH
answer count: 2
tagged with: modelform
has answer: http://stackoverflow.com/a/49733261
score: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: django-forms
favorite count: 0
has body: For some reason on Localhost (LH) everything works fine but on my Production server, my form does not add a new user submission properly. The error I am getting is: duplicate key value violates unique constraint "..." DETAIL: Key (id)=(8) already exists. Is there some sort of production "sudo systemctl restart gunicorn" I need to run (I have already tried the example above)? Maybe it's only working on LH because there I have tested there more and the increment naturally fell on the same level as the total amount of users? I really am out of ideas here. models.py class Lead(models.Model): username = models.CharField(max_length=15, blank=True, null=True) email = models.CharField(unique=True, max_length=150, validators=[validate_email]) created = models.DateTimeField(auto_now_add=True) ... forms.py class LeadCaptureForm1(forms.ModelForm): birth_date = forms.DateField(widget=SelectDateWidget(years=range(1999, 1910, -1))) class Meta: model = Lead widgets = { 'email': forms.TextInput(attrs={'class': 'form-control'}), } fields = ('email', 'birth_date',) views.py def iframe1(request): ip = get_real_ip(request) created = timezone.now() if request.method == 'POST': form = LeadCaptureForm1(request.POST) if form.is_valid(): # Save lead lead = form.save() # attempt at fixing it #lead.id = Lead.objects.get(all).count() #print(lead.id) lead.created = created lead.birth_date = form.cleaned_data.get('birth_date') lead.ipaddress = get_real_ip(request) lead.joinmethod = "Iframe1" lead.save() print(lead)

http://stackoverflow.com/a/49632426
answers question: http://stackoverflow.com/q/49632311
score: 0
has body: Yes, else only refers to the last if written. You might want to use elif instead of the 2nd if, which will break the loop if the condition on the first if is met. x = input("Numeral: ") y = input("Numeral: ") if x &lt; y: print(f'{x} is less than {y}.') elif x &gt; y: print(f'{x} is greater than {y}.') else: print(f'{x} is equal to {y}.')
type: Answer

http://stackoverflow.com/comment/86323044
comment on: http://stackoverflow.com/q/49656326
type: Comment
has text: `django.setup()` is for use in stand alone scripts. You shouldn't put it in settings. I always wonder why people are trying to add it to settings. Perhaps it's [the question](https://stackoverflow.com/questions/34114427/django-upgrading-to-1-9-error-appregistrynotready-apps-arent-loaded-yet) you linked to.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/112920749
score: 0
type: Comment
has text: hi. what if in the above code I want to increase and decrease the size of the mask as per the user's request?
comment on: http://stackoverflow.com/a/49758379
type: AnswerComment

http://stackoverflow.com/comment/86267707
comment on: http://stackoverflow.com/q/49630322
score: 0
type: QuestionComment
type: Comment
has text: @ScottHunter Humm... In that case will the test be done at each iteration of the loop? Or will it be optimized away?

http://stackoverflow.com/comment/101602097
type: Comment
has text: Ofcours there is something wrong with xarray. Tools are there to make our life easier not harder. In this case the developer should take care about the issue.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49853048

http://stackoverflow.com/a/49603056
answers question: http://stackoverflow.com/q/49602333
type: Answer
accepted answer of: http://stackoverflow.com/q/49602333
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: from wordpress_xmlrpc import Client from wordpress_xmlrpc.methods import posts wp = Client(wp_url, wp_username, wp_password) posts = wp.call(posts.GetPosts()) values = ','.join(str(v) for v in posts) # Changes list to a string Then you can just check the string for matches. if title in values: print('Post already exists!') continue else: pass Hope this helps someone in the future.

http://stackoverflow.com/comment/86398029
type: Comment
comment on: http://stackoverflow.com/q/49630662
has text: @TarunLalwani, no because it doesn't generate class source code. It just works during runtime. I want class code so that PyCharm or vim etc do IDE support during development.
type: QuestionComment
score: 0

http://stackoverflow.com/q/49756175
favorite count: 0
type: Question
has body: How to find next value after building a decision tree from the training set? I need to know probability for next value of the A field in my example, when I put B and C values. df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 3)), columns=['a', 'b', 'c']) &gt;&gt;&gt; a b c 0 2 8 8 1 4 2 9 2 1 0 7 3 5 1 7 4 6 0 2 X = df[ ['b','c'] ] Y = df[ ['a'] ] clf = DecisionTreeClassifier(random_state=241) clf.fit(X, Y) How to find out probability of the next value for field A if B=8, C=8 ?
upvote count: 0
tagged with: machine-learning
has title: DecisionTreeClassifier how to find next value
tagged with: python
accepted answer: http://stackoverflow.com/a/49757139
has answer: http://stackoverflow.com/a/49757139
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86548730
answer count: 1
tagged with: scikit-learn
downvote count: 1
score: -1

http://stackoverflow.com/q/49646959
has answer: http://stackoverflow.com/a/49647022
upvote count: 4
has title: How can I include missing items using groupby in Pandas?
score: 3
has comment: http://stackoverflow.com/comment/86302017
tagged with: pandas
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49647049
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has body: Let's say I have a dataframe with the following columns: date, time, day, month, year, description, price, type, manufacturer Using pandas and value_counts(), I can get the count for every unique item in a column: df.manufacturer.value_counts() Also, using groupby I can get the average price for every day in my data: df.groupby("day").price.mean() The issue with that is there are 7 days in total but in my data there might be only 5 or 6, so I need to add the missing days with the mean being zero or None. In general, if I have a specific list how do I include the missing items when I do something like value_counts or groupby operations ?

http://stackoverflow.com/q/49738518
has comment: http://stackoverflow.com/comment/86491498
tagged with: python
score: -1
type: Question
has body: I want to access one class attribute s and split it into 2 strings in another class. Any tips? class lyssna: def du(): s = '5-22' class Fixish(): strt, stpp = lyssna.s.split('-')
upvote count: 0
type: UnansweredQuestion
answer count: 1
has title: AttributeError: type object 'lyssna' has no attribute 's'
has comment: http://stackoverflow.com/comment/86491658
has comment: http://stackoverflow.com/comment/86491690
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/19326004
has answer: http://stackoverflow.com/a/49738844
tagged with: class-attributes

http://stackoverflow.com/comment/105242267
has text: The calendar popup is not dismissed after send keys. How can I make the calendar dismissed?
comment on: http://stackoverflow.com/a/49748121
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86211313
score: 2
comment on: http://stackoverflow.com/q/49602041
has text: Would depend on how the images are stored in each row. But, for a general theory on such transformations, follow this - https://stackoverflow.com/questions/47977238/intuition-and-idea-behind-reshaping-4d-array-to-2d-array-in-numpy
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49639744
type: Answer
has comment: http://stackoverflow.com/comment/86287684
has comment: http://stackoverflow.com/comment/86287291
has comment: http://stackoverflow.com/comment/86287437
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49639122
has body: You don't need recursion here. You just have to build a current list until you find a special number. Then yield the current list and the singleton with the special number. Don't forget to yield the current list at the end if it is not empty. xs = list(range(1, 11)) s = set([5,8]) def gen(xs, s): cur = [] for x in xs: if x in s: if cur: yield cur yield [x] cur = [] else: cur.append(x) if cur: yield cur print (list(gen(xs, s))) # output: [[1, 2, 3, 4], [5], [6, 7], [8], [9, 10]] You may also use a pair of indices and yield slices. EDIT To group special codes together, you just need a little adaptation of the loop: def func(xs, s): cur = [] for x in xs: if x in s: # a special code if cur and cur[-1] not in s: # cur is not special yield cur # yield it cur = [] # and restart else: # a non special code if cur and cur[-1] in s: # cur is special yield cur # yield it cur = [] # and restart cur.append(x) # always add the current code to cur if cur: yield cur
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49639122
score: 1

http://stackoverflow.com/a/49621728
downvote count: 0
has body: One liner python approach using list comprehension: [group.to_csv(data, 'data_' + index + '.txt', sep = '\t', header = True, index=False) for index, group in my_df.groupby('chr')]
type: Answer
answers question: http://stackoverflow.com/q/49621634
score: 1
upvote count: 1

http://stackoverflow.com/a/49642283
has body: I don't think a simple reference to dict.items() should be counted a full fledged answer but since you insist: state_values = [value for key, value in kwargs.items() if key.startswith("state_")] The issue was due to kwargs being a dict, and if you want to do a parameter expansion into key and value, you have to use kwargs.items(). This will return a list of key-value tuples which can then be readily expanded into, well, key and value. Beware that in Python 2.x dict.items() creates a whole list of key-value tuples instead of just giving you an iterator. To avoid needless resource usage, use dict.iteritems() instead.
accepted answer of: http://stackoverflow.com/q/49642103
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49642103

http://stackoverflow.com/comment/89289422
has text: the above commands for my windows 10 and python 3.6.5 gave error `The target principal name is incorrect.` how did get this one working.
type: AnswerComment
comment on: http://stackoverflow.com/a/50265809
score: 1
type: Comment

http://stackoverflow.com/q/49674049
type: UnansweredQuestion
tagged with: autocomplete
has answer: http://stackoverflow.com/a/49682472
tagged with: input
tagged with: python
tagged with: gtk
score: 2
has body: How can i use Gtk+ 3 EntryCompletion and Entry to show auto completion suggestions even if the entry is empty? I tried forcing the entry to show the auto completion with completion.complete() but it does not work. My code looks something like this: class MainWindow(Gtk.Window): def init(self): Gtk.Window.init(self, title="...") # ... self.liststore = Gtk.ListStore(str) self.completion = Gtk.EntryCompletion() self.completion.set_model(self.liststore) self.completion.set_text_column(0) #... for h in history: self.liststore.append((h,)) #... self.query_entry = Gtk.Entry() self.query_entry.set_completion(self.completion) self.completion.complete() Another thing i would like to know: If i want to auto-complete file paths, how can i force showing the auto completion suggestions right after i selected an auto completion?
downvote count: 0
answer count: 1
tagged with: gtk3
has title: How to show autocompletion for empty Gtk+ Entry
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86376330
upvote count: 2

http://stackoverflow.com/comment/86215220
type: AnswerComment
comment on: http://stackoverflow.com/a/49603903
type: Comment
has text: That's literally all I needed to know. Thank you very much. I was screwing up on not assigning variables to the result of functions.
score: 0

http://stackoverflow.com/comment/86364474
has text: @abarnert Mmm, not sure what you mean by telepathy here. Please take a look to [this](https://dl.dropboxusercontent.com/s/slm2gn6k0przq1o/chrome_2018-04-05_17-49-52.png), that's the way i see the structure of this question. IMHO you could say there is no explicit question formulated or the title is not google-friendly... but what I see here is one question where the author didn't probably understand very well what the docs were saying about an specific function. Just asking you because I'd personally like to learn how these type of questions should be edited... how would you improve it?
comment on: http://stackoverflow.com/q/49661963
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86352374
comment on: http://stackoverflow.com/q/49671116
has text: `f.write(hex(i))` writes a *minimum* of 3 characters: `"0x"` followed by the actual number as a hex. That number can be longer than a single character as well, i.e. `255` would be `"0xFF"`, 4 characters. It is entirely unsurprising that your file ends up much larger than 2^20 bytes, since you write *at least* 3 times that many chars to it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49691955
has title: Python, effect of parentheses on booleans in print statement
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49692061
accepted answer: http://stackoverflow.com/a/49692061
favorite count: 0
type: Question
tagged with: python-3.x
has body: Would you please explain to me why the parentheses affect the output of booleans passed to a print statement? Example: print(True and False) or (True or False) # False or True # Python 2.7 &gt;&gt;&gt; True # Python 3.6 &gt;&gt;&gt; False But when I use parentheses: print((True and False) or (True or False)) # False or True # Python 2.7 &gt;&gt;&gt; True # Python 3.6 &gt;&gt;&gt; True Does the interpreter in Python 3 only see the first part (the one inside the first parentheses)? if so, why it doesn't throw an error for the rest of the line? Other examples: print(True and True) and (True and False) # True and False # Python 2.7 &gt;&gt;&gt; False # Python 3.6 &gt;&gt;&gt; True print((True and True) and (True and False)) # True and False # Python 2.7 &gt;&gt;&gt; False # Python 3.6 &gt;&gt;&gt; False print(True and True) and not (False or True) # True and not True # Python 2.7 &gt;&gt;&gt; False # Python 3.6 &gt;&gt;&gt; True print((True and True) and not (False or True)) # True and not True # Python 2.7 &gt;&gt;&gt; False # Python 3.6 &gt;&gt;&gt; False print(False or True) and not (True and True) # True and not True # Python 2.7 &gt;&gt;&gt; False # Python 3.6 &gt;&gt;&gt; True print((False or True) and not (True and True)) # True and not True # Python 2.7 &gt;&gt;&gt; False # Python 3.6 &gt;&gt;&gt; False UPDATE FROM ANSWERS AND COMMENTS: my question in BOLD: In Python3, print is a function. print(True and False) is None, and print(True and False) or (True or False) is the same as None and (True or False) which is False, as None is false-y in boolean context. isn't like telling the interpreter to print something or evaluate other stuff? how can this be a valid syntax? since the first part was evaluated to None then the second evaluation: None and (True or False) shouldn't print anything unless i run it in the shell. for example: running None and (True or False) wouldn't print the result to user if it run in a code editor like SublimeText3 (I don't use any extra pl…
has answer: http://stackoverflow.com/a/49692056
possible better answer: http://stackoverflow.com/a/49692056
has answer: http://stackoverflow.com/a/49692094
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3

http://stackoverflow.com/q/49692635
upvote count: 2
type: UnansweredQuestion
has title: Threading, multiprocessing shared memory and asyncio
tagged with: multithreading
has comment: http://stackoverflow.com/comment/86428097
downvote count: 0
favorite count: 0
tagged with: multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86419602
has comment: http://stackoverflow.com/comment/86424559
tagged with: python-asyncio
has body: I am having trouble implementing the following scheme : class A: def __init__(self): self.content = [] self.current_len = 0 def __len__(self): return self.current_len def update(self, new_content): self.content.append(new_content) self.current_len += 1 class B: def __init__(self, id): self.id = id And I also have these 2 functions that will be called later in the main : async def do_stuff(first_var, second_var): """ this function is ideally called from the main in another process. Also, first_var and second_var are not modified so it would be nice if they could be given by reference without having to copy them """ ### used for first call yield None while len(first_var) &lt; CERTAIN_NUMBER: time.sleep(10) while True: ## do stuff if condition_met: yield new_second_var ## which is a new instance of B ## continue doing stuff def do_other_stuff(first_var, second_var): while True: queue = multiprocessing.JoinableQueue() results = multiprocessing.Queue() ### do stuff first_var.update(results) The main looks like this at the moment : first_var = A() second_var = B() while True: async for new_second_var in do_stuff(first_var, second_var): if new_second_var: ## stop the do_other_stuff that is currently running ## to re-launch it with the updated new_var do_other_stuff(first_var, new_second_var) else: ## used for the first call do_other_stuff(first_var, second_var) Here are my questions : Is there a better solution to make this scheme work? How can I implement the "stopping" part since there is a while True loop that fills first_var by reference? Will the instance of A (first_var) be passed by reference to do_stuff if first_var doesn't get modified inside it? Is it even possible to have an asynchronous generator in another process? Is it even possible at all? This is using Python 3.6 for the async generators. I hope this is somewhat clear! Thanks a lot!
tagged with: python
type: Question
score: 2
has comment: http://stackoverflow.com/comment/86404216
answer count: 0

http://stackoverflow.com/q/49750270
has title: Can't get rid of characters in Webscraped Table in dataframe
type: Question
tagged with: replace
has comment: http://stackoverflow.com/comment/86515101
has comment: http://stackoverflow.com/comment/86520258
accepted answer: http://stackoverflow.com/a/49752891
linked to: http://stackoverflow.com/q/40106074
tagged with: python
tagged with: unicode
has body: I have scraped a table from a wikipedia page. I want to get rid of the special characters in the country names - mostly \xa0 I found this question: remove control character whitespaces from dataframe that seemed perfect - but when I use the code, it seems to do nothing. I suspect that is because the line not working in my code is looking for a complete field that is just the character. How do I get the non working line to get rid of the space characters? I don't mind using another method, or a different approach - but that just seemed so clean &amp; efficient... url = "https://en.wikipedia.org/wiki/List_of_countries_by_past_population_(United_Nations,_estimates)" response = requests.get(url) scraping_html_table_EQ = BeautifulSoup(response.content, "lxml") scraping_html_table_EQ = scraping_html_table_EQ.find_all("table", "wikitable") df = pd.read_html(str(scraping_html_table_EQ)) df = df[0] df.replace(u'\xa0',u'', regex=True, inplace=True) #&lt;-- line that doesn't work df
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/49752891
has comment: http://stackoverflow.com/comment/86514997

http://stackoverflow.com/q/49684379
type: UnansweredQuestion
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/49697740
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/49684541
has body: I have a Python script which uses Keras for machine learning. I am building X and Y which are features and labels respectively. The labels are built like this: def main=(): depth = 10 nclass = 101 skip = True output = "True" videos = 'sensor' img_rows, img_cols, frames = 8, 8, depth channel = 1 fname_npz = 'dataset_{}_{}_{}.npz'.format( nclass, depth, skip) vid3d = videoto3d.Videoto3D(img_rows, img_cols, frames) nb_classes = nclass x, y = loaddata(videos, vid3d, nclass, output, skip) X = x.reshape((x.shape[0], img_rows, img_cols, frames, channel)) Y = np_utils.to_categorical(y, nb_classes) # This needs to be changed The used function "to_categorical" in Keras is explain as follows: to_categorical keras.utils.to_categorical(y, num_classes=None) Converts a class vector (integers) to binary class matrix. Now I am using NumPy. May you let me know how the build the same line of code in order to work? In other words, I am looking for the equivalent of the "to_categorical" function in NumPy.
tagged with: numpy
has answer: http://stackoverflow.com/a/49687065
score: 9
has title: NumPy equivalent to Keras function utils.to_categorical
has comment: http://stackoverflow.com/comment/98824125
downvote count: 0
has comment: http://stackoverflow.com/comment/86382567
answer count: 3
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/86220947
type: QuestionComment
comment on: http://stackoverflow.com/q/49606662
score: 0
has text: This means the app you are using is unauthorized to make any webhooks. You may need to get the token before making any requests.
type: Comment

http://stackoverflow.com/q/49618205
type: Question
has title: How do I define blank space in python?
has answer: http://stackoverflow.com/a/49618261
tagged with: if-statement
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49618264
linked to: http://stackoverflow.com/q/8075877
has answer: http://stackoverflow.com/a/49618304
has comment: http://stackoverflow.com/comment/86243515
tagged with: python
has body: I'm trying to create GUI interface where user needs to enter a value. If he enters it wrong, error message appears. Otherwise it keeps the correct answer. But what if user forgot to enter a value and just left it blank? Or pressed enter without entering anything? How do I call up error message in this case? Just to keep it simple here is basic example without GUI: h = int(raw_input("Enter ")) if h &gt;= 10: print True elif h &lt; 10: print False else: print "Error" Idea is that if user did not enter anything, it would print "Error". However, program just stalls and prints the following: ValueError: invalid literal for int() with base 10: '' So how do I make python see blank space as value and print "Error" instead?
tagged with: error-messaging
has comment: http://stackoverflow.com/comment/86243479
answer count: 3
score: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86377764
type: QuestionComment
has text: But a better solution is to not pop in the first place. Just use the elements one by one, and then, if you really want to empty out the list at the end, you can del all of the elements at once, or del the whole list. Less code, harder to get wrong, and faster.
score: 0
comment on: http://stackoverflow.com/q/49683026
type: Comment

http://stackoverflow.com/a/49755859
has body: Im not 100% sure what you are trying to accomplish but if you want the variable to be a string just do: a = str(b)
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49755496
score: 1
type: Answer

http://stackoverflow.com/comment/86353969
score: 0
comment on: http://stackoverflow.com/q/49657455
type: Comment
has text: Sure! `float64` and `(1, 1288)` for `state` & `next_state` `float32` and `(1, 13)` for `y`
type: QuestionComment

http://stackoverflow.com/q/49716044
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86445096
has comment: http://stackoverflow.com/comment/86445076
type: UnansweredQuestion
has body: I followed the procedure given on the Pelican website by: Creating a virtualenv and then source bin/activate Installing pelican using pip install pelican Writing pelican-quickstart When I typed in pelican-quickstart, I got the following error: Traceback (most recent call last): File "/home/ashutosh_mishra/virtualenvs/pelican/bin/pelican-quickstart", line 7, in <module> from pelican.tools.pelican_quickstart import main File "/home/ashutosh_mishra/virtualenvs/pelican/lib/python3.2/site-packages/pelican/__init__.py", line 19, in <module> from pelican.generators import (ArticlesGenerator, PagesGenerator, File "/home/ashutosh_mishra/virtualenvs/pelican/lib/python3.2/site-packages/pelican/generators.py", line 14, in <module> from jinja2 import (BaseLoader, ChoiceLoader, Environment, FileSystemLoader, File "/home/ashutosh_mishra/virtualenvs/pelican/lib/python3.2/site-packages/jinja2/__init__.py", line 33, in <module> from jinja2.environment import Environment, Template File "/home/ashutosh_mishra/virtualenvs/pelican/lib/python3.2/site-packages/jinja2/environment.py", line 677 u'\xff\xff\xff\xff'.encode('iso-8859-15') ^ SyntaxError: invalid syntax I googled the error and found Pelican 3.3 pelican-quickstart error "ValueError: unknown locale: UTF-8"', but this doesn't solve my problem. Can anyone suggest a solution?
has title: Pelican-quickstart not working
tagged with: python
tagged with: pelican
score: 0
has comment: http://stackoverflow.com/comment/86445166
answer count: 1
has answer: http://stackoverflow.com/a/49734146
linked to: http://stackoverflow.com/q/19961239
type: Question
has comment: http://stackoverflow.com/comment/86657632

http://stackoverflow.com/q/49604736
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: insert
has title: How to insert into pandas dataframe by alphabetical order of a column?
type: Question
has body: Now I have this: #old df: bar foo 1 a 3 b 5 z I want to insert a line [6,"d"], so the df becomes: #new df: bar foo 1 a 3 b 6 d 5 z
accepted answer: http://stackoverflow.com/a/49604766
answer count: 1
tagged with: insertion-sort
tagged with: python
has answer: http://stackoverflow.com/a/49604766

radix
tags question: http://stackoverflow.com/q/49756433
tag name: radix
type: Tag

http://stackoverflow.com/q/49605603
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49605745
has answer: http://stackoverflow.com/a/49605745
tagged with: python
tagged with: regex
type: AnsweredQuestion
answer count: 1
has title: Strip wrapping spaces in a regexp
downvote count: 0
score: 1
upvote count: 1
has body: I wanna find the Target string without the wrapping spaces, it can have any non \s\w\d characters like +!# etc and have arbitrary number of white spaces inbetween, and at the edges(left, right) Target (foo) {bar} [spam] | (foo2) Current expression looks like this: re.search(r"([^\[\]}{()|]+)", " +34s kj-3 R B# (foo) {bar} [spam] | (foo2)") and group(0) returns: ' +34s kj-3 R B# ' the problem with this expr is that I have to write two if match: conditions, because it also accepts only spaces as well. So I have to strip it and check again. Closest solution is to use \b like that r"\b([^\[\]}{()|]+)\b", but it "strippes" characters like +#: '34s kj-3 R B' EDIT: Target string can have no wrapping spaces as well on ether sides. EDIT: Included the rest of the sting in the example (foo) {bar} [spam] | (foo2)
favorite count: 0

http://stackoverflow.com/a/49631995
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Maybe, inside your serializer method approve(), you can use the Serializer's context, then you have access to the request. Based on that you should get the request.data. Inside your Serializer method: request = self.context.get('request') # In cases of your data came as a GET params print(request.query_params) # Normal post/patch/put method request data print(request.data)
accepted answer of: http://stackoverflow.com/q/49631820
has comment: http://stackoverflow.com/comment/86313287
answers question: http://stackoverflow.com/q/49631820
type: Answer
has comment: http://stackoverflow.com/comment/86293651

http://stackoverflow.com/q/49696980
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86406852
has title: Language translation by reading .txt file and print out a translated sentence
has answer: http://stackoverflow.com/a/49697062
has answer: http://stackoverflow.com/a/49711109
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has body: I am trying to make a Python program to translate from English to Aboriginal language which reads from dictionary.txt file. That program should contain pairs of English and translated words separated by a comma (,) and builds a dictionary with them. Program should then read in lines of text from the user (until a blank line) and print out a translated sentence, where each word has been looked up in the dictionary. dictionary.txt file looks like following: afternoon,wuraji-wuraji I,ngaju bird,jirripirdi like,kuja-piya dance,juka-pinyi python,malilyi laugh,ngarlarrimi we,ngalipa My program should work like this: English: I like python ngaju kuja-piya malilyi English: we laugh ngalipa ngarlarrimi English: I am so far able to make a program which produces translation for individual words but not the combined sentences. I am just wondering how can I do that? My code is like following: user_input = [] translate = {} for line in open('dictionary.txt'): english, aboriginal = line.split(',') translate[english] = aboriginal while user_input != "": user_input = input("English: ") if user_input == "": break else: print(translate[user_input])
accepted answer: http://stackoverflow.com/a/49711109
upvote count: 1
tagged with: python
downvote count: 1
possible better answer: http://stackoverflow.com/a/49697062

http://stackoverflow.com/a/49639356
type: AcceptedAnswer
downvote count: 0
score: 6
upvote count: 6
type: Answer
has body: That’s expected behaviour, because OS-level file handles are integers. There are several functions in the os module that’ll accept such integers: These functions operate on I/O streams referenced using file descriptors. File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors. They are not Python file objects but you could create a Python file object for a given descriptor with io.FileIO(). However, if all you wanted was a temporary file as a Python file object, just stick to the higher-level functions of the temp module, such as tempfile.TemporaryFile().
accepted answer of: http://stackoverflow.com/q/49639329
answers question: http://stackoverflow.com/q/49639329

http://stackoverflow.com/q/49657046
tagged with: django
tagged with: python
type: UnansweredQuestion
has body: I have a model: class Course(models.Model): class Meta: ordering = ['completion_order'] degree = models.ForeignKey(Degree, on_delete=models.CASCADE) name = models.CharField(max_length=30, null=False, blank=False) completion_order = models.PositiveSmallIntegerField(default=0,null=False, blank=False) required = models.ManyToManyField('Task', default=1, blank=True, symmetrical=False) And I have written a function to run on "m2m_changed" to automatically adjust the completion order to take into account any changes in prerequisites: def required_changed(sender, instance, **kwargs): degreecourses = Courses.objects.all().filter(degree=instance.degree) for zcr in degreecourses: #resets the order for the all the degree's course instances zcr.completion_order = 0 for cr in degreecourses: #assigns new completion_order values if cr.required.count() is 0: # if no requirements sets 'completion_order' to 1 cr.completion_order = 1 else: #sets 'completion_order' to the increment of the highest (max) value of this courses's required course mx = cr.required.all().aggregate(Max('completion_order')) neworder = mx['completion_order__max'] + 1 cr.completion_order = neworder cr.save() This is run after any change in the m2m thus: m2m_changed.connect(required_changed, sender=Course.required.through) I originally set this up iterating through multiple times, but then realised it was unnecessary -my (novice) question is: Can someone explain how this is able to resolve all of the "required" values in one pass, i.e. without having to iterate through the second loop multiple times? I'm guessing it's to do with python being object oriented - but I'm new to object oriented programming, so whilst I'm pleased it works, I'm perplexed as to how it can assign the correct running order (i.e. even with many complex interdependencies between multiple courses) with seemingly only one pass?
tagged with: many-to-many
score: 0
has comment: http://stackoverflow.com/comment/86324873
has title: Django manytomany m2m_changed script works, but how?
type: Question
has comment: http://stackoverflow.com/comment/86345013
answer count: 0

http://stackoverflow.com/q/49660861
has comment: http://stackoverflow.com/comment/86353293
score: 5
has answer: http://stackoverflow.com/a/49676127
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: We have been using Airflow for a while, it is just great. Now we are considering moving some of our very frequent tasks into our airflow server too. Let's say I have a script running every second. What's the best practice to schedule it with airflow: Run this script in DAG that is scheduled every second. I highly doubt this will be the solution, there is significant overhead for a DAGRUN Run this script in a while loop that stops after 6 hours, then schedule it on Airflow to be run every 6 hour? Create a DAG with no schedule, put the task in a while True loop with proper sleep time, so the task will never terminates unless there is an error. Any other suggestions? Or this kind of task is just not suitable for Airflow? should do it with a lambda function and AWS scheduler? Cheers!
type: UnansweredQuestion
tagged with: airflow
upvote count: 5
has title: Use Airflow for frequent tasks
tagged with: python

http://stackoverflow.com/comment/86317892
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49654530
has text: This can help you in the future: you can start by, for example, printing the type of a variable with `print type(your_variable)`
score: 0

http://stackoverflow.com/q/49673465
tagged with: selenium
downvote count: 0
upvote count: 1
tagged with: webdriver
favorite count: 0
type: Question
has body: I'm having an issue when trying to select data from a class. What I need to do is get the third TD (the report name) of every class (named "odd" or "even"), then compare that to a string variable in python (which is the name of the report submitted, for example "Name of Report 2 (scrubbed)"), and if it matches I need to grab the value of the first td. I just need to be able to grab that number using that report name in the third td. Any ideas? I tried CSS selectors like driver.find_element_by_xpath("//table[contains(@class, 'data') and contains(., 'Name of Report 1 (scrubbed)')]") But I keep getting garbage put into the string var in python. Thanks! 4933047 Name of Report 1 (scrubbed) 'PRO_DET' 2018-05-19 2018-04-04 Complete 4933041 Name of Report 2 (scrubbed) 'PRO_DET' 2018-05-19 2018-04-04 Complete
has title: How to extract attributes from elements identified with reference to other elements selected through xpath from multiple classes
possible better answer: http://stackoverflow.com/a/49673747
has comment: http://stackoverflow.com/comment/86359645
has answer: http://stackoverflow.com/a/49673747
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath
accepted answer: http://stackoverflow.com/a/49675543
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49675543
score: 1
has comment: http://stackoverflow.com/comment/86359790

http://stackoverflow.com/a/53174660
has body: Hey you can get all the urls from the Playlist and then call download one by one. this works for me all the best. def getAllLinks(playList): ''' : This function take a link of playlist and return the link of each videos :param playList: :return: A list of all Url links ''' allLinks = [] youtubeLink = 'https://www.youtube.com' pl = Playlist(playList) for linkprefix in pl.parse_links(): allLinks.append(youtubeLink + linkprefix) return allLinks from this you will get all the urls and then def downloadPlaylist(playlistLink): linkArray = getAllLinks(playlistLink) for link in linkArray: downloadVideo(link)
accepted answer of: http://stackoverflow.com/q/49743626
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49743626
downvote count: 0

http://stackoverflow.com/q/49754413
accepted answer: http://stackoverflow.com/a/49757695
upvote count: 2
has answer: http://stackoverflow.com/a/49757695
answer count: 1
downvote count: 0
has body: I want to accept multiple concurrent request for Flask API. API is currently getting "company name" through POST method and call the crawler engine, and each crawling process takes 5-10 minutes to finish. I want to run many crawler engine in parallel for different respective that many request. I followed this, but could not get it working. Currently, second request is cancelling the first request. How can I achieve this parallelism? Current API implementation: app.py app = Flask(__name__) app.debug = True @app.route("/api/v1/crawl", methods=['POST']) def crawl_end_point(): if not request.is_json: abort(415) inputs = CompanyNameSchema(request) if not inputs.validate(): return jsonify(success=False, errros=inputs.errors) data = request.get_json() company_name = data.get("company_name") print(company_name) if company_name is not None: search = SeedListGenerator(company_name) search.start_crawler() scrap = RunAllScrapper(company_name) scrap.start_all() subprocess.call(['/bin/bash', '-i', '-c', 'myconda;scrapy crawl company_profiler;']) return 'Data Pushed successfully to Solr Index!', 201 if __name__ == "__main__": app.run(host="10.250.36.52", use_reloader=True, threaded=True) gunicorn.sh #!/bin/bash NAME="Crawler-API" FLASKDIR=/root/Public/company_profiler SOCKFILE=/root/Public/company_profiler/sock LOG=./logs/gunicorn/gunicorn.log PID=./guincorn.pid user=root GROUP=root NUM_WORKERS=10 # generally in the 2-4 x $(NUM_CORES)+1 range TIMEOUT=1200 #preload_apps = False # The maximum number of requests a worker will process before restarting. MAX_REQUESTS=0 echo "Starting $NAME" # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your gunicorn exec gunicorn app:app -b 0.0.0.0:5000 \ --name $NAME \ --worker-class gevent \ --workers 5 \ --keep-alive 900 \ --graceful-timeout 1200 \ --worker-connections 5 \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level info \ --backlog 0 \ --pid=$PID \ --acce…
favorite count: 0
type: Question
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/86526625
tagged with: python
tagged with: concurrency
tagged with: flask
has title: How to accept concurrent request using Gunicorn for Flask API?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/10938360
score: 2

http://stackoverflow.com/comment/86355560
type: QuestionComment
comment on: http://stackoverflow.com/q/49672249
has text: If you want to get a "constant" random input, you might want to use `numpy.random.seed` with a constant, see for instance: https://stackoverflow.com/a/21494630/4121573
score: 0
type: Comment

http://stackoverflow.com/q/49702797
has comment: http://stackoverflow.com/comment/86438773
answer count: 1
has comment: http://stackoverflow.com/comment/86419339
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49712680
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/86438296
has body: I have this function here and it looks like this when disassembled: def game_on(): def other_function(): print('Statement within a another function') print("Hello World") sys.exit() print("Statement after sys.exit") 8 0 LOAD_CONST 1 (&lt;code object easter_egg at 0x0000000005609C90, file "filename", line 8&gt;) 3 LOAD_CONST 2 ('game_on.&lt;locals&gt;.other_function') 6 MAKE_FUNCTION 0 9 STORE_FAST 0 (other_function) 10 12 LOAD_GLOBAL 0 (print) 15 LOAD_CONST 3 ('Hello World') 18 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 21 POP_TOP 11 22 LOAD_GLOBAL 1 (sys) 25 LOAD_ATTR 2 (exit) 28 CALL_FUNCTION 0 (0 positional, 0 keyword pair) 31 POP_TOP 12 32 LOAD_GLOBAL 0 (print) 35 LOAD_CONST 4 ('second print statement') 38 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 41 POP_TOP 42 LOAD_CONST 5 (None) 45 RETURN_VALUE Is there a way to modify the bytecode so it doesn't print "Hello world." It's like I want to skip line 10 and continue to 11. There's a lot of material like inspectors and settrace but it's not very direct. does anyone have any info on this or can someone point me to what I could do?
has comment: http://stackoverflow.com/comment/86419400
tagged with: python
has title: Stop a function from printing using the disassembler in Python?
tagged with: disassembly
accepted answer: http://stackoverflow.com/a/49712680
type: AnsweredQuestion
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86438180
has comment: http://stackoverflow.com/comment/86419381

http://stackoverflow.com/q/49617712
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86242668
answer count: 1
has answer: http://stackoverflow.com/a/49617838
type: Question
has title: Select the first condition per group iteration
has comment: http://stackoverflow.com/comment/86242560
accepted answer: http://stackoverflow.com/a/49617838
tagged with: python
has comment: http://stackoverflow.com/comment/86242631
has body: A B C D 0 01:00:00 2002-01-16 10 3 1 01:30:00 2002-01-16 10 -12 2 02:00:00 2002-01-16 10 7 3 01:00:00 2002-01-17 20 33 4 01:30:00 2002-01-17 20 -27 5 02:00:00 2002-01-17 20 12 results = {} I want to select one row per each A group, taking the first row which satisfy one of the next conditions: D >= C*(0.5) D &lt;= C*(-1) Else, take last row. Output should be: A B C D 1 01:30:00 2002-01-16 10 -12 3 01:00:00 2002-01-17 20 33 I´ve tried: grouped = df.groupby('B') for name, group in grouped: if (group["D"] &gt;= group["C"]*(0.5)).any(): results[name] = group[group["D"] &gt;= group["C"]*(0.5)].head(1) elif (group["D"] &lt;= group["C"]*(-1)).any(): results[name] = group[group["D"] &lt;= group["C"]*(-1)].head(1) else: results[name] = group.tail(1)
type: AnsweredQuestion
tagged with: conditional-statements

http://stackoverflow.com/comment/86310774
has text: Since you tagged `dataframe` I assume you want a `pandas` solution.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49651170
score: 0

http://stackoverflow.com/q/49644926
has answer: http://stackoverflow.com/a/49645546
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/86297881
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has title: Python prints two times when there is only one print() function
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86297812
has comment: http://stackoverflow.com/comment/86297959
has body: I am wondering why my code prints two same output even though I printed once. I was trying to Read and Edit the .docx files using python-docx and readDocx modules in Python 3 from a book called Automate the boring stuff with Python by Al Sweigart. The demo.docx contains these simple 6 text lines: Document Title A plain paragraph with some bold and some italic Heading, level 1 Intense quote first item in unordered list first item in ordered list import docx, readDocx def getText(filename): doc = docx.Document(filename) fullText = [] for para in doc.paragraphs: fullText.append(' ' + para.text) return '\n'.join(fullText) print(readDocx.getText('demo.docx')) Output: Document Title A plain paragraph with some bold and some italic Heading, level 1 Intense quote first item in unordered list first item in ordered list Document Title A plain paragraph with some bold and some italic Heading, level 1 Intense quote first item in unordered list first item in ordered list And this file appeared, I deleted this file and when rerun the program its been created again in the folder name pycache
tagged with: python
has answer: http://stackoverflow.com/a/49645323

http://stackoverflow.com/comment/86446952
type: Comment
type: QuestionComment
score: 0
has text: Still the same error : InvalidRequestError: Multiple classes found for path "user_model.Users" in the registry of this declarative base. Please use a fully module-qualified path.
comment on: http://stackoverflow.com/q/49716257

http://stackoverflow.com/comment/86332350
score: 0
has text: So in those cases the regexp won't match, and you can test for that separately.
comment on: http://stackoverflow.com/q/49661206
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86262387
comment on: http://stackoverflow.com/q/49625386
has text: Please stop opening new questions asking the same thing stick with one and improve it. stackoverflow.com/q/49622725/1841839 stackoverflow.com/q/49625386/1841839 stackoverflow.com/q/49627579/1841839
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49659643
type: AcceptedAnswer
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/86329698
has body: I don't use those functions in Python much but the data seems to imply that the difference is that the functions in Python use 'n' when calculating the variance to standardize with and R uses 'n-1'. We can convert between the two by multiplying and the following shows that after multiplying by sqrt(5/4) the data from R matches the Python values. &gt; tab &lt;- read.table(textConnection("1 1 1.7887437 -0.4999873 pen + 2 2 -0.4453054 -0.4083792 wf + 3 3 -0.4603495 -0.4517725 gher + 4 4 -0.4302613 -0.4276651 dger + 5 5 -0.4528275 1.7878041 ww")) &gt; tab V1 V2 V3 V4 V5 1 1 1 1.78874369999999994 -0.49998730000000002 pen 2 2 2 -0.44530540000000002 -0.40837920000000000 wf 3 3 3 -0.46034950000000002 -0.45177250000000002 gher 4 4 4 -0.43026130000000001 -0.42766510000000002 dger 5 5 5 -0.45282749999999999 1.78780410000000001 ww &gt; # To transform as if we used n in the denominator instead of &gt; # n-1 we just multiply by sqrt(n/(n-1)) &gt; tab$V3 * sqrt(5/4) [1] 1.99987625376224520 -0.49786657257386746 -0.51468638770401975 [4] -0.48104675744371517 -0.50627653604064304 &gt; tab$V4 * sqrt(5/4) [1] -0.55900279534329034 -0.45658182589849106 -0.50509701018251196 [4] -0.47814411760212272 1.99882574902641608
has comment: http://stackoverflow.com/comment/86328888
has comment: http://stackoverflow.com/comment/86328840
has comment: http://stackoverflow.com/comment/86329837
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/49659417
answers question: http://stackoverflow.com/q/49659417

http://stackoverflow.com/q/49719514
has comment: http://stackoverflow.com/comment/86451962
accepted answer: http://stackoverflow.com/a/49719704
has answer: http://stackoverflow.com/a/49719704
has comment: http://stackoverflow.com/comment/86451938
tagged with: python
possible better answer: http://stackoverflow.com/a/49719653
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49719653
answer count: 3
has comment: http://stackoverflow.com/comment/86452096
has answer: http://stackoverflow.com/a/49719662
score: 1
has body: I know how to substitute individual letters in a normal for loop without using the replace function but I don't know how to do it on a definition with 3 parameters. Per example def substitute(sentence, target, replacement) Basically it'll be like substitute("The beach is beautiful", "beach", "sky")and give back The sky is beautiful. How do you do that without using the replace or find function? Thanks def replace_word(sentence, target, replacement): newSentence = "" for target in sentence: if target in sentence: newSentence += replacement print(newSentence) else: True return newSentence
downvote count: 0
has comment: http://stackoverflow.com/comment/86452147
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86452027
has title: Create a definition to substitute words in a sentence in Python

http://stackoverflow.com/comment/86271296
score: 0
type: AnswerComment
has text: I think the most time is used for creation of the int-objects. Please see my last edit which shows, that for bigger values it becomes slower, because another "integer"-type is used internally.
comment on: http://stackoverflow.com/a/49630819
type: Comment

http://stackoverflow.com/q/49662266
tagged with: python
has comment: http://stackoverflow.com/comment/86334625
has title: Performing inference in Tensorflow with multiple graphs on same GPU parallely
score: 2
has comment: http://stackoverflow.com/comment/86374616
has comment: http://stackoverflow.com/comment/86369689
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
has body: I created 2 tf.graph() (loaded the same frozen model) from different threads, which seem to happen based on the different tf.graph object address that I see in each thread. When I tried to run inference on these 2 graphs parallely using the same GPU, I feel it is running like a sequential pipeline. This is based on the GPU memory &amp; utilization stats and also the time taken. ie, A single graph would consume 7GB of GPU memory and utilize ~15% of compute. With 2 graphs running parallely I would expect to use twice the GPU memory and increased compute, but that doesn't seem to happen.
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49735311
score: 2
has comment: http://stackoverflow.com/comment/86485717
has comment: http://stackoverflow.com/comment/86515393
answer count: 0
upvote count: 2
downvote count: 0
has body: I have both anaconda for python 2.7 and for python 3 installed on my machine. I am trying to install user-agents (https://github.com/selwin/python-user-agents) and I get the following error: (base) C:\Users\john&gt;conda install user-agents Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - user-agents - zict Use "conda info &lt;package&gt;" to see the dependencies for each package. I have looked at the FAQ https://conda.io/docs/user-guide/tasks/manage-python.html but I do not understand how to avoid this issue. Running the -info command on both packages shows (base) C:\Users\john&gt;conda info user-agents user-agents 1.1.0 py27_0 ------------------------ file name : user-agents-1.1.0-py27_0.tar.bz2 name : user-agents version : 1.1.0 build string: py27_0 build number: 0 channel : https://conda.anaconda.org/conda-forge/win-64 size : 16 KB arch : x86_64 constrains : () license : MIT license_family: MIT md5 : 98e6b4d286813445d0a2f222ca3f08fa platform : win32 subdir : win-64 url : https://conda.anaconda.org/conda-forge/win-64/user-agents-1.1.0-py27_0.tar.bz2 dependencies: python 2.7* ua-parser &gt;=0.4.1 user-agents 1.0.1 py34_0 ------------------------ file name : user-agents-1.0.1-py34_0.tar.bz2 name : user-agents version : 1.0.1 build string: py34_0 build number: 0 channel : https://conda.anaconda.org/conda-forge/win-64 size : 12 KB arch : x86_64 constrains : () license : MIT md5 : 960c836c6c8fd5e7a126c15b39be5d35 platform : win32 subdir : win-64 url : https://conda.anaconda.org/conda-forge/win-64/user-agents-1.0.1-py34_0.tar.bz2 dependencies: python 3.4* ua-parser &gt;=0.4.1 user-agents 1.0.1 py27_1 ------------------------ file name : user-agents-1.0.1-py27_1.tar.bz2 name : user-agents version : 1.0.1 build string: py27_1 build number: 1 channel : https://conda.anaconda.org/conda-forge/win-64 size : 13 KB arch : x86_64 constrains : () license : MIT md5 : 9c829288911183766ddaa741f537b6ca platform : win32 subd…
has comment: http://stackoverflow.com/comment/86484848
favorite count: 0
has comment: http://stackoverflow.com/comment/86531403
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/86485653
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86485556
has comment: http://stackoverflow.com/comment/86484683
tagged with: python
tagged with: conda
has comment: http://stackoverflow.com/comment/86613574
has title: how to install conflicting packages?

http://stackoverflow.com/q/49648699
has comment: http://stackoverflow.com/comment/86308930
has body: I am going to try to fit a model to my data. I've read a little about Statsmodels in Python here: http://www.statsmodels.org/stable/example_formulas.html but I haven't found anything about the function f used to model the data: f(X) = Y. A lot of parameters appear when we print res.summary(), but the only thing it says about the actual model is: Model: OLS Method: Least Squares Can I somehow retrieve the function?
has comment: http://stackoverflow.com/comment/86355042
has comment: http://stackoverflow.com/comment/86354808
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: static-methods
tagged with: statsmodels
type: Question
has title: How to retrieve the modelling function in statsmodels, Python?
score: 0

http://stackoverflow.com/comment/86360775
type: Comment
type: QuestionComment
score: 0
has text: What do you expect `client` to be?
comment on: http://stackoverflow.com/q/49674959

http://stackoverflow.com/comment/86419623
type: QuestionComment
has text: Fix your indentation. Code under while blocks should be a level of indentation higher than the indentation of the while loop above it.
comment on: http://stackoverflow.com/q/49703016
score: 1
type: Comment

http://stackoverflow.com/comment/86552078
comment on: http://stackoverflow.com/a/49757134
type: Comment
has text: When you train a model you first give some <x,y> where y is the result of the classification. After the training you can give the model new input and it will output the classification results y.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86424934
type: Comment
score: 0
type: QuestionComment
has text: The composed primary key is your problem. Primary key composed of multiple key are generally inconvenient to say it at its mildest. It might be a good idea to add a kind of auto increment field as the primary key. Like Django does when it is creating the database.
comment on: http://stackoverflow.com/q/49705454

http://stackoverflow.com/q/49710943
score: 0
has title: Execute command over ssh and paramiko in python
answer count: 0
has comment: http://stackoverflow.com/comment/86442256
type: UnansweredQuestion
tagged with: exec
has comment: http://stackoverflow.com/comment/86444327
has body: I'm writing a script that loads calculation files to a server, runs calculations and downloads the finished files again. Everything works, except the command does not. A needed command is "bbjobs" and it works fine when I'm working with WinSCP, in python with paramiko this error message arrives: ['bash: bbjobs: command not found\n'] With "which bbjobs" I found the complete path of the command. But when I try it with the complete path this error message arrives: ['/cluster/apps/lsf/10.1/linux2.6-glibc2.3-x86_64/bin/bbjobs: error while loading shared libraries: liblsf.so: cannot open shared object file: No such file or directory\n'] Here is the code I'm using: from paramiko import SSHClient, AutoAddPolicy ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect('host',22,'login','pwd') (InputStream, OutputStream, Error) = ssh.exec_command('bbjobs') print(list(OutputStream)) print(list(Error)) I have no idea what to do now... Thanks for your help!
has comment: http://stackoverflow.com/comment/86435545
has comment: http://stackoverflow.com/comment/86466688
has comment: http://stackoverflow.com/comment/86436302
duplicate of: http://stackoverflow.com/q/31964108
has comment: http://stackoverflow.com/comment/86491022
tagged with: ssh
tagged with: python
tagged with: paramiko
tagged with: command
type: Question
linked to: http://stackoverflow.com/q/31964108

http://stackoverflow.com/q/49626707
has answer: http://stackoverflow.com/a/49626861
has title: How to disable notification popup in Chrome Browser
tagged with: python
tagged with: webdriver
possible better answer: http://stackoverflow.com/a/61331423
downvote count: 6
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/61331423
accepted answer: http://stackoverflow.com/a/49626861
upvote count: 2
has body: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import time chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications" : 2} chrome_options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome("C:\\chromedriver\\chromedriver.exe") driver.maximize_window() driver.get("https://www.arttoframe.com/") time.sleep(6) driver.close() Console Logs : C:\Users\Dell\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Dell/PycharmProjects/untitled/newaaa.py Process finished with exit code 0
tagged with: selenium
score: -4
favorite count: 0
type: Question

http://stackoverflow.com/comment/86333108
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49661411
has text: I give up. How many times do I have to ask for a precise description, not examples?
type: Comment

http://stackoverflow.com/a/49702233
has body: If no 2 ids can generate the same result from generate, this is impossible. (If that constraint does not hold, you can always return the same string, regardless of what id is.) There is a limit to how many different strings have a base64 decoding of exactly 32 characters. You have placed no limit on how many different values of id this function should work for. Thus, there must be at least 2 ids that generate will return the same value for.
answers question: http://stackoverflow.com/q/49702145
has comment: http://stackoverflow.com/comment/86419174
has comment: http://stackoverflow.com/comment/86418187
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86418595
has comment: http://stackoverflow.com/comment/86419211
score: 1
has comment: http://stackoverflow.com/comment/86419190
has comment: http://stackoverflow.com/comment/86419138
upvote count: 1

http://stackoverflow.com/a/49712733
has body: To get the text string from the response object, you can use json_resp.text. You can then use the json library to convert this into a dict, and then extract the field you want: json_resp = requests.post(...) ## Your post request, as written above node = json.loads(json_resp.text) face_token = node['faces'][0]['face_token'] Here is the full code (using your snippets above): import requests import json api_key = 'your api key' api_secret = 'your api secret' json_resp = requests.post( 'https://api-us.faceplusplus.com/facepp/v3/detect', data = { 'api_key' : api_key, 'api_secret' : api_secret, 'image_url' : 'http://www.pick-health.com/wp-content/uploads/2013/08/happy-person.jpg' } ) node = json.loads(json_resp.text) face_token = node['faces'][0]['face_token'] json_resp2 = requests.post( 'https://api-us.faceplusplus.com/facepp/v3/face/analyze', data = { 'api_key' : api_key, 'api_secret' : api_secret, 'face_tokens' : face_token, 'return_landmark' : 0, 'return_attributes' : 'emotion' } ) print("Response2 : ", json_resp2.text) PS: It's a bad idea to post API keys online, since people can run your bill up by using your services.
accepted answer of: http://stackoverflow.com/q/49712538
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49712538
type: Answer

precision
tags question: http://stackoverflow.com/q/49656090
tag name: precision
type: Tag

http://stackoverflow.com/comment/86488041
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49736700
has text: Is the final dictionary correct or a copy/paste error? Otherwise, cool question.
type: Comment

http://stackoverflow.com/a/49599775
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49599735
has body: Your code seems a bit confused to me. Do you really want raw_input().split()? I don't think so. Try this: inp = raw_input() for el in inp.split(): print(''.join(mergesort(el)))

http://stackoverflow.com/comment/86369122
comment on: http://stackoverflow.com/a/49677935
type: AnswerComment
score: 0
has text: This `"{}".format(base64.b64encode(img))` produces `"b'/9j/4AAQSkZJRgA='"`. Notice that the double quotes are around the `b'` which implies that it is being incorporated into the string.
type: Comment

http://stackoverflow.com/comment/86398057
comment on: http://stackoverflow.com/a/49692094
score: 0
type: AnswerComment
has text: @MuhammadOsta There is no python where that throws a syntax error. I don't know what you're doing wrong, but the syntax error is probably on a different line.
type: Comment

http://stackoverflow.com/comment/86489036
type: Comment
has text: What's with the 6?
score: 1
comment on: http://stackoverflow.com/q/49737345
type: QuestionComment

http://stackoverflow.com/comment/86432276
type: Comment
comment on: http://stackoverflow.com/q/49709395
score: 0
type: QuestionComment
has text: comp is a list(I hope) of dataset. it represent name of the company., and name is name of the ETFs. It also consists of list made with using pands and numpy. The date isn't mentioned in the dataset I showed you. because it is out in the loop. In the inner side of the loop I made those dataframe. and I like to converge with the list.

http://stackoverflow.com/a/49672033
type: Answer
answers question: http://stackoverflow.com/q/49671754
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86355059
has comment: http://stackoverflow.com/comment/86355653
has body: You could use the sample_degseq function from the igraph package for this, which creates a graph with given vertex degrees. The adjacency matrix of this graph will have your desired property. library(igraph) row_col_sum = 3 dim = 8 g = sample_degseq(rep(row_col_sum,dim), method = "simple.no.multiple") as_adj(g) Output: 8 x 8 sparse Matrix of class "dgCMatrix" [1,] . . . . . 1 1 1 [2,] . . 1 1 1 . . . [3,] . 1 . . 1 . 1 . [4,] . 1 . . . 1 . 1 [5,] . 1 1 . . . 1 . [6,] 1 . . 1 . . . 1 [7,] 1 . 1 . 1 . . . [8,] 1 . . 1 . 1 . . Hope this helps!

http://stackoverflow.com/comment/86378600
type: Comment
comment on: http://stackoverflow.com/a/49683542
type: AnswerComment
has text: That worked! But now how would I manage to change the values in this image?
score: 0

http://stackoverflow.com/q/49734789
has title: Pytesseract error in using language mode
tagged with: python
has comment: http://stackoverflow.com/comment/86486092
tagged with: tesseract
tagged with: python-tesseract
has comment: http://stackoverflow.com/comment/86486035
downvote count: 0
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86483658
has body: import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract- OCR/tesseract' result = pytesseract.image_to_string(Image.open('Sanskrit.png'), lang="san") print(result) with open('magic.txt', mode='w') as file: file.write(result) print('see &gt; the output file') This is the above code that I tried to execute. This code works well when I am using lan="eng" but doesn't seem to work for any other languages. I have already download the tessdata files for all the languages and I am using Tesseract-OCR 4.00dev version of the engine. Any help regarding this would be much appreciated. Thanks.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86493870
type: UnansweredQuestion

http://stackoverflow.com/a/49698006
accepted answer of: http://stackoverflow.com/q/49697848
type: Answer
has body: This is a more interesting problem than it first appears. for x in a: will iterate over 1,2,3,4. if x in b: b[x] = 'bull' checks if 1,2,3,4, respectively, are in b, and sets b[x] to bull. Since Python is zero-based indexed, what a simple guess would expect to see is this: b = [1,'bull','bull','bull'] Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; IndexError: list assignment index out of range Instead you see this: b = [1, 'bull', 3, 'bull'] What gives? And what is zero-based indexing? Zero-based indexing just means that, if you want the first element of something, you call it at index 0. In other words, if a = [1,2,3,4], then a[1] gives 2, and a[0] gives 1. Confusing, and there are debates among some computer scientists whether this is actually the best way to do it. Some languages, like Fortran and Julia, have one-based indexing, so something like what you're trying to do would actually work there. Now back to the problem: let's go loop-by-loop. On your first loop, x = 1, so x in b evaluates to True and b[1] = 'bull' evaluates to: b = [1,'bull',3,4]. On your second loop, x = 2, but x in b evaluates to False! Remember that b = [1,'bull',3,4], so there's no longer a 2 in b, and it skips element assignment! On the third loop, 3 in b is True, so now b[3] = 'bull' and b = [1,'bull',3,'bull']. On the fourth loop, there is no 4 in b, so nothing happens. For what you're trying to accomplish instead, you can approach this in one of two ways: for (i,x) in enumerate(a): if x in b: b[i] = 'bull' In this method, i is initialized at 0, and increased by one each loop. So i will span: 0,1,2,3. Perfect for zero-based indexing! Another approach is to do this: for x in a: if x in b: b[x-1] = 'bull' When x is 1, x-1 gives you 0, and remember that b[0] = 1.
answers question: http://stackoverflow.com/q/49697848
has comment: http://stackoverflow.com/comment/86409069
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86429121
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86409093

http://stackoverflow.com/comment/86282001
has text: In my application this only loads on application startup so think searching is only a one time hit. Iterating through a hundred configs items should only take milliseconds.
type: Comment
comment on: http://stackoverflow.com/a/49617165
score: 0
type: AnswerComment

http://stackoverflow.com/comment/102083270
has text: Interesting solution. So this is essentially adding custom fields to the 'userinfo' response object with role, or group, or other available info. Am I understanding correctly?
score: 0
comment on: http://stackoverflow.com/a/55731937
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86412757
type: QuestionComment
comment on: http://stackoverflow.com/q/49699737
score: 0
type: Comment
has text: In addition to @chepner's comment, also see [_What's the pythonic way to use getters and setters?_](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters)

http://stackoverflow.com/q/49600631
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86208339
tagged with: web
has title: extract array from web fetched json file python
has answer: http://stackoverflow.com/a/49600837
has answer: http://stackoverflow.com/a/49600660
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49600786
type: UnansweredQuestion
tagged with: python
score: -1
has body: i want to fetch live quotes from this page in python 3 link the quotes here is stored in json file in array "JsonData" i want to get the value stored in LTP inside the json file from urllib.request import urlopen import json url = ("https://ewmw.edelweiss.in/api/Market/Process/GetFutureValue/BANKNIFTY/05%20Apr%202018") response = urlopen(url) data = response.read().decode("utf-8") y = json.loads(data['JsonData']) print(y)
tagged with: fetch
answer count: 3

http://stackoverflow.com/a/49619241
type: Answer
has comment: http://stackoverflow.com/comment/86317295
has comment: http://stackoverflow.com/comment/86306325
has comment: http://stackoverflow.com/comment/86306338
has comment: http://stackoverflow.com/comment/86246391
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49619062
has body: You forgot about the header when you read your file This is how I would read the file X, Y = [], [] with open('ParameterValues', 'r') as parameterFile: header = parameterFile.readline() for line in parameterFile: items = [float(x) for x in line.split(',')] X.append(items[1]) Y.append(items[2]) _ print X # [0.581261625, 0.470764982, 0.44202262, 0.447475587] print Y # [0.010561718, 0.01282931, 0.011346878, 0.011324991] And then do your interpolation which I don't really understand how is supposed to work (This is an entirely separate issue) Z = givemeomege(X,Y)
has comment: http://stackoverflow.com/comment/86316785
has comment: http://stackoverflow.com/comment/86271793
score: 1

http://stackoverflow.com/comment/86327579
score: 1
type: QuestionComment
has text: If you give a more specific input example I can update my answer to be less general.
comment on: http://stackoverflow.com/q/49659044
type: Comment

http://stackoverflow.com/a/49730810
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86476249
accepted answer of: http://stackoverflow.com/q/49730559
type: Answer
answers question: http://stackoverflow.com/q/49730559
has body: I don't think this is a very good StackOverflow question because it is very broad and not programming specific. You are asking how to start a new software project which in my opinion belongs more in the software engineering meta: https://softwareengineering.stackexchange.com/ Anyhow, how I would take on such a project: First I would define my project scope. What is the functionality of the end-product? What must it be able to do and what not? Who are the end-users using the product and what do they expect? These are so called functional requirements. In which way does the product deliver value? Is it fast, modifiable, distributed... These are so called non-functional requirements. Develop a basic software architecture based on the previous requirements using patterns and tactics and identify the different subsystems. On the top of my hat I would divide it in a frontend component using a web application, backend component in your favourite language and a database component for persistence. Research possible languages frameworks for each component, decide and start coding! For the 4th step I suggest you have a look at Python Django which includes all of this stuff out-of-the-box.
score: 0

http://stackoverflow.com/comment/86500943
type: QuestionComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ is my answer something like what you meant?
type: Comment
comment on: http://stackoverflow.com/q/49742196

http://stackoverflow.com/comment/86423066
comment on: http://stackoverflow.com/a/49689204
score: 0
has text: @M.Rod Check out my updated answer and let me know the status.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86280397
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49636335
has text: I'd use `assign` but this is my answer.

http://stackoverflow.com/a/49724945
accepted answer of: http://stackoverflow.com/q/49724816
type: AcceptedAnswer
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49724816
has body: Structure of file : (Note that the number lines are tab separated) 1 3 abc def ghi 2 2 jkl mno 3 4 pqr stu vwx yz Now try : f=open(filename) all_lines=f.readlines() #read all lines content=[] #empty list for i in range(len(all_lines)): #for each line if(len(all_lines[i].split('\t'))==2): #check if when you split by tab the line has two members only i=i+1 c=[] #for the current segment while(i&lt;len(all_lines) and len(all_lines[i].split('\t'))!=2): #until next segment is reached c.append(all_lines[i].strip()) #append to current segment i=i+1 content.append(c) #append entire current segment to overall content for c in content: print(c) Output : ['abc', 'def', 'ghi'] ['jkl', 'mno'] ['pqr', 'stu', 'vwx', 'yz']
score: 0

google-cloud-functions
tag name: google-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/49716767

http://stackoverflow.com/q/49679283
downvote count: 1
has answer: http://stackoverflow.com/a/49679964
has comment: http://stackoverflow.com/comment/86371391
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86370447
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86370529
has comment: http://stackoverflow.com/comment/86370346
favorite count: 0
type: Question
upvote count: 2
has body: I'm using python 2.7.10 virtualenv when running python codes in IntelliJ. I need to install requests[security] package. However I'm not sure how to add that [security] option/config when installing requests package using the Package installer in File > Project Structure settings window.
type: UnansweredQuestion
tagged with: intellij-idea
has title: How to Install requests[security] in virtualenv in IntelliJ
tagged with: python
tagged with: virtualenv

http://stackoverflow.com/comment/139968794
type: AnswerComment
score: 0
has text: Is there any information on what order the drivers will be listed? Is there any merit in using `drivers[-1]`?
type: Comment
comment on: http://stackoverflow.com/a/49736571

http://stackoverflow.com/q/49746712
score: 1
has title: python subprocess.popen kill subprog when parent prog exits?
answer count: 1
has answer: http://stackoverflow.com/a/49746941
downvote count: 0
has body: In python 2.7 if program master uses subprocess.Popen to start subprocess and then exits, subprocess will continue to run. I think that this is consistent with process handling in general, at least for *nix. This seems to imply that if some of my subprocess programs run forever and I kill master the subprocesses will continue to run. Is that correct? (I ask because of the possibility that killing a process behaves differently than simply having it exit of its own accord). In StackOverflow entries about command shells (not Python) there is mention of being able to create a subprocess that actually will terminate if its creator process dies. They seem to be called "daemonic" processes. Is there a similar way to make this happen automatically in Python? That is, is there a way I can use subprocess.Popen or another method to start a subprocess that will automatically die if the parent dies? The child processes are very different so threading is not an option.
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86507655
tagged with: python
tagged with: subprocess

http://stackoverflow.com/comment/101074841
has text: Apparently I was not the only one with a segfault: https://github.com/keras-team/keras/issues/11322
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49675283

http://stackoverflow.com/a/49695938
has comment: http://stackoverflow.com/comment/126312217
upvote count: 10
downvote count: 1
has body: data['result'] is a dictionary. Iterating over dict means iterating over its keys. Therefore key variable stores a string. That's why key['id'] raises TypeError: string indices must be integers.
type: Answer
accepted answer of: http://stackoverflow.com/q/49695836
score: 9
answers question: http://stackoverflow.com/q/49695836
has comment: http://stackoverflow.com/comment/126317254
type: AcceptedAnswer

http://stackoverflow.com/a/49651569
answers question: http://stackoverflow.com/q/49651202
has comment: http://stackoverflow.com/comment/86311414
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86311338
has comment: http://stackoverflow.com/comment/86311447
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86311525
has body: Why don't you use datetime? Use something like this import datetime logtime = datetime.datetime.fromtimestamp(x) begintime = datatime.datetime.fromtimestamp(a) arrivaltime = logtime - datetime.timedelta(minutes=5) return (arrivaltime &lt;= logtime and logtime &lt;= begintime) logtime is the datetime from x begintime is the datetime from a and arrivaltime is 5 minutes earlier than begintime

http://stackoverflow.com/comment/101421795
score: 0
comment on: http://stackoverflow.com/q/49623249
has text: **You say "dataframe" but you show a 1D dataframe/Series, then you say "Note: I have matrix not vector". Which is it?** And `df1 = [1,2,8,6]` is a plain Python list, not any of those. Please give executable code (MCVE).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86402135
score: 0
comment on: http://stackoverflow.com/q/49694818
type: Comment
has text: Additionally getting the error as below, kindly have a look: ~\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs) 648 class HTTPDefaultErrorHandler(BaseHandler): 649 def http_error_default(self, req, fp, code, msg, hdrs): --> 650 raise HTTPError(req.full_url, code, msg, hdrs, fp) 651 652 class HTTPRedirectHandler(BaseHandler): HTTPError: HTTP Error 405: Method Not Allowed
type: QuestionComment

http://stackoverflow.com/comment/86291428
has text: @LeonChen - Ok, I've added the 'other' approach. It does require the change of the call to `magic_debug()` tho.
type: AnswerComment
comment on: http://stackoverflow.com/a/49641717
score: 0
type: Comment

http://stackoverflow.com/a/49677786
has body: There are two ways melt and stack df.melt('Date') Out[1303]: Date variable value 0 11-30-86 Stock1 2.45000 1 12-31-86 Stock1 -2.57000 2 01-31-87 Stock1 13.50000 3 02-28-87 Stock1 3.99000 4 11-30-86 Stock2 0.47021 5 12-31-86 Stock2 1.09626 6 01-31-87 Stock2 9.33911 7 02-28-87 Stock2 4.63777 8 11-30-86 Stock3 1.45879 9 12-31-86 Stock3 -2.67784 10 01-31-87 Stock3 11.14448 11 02-28-87 Stock3 5.96181 df.set_index('Date').stack().reset_index() Out[1304]: Date level_1 0 0 11-30-86 Stock1 2.45000 1 11-30-86 Stock2 0.47021 2 11-30-86 Stock3 1.45879 3 12-31-86 Stock1 -2.57000 4 12-31-86 Stock2 1.09626 5 12-31-86 Stock3 -2.67784 6 01-31-87 Stock1 13.50000 7 01-31-87 Stock2 9.33911 8 01-31-87 Stock3 11.14448 9 02-28-87 Stock1 3.99000 10 02-28-87 Stock2 4.63777 11 02-28-87 Stock3 5.96181
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49677717
upvote count: 1
has comment: http://stackoverflow.com/comment/86481660

http://stackoverflow.com/comment/86389442
type: Comment
type: QuestionComment
has text: @pissall, I used softmax using my dataset(not mnist's data) and for that I got a score of 65%. I am working on CNN against my dataset, but the accuracy is still low.
score: 0
comment on: http://stackoverflow.com/q/49688880

http://stackoverflow.com/q/49673910
favorite count: 0
type: Question
upvote count: 4
tagged with: tkinter
tagged with: treeview
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49674744
has title: How to insert value in tkinter entry widget while entry is disabled
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49674744
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86360083
has body: Am trying to insert value in tkinter entry while the widget is disabled.I want to achieve that for the value in the entry widget not to be deleted.Have checked this site to find similar question to address this but couldn't found any. from tkinter import ttk import tkinter as tk blow = [("january", "2013")] def func(): for child in tree.get_children(): sum =(tree.item(child, "values")[1]) e1.delete(0, tk.END) e1.insert(0, sum) print(sum) root = tk.Tk() root.geometry("400x300") tree = ttk.Treeview(columns=("columns1", "columns"), show="headings", selectmode="browse") tree.heading("#1", text="Month") tree.heading("#2", text="Year") for n in blow: tree.insert("", tk.END, values=(n)) tree.pack() b1 = tk.Button(text="insert", command=func) b1.pack() e1 = tk.Entry() e1.config(state="disable") e1.pack() root.mainloop()

http://stackoverflow.com/q/49684813
has answer: http://stackoverflow.com/a/49685456
tagged with: cassandra
has comment: http://stackoverflow.com/comment/86381352
has comment: http://stackoverflow.com/comment/86381271
downvote count: 0
score: 1
tagged with: python
has body: I'm new in Flask. I'm trying to write a very simple app. Since I come from the MVC world I'm trying to organice my code following a minimalistic MVC structure. So I've got the following: priceChecker/ core/ controllers/ __init__.py ItemController.py models/ model.py item.py __init__.py services __init__.py static/ templates/ __init__.py priceChecker.py priceChecker.py: import os from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash from cassandra.cluster import Cluster app = Flask(__name__) # load config from this file, app.py app.config.from_object(__name__) #app.run(debug=True, use_debugger=False, use_reloader=False) cluster = Cluster() keyspace = 'testdb' db = cluster.connect(keyspace) from priceChecker.core.controllers.ItemController import ItemController app.debug = True @app.route('/search', methods=['GET', 'POST']) def show_search_form(): item = ItemController() if request.method == 'POST': return 'post' else: a='get' first_order = item.retrieveItems for order in first_order: print(order.shipname) return render_template('search.html') model.py from priceChecker.priceChecker import db class Model(db): def __init__(self, tableName): self.__tablename__ = tableName def getAll(self, conditions=[]): try: result = db.execute("SELECT * FROM " + self.__tablename__) return result except ValueError: print("Oops, something went wrong!...") item.py from priceChecker.core.models.model import Model as db class Item(db): def __init__(self): super().__init__('orders') def getAllItems(self): return db.getAllItems() ItemController.py from priceChecker.core.models.item import Item class ItemController: def __init__(self): self.item = Item() def retrieveItems(self): allItms = self.item.getAllItems() return allItms When running the app I'm getting some errors: AttributeError: 'str' object has no attribute 'profile_manager' and if I move the following line to the top from priceChecker.core.controllers.ItemController import ItemController I'm…
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86381873
has comment: http://stackoverflow.com/comment/86381124
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86381318
has title: Flask: ImportError: cannot import name 'db'
tagged with: flask
favorite count: 0

http://stackoverflow.com/q/49683215
score: 0
tagged with: list
answer count: 2
has title: read instrument file and print the waveform
has comment: http://stackoverflow.com/comment/86378325
tagged with: string
type: Question
has body: I tried to print the sound wave, read a score.txt file from scores folder, in this case, 'piano', then I locate instrument file 'piano' in instruments folder With a score .txt file 'score': piano |*********************| And instrument file 'piano': 3 --- 2 / \ 1 / \ 0 --- --- -1 \ / -2 \ / -3 --- Note that the character after the number is a tab character('\t') and the rest of the character in the line are either spaces, slashes or dashes. I wonder how could I print the final waveform python waveform.py score piano: 3: *** 2: * * 1: * * 0: *** * *** -1: * * -2: * * -3: ***
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49683276
tagged with: python
has answer: http://stackoverflow.com/a/49692811

http://stackoverflow.com/comment/86563544
has text: Can you help me with flattening the image after the images have been flipped? Where do I put the placeholder for flatten?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49709517

http://stackoverflow.com/q/49688476
tagged with: vb.net
has comment: http://stackoverflow.com/comment/86388299
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49689239
has comment: http://stackoverflow.com/comment/86388606
has answer: http://stackoverflow.com/a/49689239
linked to: http://stackoverflow.com/q/2017225
upvote count: 0
has title: Converting python code to vb.net
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 3
tagged with: uipath
linked to: http://stackoverflow.com/q/44721351
favorite count: 0
type: Question
tagged with: rest
score: -3
has body: I have a python code. I need vb.net equivalent of it. Thanks in advance. payload2 = {"auth_token": "YOUR_AUTH_TOKEN", "status":"green", "data-title1":"index", "data-title2":"machine1", "data-title3":"package10", "data-title4":"current", "data-title5":"tmp"} r=requests.post("http://localhost:3030/widgets/hot21",data=json.dumps(payload2)) Extra information Code is invoked in "UiPath community edition" Last code (thanks to JussiV) is Imports System.Text Dim payload2 As New Dictionary(Of String, String) payload2.Add("auth_token", "YOUR_AUTH_TOKEN") payload2.Add("status", "green") payload2.Add("data-title1", "index") payload2.Add("data-title2", "machine1") payload2.Add("data-title3", "package10") payload2.Add("data-title4", "current") payload2.Add("data-title5", "tmp") Dim params As String = JsonConvert.SerializeObject(payload2, Formatting.None) Dim Uri As New Uri(String.Format("http://10.10.115.99:3030/widgets/hot21")) Dim webClient As New WebClient() Dim resByte As Byte() Dim resString As String Dim reqString() As Byte webClient.Headers("content-type") = "application/json" Dim senddata As Object = JsonConvert.SerializeObject(New With {Key .param = params}).ToString() reqString = Encoding.Default.GetBytes(senddata) resByte = webClient.UploadData(Uri, "post", reqString) resString = Encoding.Default.GetString(resByte) Last error-messages are webservice has thrown an exception Source: Invoke code Message: Error compiling code error BC30035: syntax error. At line 1 error BC30561: 'Formatting' is ambiguous, imported from the namespaces or types 'Newtonsoft.Json, System.Xml'. At line 10 error BC30002: Type 'WebClient' is not defined. At line 12 error BC30451: 'Encoding' is not declared. It may be inaccessible due to its protection level. At line 18 error BC30451: 'Encoding' is not declared. It may be inaccessible due to its protection level. At line 20 Exception Type: ArgumentException
tagged with: python

http://stackoverflow.com/comment/86498762
type: Comment
type: QuestionComment
has text: Use this command to run scrapy scripts: scrapy crawl Quotes -o result123.csv
comment on: http://stackoverflow.com/q/49741770
score: 0

http://stackoverflow.com/comment/86246273
type: AnswerComment
has text: I am not sure what is installed with `brew install htslib`. If only the library — it's not enough. `pysam` seems to be required htslib's sources.
comment on: http://stackoverflow.com/a/49619051
score: 0
type: Comment

http://stackoverflow.com/a/49617866
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49601031
downvote count: 0
upvote count: 1
has body: Python uses arbitrary-size integers, whereas z3 clamps all intermediate results to 32 bits, so F gives different results for Python and z3. You'd need something like def F1(w): return ((w * 31337) ^ (((w * 1337) &amp; 0xffffffff) &gt;&gt; 16)) % 2**32 def F1Z(w): return ((w * 31337) ^ LShR(((w * 1337) &amp; 0xffffffff), 16)) % 2**32 s.add ( F1Z(w) == F1(0x41414141))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49601031

http://stackoverflow.com/comment/86321915
score: 1
comment on: http://stackoverflow.com/q/49639586
type: Comment
type: QuestionComment
has text: You _can_ write a MCVE for this problem: the simplest program that sets `foo` and kicks off the crawler, and also registers a trivial pipeline class and gets the pipeline created by the crawler. Of course that program will not get `foo` passed in anywhere—but that's exactly the problem you're trying to demonstrate. So just add `# I need to use foo here, but I don't have it and don't know where to get it from`, and you've got an MCVE. Then someone can just show you how to get `foo` from one part of your program to the other, without having to guess that's what you're after.

http://stackoverflow.com/q/49664010
tagged with: python
tagged with: flask
tagged with: routes
has body: I am learning Flask and have a question regarding use of variables in the context of routes.For Example, my app.py: from flask import Flask, render_template app = Flask(__name__) @app.route("/index") def index(): a=3 b=4 c=a+b return render_template('index.html',c=c) @app.route("/dif") def dif(): d=c+a return render_template('dif.html',d=d) if __name__ == "__main__": app.run() Under the route /dif the variable d is calculated by taking the values of already calculated c and a.How to share variables c and a between pages, so that variable d is calculated and rendered to dif.html? Thank You
answer count: 2
has answer: http://stackoverflow.com/a/49664342
duplicate of: http://stackoverflow.com/q/32815451
upvote count: 7
linked to: http://stackoverflow.com/q/32815451
tagged with: jinja2
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49665802
type: UnansweredQuestion
has title: Using variables across Flask routes
score: 6

http://stackoverflow.com/comment/86386798
type: Comment
has text: `Why "left" and "right" should return a sorted function`. left and right are list variables, they don't return a sorted function. The lambda function is needed for comparison. In other words: it defines how (in which order) you sort elements. Can you be more clear on what you are asking? I really struggle to understand what the questions are.
score: 0
comment on: http://stackoverflow.com/q/49687566
type: QuestionComment

http://stackoverflow.com/a/49629918
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49629390
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49629390
has body: I assume your Python program does not see your host machine local directory from the container. You did not provide your dockerfile or docker command you used for running the container. You need to declare a volume in your dockerfile and bind a local directory from your computer to the container volume. You can find more information about declaring a volume and mounting it here: https://docs.docker.com/engine/reference/builder/ https://docs.docker.com/storage/bind-mounts/ Hope this helps. Br, Veikko

http://stackoverflow.com/q/49631137
accepted answer: http://stackoverflow.com/a/49631283
has answer: http://stackoverflow.com/a/49631283
has answer: http://stackoverflow.com/a/49631398
upvote count: 1
downvote count: 1
has body: Purpose: To create a code that can check a list of variables to see if they are prime numbers or not. Problem: Upon running this code, for the value of 8 I will see False followed by True. Question: Why am I seeing False then True when I just expect to see False because 8 is not a prime number? Is it because I am using break wrongly? Or is it because of where I put print? I placed it at that indentation because I wanted I to check if all values of number % n!=0 before it returned True. Code def prime_number(x): for number in x: n = 2 if number &lt;=2: return False elif number &gt; 2: while n &lt; number -1: if number % n == 0: print False n+=1 break elif number % n !=0: print number % n n +=1 print True print prime_number([8])
favorite count: 0
type: Question
has title: Whats wrong with my indentation/position of print or use of break? Python
possible better answer: http://stackoverflow.com/a/49631398
has comment: http://stackoverflow.com/comment/86269357
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/a/49980435
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87096910
has comment: http://stackoverflow.com/comment/87055804
has comment: http://stackoverflow.com/comment/87054878
has comment: http://stackoverflow.com/comment/87096866
has comment: http://stackoverflow.com/comment/86979780
has comment: http://stackoverflow.com/comment/86977536
type: Answer
has comment: http://stackoverflow.com/comment/86979849
has comment: http://stackoverflow.com/comment/86977371
has body: UPDATE I am able to run the code below with no problems in both GCE VM instance and in a Google Cloud Datalab Instance, and using both Python 2 and Python 3. However, I think there is some issue going on with the lightgbm package. If I set n_jobs=1 it runs quite fast (less than 1 minute). If I set n_jobs to i.e. 16 or whatever the number of cores available, it gets super slow (it lasts 10-15 min.). Maybe it would be worth opening an issue in the Github Repo to find out about this. (btw: see that I'm not using the %matplotlib inline command in Datalab, doesn't look like it's needed.) import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve from sklearn.model_selection import ShuffleSplit from sklearn.metrics import r2_score from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import pandas as pd import numpy as np !pip install lightgbm from lightgbm import LGBMRegressor def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.legend(loc="best") return plt df = pd.DataFrame.from_csv(…
answers question: http://stackoverflow.com/q/49666274

http://stackoverflow.com/comment/86380284
has text: @ErikIverson The QScrollArea is a widget whose only task is to manage the scrollbars when they are needed, the container, in the case of scrollAreaWidgetContents is the content, and it must be unique, if you want to place several widgets then those widgets must be part of scrollAreaWidgetContents. If my answer helped, do not forget to mark it as correct, if you do not know how to do it, review the [tour], that's the best way to thank.
score: 0
comment on: http://stackoverflow.com/a/49678291
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86378987
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49659620
has text: So I did get that to work by running the whole code at once, I was trying to run it line by line and ran into an issue for some reason. I was planning on using the html tags to identify the items that i wanted to isolate but given the format I don't think that will work here. Any suggestions? I appreciate the help.

http://stackoverflow.com/a/49725333
downvote count: 0
upvote count: 7
has body: You can using value_counts df.groupby(['id','group']).Animal.value_counts().unstack(fill_value=0).loc[:,'Cat'].tolist() Out[144]: [2, 0, 0, 2] More info return before the last step .loc df.groupby(['id','group']).Animal.value_counts().unstack(fill_value=0) Out[145]: Animal Cat Dog Rat id group A A 2 1 0 B 0 1 0 B B 0 0 1 C 2 0 0
answers question: http://stackoverflow.com/q/49725273
type: Answer
score: 7

http://stackoverflow.com/comment/86233172
type: QuestionComment
comment on: http://stackoverflow.com/q/49613309
type: Comment
score: 0
has text: Welcome to SO. Please provide a [mcve]. It would help, for example, if you fixed your code formatting and provided some code so we can replicate your error.

http://stackoverflow.com/comment/86441197
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49713914
has text: @AllenUnderwood my apologies i made a typo, it is fixed now :)

http://stackoverflow.com/comment/86237988
has text: My guess is that this is related to the issue [here](https://stackoverflow.com/q/47738537/4799172) but can't be sure. Point 2 in my answer will make Spyder behave more rationally so that these issues don't slip under the radar until you take scripts out of the environment. Does it work?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49615426
score: 0

http://stackoverflow.com/comment/86288794
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49640468
type: QuestionComment
has text: Thanks for your response @user2357112 . I am pretty new to python. Do you have any suggestions how to make the python interpreter run the output of the curl command (and not process it as a file as you correctly noticed)

http://stackoverflow.com/comment/86527276
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49751507
has text: Unfortunately, serializer validation and model validation are two different things. The latter is not called by DRF as far as I know. You may have to force a call to your model instance validate_unique method if you want it to work. But I don't see the point, the easier way is clearly to use the validator from DRF.

http://stackoverflow.com/comment/86246250
type: Comment
has text: Okay, I understand this now, thank you so much! Good luck in the future man.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49619532

http://stackoverflow.com/a/49691993
accepted answer of: http://stackoverflow.com/q/49691170
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49691170
upvote count: 2
downvote count: 0
type: Answer
has body: Here's a concept... Generate 30,000,000 line CSV with Perl - takes 11 seconds on my Mac: perl -E 'for($i=0;$i&lt;30000000;$i++){say "Line $i,field2,field3,",int rand 100}' &gt; BigBoy.csv Sample Output Line 0,field2,field3,49 Line 1,field2,field3,6 Line 2,field2,field3,15 ... Line 29999998,field2,field3,79 Line 29999999,field2,field3,19 Take 1% of the lines and shuffle them - takes 3 seconds and 15MB of RAM: awk 'rand()&gt;0.99' BigBoy.csv | gshuf &gt; RandomSet.csv RandomSet.csv contains 299,748 lines: Sample Output Line 15348259,field2,field3,95 Line 1642442,field2,field3,93 Line 29199452,field2,field3,52 gshuf installed on Mac using homebrew: brew install coreutils
score: 2

http://stackoverflow.com/q/49639576
possible better answer: http://stackoverflow.com/a/49639589
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: List Comprehension Check for strings and Give a custom printed error
accepted answer: http://stackoverflow.com/a/49639624
has answer: http://stackoverflow.com/a/49639589
tagged with: python
has answer: http://stackoverflow.com/a/49639624
has body: I need to check if the list contain a string or letter instead of number. The code give me a custom printed error for e.g print(list contain letter try again) What I've Tried so far here are two list of mine p=[4,8,9,5,1,2,3, 4,5,6,7,8,9,10,11,12,13,14,15,3,'a'] b=[8,10,12,6,2,3,4,5,6,7,8,9,10,11,19,13,17,14,13,5] What my code needs to check is that if one of both list contain a variable or are not of same length it gives me custom printed error: if len(p) != len(b) or (Check for string): print('The length is not equal') else: print([(p[i] ** 2 + b[i] ** 2) ** 1 / 2 for i in range(len(p))]) .isdigit or isalpha doesnot work on lists. So what is the simplest way to check if list contain a str it works with my if condition?
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/comment/86210401
type: QuestionComment
score: 1
has text: For future reference: There are many tkinter behaviors that are not documented, or only documented in a third-party site that's impossible to search for because of dozens of useless crapsites like pythonspot—but [the underlying Tcl/Tk docs](https://www.tcl.tk/man/tcl8.6/TkCmd/getOpenFile.htm#M15) are always thorough. You do have to figure out how to map that Tcl stuff to what tkinter does in Python, but in this case, you could probably guess at and test at least passing separate filetypes with the same names.
comment on: http://stackoverflow.com/q/49601432
type: Comment

pandas-groupby
tags question: http://stackoverflow.com/q/49602329
tags question: http://stackoverflow.com/q/49672081
tags question: http://stackoverflow.com/q/49736311
type: Tag
tags question: http://stackoverflow.com/q/49702955
tags question: http://stackoverflow.com/q/49754398
tags question: http://stackoverflow.com/q/49689780
tags question: http://stackoverflow.com/q/49683143
tags question: http://stackoverflow.com/q/49696135
tags question: http://stackoverflow.com/q/49637320
tags question: http://stackoverflow.com/q/49656909
tags question: http://stackoverflow.com/q/49697056
tags question: http://stackoverflow.com/q/49704283
tags question: http://stackoverflow.com/q/49626132
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/49702696
tags question: http://stackoverflow.com/q/49685215
tags question: http://stackoverflow.com/q/49661049
tags question: http://stackoverflow.com/q/49690973
tags question: http://stackoverflow.com/q/49738381
tags question: http://stackoverflow.com/q/49732049
tags question: http://stackoverflow.com/q/49690316
tags question: http://stackoverflow.com/q/49642062
tags question: http://stackoverflow.com/q/49725273
tags question: http://stackoverflow.com/q/49671050

http://stackoverflow.com/q/49619681
accepted answer: http://stackoverflow.com/a/49620662
has comment: http://stackoverflow.com/comment/86247116
has answer: http://stackoverflow.com/a/49620662
favorite count: 0
tagged with: numpy
has title: Python - Pandas random sampling per group
type: AnsweredQuestion
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86247305
tagged with: python
answer count: 1
has body: I have a dataFrame really similar to that, but with thousands of values : import numpy as np import pandas as pd # Setup fake data. np.random.seed([3, 1415]) df = pd.DataFrame({ 'Class': list('AAAAAAAAAABBBBBBBBBB'), 'type': (['short']*5 + ['long']*5) *2, 'image name': (['image01']*2 + ['image02']*2)*5, 'Value2': np.random.random(20)}) I was able to find a way to do a random sampling of 2 values per images, per Class and per Type with the following code : df2 = df.groupby(['type', 'Class', 'image name'])'Value2'.apply(lambda s: s.sample(min(len(s),2))) I got the following result : I'm looking for a way to subset that table to be able to randomly choose a random image ('image name') per type and per Class (and conserve the 2 values for the randomly selected image. Excel Example of my desired output :
tagged with: random
type: Question
tagged with: pandas
score: 3

http://stackoverflow.com/a/49669790
has body: I know that you are trying to achieve this with selenium. But more efficiently it would be to use requests and beautifulsoup libs. They work with both 2.7 and 3.x versions of Python. Simple example for your problem: Ok, so the html looks like this: .. .. .. .. .. .. .. My previous code: import requests from bs4 import BeautifulSoup response = requests.get(yourUrl) soup = BeautifulSoup(response.text, 'html.parser') companyPersons = {} for company in soup.find_all('tr',{'class': 'company'}): # find all class'es with company for person in company.children: # finds all children tags, e.g. company has 2 childrens person1 and person2, so it will find both if company in companyPersons: companyPersons[company].append(person) else: companyPersons[company] = person Edit to previous answer I have checked the html and what is needed to get. Well the way is similar to what I wrote earlier, just with little tweaks. test_dict = {} for company in soup.find_all('tr', {'class': 'regroworg'}): for child in company.find_all('span', {'class': 'regorgname'}): for person in company.find_next_siblings('tr', {'class': 'regrow'} != {'class': 'regroworg'}): if person['class'] != company['class']: if child.text not in test_dict: test_dict[child.text] = [person.text] else: test_dict[child.text].append(person.text) else: break The code above works as you wrote. It should grab all the company's persons. This part in the code {'class': 'regrow'} != {'class': 'regroworg'} is doing all the magic for finding needed siblings. And result will be similar to this: test_dict['ABB Secheron Ltd.'] ['\nMr. Emmanuel Mittay, Key Account Manager\nemmanuel.mittay@ch.abb.com\n41 58 586 25 09\n41 58 586 22 28'] And now you can write data to .CSV or anywhere else. Some issues with code that solves current problem Of course I think that it could be done better from performance view, but for current problem it should be fine. And I noticed that there is roughly 607 company's (but I'm not 100% sure about this number),…
answers question: http://stackoverflow.com/q/49665316
score: 0
has comment: http://stackoverflow.com/comment/86357145
has comment: http://stackoverflow.com/comment/86356906
type: Answer

http://stackoverflow.com/a/49681608
has comment: http://stackoverflow.com/comment/86375127
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49681524
score: 2
has body: arr = ['z', 'r', 't'] n = 5 arr = [-1] * n print arr ''' [-1, -1, -1, -1, -1] ''' # the values of 'arr' have been changed

http://stackoverflow.com/q/49743661
has title: Pandas - Set DateTimeIndex on Melted DF
tagged with: pandas
score: 1
downvote count: 0
has body: price size 0 6759.0 19493 1 6758.5 39015 2 6758.0 31137 3 6757.5 30 4 6757.0 2730 5 6756.5 1290 6 6756.0 4287 7 6755.5 20117 8 6755.0 227173 9 6754.5 368844 10 6754.0 618665 11 6753.5 9000 12 6753.0 28846 13 6752.5 72021 14 6752.0 229463 15 6751.5 110 16 6751.0 13008 17 6750.5 15150 18 6750.0 65950 19 6749.5 19916 Melt,set column names and take values only: df = df.melt().T df.columns = [colnames] df = df[-1:] To produce the final df I want to set the index of: sell_price_10 sell_price_9 sell_price_8 sell_price_7 sell_price_6 sell_price_5 sell_price_4 sell_price_3 sell_price_2 sell_price_1 buy_price_1 buy_price_2 buy_price_3 buy_price_4 buy_price_5 buy_price_6 buy_price_7 buy_price_8 buy_price_9 buy_price_10 sell_size_10 sell_size_9 sell_size_8 sell_size_7 sell_size_6 sell_size_5 sell_size_4 sell_size_3 sell_size_2 sell_size_1 buy_size_1 buy_size_2 buy_size_3 buy_size_4 buy_size_5 buy_size_6 buy_size_7 buy_size_8 buy_size_9 buy_size_10 value 6759 6758.5 6758 6757.5 6757 6756.5 6756 6755.5 6755 6754.5 6754 6753.5 6753 6752.5 6752 6751.5 6751 6750.5 6750 6749.5 19493 39015 31137 30 2730 1290 4287 20117 227173 368844 618665 9000 28846 72021 229463 110 13008 15150 65950 19916 This has worked for me in the past, but gives a ValueError: Must pass DataFrame with boolean values only error when setting the new index when I try with this df. df['time'] = pd.to_datetime(round(time.time(),0), unit='s') df.set_index(df['time'], inplace=True) df.drop(['time'],axis=1, inplace=True)
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86502539
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49743915
has comment: http://stackoverflow.com/comment/86502497
has answer: http://stackoverflow.com/a/49743915
type: AnsweredQuestion

http://stackoverflow.com/comment/86502089
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49743230
type: QuestionComment
has text: Since your code works as you posted it here, try copy-pasting from here.

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/49722276
type: Tag

http://stackoverflow.com/a/49620681
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86248552
has comment: http://stackoverflow.com/comment/86248508
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49620220
type: Answer
has body: That's what the terminate method is for, but you have to be careful how you use it. It will kill the worker processes, but surprisingly it won't stop you from blocking forever on a waiting call. So you can only use it if you do apply_async or imap_unordered calls. Closing from another thread typically causes your calls into the pool to hang. In this example I set chunksize to 1 which is the preferred value if a single work item has a significant amount of processing. You can set chunksize to something greater if work item cost is low and you don't mind processing more items before you are done. But don't use the default... must items will be processed before anything makes it back to you. import multiprocessing def worker(item): print(item) return item if __name__ == "__main__": with multiprocessing.Pool(4) as pool: for i in pool.imap_unordered(worker, range(100), chunksize=1): if i == 10: print('terminate') pool.terminate() break print('done')
has comment: http://stackoverflow.com/comment/86248488
accepted answer of: http://stackoverflow.com/q/49620220
downvote count: 0
has comment: http://stackoverflow.com/comment/86248373

http://stackoverflow.com/comment/86370976
type: Comment
comment on: http://stackoverflow.com/a/49679349
score: 0
type: AnswerComment
has text: I am suggesting you convert all of your arithmetic here to fractions and get rid of the floats altogether

http://stackoverflow.com/comment/86319137
type: Comment
comment on: http://stackoverflow.com/a/49655134
type: AnswerComment
has text: I want to generate a table from that user_list. I want 3 columns on each row.
score: 0

http://stackoverflow.com/comment/86213411
comment on: http://stackoverflow.com/q/49603044
has text: Have you tried a more refined regex? `\w+` is too broad.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86477347
has text: @jpp - self: https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self - removed it it's not relevant. Neither is what happens afterwards. I am unable to use the `any`-method properly and would like to know if in my case this is the method which is supposed to be used and if there is a method existing. My question is clear, why is it important what the rest of the code is doing?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49731099
type: QuestionComment

http://stackoverflow.com/a/49744753
has body: You have not provided the full code and data file to reproduce your problem exactly. But it's possible to guess your issue from the error message. Your line[:-1].split(token) failed to break up line into single-number strings. Either you picked an incorrect separator (token is a poor choice of name), or/and omitting the last character from line broke it. Try this (also reducing many unnecessary lines) def read_data_file(datafile): dataset = [] for line in open(datafile, 'r'): # no need to assign open() to file, it will be closed when for is done dataset.append( [ float(token) for token in line.split() ] ) # default (separator=None) works for most situations dataset.append(1e+99) # do you really need to append a fake number? # a better way might be a list of lists return dataset
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49744601

http://stackoverflow.com/comment/86349003
score: 0
type: Comment
has text: Thanks a lot. One more question: It does not work if I use it with (2464,150,1) and input _shape: (150,1). I ask, as I later want to also use different input data of the same dimensions but with multiple features. But then changing the input dimension to (150,num_features), might not work, or is this only a problem of the 1 in (150,1)?
type: AnswerComment
comment on: http://stackoverflow.com/a/49668012

http://stackoverflow.com/comment/89806582
type: Comment
has text: I have sent you an email! Would you please take a look? My email address is p[dot]morad[at]hotmail.com
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49643273

http://stackoverflow.com/a/49708904
has comment: http://stackoverflow.com/comment/86473918
has comment: http://stackoverflow.com/comment/86431847
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86433969
answers question: http://stackoverflow.com/q/49708847
has body: Your code creates a list immediatly then prints every list. Your question is unclear exactly what you want, but I believe you want a list of all of the metadata objects. You would do that by changing the code: for match, positions in d.items(): listMetaData = [{"file Name":fileName,"searched Word":match,"number of occurence":len(positions)}] jsondata = json.dumps(listMetaData) print(jsondata) to all_metadata = [] for match, positions in d.items(): meta_data = {"file Name":fileName,"searched Word":match,"number of occurence":len(positions)} all_metadata.append(meta_data) json_data = json.dumps(all_metadata) print(json_data) return json_data note that python is meant to not use camel case for variables, but snake case. Also, indentation should be with 4 spaces (or a tab), not 10 spaces.

http://stackoverflow.com/comment/86400732
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49683090
has text: I gave the wrong link, I changed my comment and answer. Sorry

http://stackoverflow.com/comment/86922421
type: Comment
score: 0
has text: Well there is an easy solution for that.
type: AnswerComment
comment on: http://stackoverflow.com/a/49603871

http://stackoverflow.com/comment/86235676
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49614516
has text: Could it be a missing "return contacts" in your load() function?
score: 1

http://stackoverflow.com/q/49602310
tagged with: python-magic
linked to: http://stackoverflow.com/q/2953834
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86211968
has comment: http://stackoverflow.com/comment/86211953
favorite count: 0
has body: I want to use Python-Magic library, but I get: magic.magic.MagicException: b'could not find any valid magic files!' Error on a simple code like this: filepath = 'path\\somefile.txt' print(magic.from_file(filepath)) I did google the error message and I tried this; as mentioned Missing files for `magic` library on Windows magic_object = magic.Magic(magic_file = 'C:\\Program Files (x86)\\GnuWin32\\share\\misc\\magic') This time I get this error: magic.magic.MagicException: b"File 5.32 supports only version 14 magic files. `C:\Program Files (x86)\GnuWin32\share\misc\magic.mgc' is version 7" I also did this; Python Error : File 5.3 supports only version 7 magic file nothing changes. Also I tried changing environment variableMAGIC=path\to\gnuwin32\share\misc\magic and downloading http://gnuwin32.sourceforge.net/packages/file.htm and nothing changes. Thanks in advance,
type: Question
has comment: http://stackoverflow.com/comment/86211911
type: UnansweredQuestion
tagged with: python
has title: Python-Magic 'could not find any valid magic files!'
has comment: http://stackoverflow.com/comment/86211837
has comment: http://stackoverflow.com/comment/86212017
linked to: http://stackoverflow.com/q/41390318
linked to: http://stackoverflow.com/q/14761961
upvote count: 3
has comment: http://stackoverflow.com/comment/86212005
score: 3

http://stackoverflow.com/q/49659474
tagged with: python
has comment: http://stackoverflow.com/comment/86328482
has answer: http://stackoverflow.com/a/49659525
score: 0
answer count: 3
has body: I'm very, very new to Python and thought I would try to experiment with some practical applications. I'm trying to put together a basic web price scraper using the requests library. I picked this webpage :https://www.usstoragecenters.com/storage-units/fl/north-miami-beach/15555-w-dixie-hwy This is the basic structure that I am using: import requests page = requests.get("my url from above") page page.content But for some reason the html print via .content or .text looks very wrong. Instead of seeing the html structure I get what looks like a ton of carriage returns. There is definitely missing data. I tried parsing using beautiful soup (html-parser,html5lib, etc.) which cut out even more of the data. Is this just coded in a way that blocks scraping or am I doing something wrong?
has answer: http://stackoverflow.com/a/49659620
has title: Web Scraping via Python Requests returning gibberish
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49660344

http://stackoverflow.com/q/49689793
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49690317
has comment: http://stackoverflow.com/comment/86391507
has comment: http://stackoverflow.com/comment/86391718
tagged with: pandas
has comment: http://stackoverflow.com/comment/86391850
has body: I have a Pandas DataFrame like : ID Traverse 001 1-&gt;1-&gt;1-&gt;2-&gt;3-&gt;1 002 13-&gt;13 003 2-&gt;3-&gt;13-&gt;15 004 5-&gt;6-&gt;3 005 16-&gt;7-&gt;7-&gt;7-&gt;7-&gt;8 006 4-&gt;4-&gt;3-&gt;5 007 5-&gt;5-&gt;1-&gt;1-&gt;1-&gt;2 Output Should Be Like :- 1 to 1 : 4 1 to 2 : 2 2 to 3 : 2 4 to 4 : 1 3 to 5 : 1 13 to 13 : 1 7 to 7 : 3 . . . So On It's basically identifying the pattern and counting the occurrence of it and giving the output for a DataFrame like this. I wrote a query like :- df.Quad.str.contains(r'1-&gt;1').sum()` #To get 1-&gt;1 But it's adding up the rows which contain pattern like 1->1 but not adding individually Note : 1->1->1 should give an output 1 to 1 : 2 (Likewise)
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86391414
has comment: http://stackoverflow.com/comment/86391643
has comment: http://stackoverflow.com/comment/86391218
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86391949
has comment: http://stackoverflow.com/comment/86391151
has comment: http://stackoverflow.com/comment/86391187
has title: Sum of String Pattern?
has comment: http://stackoverflow.com/comment/86391804
has answer: http://stackoverflow.com/a/49690317
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86391373
has comment: http://stackoverflow.com/comment/86391678
has comment: http://stackoverflow.com/comment/86391915
downvote count: 1
has comment: http://stackoverflow.com/comment/86391889

http://stackoverflow.com/comment/86472384
comment on: http://stackoverflow.com/a/49688262
type: AnswerComment
has text: Are you writing that `self.env.user.id` inside a method called with `sudo()`? Because if you do that, you'll always get the UID 1, it doesn't matter if your current user isn't the *Administrator*.
score: 0
type: Comment

http://stackoverflow.com/q/49711563
has body: I have a list of tensors, with different dimensions. I want to find the maximum absolute scalar value of all the tensors. Trouble is, I think I need a way to do greater than or less than on tensors, but I can only find tf.equal(). This is the kind of thing I'd like to do: curMaxAbs = tf.Variable(-1, tf.float64) for g in myList: maxG = tf.abs(tf.reduce_max(g)) minG = tf.abs(tf.reduce_min(g)) maxAbsG = maxG if tf.greaterThan(maxG,minG) else minG curMaxAbs = maxAbsG if tf.greaterThan(maxAbsG, curMaxAbs) else curMaxAbs Of course there doesn't seem to be a tf.greaterThan() function. Obviously this would be trivial if I could use tf.eval() and convert to numpy arrays but unfortunately I need to do this during construction.
answer count: 1
has answer: http://stackoverflow.com/a/49712553
tagged with: tensorflow
type: Question
has title: Find maximum absolute scalar value in list of tensors
accepted answer: http://stackoverflow.com/a/49712553
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86260046
comment on: http://stackoverflow.com/a/49625980
type: Comment
has text: @Jean-FrançoisFabre one more question, how can I include os.path.dirname ?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86288795
type: QuestionComment
has text: @Brayden I am setting `Class` variables based on a `dataframe` (read from a `.csv` file) which is a table of parameters, all of which have different default values.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49640437

http://stackoverflow.com/comment/137780814
score: 7
has text: For me, this doesn't work, since `defaultdict` will call its first argument (to allow for factories), and `str()` evaluates to `''`, which is not a valid type. Therefore, this should be `defaultdict(lambda: str, …)` instead.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49685031

http://stackoverflow.com/a/49668259
has body: This self.request.url or this (if you need the query_string) self.request.query_string
upvote count: 0
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/49668206
type: Answer

http://stackoverflow.com/q/49641454
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86291495
has comment: http://stackoverflow.com/comment/86290617
score: 1
tagged with: function
downvote count: 0
linked to: http://stackoverflow.com/q/4450592
upvote count: 1
has answer: http://stackoverflow.com/a/49641911
favorite count: 0
has comment: http://stackoverflow.com/comment/86291547
has comment: http://stackoverflow.com/comment/86291295
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86291777
has answer: http://stackoverflow.com/a/49641900
has answer: http://stackoverflow.com/a/49641814
possible better answer: http://stackoverflow.com/a/49641814
answer count: 5
has answer: http://stackoverflow.com/a/49641513
has comment: http://stackoverflow.com/comment/86291050
has comment: http://stackoverflow.com/comment/86291222
tagged with: python
has body: I tried to search the question for a bit but can't find a actual answer. I'm trying to implement a function (magic_debug) so that when called in another function (somefunc), it can access the variable within the somefunc and print it out as follow: def magic_debug(s, *args, **kwargs): s2 = s.format(x=x,y=y,z=args[0]) print(s2) def somefunc(): x = 123 y = ['a', 'b'] magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y)) somefunc() the expected output --> The value of x is 123, and the list is ['a', 'b'] of len 2
has comment: http://stackoverflow.com/comment/86290562
has comment: http://stackoverflow.com/comment/86291401
has comment: http://stackoverflow.com/comment/86291613
has answer: http://stackoverflow.com/a/49641717
accepted answer: http://stackoverflow.com/a/49641717
has title: Python variable scoping of two functions
tagged with: scope

http://stackoverflow.com/a/49659404
score: 0
has body: There's a fantastic function in python called zip that's a bit easier to understand then a list comprehension. What zip does is allow you to iterate over all three lists at the same time, take a look at the following example: A = [1,2,3,4,5] B = [1,2,3,4,5] answers = [2,6,9,16,25] for a, b, answer in zip(A, B, answers): # Check if the element in a is the same as b if a == b: # Multiply them together mult = a * b # Check if a*b is answer if mult == answer: print('{} * {} equals {}. Hooray!'.format(a, b, answer)) else: print('{} * {} does not equal {} '.format(a, b, answer)) else: print('{} does not equal {}'.format(a, b)) Notes: This assumes that A B and answers are all the same length It doesn't check that mult is anywhere in answers, only that it's at the exact same index as the a &amp; b multiplied.
has comment: http://stackoverflow.com/comment/86356500
answers question: http://stackoverflow.com/q/49659237
type: Answer
has comment: http://stackoverflow.com/comment/86335749

http://stackoverflow.com/a/49683389
score: 0
type: AcceptedAnswer
has body: t = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] x = [] for v in t: x.append([v[0], v[2]])
answers question: http://stackoverflow.com/q/49683357
type: Answer
has comment: http://stackoverflow.com/comment/86381065
accepted answer of: http://stackoverflow.com/q/49683357

http://stackoverflow.com/comment/86271943
type: QuestionComment
has text: @kidright, what is `n` (`cv=n`) in your code?
comment on: http://stackoverflow.com/q/49630994
score: 0
type: Comment

http://stackoverflow.com/q/49748498
favorite count: 0
possible better answer: http://stackoverflow.com/a/49748585
type: AnsweredQuestion
score: 3
has body: I am a R programmer currently trying to learn Python / Pandas. Currently I am trying to grapple with how to clearly and cleanly create a new variable from a function that uses multiple existing variables. Note that the function used in my example isn't that complex but I am trying to generalise to the case of an arbitrary function that could be significantly more complex or require more variables, that is to say I am trying to avoid solutions that are optimised for this specific function and more looking how to handle the general scenario. For reference this is an example of how I would do this in R. library(tidyverse) df &lt;- data_frame( num = c(15, 52 , 24 , 29), cls = c("a" , "b" , "b", "a") ) attempt1 &lt;- function( num , cls){ if ( cls == "a") return( num + 10) if ( cls == "b") return( num - 10) } ## Example 1 df %&gt;% mutate( num2 = map2_dbl( num , cls , attempt1)) ## Example 2 df %&gt;% mutate( num = ifelse( num &lt;= 25 , num + 10 , num)) %&gt;% mutate( num2 = map2_dbl( num , cls , attempt1)) Reading the pandas documentation as well as various SO posts I have found multiple ways of achieving this in python, however none of them sit well with me. For reference I've posted my current 3 solutions below: import pandas as pd import numpy as np df = pd.DataFrame({ "num" : [14, 52 , 24 , 29], "cls" : ["a" , "b" , "b" ,"a"] }) ### Example 1 def attempt1( num, cls): if cls == "a": return num + 10 if cls == "b": return num - 10 df.assign( num2 = df.apply( lambda x: attempt1(x["num"] , x["cls"]) , axis = 1)) def attempt2( df): if df["cls"] == "a": return df["num"] + 10 if df["cls"] == "b": return df["num"] - 10 df.assign( num2 = df.apply(attempt2, axis=1)) def attempt3(df): df["num2"] = attempt1(df["num"], df["cls"]) return df df.apply( attempt3 , axis = 1) ### Example 2 df.assign( num = np.where( df["num"] &lt;= 25 , df["num"] + 10 , df["num"]))\ .apply( attempt3 , axis = 1) My issue with attempt 1 is that it appears to be quite horribly verbose. In addition you ne…
tagged with: pandas
has title: What is the pythonic way of creating a pandas variable from multiple other variables
has comment: http://stackoverflow.com/comment/86516710
tagged with: dataframe
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49748695
has answer: http://stackoverflow.com/a/49748585
linked to: http://stackoverflow.com/q/49259580
upvote count: 3
has answer: http://stackoverflow.com/a/49748695
downvote count: 0
tagged with: python

http://stackoverflow.com/q/49637320
type: Question
has answer: http://stackoverflow.com/a/49637691
type: UnansweredQuestion
tagged with: python
has title: pandas groupby with a conditional
answer count: 4
has body: I have this: IDS CR_EARNED TYPE TOT_ALL_TYPES 001 3 A 7 001 3 A 7 001 1 B 7 002 3 A 6 002 3 A 6 003 2 C 8 003 4 C 8 003 2 A 8 TOT_ALL_TYPES is a column I created to sum all TYPE of CR_EARNED for each ID by doing the following: df['TOT_ALL_TYPES'] = df['CR_EARNED'].groupby(df['IDS']).transform('sum') Next, I want to create an new column that will sum CR_EARNED by ID where TYPE = A or B. The result would look like this: IDS CR_EARNED TYPE TOT_ALL_TYPES TOT_AB 001 3 A 7 7 001 3 A 7 7 001 1 B 7 7 002 3 C 6 3 002 3 A 6 3 003 2 C 8 2 003 4 C 8 2 003 2 A 8 2 How would I go about doing this?
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49637400
has answer: http://stackoverflow.com/a/49637393
has answer: http://stackoverflow.com/a/49637761
favorite count: 0

http://stackoverflow.com/a/49650540
answers question: http://stackoverflow.com/q/49645958
upvote count: 1
has body: Just open up a tkMessageBox inside your on_close_release and check the result: #make sure to use import tkMessageBox #[...] # ask the question result = tkMessageBox.askyesno("Really?", "Really really?") # check result as well if "close" in element and self._active == index and result: self.forget(index) self.event_generate("&lt&ltNotebookTabClosed>>")
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/86255313
has text: Then you may have to set a user-agent or referer or other headers. Sorry, i can't help more since i don't have an account.
comment on: http://stackoverflow.com/q/49623406
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/76834801
score: 4
has body: I had the same issue recently and in my case it was because I was writing to a different database than the "default". I have a custom database router that selects the database depending on the request but both read and writes happen on the same database. Note: All my models use the same database during the request. From the django documentation, one must specify a database by providing using="database_alias" to the using block: database_alias = ... # Get the database alias by using the same logic as in the router with transaction.atomic(using=database_alias): Model.objects.create(name="something") raise Exception
downvote count: 0
answers question: http://stackoverflow.com/q/49640460
type: Answer
upvote count: 4

http://stackoverflow.com/comment/86487769
type: QuestionComment
has text: @ma3oun `cls` is not reserved, it's merely idiomatic.
score: 10
type: Comment
comment on: http://stackoverflow.com/q/49736753

http://stackoverflow.com/comment/86520169
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49752808
has text: In your editor settings you can define line length... if you outformated the code, it would take this as reference... its most likely set based on PEP standard...

http://stackoverflow.com/q/49680943
score: 0
tagged with: selenium
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88032314
tagged with: apache
tagged with: python
has body: "Can Selenium be run on an Apache web server?" Update: The solution was to use Docker and a micro services architecture on a cloud hosted virtual machine.
has title: Selenium running on Apache
has comment: http://stackoverflow.com/comment/86374212
tagged with: selenium-webdriver

http://stackoverflow.com/comment/86504644
has text: My bad I had another syntax error while using the single quotes, my bad. It works now thanks :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49744848
score: 1
type: Comment

http://stackoverflow.com/comment/86281149
type: QuestionComment
score: 0
has text: Are you trying to launch a brand-new GUI every 5 minutes, or to create a GUI that gets updated every 5 minutes?
type: Comment
comment on: http://stackoverflow.com/q/49636754

http://stackoverflow.com/comment/86355717
type: Comment
type: QuestionComment
has text: Forgive me if I'm misunderstanding (only just started picking up python), but doesn't it appear that the loop is already running more than once, since it seems like it has copied everything? After running this my "Backup" folder has all 13 folders + one file as it should, but the error hits after this. If I am misunderstanding something, what would I have to do to fix this to still duplicate a directory?
score: 0
comment on: http://stackoverflow.com/q/49672411

http://stackoverflow.com/comment/86540149
has text: Edited to include the HTML
comment on: http://stackoverflow.com/q/49736503
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49720564
answers question: http://stackoverflow.com/q/49720343
downvote count: 2
score: -2
has body: how about this: randomList = [random.integer() for i in range(userinput)]
type: Answer
upvote count: 0

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/49638225
type: Tag

http://stackoverflow.com/comment/86264144
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49628478
has text: But generally, with huge XML documents it's better to use an iterating parser to lower the memory requirements. See e.g. http://lxml.de/parsing.html#iterparse-and-iterwalk

http://stackoverflow.com/a/50047189
type: AcceptedAnswer
has body: I have determined that using threading is the best solution to my problem. It is able to send termination signals at any point in the program and it will restart the thread with new parameters. Let me know if anyone would like to view the code I used.
answers question: http://stackoverflow.com/q/49657533
accepted answer of: http://stackoverflow.com/q/49657533
type: Answer
score: 0

http://stackoverflow.com/a/73606320
type: Answer
has comment: http://stackoverflow.com/comment/130078715
score: 0
has body: How to make a "Hollow Diamond In Python 3.10" You can use this code here: my personal code
answers question: http://stackoverflow.com/q/49720711

http://stackoverflow.com/q/49738758
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49751501
downvote count: 0
has body: I am new to CNN and I am not able to identify how to solve this problem. In this code I am training a set of images to obtain mask from convolutional network.the images are grayscale with shape (200,200). I am not able to identify where I am making a mistake.Also everytime I run my code there is error at different inputs.Any help would be appreciated. following is the log generated: Creating training images... Saving to .npy files done. Creating test images... Saving to .npy files done. ------------------------------ Loading and preprocessing train data... ------------------------------ ------------------------------ Creating and compiling model... ------------------------------ C:/Users/Asus/Desktop/training.py:101: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(25, (3, 3), activation="relu", padding="same", data_format="channels_last")` conv2 = Conv2D(25, (3, 3), activation='relu', padding='same',dim_ordering="th")(inputs) C:/Users/Asus/Desktop/training.py:102: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(25, (3, 3), activation="relu", padding="same", data_format="channels_first")` conv2 = Conv2D(25, (3, 3), activation='relu', padding='same',dim_ordering="th")(conv2) C:/Users/Asus/Desktop/training.py:103: UserWarning: Update your `MaxPooling2D` call to the Keras 2 API: `MaxPooling2D(pool_size=(2, 2), data_format="channels_last")` pool2 = MaxPooling2D(pool_size=(2, 2), dim_ordering="tf")(conv2) C:/Users/Asus/Desktop/training.py:105: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(50, (3, 3), activation="relu", padding="same", data_format="channels_first")` conv3 = Conv2D(50, (3, 3), activation='relu', padding='same',dim_ordering="th")(pool2) C:/Users/Asus/Desktop/training.py:106: UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(50, (3, 3), activation="relu", padding="same", data_format="channels_first")` conv3 = Conv2D(50, (3, 3), activation='relu', padding='same',dim_ordering="th")(conv…
has title: Error when checking input: expected input_19 to have 4 dimensions, but got array with shape (1190, 200, 200)
has answer: http://stackoverflow.com/a/49751501
tagged with: python
has answer: http://stackoverflow.com/a/62948075
tagged with: dimension
tagged with: conv-neural-network
type: Question
has answer: http://stackoverflow.com/a/56301523
answer count: 3
tagged with: tensorflow
favorite count: 0
tagged with: keras
possible better answer: http://stackoverflow.com/a/56301523
score: 2
upvote count: 2

http://stackoverflow.com/q/49644352
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86296867
type: Question
tagged with: glob
answer count: 0
tagged with: python
type: UnansweredQuestion
has body: I want to use my pre-define path in glob function like code: import glob import os list_of_files = glob.glob('/Jaymin/MAC Report/*.txt') latest_file= max(list_of_files, key=os.path.getctime) but instead of this I have path stored in my variable like: My_path=/Jaymin/MAC Report so how can I replace my_path variable to the path ? like: list_of_files = glob.glob(MY_PATH'/*.txt')
has comment: http://stackoverflow.com/comment/86306675
score: 0
has title: How to use glob.glob function with pre-define path?
upvote count: 1
has comment: http://stackoverflow.com/comment/86306632
downvote count: 1

http://stackoverflow.com/comment/86334829
type: Comment
has text: thanks so much that also work as well i will do some testing now and i still have any update about this case i will share it
type: AnswerComment
comment on: http://stackoverflow.com/a/49661555
score: 0

http://stackoverflow.com/q/49728090
has title: kill adb opened with subprocess.popen in python
has answer: http://stackoverflow.com/a/49728428
score: 0
tagged with: subprocess
has body: I need to run a command adb get-state from my python library. I used subprocess.popen to execute the command and killed the process using pid. If the adb daemon is not in running state, adb process will create an extra adb process and terminate the first process created after starting the daemon (even manually its the same). Hence I am not able to kill the adb process opened by subprocess open since it has the pid of the first adb process (which has already terminated) Is there any way I can kill the real adb process which executes the command from python.
answer count: 1
tagged with: adb
type: Question
has comment: http://stackoverflow.com/comment/86475185
tagged with: pid
type: UnansweredQuestion
tagged with: kill
tagged with: python
has comment: http://stackoverflow.com/comment/86470112

http://stackoverflow.com/comment/86329818
comment on: http://stackoverflow.com/q/49659796
type: QuestionComment
score: 2
has text: Could it happen that your `python` is aliased? What do you get when you issue: `which python`?
type: Comment

http://stackoverflow.com/q/49605003
score: 0
has title: While Loop in a while loop [Python]
has answer: http://stackoverflow.com/a/49605065
upvote count: 1
has answer: http://stackoverflow.com/a/49605167
has comment: http://stackoverflow.com/comment/86217081
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86217117
has answer: http://stackoverflow.com/a/49605063
possible better answer: http://stackoverflow.com/a/49605063
has answer: http://stackoverflow.com/a/49605105
has body: I'm having an issue with my program for some homework I'm working on. I have multiple while loops in my program and it seems that the ones after the first one are causing the first one to just re-print the data I've already had the user input. repeat = 'y' p = 'y' b = 'y' s = 'y' while repeat != 'n': while p == 'y': stocksPurchased = float(input("Number of stocks purchased: ")) if stocksPurchased &lt; 0: print("Negative Values are not allowed. Please re-enter.") else: p = 'n' while b == 'y': pricePerStockBought = float(input("Amount per stock purchased in $: ")) if pricePerStockBought &lt; 0: print("Negative Values are not allowed. Please re-enter.") else: b = 'n' while c == 'y': commissionWhole = float(input("Commission Rate as a percent %: ")) if commissionWhole &lt; 0: print("Negative Values are not allowed. Please re-enter.") else: c = 'n' while s == 'y': pricePerStockSold = float(input("Amount per stock sold in $: ")) if pricePerStockSold &lt; 0: print("Negative Values are not allowed. Please re-enter.") else: s = 'n' commissionRate = commissionWhole/100 grossPurchasePrice = stocksPurchased*pricePerStockBought purchaseCommission = grossPurchasePrice*commissionRate totalPurchasePrice = grossPurchasePrice+purchaseCommission grossSalesPrice = stocksPurchased*pricePerStockSold saleCommission = grossSalesPrice*commissionRate netSalePrice = grossSalesPrice-saleCommission totalCommissionPaid = purchaseCommission+saleCommission profit = netSalePrice-totalPurchasePrice profitPercentage = (profit/grossPurchasePrice)*100 print("Commission Fee paid after buying: $", format(purchaseCommission, ',.2f')) print("Amount stock sold for: $", format(grossSalesPrice, ',.2f')) print("Commission Fee paid after selling: $", format(saleCommission, ',.2f')) print("Total Commission Paid: $", format(totalCommissionPaid, ',.2f')) print("Total Profit made: $", format(profit, ',.2f')) print("Profit Percentage: %", format(profitPercentage, ',.1f')) if profitPercentage &gt;= 8: print("Congrats…
has answer: http://stackoverflow.com/a/49605064
accepted answer: http://stackoverflow.com/a/49605065
has answer: http://stackoverflow.com/a/49605070
tagged with: python
answer count: 6
has comment: http://stackoverflow.com/comment/86217052
type: AnsweredQuestion

http://stackoverflow.com/a/60728869
answers question: http://stackoverflow.com/q/49603097
score: 0
type: Answer
has body: conda upgrade --all works for me

http://stackoverflow.com/comment/86332376
has text: @mypetlion Where do you see sarcasm here?
type: Comment
comment on: http://stackoverflow.com/a/49628198
score: 9
type: AnswerComment

http://stackoverflow.com/a/49630759
has comment: http://stackoverflow.com/comment/86361345
accepted answer of: http://stackoverflow.com/q/49628476
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49628476
has body: If I've understood you well, you're opening the list of the calendars of each patient rightly filtered, but the problem is that when you click on any of these records, it does nothing, and you need to open the calendar in a form view. If so, specify in your button that you also want to open the form view of the calendrier model, not only the tree view: @api.multi def btnVoirCalendriers(self): self.ensure_one() return { 'type' : 'ir.actions.act_window', 'res_model': 'calendrier', 'view_mode': 'tree,form', 'domain' : "[('patient_id', '=', %d)]" % self.id }
type: Answer

http://stackoverflow.com/comment/86442069
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49714285
has text: The ` ` tag.
score: 0

pyspark
tags question: http://stackoverflow.com/q/49681837
tags question: http://stackoverflow.com/q/49624014
tags question: http://stackoverflow.com/q/49666927
tags question: http://stackoverflow.com/q/49703022
tags question: http://stackoverflow.com/q/49710133
tags question: http://stackoverflow.com/q/49714328
tags question: http://stackoverflow.com/q/49729510
tags question: http://stackoverflow.com/q/49683897
tags question: http://stackoverflow.com/q/49699936
tags question: http://stackoverflow.com/q/49686275
tags question: http://stackoverflow.com/q/49742065
tags question: http://stackoverflow.com/q/49676701
tags question: http://stackoverflow.com/q/49603529
tags question: http://stackoverflow.com/q/49677780
tags question: http://stackoverflow.com/q/49755034
tags question: http://stackoverflow.com/q/49685206
tags question: http://stackoverflow.com/q/49623620
tags question: http://stackoverflow.com/q/49754476
tags question: http://stackoverflow.com/q/49723626
tags question: http://stackoverflow.com/q/49633315
tags question: http://stackoverflow.com/q/49682576
tags question: http://stackoverflow.com/q/49721738
tags question: http://stackoverflow.com/q/49645139
tags question: http://stackoverflow.com/q/49634651
tags question: http://stackoverflow.com/q/49675860
tags question: http://stackoverflow.com/q/49614856
tags question: http://stackoverflow.com/q/49669226
type: Tag
tags question: http://stackoverflow.com/q/49641137
tags question: http://stackoverflow.com/q/49680326
tags question: http://stackoverflow.com/q/49716307
tags question: http://stackoverflow.com/q/49703810
tags question: http://stackoverflow.com/q/49754318
tags question: http://stackoverflow.com/q/49648581
tags question: http://stackoverflow.com/q/49632616
tags question: http://stackoverflow.com/q/49707239
tags question: http://stackoverflow.com/q/49698111
tags question: http://stackoverflow.com/q/49734374
tags question: http://stackoverflow.com/q/49757739
tag name: pyspark
tags question: http://stackoverflow.com/q/49661371
tags question: http://stackoverflow.com/q/49646757
tags question: http://stackoverflow.com/q/49646184
tags question: http://stackoverflow.com/q/49663835
tags question: http://stackoverflow.com/q/49606742
tags question: http://stackoverflow.com/q/49751909
tags question: http://stackoverflow.com/q/49624744
tags question: http://stackoverflow.com/q/49661434
tags question: http://stackoverflow.com/q/49711665
tags question: http://stackoverflow.com/q/49725614
tags question: http://stackoverflow.com/q/49697086
tags question: http://stackoverflow.com/q/49641873
tags question: http://stackoverflow.com/q/49753377

http://stackoverflow.com/q/49634108
has comment: http://stackoverflow.com/comment/86275649
tagged with: python
has body: I'm writing a Webapp with Django and im trying to open a csv file. On my local machine that was no problem (there I used python2.7 or something). On the Server, Python 3 is installed and I get an Error: '_io.BufferedReader' object has no attribute 'xreadlines' But i didnt use this xreadlines... with open(os.path.dirname(__file__) + '/../***.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=';') for row in readCSV: #... What am I doing wrong?
answer count: 0
score: 1
downvote count: 0
tagged with: file
upvote count: 1
tagged with: string
has title: CSV File read in Python 3 and Django
favorite count: 0
has comment: http://stackoverflow.com/comment/86275814
type: Question
has comment: http://stackoverflow.com/comment/86354027
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/49732736
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49732469
score: 1
has comment: http://stackoverflow.com/comment/86479366
has body: Your problem here is not related to Tensorflow at all but to OpenCV. For some reason, OpenCV loads images in a BGR format and not RGB as Tensorflow expects them to be. Invert your first and third channels in your image before passing it to Tensorflow and everything should be fine.
accepted answer of: http://stackoverflow.com/q/49732469
type: AcceptedAnswer

http://stackoverflow.com/comment/86309816
has text: Try to checkout frameworks for web scraping, like Scrapy for example https://scrapy.org/
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49650369
score: 0

http://stackoverflow.com/comment/86325962
type: Comment
comment on: http://stackoverflow.com/a/49653787
type: AnswerComment
has text: it will anyways come in the form of a dictionary like below : [{'ReportDate': u'2018-03-30T00:00:00', 'ActualSalesPrice': 2.49, 'CSPAccountNo': u'414693', 'DiscountCount': 0, 'Description': u'NEURO WHT RASPBE', 'ZIP': u'60098', 'PromotionAmount': 0.0, 'POSCode': u'89940700401', 'RefundAmount': 0.0, 'Totalsales': 2.49, 'TotalCount': 1, 'RefundCounts': 0, 'DiscountAmount': 0.0, 'PromotionCount': 0, 'POSCodeModifier': u'0'}]
score: 0

http://stackoverflow.com/a/49697569
upvote count: 1
answers question: http://stackoverflow.com/q/49697034
has body: The main error in your code was to use mid = (end-start)//2 instead of mid = (end+start)//2 to compute the mid-range value. This created the infinite loop. So you were not very far from the solution : def sqrt(x): if x == 0: return x start = 1 end = x while start+1 &lt; end: mid = (end + start) // 2 delta = mid*mid - x if delta &lt; 0: start = mid elif delta &gt; 0: end = mid else: return mid return start for x in (2, 5, 9, 13, 18, 24, 27): print("sqrt(%s) ~= %s" % (x, sqrt(x))) which produces the following output : sqrt(2) ~= 1 sqrt(5) ~= 2 sqrt(9) ~= 3 sqrt(13) ~= 3 sqrt(18) ~= 4 sqrt(24) ~= 4 sqrt(27) ~= 5
has comment: http://stackoverflow.com/comment/86872970
type: Answer
has comment: http://stackoverflow.com/comment/86408171
has comment: http://stackoverflow.com/comment/86872672
score: 1
downvote count: 0

airflow
tags question: http://stackoverflow.com/q/49738173
tags question: http://stackoverflow.com/q/49619897
tags question: http://stackoverflow.com/q/49682576
tags question: http://stackoverflow.com/q/49633643
tag name: airflow
tags question: http://stackoverflow.com/q/49660861
type: Tag

http://stackoverflow.com/a/56301523
has body: I came across the same situation with grey images, a reshape on the images will solve it by adding the extra dimension for grey scale channel. train_images_reshape = train_images.reshape(no_images_train, h,w,1) test_images_reshape = test_images.reshape(no_images_test, h,w,1)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49738758

http://stackoverflow.com/q/49608130
has title: Implementing Cows and Bulls game
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15648407
has comment: http://stackoverflow.com/comment/86223470
has comment: http://stackoverflow.com/comment/86222963
has body: I have to code the Cows and Bulls game in which I have to generate 4 random number and ask the users to guess it. I have been trying for the past few hours to code it but can't seem to come up with a solution. The output I want is: Welcome to cows and Bulls game. Enter a number: &gt;&gt; 1234 2 Cows, 0 Bulls. &gt;&gt; 1286 1 Cows, 1 Bulls. &gt;&gt; 1038 Congrats, you got it in 3 tries. So far, I have got this: print("Welcome to Cows and Bulls game.") import random def number(x, y): cowsNbulls = [0, 0] for i in range(len(x)): if x[1] == y[i]: cowsNbulls[1] += 1 else: cowsNbulls[0] += 1 return cowsNbulls; x = str(random.randint(0, 9999)) guess = 0 while True: y = input("Enter a number: ") count = number(x, y) guess += 1 print(str(count[0]), "Cows.", str(count[1]), "Bulls") if count[1] == 4: False print("Congrats, you done it in", str(guess)) else: break; And the output is: Welcome to Cows and Bull game. Enter a number: 1234 4 Cows, 0 Bulls. It would not continue. I was just wondering what the problem is.
has comment: http://stackoverflow.com/comment/86222880
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86222831
answer count: 2
has comment: http://stackoverflow.com/comment/86222976
has comment: http://stackoverflow.com/comment/86222796
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/86222929
has answer: http://stackoverflow.com/a/49608203
favorite count: 0
has answer: http://stackoverflow.com/a/49611430
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86386607
type: Comment
comment on: http://stackoverflow.com/q/49687742
type: QuestionComment
score: 2
has text: Please add your code to show what you've tried.

http://stackoverflow.com/comment/86418053
has text: Experiment with `str.split` a little, especially `str.split('\n')`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49702173

http://stackoverflow.com/comment/86264951
has text: So you want to regress the values `(xmin, ymin, xmax, ymax)`? What were you thinking on trying after the reshape?
score: 0
comment on: http://stackoverflow.com/q/49628739
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86617804
has text: Would be great if you didn't just write some code as an answer. What is your thinking behind this code, how does it solve the question efficiently?
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49800443
type: Comment

http://stackoverflow.com/comment/86303811
type: Comment
type: QuestionComment
has text: Open the python interpreter/repl in the same terminal session where you can see that bs4 is installed.
score: 0
comment on: http://stackoverflow.com/q/49646758

http://stackoverflow.com/a/49690871
has body: Just use str.join after str.split: req_ans = ':'.join(c.split(':')[1:]) # ' AI: is: awesome' The result of str.split is a list. If you want all the components after a certain character, without removing the split character, you need to reverse the split after slicing.
type: Answer
has comment: http://stackoverflow.com/comment/86394476
score: 0
has comment: http://stackoverflow.com/comment/86395704
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49690818
downvote count: 1
answers question: http://stackoverflow.com/q/49690818

http://stackoverflow.com/q/49743649
upvote count: 3
downvote count: 2
score: 1
tagged with: hough-transform
has comment: http://stackoverflow.com/comment/86655013
has comment: http://stackoverflow.com/comment/86541400
answer count: 1
has title: Python: Calculating the angle between two bones in an x-ray
has comment: http://stackoverflow.com/comment/86536455
favorite count: 0
has answer: http://stackoverflow.com/a/49756009
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/86508217
has comment: http://stackoverflow.com/comment/86536755
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86528122
has comment: http://stackoverflow.com/comment/86503469
tagged with: python
has body: I am trying to write a script to calculate the angle between two bones given an x-ray. A sample x-ray would look like the following: I am trying to calculate the midline of each bone, essentially a line following the midpoints of the two sides of a bone, and then compare the angle between the two midlines. I have tried using OpenCV to get the outline of the bones, but it does not seem accurate enough and gets lots of extra data. I am stuck on how to move next and how I would calculate the midline. I am quite new to image processing but have experience with Python. Getting edges using OpenCV results: Code for OpenCV: import cv2 # Load the image img = cv2.imread("xray-3.jpg") # Find the contours imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(img,60,200) im2, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) hierarchy = hierarchy[0] # get the actual inner list of hierarchy descriptions # For each contour, find the bounding rectangle and draw it cv2.drawContours(img, contours, -1, (0,255,0), 3) # Finally show the image cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/86541197
tagged with: image
tagged with: opencv

http://stackoverflow.com/a/49623024
answers question: http://stackoverflow.com/q/49622811
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: You can read the file content using open method and then use elementtree module XML function to parse it. It returns an etree object which you can loop through. Example Content = open("file.xml").read() From xml.etree import XML Etree = XML(Content) Print Etree.text, Etree.value, Etree.getchildren()

http://stackoverflow.com/comment/86452935
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49719120
has text: Thanks, the `Counter` class is perfect to solve this issue! I don't understand the code you posted though, I mean, why do you call `sorted` on the original `search_list`, which contains duplicates? Wouldn't it be better to just call `sorted` on the `freq` object (since a dictionary can be iterated), and then just `enumerate` on that sorted list? After all, I just need to iterate those unique words in descending order, I'm not sure why you're creating those two additional `new_list` and `checked` variables.
score: 0

http://stackoverflow.com/a/49660545
answers question: http://stackoverflow.com/q/49660465
has comment: http://stackoverflow.com/comment/86331846
has comment: http://stackoverflow.com/comment/86333149
type: Answer
has body: Exactly as you say: LOGOUT_REDIRECT_URL = reverse_lazy('account:logout') is saying you want to redirect to the logout view. You should change this setting to some other view, e.g. the login view: LOGOUT_REDIRECT_URL = reverse_lazy('account:login') If you want to display the default Django logged_out.html template, you should not redirect, it's what the logout view renders by default (i.e. remove LOGOUT_REDIRECT_URL) from your settings. If you want to display your own custom template, either override Django's registration/logged_out.html template in one of your template directories (again, remove LOGOUT_REDIRECT_URL from settings), or create your own TemplateView for this and redirect to this new view you create.
accepted answer of: http://stackoverflow.com/q/49660465
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86352087
score: 3
type: Comment
has text: A dictionary can not have duplicate keys
type: QuestionComment
comment on: http://stackoverflow.com/q/49670906

http://stackoverflow.com/comment/86213454
comment on: http://stackoverflow.com/q/49601677
type: Comment
score: 0
has text: @TarunLalwani I think it might be something to do with this https://groups.google.com/forum/#!msg/selenium-users/2wBc9IJ10Ns/yb8lPmecSMkJ I noticed this on headed chrome http://prntscr.com/izgrkb Perhaps headless chrome has trouble dealing with that
type: QuestionComment

http://stackoverflow.com/q/49615727
tagged with: python
has comment: http://stackoverflow.com/comment/86240954
tagged with: plot
has comment: http://stackoverflow.com/comment/86239036
has body: I have a csv file as follow: Statistic,Evap_a_lm,Evap_am,Evap_lm,Evap_od STD_ctessel:,0.553843,0.572184,0.546684,0.568511 STD_htessel:,0.761471,0.938552,0.747172,0.919918 Mean_Bias_ctessel:,-0.290104,-0.248983,-0.310019,-0.267554 Mean_Bias_htessel:,-0.214769,-0.0868161,-0.233181,-0.103245 From this CSV file I would like to iterate through indexes and rows names components in order to produce barplots, like this one: For that I did produce the following code: import os,sys,math,time import csv from matplotlib import rc from matplotlib import pyplot as plt from matplotlib import patches as mpatches import numpy as np import pandas as pd variables = ["Evap"] names = ["od", "lm", "am", "a_lm"] models = ["ctessel", "htessel"] statistics = ['STD'] for variable in variables: for name in names: data = pd.read_csv("merged.txt", delimiter='\t') data.set_index('Statistic') for stat in statistics: for model in models: od = data.loc[[stat + "_" + model + ":"],[variable + "_od"]].astype(float) lm = data.loc[[stat + "_" + model + ":"],[variable + "_lm"]].astype(float) am = data.loc[[stat + "_" + model + ":"],[variable + "_am" + station]].astype(float) a_lm = data.loc[[stat + "_" + model + ":"],[variable + "_a_lm" + station]].astype(float) plt.title(variable + " " + stat, y=1.02) r1 = [1] r2 = [2] r3 = [3] r4 = [4] plt.bar(r1, od, width = barWidth, color="green", label='Original input') plt.bar(r2, lm, width = barWidth, color="yellow", label='Modis LAI') plt.bar(r3, am, width = barWidth, color="red", label='Modis Albedo') plt.bar(r4, a_lm, width = barWidth, color="blue", label='Modis LAI') plt.savefig(outdir + station + "_" + "perf.pdf") But unfortunately it is not working and I always have the error message that, obviously it cannot convert the string of the header to float: ValueError: could not convert string to float: 'Evap_od' Does anyone knows a workaround?
score: 0
has answer: http://stackoverflow.com/a/49616369
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
type: Question
type: UnansweredQuestion
has title: Python Barchart from csv file

http://stackoverflow.com/q/49676420
has answer: http://stackoverflow.com/a/49688845
has comment: http://stackoverflow.com/comment/86414780
tagged with: encoding
has comment: http://stackoverflow.com/comment/86398490
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86414576
has comment: http://stackoverflow.com/comment/86375464
tagged with: windows
has body: This question is related to Getting file path with umlauts from command line arguments under win7 using a batch file but has another twist. I installed win_unicode_console. I opened a console window and change the codepage via chcp.com 65001 > nul then I started a python script inside a path with umlauts which works fine in this console but the program throws this error: Traceback (most recent call last): File "C:\path\to\script.py", line 205, in &lt;module&gt; print err File "C:\python27\lib\site-packages\win_unicode_console\streams.py", line 256, in write self.base.write(s) File "C:\python27\lib\site-packages\win_unicode_console\streams.py", line 216, in write return self.base.write(s) File "C:\python27\lib\site-packages\win_unicode_console\streams.py", line 165, in write raise exc WindowsError: The program complaints about "print err" because this is the way I try to capture the exception: try: ... main code ... except Exception, err: print err Inside the ... main code ... part there is a line print 'ausgewählte Konfiguration:' This 'ä' character causes the error but I do not understand why. I tried everything I can to make the encoding right but the console output crashes everything. If I do not change the codepage of the console via chcp , as eryksun suggested, the error is gone but there is a new problem. The script receives a filepath containing special characters like "ä". The script opens the file without problems in the first place but writing data back is not possible 'utf8' codec can't decode byte 0xe4 in position 4: invalid continuation byte
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86386447
upvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86390568
linked to: http://stackoverflow.com/q/49445992
answer count: 1
downvote count: 1
tagged with: windows-console
favorite count: 0
type: Question
has title: Python 2 encoding in win 7 console

http://stackoverflow.com/q/49615380
upvote count: 0
linked to: http://stackoverflow.com/q/20002503
has title: i am getting Error while checking string value in list
downvote count: 2
answer count: 3
duplicate of: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/86238011
has answer: http://stackoverflow.com/a/49615469
accepted answer: http://stackoverflow.com/a/49615469
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49615452
possible better answer: http://stackoverflow.com/a/49615452
has body: i am checking two values inside list using if condition and another string should not be in list in python below is my code but it is giving wrong output lis = ['a','b','c','d','e','f'] #list values or lis =[] if ('z' or 'a') and not 'x' in lis : print "yes" else : print "no" and output is yes is there anything wrong?
score: -2
has comment: http://stackoverflow.com/comment/86237971
has answer: http://stackoverflow.com/a/49615430
duplicate of: http://stackoverflow.com/q/20002503
has comment: http://stackoverflow.com/comment/86237464
tagged with: python
has comment: http://stackoverflow.com/comment/86238172
has comment: http://stackoverflow.com/comment/86237463
has comment: http://stackoverflow.com/comment/86237411
linked to: http://stackoverflow.com/q/39983695
tagged with: python-2.7

http://stackoverflow.com/q/49699069
has body: I have some problems with pandas DataFrame. I hope that anyone can help me. I downloaded some data from cryptocompare and wrote it to a cvs file. My goal is to update this cvs file constantly on a daily basis. After downloading the new data in an extra DataFrame I want to merge it with the existing data. Therefore I wrote a function (read_dataset) that read the existing data of the cvs file in a DataFrame. The next step should to merge the new data with the existing data. I tried pd.merge and pd.concate but all this does not work. My DataFrames looks like: open time volumefrom volumeto Timestamp 0 0.04951 1279324800 20.00 9.902000e-01 2010-07-17 1 0.04951 1279411200 75.01 5.090000e+00 2010-07-18 2 0.08584 1279497600 574.00 4.966000e+01 2010-07-19 3 0.08080 1279584000 262.00 2.059000e+01 2010-07-20 4 0.07474 1279670400 575.00 4.226000e+01 2010-07-21 5 0.07921 1279756800 2160.00 1.297800e+02 2010-07-22 6 0.05050 1279843200 2402.50 1.410700e+02 2010-07-23 7 0.06262 1279929600 496.32 2.673000e+01 2010-07-24 8 0.05454 1280016000 1551.48 8.506000e+01 2010-07-25 9 0.05050 1280102400 877.00 4.691000e+01 2010-07-26 10 0.05600 1280188800 3373.69 1.969200e+02 2010-07-27 11 0.06000 1280275200 4390.29 2.557600e+02 2010-07-28 12 0.05890 1280361600 8058.49 5.283200e+02 2010-07-29 13 0.06990 1280448000 3020.85 1.985300e+02 2010-07-30 14 0.06270 1280534400 4022.25 2.439000e+02 2010-07-31 15 0.06785 1280620800 2601.00 1.626500e+02 2010-08-01 16 0.06110 1280707200 3599.00 2.212000e+02 2010-08-02 17 0.06000 1280793600 9821.46 6.060500e+02 2010-08-03 18 0.06000 1280880000 3494.00 2.107700e+02 2010-08-04 19 0.05700 1280966400 5034.07 3.036100e+02 2010-08-05 20 0.06100 1281052800 1395.00 8.591000e+01 2010-08-06 21 0.06230 1281139200 2619.00 1.573400e+02 2010-08-07 22 0.05900 1281225600 2201.00 1.326000e+02 2010-08-08 23 0.06090 1281312000 13631.09 8.869300e+02 2010-08-09 24 0.07100 1281398400 1310.39 8.887000e+01 2010-08-10 25 0.07000 1281484800 14061.18 1.015640e+03 2010-08-11 26 0.06700…
has comment: http://stackoverflow.com/comment/86411335
accepted answer: http://stackoverflow.com/a/49699232
tagged with: dataframe
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/49699205
possible better answer: http://stackoverflow.com/a/49699205
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: concatenation
tagged with: pandas
has answer: http://stackoverflow.com/a/49699232
has title: PYTHON: df.drop does not work in function
type: Question

http://stackoverflow.com/comment/86241994
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49617256
type: QuestionComment
has text: @jhpratt didn't fix the blank screen

http://stackoverflow.com/comment/86360238
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49671215
has text: 9.0.1 and Python3 as well @Vallie

http://stackoverflow.com/q/49698825
type: Question
has title: Error encoding Python
tagged with: python
accepted answer: http://stackoverflow.com/a/49699050
has answer: http://stackoverflow.com/a/49699050
has comment: http://stackoverflow.com/comment/86411253
has comment: http://stackoverflow.com/comment/86410987
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/8365660
linked to: http://stackoverflow.com/q/6202726
has comment: http://stackoverflow.com/comment/86413012
has comment: http://stackoverflow.com/comment/86411200
has body: i'm having some issues with python encode and cant find any help in the web! In the first, i begin developer in python a 3 months ago, so i'm a beginer! I'm doing some scraper and i having a issue with a encode, the error code is: Traceback (most recent call last): File "/home/thiago/crawler/src/link_produto.py", line 145, in &lt;module&gt; crawler(link) File "/home/thiago/crawler/src/link_produto.py", line 125, in crawler cursor.execute(sql) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 181, in execute query = query.encode(db.unicode_literal.charset) UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201d' in position 5013: ordinal not in range(256) [Finished in 1.633s] My Code here: from time import gmtime, strftime import MySQLdb import requests from bs4 import BeautifulSoup as bs import re import json def crawler(link_cat): html = requests.get(link_cat) soup = bs(html.content, "lxml") for div in soup.find_all('a', {"class" : "last-page"}): lp = div['href'] regex = r"^.*\/([0-9]+)\/$" strlp = lp matches = re.search(regex, strlp) if matches: for groupNum in range(0, len(matches.groups())): groupNum = groupNum + 1 valor_final = matches.group(groupNum) valor_final = int(matches.group(groupNum)) print('1º STEP: A Qtd de páginas da categoria é', valor_final) vetor = [] for i in range(0, valor_final): vetor.insert (i,'%s%d' %(link_cat, i+1) + '/') print(i) vetor[0] = link_cat for i in vetor: html = requests.get(i) soup = bs(html.content, "lxml") for a in soup.find_all('a', {"class" : "product-li"}): last_update = strftime("%Y-%m-%d %H:%M:%S", gmtime()) rank_cat = str(i) rank_pagina_cat = 2 rank_site = 300 url = requests.get(a['href']) html_sku = url.content soup_sku = bs(html_sku, 'html.parser') title = soup_sku.title.string SKU = soup_sku.find(string=re.compile("digo.*")) rows = soup_sku.find_all('tr') specList = [] for row in rows: data = row.find_all('td') spec = {data[0].get_text() : data[1].get_text()} specList.append(spec) pro…
answer count: 1
has comment: http://stackoverflow.com/comment/86411114
duplicate of: http://stackoverflow.com/q/8365660
linked to: http://stackoverflow.com/q/3942888

http://stackoverflow.com/comment/86231554
type: Comment
has text: Or, just open the reader, and then `found = any(to_find in row for row in reader)`... then you don't need to worry about initialising `found` and additional control flow logic and get short-circuiting thrown in free of charge.
comment on: http://stackoverflow.com/a/49612466
type: AnswerComment
score: 2

http://stackoverflow.com/a/49699768
answers question: http://stackoverflow.com/q/49699678
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49699678
has body: You can do with stack df['New']=df.replace('',np.nan).stack().groupby(level=0).apply(list) df Out[1666]: Str1 Str2 Str3 New 0 OK I Go [OK, I, Go] 1 Yes Hm [Yes, Hm] 2 Fine I see [Fine, I see]
type: Answer

http://stackoverflow.com/a/49942925
score: 1
upvote count: 1
has body: To implement such a function that mimics ST_SetSRID outside of PostGIS, you need to decide on the format you're willing to operate in. If you're looking at geometry in EWKT (Extended Well-Known Text), then SRID is stored in the beginning: SRID=4326;POINT(10.23 10.41) There it can be replaced using text manipulation functions. If you are looking at geom in EWKB (Extended Well-Known Binary), then SRID is stored as an integer after a header, if a header has a flag that it stores a SRID raised. Here is how postgis stores a flag: https://sourcegraph.com/github.com/postgis/postgis/-/blob/liblwgeom/lwout_wkb.c#L145 Here is how it writes the SRID value: https://sourcegraph.com/github.com/postgis/postgis/-/blob/liblwgeom/lwout_wkb.c#L583 If you are implementing it in Python, you may want to use something like WKBheader library to not manipulate the fields youself: https://github.com/MazeMap/wkbheader
downvote count: 0
answers question: http://stackoverflow.com/q/49728453
type: Answer

http://stackoverflow.com/comment/86292278
score: 0
type: AnswerComment
has text: @JoeT.Boka You understand that your current requirement is a little confusing, I could help you if you provide a [mcve], in addition to a clearer explanation as for example what percentage represents the execution of each function.
comment on: http://stackoverflow.com/a/49637095
type: Comment

gmail
type: Tag
tags question: http://stackoverflow.com/q/49756437
tag name: gmail

http://stackoverflow.com/q/49609262
answer count: 2
downvote count: 0
upvote count: 1
has body: Given that a time stamp can have several constructions i.e. HH:MM:SS H:MM:SS MMM:SS MM:SS M:SS Currently I'm using re.findall() with the | alternates operator. Is there a more efficient method of finding all of the above possible type of time stamps in a string than the following: aString = "the cat (01:03) sat on [01:01:01] the ( 9:13 )mat( 1:10:11)." bString = "the cat 01:14:23.447 sat on the mat" cString = "the cat 01:14:23.447 --&gt; 01:17:10.239 sat on the mat" dString = "the cat 323:14 sat on the mat" v = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',aString) x = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',bString) y = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',cString) z = re.findall('\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}|\d{3}:\d{2}|\d{2}:\d{2}|\d:\d{2}',dString) v ['01:03', '01:01:01', '9:13', '1:10:11'] x ['01:14:23'] y ['01:14:23', '01:17:10'] z ['323:14'] Note: I don't care about milliseconds if they are included in the time stamp.
favorite count: 0
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/86225029
accepted answer: http://stackoverflow.com/a/49609396
tagged with: python
possible better answer: http://stackoverflow.com/a/49609681
tagged with: regex
has answer: http://stackoverflow.com/a/49609396
has answer: http://stackoverflow.com/a/49609681
type: Question
tagged with: python-3.x
has title: Find all occurrences of a variable time stamp structure in a string

http://stackoverflow.com/a/49634010
score: 0
has comment: http://stackoverflow.com/comment/86281091
has body: The easiest way is to switch to requests library and try something like below. You should go for the below approach only when you have no time to code and you are in a hurry. You can see the same result in the website when you select ASSAM from dropdown and press the search button. import requests from bs4 import BeautifulSoup URL = "http://cbseaff.nic.in/cbse_aff/schdir_Report/userview.aspx" payload="__EVENTTARGET=&amp;__EVENTARGUMENT=&amp;__LASTFOCUS=&amp;__VIEWSTATE=sR0epHdr4qQ9SeEuqmUUBWzZHpFAyMj5Xr%2BhGagE8Be7zDbBqQgdx1%2BqrCMY8JfcRJ%2BBhmH8eEKMS%2F3VeboGFTjN0LZz1p2mx3FfY2OVkzs353bmDLWhtvBlOVnyFgcCXGyI9Li3Wp22e5txxKQwtdrKTWheuZLatRvI9wztvyeGueD9ZmEl8gIQHT77fIyt3N%2Bi3dn%2FhUdvvi%2FRqHR%2FaE1YfW3RmmSECDepwYfmBlSH3e4zTDQskW6XoOD7jykryp8L845QWclBE37ttOc5zXndfqkE%2FKCwOxiCxzRVPWCIFD9mBfELERlDOzq0cKwg6hHcE%2B4ZgyxJKBwNbW%2FDBtl%2BzpATY8arhjAg0CCf5CGmYMG1w2aaYz%2FSQ6bKQYWAaiH%2B0t9lrV291vPNj5Gfy1rWwrUhmw%2F6LcvX7uof41OUHtfGt%2Bn1IlxODsPu8i89hjiu5rqprmltTKSzoOZXJuQ1sfyRneShA7WeSIO0M4UmzUVdnjsNlimBmcc7vwAgvF8E6SJ8DaGCbPaLLH6tsI%2BISTBWPWw97o7KQyS%2FPicpZQA2Q5kzCHkAeroJWWrVILlCxEAEuOmzZffW7qIiiUwI3Urbixw40YDkjMPgVZMbb74EiEvmMGr1vNOMcjoICgM54sY5cViGP945D86fRlbS%2B6yYxNH951EZNrmRWnASiT2D%2FEbGMAkOwcYKrOWBrtMXEp8GPsswxryCZp2eANe7ajSioa0utT2cmGG5T7uiypveyfM0LBzgVTMqr5q7oMyUI9ML%2Bx8LHUFSh6SrjP1Nj7xs3%2BFPr2WaXoIs57hhUKfpE7u7Du9EGd1iXapf2WYKbvsl38Ov5u3FcPJ8L%2BLv%2FtksFE7Y7K2ZQ59p0Jqr%2BF%2FbMaKZeRRPp%2BMpW1TblAI8RVP1u%2BTDAHz19jrdpsralLWYoweP3wS5kdDcx68IukuaeGl0ESXcbNYWdFF0pEolfWLBSWcbOpR3YPpxVQD5Eqq3z%2FsYmk%2B%2B%2ByRXOH%2FizUrCqDqQjwbTw4UqRJY5HewB0q0Xp6jrPoT0%2FztPwteGCb6xonx1rzVkr84aOUw9IBUkCcvEtyi0S8VcUyVyii6KK9CThtyTHjbgut%2BdjuIOBlXPL9bD6u2frJiGGacVziPZInp6%2FtKcmnYn89Kcr0Ec1o3VZ6PD6xe8SUyMkupf%2FruNhbK6r6ZAXKZ3zMhkiDsMZYVGUihU43gNj3c8X%2BFD8ONb1827AfaDydgS1JxMtA9z4eOTqmoiPQ61vSr2j8IXokWJSDNg%2FhIn1uChG8BoEst2qZyVoQify0g%2FDMN%2B%2BPMMK7KPqnAfT4P17QI4Gn3mg2kFzfuQdnsQgs7aB0zAt0jrMgCoTDxuwbNvZ1w5BMF0bFbbfxi9QvbCXdpifAWbgAyutlo3wCbD1lIv3NmzLFQ61Mpih5zIOU2z9bpBeH4nClXcAN…
type: Answer
answers question: http://stackoverflow.com/q/49631055
has comment: http://stackoverflow.com/comment/86276981

http://stackoverflow.com/comment/86215179
has text: My embedded list strictly contains the client count when the 'show client summary' command is run. I supplied the code above.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49604005
score: 0

http://stackoverflow.com/comment/86456303
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49712948
has text: Thank you so much Another question please .. How can I control the settings I want to save records, additions, settings and more Each time the program is restarted, only the default settings will be restored and all additions and records will be deleted ! !

http://stackoverflow.com/comment/86376016
score: 0
has text: Thanks! I've done the exact same thing before - glad you found it.
comment on: http://stackoverflow.com/a/49678542
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86284709
score: 0
has text: @chrisz Yes,that's it,works fine.
type: QuestionComment
comment on: http://stackoverflow.com/q/49638445
type: Comment

http://stackoverflow.com/q/49709826
upvote count: 4
accepted answer: http://stackoverflow.com/a/49709965
linked to: http://stackoverflow.com/q/20330385
tagged with: subprocess
has answer: http://stackoverflow.com/a/49709965
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/49709970
has title: Cannot find the file specified when using subprocess.call('dir') in Python
tagged with: windows-10
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49709970
tagged with: python-3.x
type: Question
answer count: 2
has body: I am on Windows 10, and I run the following Python file: import subprocess subprocess.call("dir") But I get the following error: File "A:/python-tests/subprocess_test.py", line 10, in <module> subprocess.call(["dir"]) File "A:\anaconda\lib\subprocess.py", line 267, in call with Popen(*popenargs, **kwargs) as p: File "A:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 210, in __init__ super(SubprocessPopen, self).__init__(*args, **kwargs) File "A:\anaconda\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "A:\anaconda\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified Note that I am only using dir as an example here. I actually want to run a more complicated command, but I am getting the same error in that case too. Note that I am not using shell=True, so the answer to this question is not applicable: Cannot find the file specified when using subprocess.call('dir', shell=True) in Python This is line 997 of subprocess.py: hp, ht, pid, tid = _winapi.CreateProcess(executable, args, # no special security None, None, int(not close_fds), creationflags, env, os.fspath(cwd) if cwd is not None else None, startupinfo) When I run the debugger to check out the arguments being passed to CreateProcess, I notice that executable is None. Is that normal?
tagged with: python

http://stackoverflow.com/comment/86438530
score: 0
type: Comment
type: QuestionComment
has text: Did you [import](https://docs.python.org/3/reference/import.html) the other class?
comment on: http://stackoverflow.com/q/49712457

http://stackoverflow.com/a/49742116
answers question: http://stackoverflow.com/q/49741937
score: 1
downvote count: 0
upvote count: 1
has body: Call FOO_set (where FOO is the source model name - in your case post) on Topic instance. topic = Topic.objects.get(id=1) topic.post_set.all()
type: Answer

http://stackoverflow.com/comment/86475286
score: 0
comment on: http://stackoverflow.com/q/49723266
type: QuestionComment
type: Comment
has text: Try removing `company.egg-info` dir.

http://stackoverflow.com/comment/86778640
comment on: http://stackoverflow.com/a/49755445
type: Comment
has text: Thanks a lot for your help. I could understand and adapt what you sent in my application! Best regards
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86440311
type: Comment
type: QuestionComment
has text: see answer below.
comment on: http://stackoverflow.com/q/49713113
score: 0

http://stackoverflow.com/a/49612095
answers question: http://stackoverflow.com/q/49612027
has comment: http://stackoverflow.com/comment/86385423
has comment: http://stackoverflow.com/comment/86385203
has comment: http://stackoverflow.com/comment/86365199
has comment: http://stackoverflow.com/comment/86360465
has comment: http://stackoverflow.com/comment/86350740
has comment: http://stackoverflow.com/comment/86359273
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86347920
has comment: http://stackoverflow.com/comment/86396042
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86385709
has comment: http://stackoverflow.com/comment/86383707
has comment: http://stackoverflow.com/comment/86385460
has comment: http://stackoverflow.com/comment/86276243
has comment: http://stackoverflow.com/comment/86358419
has comment: http://stackoverflow.com/comment/86383256
has comment: http://stackoverflow.com/comment/86385304
has comment: http://stackoverflow.com/comment/86350654
accepted answer of: http://stackoverflow.com/q/49612027
has body: I think need: b = df.filter(like='v').columns d = {x: 'v.{}'.format(i) for i, x in enumerate(b)} d['Time[s]'] = 'Time[s].0' print (d) {'v1': 'v0', 'v2': 'v1', 'Time[s]': 'Time[s].0'} df = df.rename(columns=d) L = [x.set_index(x.columns[0]) for i, x in df.groupby(lambda x: x.split('.')[-1], axis=1)] df = pd.concat(L, axis=1) print (df.head(10)) v.0 v.1 160.846210 0.0 NaN 160.848080 NaN 7.0 161.146130 0.0 NaN 161.148020 NaN 7.0 161.538245 27.0 NaN 161.540085 NaN 7.0 162.015980 27.0 NaN 162.017865 NaN 7.0 162.315890 27.0 NaN 162.317775 NaN 7.0 Expanation: First filter columns all v columns for dictionary for pairs timestamps with values columns. rename by dict, also first timestamp column groupby by values of columna after . in list comprehension, create index by set_index and concat together EDIT: If numeric values and duplicated timestamp aggregation is by mean, if not, aggreagation by first: b = df.filter(like='v').columns d = {x: 'v.{}'.format(i) for i, x in enumerate(b)} d['Time[s]'] = 'Time[s].0' print (d) {'v1': 'v0', 'v2': 'v1', 'Time[s]': 'Time[s].0'} df = df.rename(columns=d) L = [x.groupby(x.columns[0]).mean() if np.issubdtype(df[x.columns[1]].dtype, np.number) else x.groupby(x.columns[0]).first() for i, x in df.groupby(df.columns.str.split('.').str[-1], axis=1)] df = pd.concat(L, axis=1) print (df.head(10)) v.0 v.1 v.2 158.538395 NaN NaN Active 158.538515 NaN NaN Active 159.494550 NaN NaN Active 160.846210 0.0 NaN NaN 160.848080 NaN 7.0 NaN 161.146130 0.0 NaN NaN 161.148020 NaN 7.0 NaN 161.538245 27.0 NaN NaN 161.540085 NaN 7.0 NaN 162.015980 27.0 NaN NaN
type: Answer
has comment: http://stackoverflow.com/comment/86359352
has comment: http://stackoverflow.com/comment/86275075

http://stackoverflow.com/comment/86526309
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49755496
has text: @kabanus oh sorry never saw the link
type: Comment

phantomjs
tags question: http://stackoverflow.com/q/49610605
tags question: http://stackoverflow.com/q/49703521
type: Tag
tag name: phantomjs
tags question: http://stackoverflow.com/q/49678384
tags question: http://stackoverflow.com/q/49671591

http://stackoverflow.com/q/49659818
has body: I am new in Python and I want to write a script that listens to the left, right or middle(mouse-wheel) button click event. When the left or right mouse button is clicked it should do nothing. In other words, the script should block the left and right mouse clicks. But when the middle mouse button is clicked the script should press the escape button. I already found a library for listening to mouse events: Pynput. The problem is that the script have to run on a Windows XP machine so I have to use Python 3.4.4 and I cannot find a version of Pynput for this Python version. My question now: How can I listen to mouse clicks and send keyboard events in Python 3.4.4 for WindowsXP? UPDATE: Now Pynput is installed correctly and is working. I wrote this: from pynput import mouse from pynput.keyboard import Key, Controller keyboard = Controller() def on_click(x, y, button, pressed): if button == mouse.Button.middle: keyboard.press(Key.esc) keyboard.release(Key.esc) #after pressing the esc-key: stopPropagation(middle mouse click should not be forwarded to windows) if button == mouse.Button.left: print("left") #stopPropagation(left mouse click should not be forwarded to windows) if button == mouse.Button.right: print("right") #stopPropagation(right mouse click should not be forwarded to windows) # Collect events until released with mouse.Listener( on_click=on_click) as listener: listener.join() How can I accomplish what I wrote in the # comments? Is it even possible to do such things like prevent the mouse click in windows with Python? Also what I don't understand is when I run the program and I want to quit it (with ctrl+c) I have to press it like 100 times and then it shows this: Traceback (most recent call last): File "C:\Users\path\hello.py", line 22, in &lt;module&gt; File "C:\Python34\lib\site-packages\pynput-1.3.10-py3.6.egg\pynput\_util\__init__.py", line 178, in join File "C:\Python34\lib\threading.py", line 1060, in join self._wait_for_tstate_lock() File "C:\Python34\l…
tagged with: python-3.x
has title: Mouse event keyboard event mapper
type: Question
has comment: http://stackoverflow.com/comment/86329729
type: UnansweredQuestion
tagged with: python
tagged with: pynput
has comment: http://stackoverflow.com/comment/86329708
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86329609
has comment: http://stackoverflow.com/comment/86330120

http://stackoverflow.com/a/49623542
has body: You probably don't want to assign each country data to its own variable, unless you are absolutely sure that the number of them is small and does not vary. Therefore it would be simplest to use looping to handle each country: data = ... from xml.etree import ElementTree tree = ElementTree.fromstring(data) countries = tree.findall("country") You now have a list of countries that you can iterate over to analyse each one further. for country in countries: print(country) &lt;Element 'country' at 0x10e51d818&gt; &lt;Element 'country' at 0x10e535688&gt; &lt;Element 'country' at 0x10e535cc8&gt;
has comment: http://stackoverflow.com/comment/86254362
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86278451
answers question: http://stackoverflow.com/q/49623360
has comment: http://stackoverflow.com/comment/86254635

http://stackoverflow.com/comment/86390028
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49689275
score: 1
has text: Make a list of the authorize file extension and then check if the str last characters are in the list (split at the dot). If not, then add the specified file extension.

http://stackoverflow.com/a/49711459
accepted answer of: http://stackoverflow.com/q/49710850
type: AcceptedAnswer
has body: You're mixing up path() and url(). In your main urls.py you use path() for the URL patterns. But in your app urls you use url(), but use the path style - /&lt;int:id&gt;/ - instead of the url style (regex). The easiest fix is just to change to path() throughout - if you do this you also need to change the first path to just ''.
type: Answer
answers question: http://stackoverflow.com/q/49710850
score: 0

http://stackoverflow.com/a/49732489
type: Answer
has comment: http://stackoverflow.com/comment/86478814
score: 0
has comment: http://stackoverflow.com/comment/86479935
answers question: http://stackoverflow.com/q/49732176
has body: you can do something like this on client side import socket serverName = "localhost" serverPort = 11000 while 1: var = input("Write a sentence: ") var = var.strip() if var == "": continue s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverName, serverPort)) s.sendall(str.encode(var)) data = s.recv(1024) data = str(data) print(data) s.close()
has comment: http://stackoverflow.com/comment/86479769
has comment: http://stackoverflow.com/comment/86478954

http://stackoverflow.com/comment/86296148
comment on: http://stackoverflow.com/a/49644217
type: Comment
type: AnswerComment
score: 0
has text: @India.Rocket - Super :) Glad can help!

http://stackoverflow.com/q/49680145
type: Question
tagged with: pydrive
has title: How to use io module and tornado.write at the same time
tagged with: streaming
tagged with: python
tagged with: chunked
has body: There is a huge binary file uploaded to Google Drive. I am developing a tornado-based HTTP proxy server which provides a binary stream of the same huge file. It is natural to let the huge file to be proxied in multiple chunks (Download the contents using PyDrive, upload it with self.write(chunk) or something). The problem is that there seems to be single choice : googleapiclient.http.MediaIoBaseDownloadto download chunked binary files from Google Drive, but this library only supports FDs or io.Base objects as it's first argument. https://google.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaIoBaseDownload-class.html My code looks something like this: import tornado.httpserver import tornado.ioloop import tornado.web from googleapiclient.http import MediaIoBaseDownload import io class VideoContentHandler(tornado.web.RequestHandler): def get(self,googledrive_id): googledrive_id = googledrive_id[1:] query = "'"+self.application.google_drive_folder_id+"' in parents and trashed=false" file_list = self.application.drive.ListFile({'q': query}).GetList() # io.FileIO will save the chunks to local file! # This is not what I want. # Using something different may solve the problem? with io.FileIO('/tmp/bigvid-from-pydrive.mp4', mode='wb') as local_file: for f in file_list: if f['id'] != googledrive_id: continue id = f.metadata.get('id') request = self.application.drive.auth.service.files().get_media(fileId=id) downloader = MediaIoBaseDownload(local_file, request, chunksize=2048*1024) done = False while done is False: status, done = downloader.next_chunk() # Flush buffer and self.write(chunk)? def main(): gauth = GoogleAuth() gauth.CommandLineAuth() # Already done self.drive = GoogleDrive(gauth) self.google_drive_folder_id = '&lt;GOOGLE_DRIVE_FOLDER_ID&gt;' app = tornado.web.Application([ (r"^/videocontents(/.+)?$", handlers.api.VideoContentHandler), ]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(8888) tornado.ioloop.IOLoop.instance…
tagged with: tornado
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49681046
has answer: http://stackoverflow.com/a/49681046
answer count: 1

http://stackoverflow.com/comment/86415601
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/49700931
type: Comment
has text: The original data isn't JSON - it must have double quotes around names and strings. Having a single quote inside a single quote-delimited string is very bad practice. What program generates this format? JSON needs a comma between pairs, too.

http://stackoverflow.com/comment/86463032
type: QuestionComment
has text: How is the code in your question not working (assuming it's making an attempt to do what you want)? If it's producing errors or exceptions are being raised, please [edit] your question and describe it or them (and copy and paste them into it as well).
score: 0
comment on: http://stackoverflow.com/q/49724236
type: Comment

http://stackoverflow.com/comment/86515805
type: AnswerComment
comment on: http://stackoverflow.com/a/49747916
has text: How and where do you trigger the ajax call? can you send the missing codes if any where do you get that `q_learn` library, Is it yours, can you include that too?
type: Comment
score: 0

datareader
tags question: http://stackoverflow.com/q/49604224
tag name: datareader
type: Tag

http://stackoverflow.com/comment/86410686
comment on: http://stackoverflow.com/q/49698613
type: Comment
has text: The problem description says "numbers that come immediately after a 13 also do not count". This implementation wants to do that by zeroing out the number after each 13. That's not quite the same thing, because if the last number is a 13, there _is_ no number that comes immediately after it to zero out. So it needs a check to handle that special case. This is actually a great lesson, even if not well taught—naive designs often have special cases (and especially so in places like the edges of a list) that aren't obvious at first, and that's where half your debugging time ends up being spent.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86565820
has text: @DavidParks. Unfortunately, the profiler gives the same information as the tensorboard after logging a run with metadata, which is logging a session. My bottleneck is way before the start of a session, when defining the graph.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49753793
type: Comment

http://stackoverflow.com/comment/86456875
has text: Based on my question this is in fact the solution. You can also use @roganjosh comment and save the csv without the index. Both worked. Thanks.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49721771
score: 0

http://stackoverflow.com/comment/86354094
has text: Why are you using DictWriter when you have a list rather than a dict?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49671808
type: QuestionComment

http://stackoverflow.com/comment/86404042
type: AnswerComment
score: 0
type: Comment
has text: Oh, neat. This is more concise than my answer, since I didn't know you could refer to a previous group without explicitly naming it.
comment on: http://stackoverflow.com/a/49695567

http://stackoverflow.com/q/49677112
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86366373
score: 3
has body: I have been trying to highlight some rows in a pandas dataframe based on multiple conditions. I'm expecting that when a string in the target column match the criteria defined in the function, the entire row will be highlighted. I tried different combinations of the .style.apply method, but it kept giving me the following error: ValueError: style is not supported for non-unique indicies. This is the code: def highlight_rows(s): if s['my_column'] == 'some_text': return 'background-color: green' elif s['my_column'] == 'somedifferent_text': return 'background-color: blue' df.style.apply(highlight_rows, axis = 0) I'm using Python 3.6.5 and Pandas 0.22.0 Any idea on what I'm doing wrong? Should I pass different parameters or doing a different loop? Thank you
tagged with: pandas
has answer: http://stackoverflow.com/a/54948332
possible better answer: http://stackoverflow.com/a/54948332
has comment: http://stackoverflow.com/comment/95645434
upvote count: 3
has answer: http://stackoverflow.com/a/69819529
tagged with: highlight
favorite count: 0
type: Question
tagged with: pandas-styles
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/86368182
has comment: http://stackoverflow.com/comment/86365644
accepted answer: http://stackoverflow.com/a/69819529
downvote count: 0
has title: Highlight rows from a DataFrame based on values in a column in Python Pandas
tagged with: python

http://stackoverflow.com/comment/86382068
has text: I would have never figured out final = [i.split(',') for i in f.read().splitlines() if i], in fact, I don't understand how that's working. But it does work. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/49685123
type: AnswerComment
score: 0

http://stackoverflow.com/a/49671513
answers question: http://stackoverflow.com/q/49671381
accepted answer of: http://stackoverflow.com/q/49671381
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86353611
downvote count: 0
upvote count: 1
has body: I think need concat with Series created by dtypes and iloc with metrics DataFrame created by agg: a = data.dtypes.rename('Type') b = data.iloc[0].rename('first') c = data.agg(['min','max', 'mean']).T df = pd.concat([a,b,c], axis=1) print (df) Type first max mean min col_A int64 1 4 2.5 1 col_B object x y NaN x
has comment: http://stackoverflow.com/comment/86353578
type: Answer

http://stackoverflow.com/comment/86324079
has text: Post the code you have tried. Tkinter will block gui untill your funtion return unless you use callbacks/threading etc.
type: QuestionComment
comment on: http://stackoverflow.com/q/49657500
score: 0
type: Comment

http://stackoverflow.com/q/49721400
has body: Pycharm presents me with the following template for a docstring: """ :param var1: :param var2: """ for a function def func(var1,var2). Why does Pycharm uses this template? Is there some PEP or (unwritten) convention that this is good style?
upvote count: 1
tagged with: python
tagged with: docstring
type: AnsweredQuestion
has title: Pycharm documentation template
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49721468
favorite count: 0
type: Question
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/49721468

http://stackoverflow.com/comment/86263189
comment on: http://stackoverflow.com/q/49627205
type: Comment
type: QuestionComment
has text: This doesn't seem to be a question.
score: 1

http://stackoverflow.com/q/49688731
has body: I am doing some processing on data which after processing is then stored in mongoDB collection. For this I have maintained two versions i.e. collections of processed data which are LEVEL_TWO_CLEANED_DATA_V1 and LEVEL_TWO_CLEANED_DATA_V2. If I am using one version for processing and some other application need to access the processed data, then another version is still available to use. I am maintaining all the information required to check which version is active in another collection, called VERSION_METADATA_LEVEL_TWO. The sample documents in this collection look like: &gt; db.VERSION_METADATA_LEVEL_TWO.find().pretty() { "_id" : "V1", "COLLECTION_NAME" : "LEVEL_TWO_CLEANED_DATA_V1", "DELTA" : 21, "LAST_ACTIVE_TIME" : ISODate("2018-04-06T11:56:48.020Z"), "PROCESSING_STATUS" : "COMPLETE", "STATUS" : "ACTIVE" } { "_id" : "V2", "COLLECTION_NAME" : "LEVEL_TWO_CLEANED_DATA_V2", "DELTA" : 18, "LAST_ACTIVE_TIME" : ISODate("2018-04-06T10:51:03.029Z"), "PROCESSING_STATUS" : "IN_PROGRESS", "STATUS" : "INACTIVE" } I am trying to implement it in a way that even if python script handling the processing is forcefully closed, the VERSION_METADATA_LEVEL_TWO collection can be updated to notify failed processing i.e. it should show "PROCESSING_STATUS" : "FAILED" in particular collection. I tried using try:except in python: try: LevelTwoCleanser.initaialize() except Exception as e: MongoDatabase.updateProcessingStatusForMetadataCollectionLevelTwo(DataFormatter.INACTIVE_COLLECTION_LEVEL_TWO, "FAILED") But, it didn't worked. Is there any way of doing it in python?
score: 0
has comment: http://stackoverflow.com/comment/86391655
has comment: http://stackoverflow.com/comment/86390997
answer count: 1
has answer: http://stackoverflow.com/a/49690133
type: Question
has title: How to update mongoDB from python, even if python script handling the process is stopped manually/forcefully?
tagged with: mongodb
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49647951
tagged with: python
tagged with: datatable
score: 0
has body: I'm just trying to get a working example where I can edit values of a datatable directly into cells. I'm getting JS errors, but unfortunately I don't understand anything about JS :/ Here is the code used to reproduce error : from bokeh.plotting import show, curdoc from bokeh.models import ColumnDataSource from bokeh.models.widgets.tables import DataTable, TableColumn, BooleanFormatter, CheckboxEditor from bokeh.models.widgets.tables import NumberFormatter, NumberEditor, IntEditor, TextEditor, StringEditor, StringFormatter # DataTable construction dico = dict( nom=["Abathur", "Tychus", "Nova"], alive=[False] * 3, age=[x for x in range(0, 3)]) source_dt = ColumnDataSource(data = dico) columns = [ TableColumn(field="nom", title="Nom", editor=StringEditor(), formatter=StringFormatter()), TableColumn(field="alive", title="Alive", editor=CheckboxEditor(), formatter=BooleanFormatter(icon="check")), TableColumn(field="age", title="Age", formatter=NumberFormatter(), editor=IntEditor()) ] dt = DataTable(width=400, height=600, source=source_dt, columns=columns, editable=True, selectable=True) # show(dt) curdoc().add_root(dt) Here is a screenshot of the datatable where I try to change a String/text value: And when I validate with enter-key or clicking somewhere else, datatable is frozen and I get an error from JS console in firefox : Same observations with chrome, the error from JS console in chrome : Working environnment is Windows 10, python 3.6 and bokeh 0.12.15 supplied by Anaconda, webbrowser firefox 59 or chrome 65 Also tested on debian 8 with bokeh provided by fresh anaconda installation Am I doing something wrong ? Do you have a working sample where a value of a datatable is editable in the cell ? EDIT : I was able to locate the line of code which raise the error, it is in file https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.12.15.js at line 13440 var validationResults = currentEditor.validate(); if (validationResults.valid) { &lt;&lt;---- RAISE THE ERROR For a reaso…
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49705389
tagged with: bokeh
type: Question
has title: Bokeh datatable in-cell edition - error in bokeh-tables-0.12.15.js?

http://stackoverflow.com/q/49709502
has answer: http://stackoverflow.com/a/49794082
tagged with: django
tagged with: python
tagged with: django-viewflow
has title: Django-Viewflow, customize archive view
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
has body: I am trying to customize the default /workflow/archive/ view from Viewflow. (as in http://demo.viewflow.io/workflow/archive/) I need to remove some of the columns and add some additional ones specific to my task. I can't seem to find an easy way. I have been digging and have found that I can try to override the class viewflow.frontend.views.AllArchiveListView and adding the mapping url('^test/', AllArchiveListView.as_view()) but I get no data when doing that (seems like the flow_classes internal parameter is empty when it gets called like that) I have also tried to create the viewflow/site_archive.html template but seems overkill. Any ideas that may point me in the right direction would be highly appreciated!
type: Question

http://stackoverflow.com/q/49725516
has comment: http://stackoverflow.com/comment/86502166
downvote count: 0
has comment: http://stackoverflow.com/comment/86500303
has comment: http://stackoverflow.com/comment/86500410
has comment: http://stackoverflow.com/comment/86464857
favorite count: 0
has comment: http://stackoverflow.com/comment/86506364
tagged with: graph
score: 3
has body: We've been given standard beginner's python problem as a homework exercise, but my research into it shows people always use Networkx to solve these graph type node problems, whereas we're not allowed to use the Networkx built-in to solve it. I'm hoping for advice on a nice way to tackle this please. There are five nodes (named 1,2,3,4,5) and the order is this: 1 goes nowhere 2 only goes to 1 3 goes to 1 and 5 (but 5 is closer which makes the 3 to 1 path redundant) 4 goes to 1 and 2 (but 2 is closer so 4-1 is redundant) 5 goes to 2 This is the example data to read in (note this is just one data set - it has to work with other pairs too): ['R(3,5)', 'R(4,2)', 'R(5,2)', 'R(2,1)', 'R(3,1)', 'R(4,1)'] This is the non-redundant pair output: ['R(3,5)', 'R(4,2)', 'R(5,2)', 'R(2,1)'] My attempt so far has been to split into two lists for start node and end node: start_value = [] end_value = [] for i in range(len(partial_order)): start_value.append(int(partial_order[i][2])) for i in range(len(partial_order)): end_value.append(int(partial_order[i][4])) dictionary = dict(zip(start_value, end_value)) Output: [3, 4, 5, 2, 3, 4] [5, 2, 2, 1, 1, 1] {3: 1, 4: 1, 5: 2, 2: 1} I thought if I put it into a dictionary, I can try something from there, but my dictionary only shows 3:1 instead of 3:[1,5]. It is the 3-5 pair that I need to keep since it is closer, so 3-1 is redundant. Thanks for any tips on how to progress without Networkx. This is one of pages I was reading - I'm trying to set up graph dictionary like that so I can try out their find_shortest_path function, to see if that gives me a solution. https://www.python.org/doc/essays/graphs/ UPDATE: I ended up abandoning the dictionary idea and zipping the two lists together then performed a whole bunch of if statements to get it working. But I really would like to hear anyone's solution for something more Pythonic (so long as it doesn't use packages like Networkx). Happy coding.
has comment: http://stackoverflow.com/comment/86488814
tagged with: redundancy
tagged with: python
tagged with: nodes
has title: Python: graph redundant nodes (without Networkx)
type: Question
has comment: http://stackoverflow.com/comment/86465862
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/86507798
type: UnansweredQuestion

http://stackoverflow.com/comment/86489332
score: 0
has text: Just month. The year is the part causing the issue, which is why I want to go to just month (since I know I'll only have 12 months anyway).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49737327

http://stackoverflow.com/q/49732049
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
upvote count: 4
score: 4
has body: I have a dataframe with 38 columns, one of them is Time. I established a bin frame space timeframe=['4-6','7-9','10-12','13-15','16-18','19-21','22-24' ] bins = [3,6,9,12,15,18,21,24] Now I cut: frameddata=pd.cut(df['time'],bins,retbins=True, labels=timeframe) and want to group the df for different bins: groups=df.groupby(frameddata) here I get the following error: ValueError: Grouper and axis must be same length Any help on this?
tagged with: pandas-groupby
downvote count: 0
has title: ValueError: Grouper and axis must be same length
tagged with: pandas
has answer: http://stackoverflow.com/a/49732100
answer count: 1

http://stackoverflow.com/q/49608967
has answer: http://stackoverflow.com/a/49609357
type: UnansweredQuestion
score: -3
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49609150
has body: I have a python file (abc.py) where all constants are defined. Now, I want to assign those constants in a JSON file. Once the values are assigned in the JSON file, I want to be able to convert it to an object. For example: abc.py val1 = 10 val2 = 20 info.json import abc as C #which should be a *.py file { c1 = C.val1 #from python file c2 = C.val2 } Is this possible?
has comment: http://stackoverflow.com/comment/86224613
answer count: 2
downvote count: 4
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
type: Question
has title: import a python file into json file

http://stackoverflow.com/comment/86340160
type: AnswerComment
comment on: http://stackoverflow.com/a/49648392
has text: This gives this error: phI_max = phI[(I_max_index - 50, 0):(I_max_index + 50)] Error: slice indices must be integers or None or have an __index__ meth
type: Comment
score: 0

http://stackoverflow.com/comment/86271420
score: 0
type: AnswerComment
has text: I want to do this, because I want a central place to configure logging for my project. There is roughly 15 modules and it is cumbersome to configure logging for all of them.
type: Comment
comment on: http://stackoverflow.com/a/49632138

pygame
tags question: http://stackoverflow.com/q/49653573
tags question: http://stackoverflow.com/q/49737552
tags question: http://stackoverflow.com/q/49707248
tags question: http://stackoverflow.com/q/49661810
tags question: http://stackoverflow.com/q/49674063
tag name: pygame
tags question: http://stackoverflow.com/q/49752275
tags question: http://stackoverflow.com/q/49661056
tags question: http://stackoverflow.com/q/49628421
tags question: http://stackoverflow.com/q/49602691
tags question: http://stackoverflow.com/q/49617256
tags question: http://stackoverflow.com/q/49680723
tags question: http://stackoverflow.com/q/49608065
tags question: http://stackoverflow.com/q/49658888
tags question: http://stackoverflow.com/q/49611180
tags question: http://stackoverflow.com/q/49719322
tags question: http://stackoverflow.com/q/49650793
tags question: http://stackoverflow.com/q/49723696
tags question: http://stackoverflow.com/q/49658623
tags question: http://stackoverflow.com/q/49649288
tags question: http://stackoverflow.com/q/49711810
tags question: http://stackoverflow.com/q/49658954
tags question: http://stackoverflow.com/q/49730152
tags question: http://stackoverflow.com/q/49713943
tags question: http://stackoverflow.com/q/49754923
tags question: http://stackoverflow.com/q/49678008
tags question: http://stackoverflow.com/q/49693337
tags question: http://stackoverflow.com/q/49724494
tags question: http://stackoverflow.com/q/49707919
tags question: http://stackoverflow.com/q/49723410
tags question: http://stackoverflow.com/q/49748246
tags question: http://stackoverflow.com/q/49665655
tags question: http://stackoverflow.com/q/49619287
tags question: http://stackoverflow.com/q/49713337
tags question: http://stackoverflow.com/q/49713808
tags question: http://stackoverflow.com/q/49647845
type: Tag
tags question: http://stackoverflow.com/q/49730635

http://stackoverflow.com/q/49682846
tagged with: selenium
favorite count: 0
type: Question
answer count: 1
downvote count: 0
has body: I am building a webscraper based on Python 3, Selenium (Firefox) and BeautifulSup, so I am interested only in Python support. In this section of html I want to click on the Execute Script button. html code snippet I am able to read the page source, but it looks like when I call: driver.find_element_by_xpath('//a[@id="menu_link_-481524888_1374656230"]').click() I receive this error: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-92-dd92f6ed1ddc&gt;", line 1, in &lt;module&gt; driver.find_element_by_xpath('//a[@id="menu_link_-481524888_1374656230"]').click() File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute return self._parent.execute(command, params) File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: Element &lt;a id="menu_link_-481524888_1374656230" href="javascript:window.location=getPath()+"/ForwardAction.do?modulo=proposta&amp;path=/SelecionarConvenio/SelecionarConvenio.do?destino=ListarContratos""&gt; could not be scrolled into view I looked on internet I realized the tab is inactive, since there is an attribute inactiveTab. If I manually click, the site runs fine. So, how do I access a button under and inactive tab? Thanks!
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49683145
has title: How to click on a link in an inactiveTab?
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/49683145
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/49713298
has body: I have a text file which contains an array like this example: myarray=['banana', 'carrot', 'apple'] I have to read all the lines in that file and get the content of myarray, but I don't know how to tell python that that content is a list. with open(myFilePath) as myFile: for line in myFile: line = line.rstrip() if 'myarray' in line: line_splitted = line.split('myarray=') if len(line_splitted) &gt; 1: myArrayContent = line_splitted[1] Python, as it is logical, read myArrayContent as string. Any ideas?
downvote count: 2
favorite count: 0
type: Question
answer count: 2
has title: Get an array from a text file to be a list in python
accepted answer: http://stackoverflow.com/a/49713321
possible better answer: http://stackoverflow.com/a/49715092
upvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49713321
has answer: http://stackoverflow.com/a/49715092
type: AnsweredQuestion

http://stackoverflow.com/comment/86460902
score: 0
has text: @ScottHunter - to quote the OP, _I created a string variable containing the valid formats **and added a few** to check if my code would work._
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49723541

http://stackoverflow.com/q/49709309
has title: Prevent Python print()'s automatic newline conversion to CRLF on Windows
has comment: http://stackoverflow.com/comment/86432692
has body: I'd like to pipe text with unix-like EOL (LF) from Python via Windows CMD (console). However, Python seems to automatically convert single newlines into Windows-style end-of-line (EOL) characters (i.e. \r\n, &lt;CR&gt;&lt;LF&gt;, 0D 0A, 13 10): #!python3 #coding=utf-8 import sys print(sys.version) print("one\ntwo") # run as py t.py &gt; t.txt results in 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] one two or in hexadecimal ... 6F 6E 65 0D 0A 74 77 6F 0D 0A The second EOL is because print() defaults to end='\n', but it also does the conversion. There is no newline argument or property for print like there is for open(), so how can this be controlled?
answer count: 1
tagged with: eol
downvote count: 0
linked to: http://stackoverflow.com/q/34447623
has comment: http://stackoverflow.com/comment/86432834
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/34960955
type: AnsweredQuestion
upvote count: 8
has comment: http://stackoverflow.com/comment/86432794
accepted answer: http://stackoverflow.com/a/49709310
tagged with: newline
tagged with: windows
duplicate of: http://stackoverflow.com/q/34960955
has answer: http://stackoverflow.com/a/49709310
tagged with: python
has comment: http://stackoverflow.com/comment/86432729
score: 8

http://stackoverflow.com/a/49764576
score: 1
type: Answer
has body: Given a vtkCamera object, there is a method ApplyTransform which will allow you to apply a vtkTransform object to your camera. vtkTransform objects have many more methods for transforms than the simple ones exposed in the vtkCamera interface. You can even use multiple transform objects to build up a transform system. If you have a transformation matrix for the camera already, you can pass it to the vtkTransform object with the SetMatrix method. https://www.vtk.org/doc/nightly/html/classvtkTransform.html
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49675452
accepted answer of: http://stackoverflow.com/q/49675452

http://stackoverflow.com/a/49690652
has comment: http://stackoverflow.com/comment/130648738
has body: May be you should try this ablists = [alist, blist] with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: future_list= {executor.submit(func, a, b): i for i in ablists} You can read more here about futures and also executors
type: Answer
answers question: http://stackoverflow.com/q/49690198
upvote count: 2
has comment: http://stackoverflow.com/comment/86393405
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/130648809

http://stackoverflow.com/comment/86530789
has text: You forgot the `return` statement in `len()`, that's why is does not work. Also this seems like a job for [collections.deque](https://docs.python.org/2/library/collections.html#collections.deque)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49757833
score: 0

http://stackoverflow.com/a/49787235
has comment: http://stackoverflow.com/comment/86605439
type: Answer
has comment: http://stackoverflow.com/comment/86597495
has body: I Have solved it by update GDAL 2.2.4 with pip command. Note: Dont use conda update command ,because packages2.2.2 is not support big tiff.
accepted answer of: http://stackoverflow.com/q/49744330
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49744330

http://stackoverflow.com/comment/86414354
comment on: http://stackoverflow.com/q/49660091
type: Comment
type: QuestionComment
has text: Have you read that tutorial on [summaries and TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard)? The instructions therein should be sufficient.
score: 0

http://stackoverflow.com/a/49647971
has body: im guessing that you are trying to import like this: import bs4 try this line instead from bs4 import BeautifulSoup
answers question: http://stackoverflow.com/q/49646758
type: Answer
accepted answer of: http://stackoverflow.com/q/49646758
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49627683
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49627003
has comment: http://stackoverflow.com/comment/86262505
has body: There are two way to do this. 1) If you want django messages, then your template should contain below codes template.html {% if messages %} {% for message in messages %} &lt;div class="alert alert-success" role="alert"&gt; &lt;strong&gt;{{ message }}&lt;/strong&gt; &lt;/div&gt; {% endfor %} {% endif %} 2) If you want to use form.errors you should not send a new instance of form like you are doing currently. You should be sending the invalid form instance. views.py ####### else: form=BuyCurForm() return render(request, template_name,{'form':form,'newbc':newbc, }) correct views.py #### else: return render(request, template_name,{'form':form,'newbc':newbc})
type: Answer
accepted answer of: http://stackoverflow.com/q/49627003

http://stackoverflow.com/q/49679254
has answer: http://stackoverflow.com/a/49679349
favorite count: 0
type: Question
tagged with: rounding
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49683918
has body: I am working with Python to isolate elements from music. Training a model, I break my audio into frames, and have a label for each frame - 1 or 0. Unfortunately, due to rounding errors, my labels are always 1 or 2 frames short. Converting my audio to frames, I get a value of (13, 3709) s = [] for y in audio: mfcc = librosa.feature.mfcc(y= y, sr = 16000, n_mfcc=13, n_fft=2048, hop_length = 1024) s.append(mfcc) Converting my text file (for the mp3 I am working with) from milliseconds to frame numbers, I get a vector value of 3708. output = [] for block in textCorpus: block_start = int(float(block[0]) * 16000 / 1024) # Converted to frame number block_end = int(float(block[1]) * 16000 / 1024) # Converted to frame number singing = block[2] block_range = np.arange(block_start, block_end, 1) # Step size is 1 (per frame number) # extraneous code I have tried using Decimal, math.floor and also math.ceil within my block_start and block_stop variables, but I can't seem to match my audio frame length.
tagged with: python
has comment: http://stackoverflow.com/comment/86370241
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86370765
has title: Machine Learning - any suggestions to solve Python rounding errors?
answer count: 2
downvote count: 0
tagged with: librosa

http://stackoverflow.com/a/49713438
accepted answer of: http://stackoverflow.com/q/49710734
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49710734
score: 5
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/108792458
has body: Here is one way of doing it in numpy that doesn't require casting to a larger integer type: f - b.clip(None, f) or, equivalently, f - np.minimum(b, f)

http://stackoverflow.com/a/49665652
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49664708
upvote count: 1
has body: First, you have have strings and lists at the same level. Python won't let you compare these: &gt;&gt;&gt; 'abc' &lt; [1] TypeError: '&lt;' not supported between instances of 'str' and 'list' If you come up with a rule for what you want to do with these, you can write a key function to apply that rule. For example, let's say we want to sort lists before strings. We could sort each element x as if it were the pair (type(x).__name__, x): &gt;&gt;&gt; ('str', 'abc') &lt; ('list', [1]) False A bit hacky, but it works, and since you haven't specified how you want to handle this, I'm going to go with that key function. For your actual answer, you'll need to add on to that key function to use int(lst[1]) for 2-element lists, or something like that (it's not entirely clear how you want to distinguish between the "special" lists and normal nested ones), but I'll leave that for you to do. Now, we just need to sort recursively. If you want to do it in-place, you just sort the list, then, for each element, if it's a list, nested-sort it. Again, you'll want to add in some rule for special-casing those 2-element lists, but I'm not sure what rule you want, so you can figure it out for yourself. You might want to change things to sort every mutable sequence, not just lists, or… well, whatever seems appropriate. def nested_sort(lst): lst.sort(key=lambda x: (type(x).__name__, x)) for elem in lst: if isinstance(elem, list): nested_sort(elem) If you want a sorted copy instead, the recursion is even easier. Again, you'll have to write your own code for the special-case lists, and now you have even more options for types to handle as nested (e.g., maybe all sequences except string types?), but here's the basic idea: def nested_sorted(lst): if not isinstance(lst, list): return lst return sorted(map(nested_sorted, lst), key=lambda x: (type(x).__name__, x))
type: Answer

http://stackoverflow.com/a/49614948
type: Answer
has body: Use pandas like so: import pandas df = pandas.read_csv("yourfile.csv") df.columns = ['word', 'sentiment'] to choose words by sentiment: positive = df[df['sentiment'] &gt; 0]['word'] negative = df[df['sentiment'] &lt; 0]['word'] neutral = df[df['sentiment'] == 0]['word']
score: 0
answers question: http://stackoverflow.com/q/49614798

http://stackoverflow.com/a/55967966
type: Answer
has comment: http://stackoverflow.com/comment/114096398
has body: Adding @classmethod before setUp and tearDown will resolve the issue. @classmethod is bound to the class. class LoginTest(unittest.TestCase): @classmethod def setUpClass(cls): **Your code** @classmethod def tearDownClass(self):
answers question: http://stackoverflow.com/q/49651815
upvote count: 2
downvote count: 1
score: 1

http://stackoverflow.com/a/49720334
score: 0
has comment: http://stackoverflow.com/comment/86453709
type: Answer
has comment: http://stackoverflow.com/comment/86453766
answers question: http://stackoverflow.com/q/49720280
has body: This is one way to extract numbers enclosing within paranthesis: import re text = 'Bounding box for object 1 "PASpersonWalking" (Xmin, Ymin) - (Xmax, Ymax) : (160, 182) - (302, 431)' print(re.findall(r'(\d{3,})', text)) # ['160', '182', '302', '431']

http://stackoverflow.com/comment/86494082
score: 1
type: Comment
type: QuestionComment
has text: Seems like `unstack`?
comment on: http://stackoverflow.com/q/49739799

http://stackoverflow.com/comment/86452723
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49719407
type: Comment
has text: Each Line is a folder name: 01_Stream1 02_Stream2 ... Each top-folder will have the same subfolders: 01_Subfolder1, 02_Subfolder2 and s on. I have no list for the subfolders as there are only 8.

http://stackoverflow.com/q/49755892
has answer: http://stackoverflow.com/a/53092935
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87025224
tagged with: python
has comment: http://stackoverflow.com/comment/94957563
has title: Updating an OpenCV tracker with a bounding box in python
has body: I am using an OpenCV tracker to perform face tracking in videos, together with a face detector every few frames. If a face is detected by the face detector, I would like to update the tracker with the "detected" bounding box. I see that there is an option to enter a Rect in the C++ implementation but for some reason not in the python implementation as written in the opencv documentation. This is also an option when using dlib's correlation_tracker. Currently, I can only initialize the tracker with a bounding box, but not update it with one in Python. if my tracker has drifted off the initial face it was tracking, I can't "bring it back" even if I know where the face is now (using my face detector). Is there a way to do this in python (e.g. should I kill the current tracker and init another with detected bounding box)?
has comment: http://stackoverflow.com/comment/97889532
tagged with: opencv
downvote count: 0
has comment: http://stackoverflow.com/comment/87249530
answer count: 1
favorite count: 0
type: Question
upvote count: 9
score: 9

http://stackoverflow.com/a/49771955
score: 3
accepted answer of: http://stackoverflow.com/q/49632451
type: Answer
has comment: http://stackoverflow.com/comment/86601645
has body: Update the column names as string and try. df.columns = df.columns.astype(str)
answers question: http://stackoverflow.com/q/49632451
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49618930
answers question: http://stackoverflow.com/q/49618782
has comment: http://stackoverflow.com/comment/86416740
has comment: http://stackoverflow.com/comment/86419531
has comment: http://stackoverflow.com/comment/86250640
type: Answer
accepted answer of: http://stackoverflow.com/q/49618782
upvote count: 4
has comment: http://stackoverflow.com/comment/86245803
type: AcceptedAnswer
downvote count: 0
score: 4
has body: Perhaps you can move the question to GIS stack exchange site. There you will probably get more help on this. Anyway, a quick search shows this anwer, where it is suggested to use rasterio library, which I understand is what you need. Adapted to your case, it can be something as: import numpy as np import rasterio.features # Convert your array to 0-1 integers myarray = [[1 if t else 0 for t in row] for row in myarray] # Build a numpy array myarray = np.array(myarray) # Convert the type (don't even know why this was needed in my computer, but raised exception if not converted. myarray = myarray.astype(np.int32) # Let the library do the magic. You should take a look at the rasterio.features.shapes output mypols = [p[0]['coordinates'] for p in rasterio.features.shapes(myarray)] mypols is now an array of coordinates that you can easily convert to shapely Polygons. Beware of properly testing stranger cases. I tried to build a multipolygon, and the library returned each connected component as a polygon. Fortunately, it returns for each polygon the associated value, so you can post process as you like. Polygons with interior rings seem to be handled OK, though. I don't know what is the behavior you would expect in those cases.

http://stackoverflow.com/q/49684176
tagged with: scikit-learn
favorite count: 0
linked to: http://stackoverflow.com/q/216972
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49685503
has title: Recoding Catigorical Variables in Python
has answer: http://stackoverflow.com/a/49685503
tagged with: feature-extraction
tagged with: python
type: Question
has body: I've been trying to learn Python 3.6 using the Anaconda distribution. I've hit a snag with the content of the online course I'm using, and could use some help working through some error messages. I'd ask the instructors of the course, but they don't seem very responsive to questions from students. I've been having some trouble working with the three dominant classes used to recode categorical data. As I understand it, there are three classes drawn from the scikitlearn package used for recoding variables: LabelEncoder, OneHotEncoder and LabelBinarizer. I have attempted to employ each to recode a categorical variable inside a dataset, but keep getting errors for each. Please pardon my relative noobness for the samples codes. As one might have guessed by the baseness of my question, I am not well versed in python. The object X contains a few columns, the first being a categorical string I need to convert (If someone could also tell me how to insert tables, that'd be helpful. Do I have to use HTML?): "Fish" 1 5 3 "Dog" 2 6 9 "Dog" 8 8 8 "Cat" 5 7 6 "Cat" 6 6 6 Label Encoder Attempt Below is the code I attempted to implement, and the resulting error message I received for the object X, which has roughly the properties I described above. from sklearn.preprocessing import LabelEncoder labelencoder_X =LabelEncoder X[:, 0] = LabelEncoder.fit_transform(X[:, 0]) TypeError: fit_transform() missing 1 required positional argument: 'y' What is throwing me is I thought the above code was clearly defining what y is, the first column of X. OneHotEncoder from sklearn.preprocessing import OneHotEncoder onehotencoder = OneHotEncoder(categorical_features=[0]) X = onehotencoder.fit_transform[X].toarray() TypeError: 'method' object is not subscriptable Label Binarizer I've found this one the hardest to understand, and actually couldn't make an attempt based on the structure of the dataset. Any guidance or suggestions you could provide would be endlessly helpful.
score: 2
tagged with: categorical-data
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86262611
comment on: http://stackoverflow.com/a/49614390
score: 0
type: Comment
has text: I did that. But some other error was causing the problem. Have corrected it now. However, I am still not getting the right results. Please can you explain the code so that I can modify it?
type: AnswerComment

http://stackoverflow.com/q/49706852
has answer: http://stackoverflow.com/a/49706933
answer count: 2
tagged with: pandas
score: 1
has title: Plot frequency of dates in interval occurred in pandas dataframe
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49706980
has answer: http://stackoverflow.com/a/49706980
tagged with: python
possible better answer: http://stackoverflow.com/a/49706933
has body: I have dataframe with dates from year 1970 to year 2018, I want to plot frequency of occurrences from year 2016 to 2017. In[95]: df['last_payout'].dtypes Out[95]: dtype('&lt;M8[ns]') The data is stored in this format: In[96]: df['last_payout'].head ​​ Out[96]: &lt;bound method NDFrame.head of 0 1970-01-01 1 1970-01-01 2 1970-01-01 3 1970-01-01 4 1970-01-01 I plot this by year using group by and count : In[97]: df['last_payout'].groupby(df['last_payout'].dt.year).count().plot(kind="bar") I want to get this plot between specific dates, I tried to put df['last_payout'].dt.year &gt; 2016, but I got this: How do I get the plot for specific date range?
linked to: http://stackoverflow.com/q/49712191
type: AnsweredQuestion

svd
type: Tag
tags question: http://stackoverflow.com/q/49753477
tag name: svd

http://stackoverflow.com/a/49665935
has body: Replace port = 1027 with port = 8080 in your ftpclient file.
answers question: http://stackoverflow.com/q/49665324
score: 0
type: Answer

http://stackoverflow.com/comment/86334112
has text: I got an error after selecting a file. The variable path doesn't seem to tie to anything.
comment on: http://stackoverflow.com/a/49661256
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49685945
type: UnansweredQuestion
has title: Is is possible to cherry-pick the db connection (persistent) django will use on each request on a per client/session basis?
tagged with: django
tagged with: python
tagged with: postgresql
score: 3
tagged with: connection-pooling
upvote count: 3
downvote count: 0
has body: I'd like to be able to tell someone (django, pgBouncer, or whoever can provide me with this service) to always hand me the same connection to the database (PostgreSQL in this case) on a per client/session basis, instead of getting a random one each time (or creating a new one for that matter). To my knowledge: Django's CONN_MAX_AGE can control the lifetime of connections, so far so good. This will also have a positive impact on performance (no connection setup penalties). Some pooling package (pgBouncer for example) can hold the connections and hand them to me as I need them. We're almost there. The only bit I'm missing is the possibility to ask pgBouncer (or any other similar tool for that matter) to give me a specific db connection, instead of "one from the pool". This is important because I want to have control over the lifetime of the transaction. I want to be able to open a transaction, then send a series of commands, and then manually commit all the work, or roll everything back should something fail. Many years ago, I've implemented something very similar to what I'm looking for now. It was a simple connection pool made in C which would hold as many connections to oracle as clients needed on one hand, while on the other it would give these clients the chance to recover these exact connections based on some ID, which could have been for example a PHP session ID. That way users could acquire a lock on some database object/row, and the lock would persist even after the apache process died. From that point on the session owner was in total control of that row until he decided it was time to commit it, or until the backend decided it was time to let the transaction go by idleness.
favorite count: 0
type: Question
answer count: 0

http://stackoverflow.com/a/49713402
answers question: http://stackoverflow.com/q/49713387
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I don't think you really need a regular expression here. You can just use basic string slicing: dbs = ['Accidental_Injuries_Clean', 'Massshootings_Clean', 'Accidental_Injuries_Teens_Clean', 'Officer_Involved_Shootings_Clean', 'Accidental_Deaths_Children', 'Accidental_Injuries_Children_Clean'] for db in dbs: if db[-6:] == '_Clean': print('Delete: ', db) Output: Delete: Accidental_Injuries_Clean Delete: Massshootings_Clean Delete: Accidental_Injuries_Teens_Clean Delete: Officer_Involved_Shootings_Clean Delete: Accidental_Injuries_Children_Clean Just a note, your current regex isn't working because you are using negative lookahead for the string you want to find. Here is one that works: ^.*_Clean$
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49713387

http://stackoverflow.com/q/49696346
answer count: 1
tagged with: mysql
upvote count: 1
tagged with: scrapy
has title: error occurred while inserting data mysql database
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86406113
has comment: http://stackoverflow.com/comment/86406083
accepted answer: http://stackoverflow.com/a/49696753
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49696753
has body: class MysqlPipeline(object): def __init__(self): **Connect the mysql** self.conn = MySQLdb.connect('localhost','root','root','zhihu', charset='utf8') self.cursor = self.conn.cursor() def process_item(self, item, spider): **insert** insert_sql = """ insert into users_info(img_url,user_name,business,user_followingCount, user_followerCount,idea_num,gender,favoriteCount,voteupCount, followingColumnsCount,participatedLiveCount,followingFavlistsCount, favoritedCount,uid,school_list, job_list,place_list,major_list,company_list,url_token) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) """ param= (item["img_url"],item["user_name"],item["business"], item["user_followingCount"],item["user_followerCount"], item["idea_num"],item["gender"],item["favoriteCount"], item["voteupCount"],item["followingColumnsCount"], item["participatedLiveCount"], item["followingFavlistsCount"], item["favoritedCount"],item["uid"],item["school_list"], item["job_list"],item["place_list"],item["major_list"], item["company_list"],item["url_token"] ) self.cursor.execute(insert_sql,param) Error How should I solve this problem? Traceback (most recent call last): File "C:\Users\Administrator.JQ8B7UF6EZUHOOH\Envs\article_spider\lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "D:/分布式爬虫相关测试/Zhihu\Zhihu\pipelines.py", line 38, in process_item self.cursor.execute(insert_sql,param) File "C:\Users\Administrator.JQ8B7UF6EZUHOOH\Envs\article_spider\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Users\Administrator.JQ8B7UF6EZUHOOH\Envs\article_spider\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Users\Administrator.JQ8B7UF6EZUHOOH\Envs\article_spider\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "C:\Users\Administrator.JQ8B7UF6EZUHOOH\Envs\article_spider\lib\s…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86422369
score: 1
has comment: http://stackoverflow.com/comment/86406017

http://stackoverflow.com/comment/98870588
comment on: http://stackoverflow.com/a/49738168
has text: Wow, that is not at all obvious.
type: Comment
type: AnswerComment
score: 23

http://stackoverflow.com/comment/125381745
type: Comment
has text: This is correct if the goal is to obtain Unicode output in UTF-8 encoding, but not a proper solution for the cases where it is not.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/70923999

http://stackoverflow.com/a/49600239
has comment: http://stackoverflow.com/comment/86208441
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49599981
upvote count: 0
has body: ID_Name = [{'id': 10, 'name': 'Anna'}, {'id': 15, 'name': 'Bob'}, {'id': 20, 'name': 'Charlie'}, {'id': 25, 'name': 'Donald'} ] AVG_INCOME = [1000, 1000, 1000, 1000] ID_income = [ {ID_Name[i]['name']:AVG_INCOME[i]} for i in range(0, len(ID_Name))] ID_income &gt;[{'Anna': 1000}, {'Bob': 1000}, {'Charlie': 1000}, {'Donald': 1000}]
downvote count: 1
has comment: http://stackoverflow.com/comment/86213450
has comment: http://stackoverflow.com/comment/86213471

http://stackoverflow.com/q/49634307
has answer: http://stackoverflow.com/a/50252220
answer count: 1
has body: Answer: I needed to grant ownership access to the storage policy and not just grant a general API ownership to the IAM connected to my instance. I have simply followed the tutorial on the website here: https://cloud.google.com/storage/docs/downloading-objects#storage-download-object-python Which says def download_blob(bucket_name, source_blob_name, destination_file_name): """Downloads a blob from the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_filename(destination_file_name) print('Blob {} downloaded to {}.'.format( source_blob_name, destination_file_name)) download_blob([BUCKETNAME],[FILENAME],"/home/me/documents/file.png") I don't receive an error but the last line to be executed is blob.download_to_filename(destination_file_name) Which creates an empty file. Additional info: My bucket is in the format "mybucketname" my file is in the format "sdg-1234-fggr-34234.png" I hope anyone has knowledge about my issue. Is it encoding? Or doesn't the download_to_filename execute? Or something else?
has comment: http://stackoverflow.com/comment/87249589
has comment: http://stackoverflow.com/comment/87064194
has comment: http://stackoverflow.com/comment/87063224
favorite count: 0
has comment: http://stackoverflow.com/comment/87063258
type: Question
has title: download_to_filename makes an empty file (google cloud storage)
has comment: http://stackoverflow.com/comment/87193219
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86311552
tagged with: python
has comment: http://stackoverflow.com/comment/86760301
has comment: http://stackoverflow.com/comment/87013947
tagged with: google-cloud-storage
upvote count: 3
has comment: http://stackoverflow.com/comment/87208308
score: 3
has comment: http://stackoverflow.com/comment/115309706
downvote count: 0
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/87026329
has comment: http://stackoverflow.com/comment/87454073

http://stackoverflow.com/q/49724953
score: 0
tagged with: list
has title: Why string element of a list converted to integer when saved in CSV file?
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/86463851
type: Question
has comment: http://stackoverflow.com/comment/86463918
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/165042
has body: I have a list of lists below: mylist = [['HBASE-5727', 2, '66772ce043', '1044d5e353'], ['HBASE-5286', 2, '180b41f518', '0132176084'], ['HBASE-532', 3, 'ef5bb6f316', 'fb2db8cdaa'] ] I need to save that list into CSV file. I wrote this code: with open("numberofbugs.csv",'w') as csvfile: header = ['bug_id', 'number_of_bugs', 'first_commitID', 'last_commitID'] writers = csv.writer(csvfile) writers.writerow(header) for item in mylist: writers.writerow(item) However, the fourth element in the second sublist is written as integer 132176084. Here's the CSV file resulted: bug_id | number_of_bugs | first_commitID | last_commitID | -------------------------------------------------------------- HBASE-5727 | 2 | 66772ce043 | 1044d5e353 | HBASE-5286 | 2 | 180b41f518 | 132176084 | HBASE-532 | 3 | ef5bb6f316 | fb2db8cdaa | Why is it happen and how to keep the type of the element as it is written in the list (as string), so the value still 0132176084 instead of 132176084?
tagged with: python
has comment: http://stackoverflow.com/comment/86463874
has comment: http://stackoverflow.com/comment/86463890
has answer: http://stackoverflow.com/a/49926545
has comment: http://stackoverflow.com/comment/86463884
tagged with: integer

http://stackoverflow.com/q/49744471
tagged with: ffmpeg
has title: Sending keystrokes to subprocess using Python's popen
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49744700
answer count: 1
downvote count: 0
tagged with: python
has body: I have a Python 3.6 program that is calling ffplay from the ffmpeg library using the Popen command. I want to send ffplay keystrokes so I can control the playback. But nothing seems to happen. Take this example: import subprocess import time # Array with the command in it my_command = ("ffplay", "-nodisp", "-autoexit", "examples/sounds/Fantascape_Looping.mp3") # Open a subprocess my_subprocess = subprocess.Popen(my_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait 2 seconds time.sleep(2) # Try to send an escape: print("Attempt to send and 'escape' to stop the sound") my_subprocess.stdin.write(b'\x1b') # Wait and see what happens print("Should no longer hear anything") time.sleep(5) I hear music for 7 seconds, rather than 2 seconds. What is wrong with the code?
tagged with: popen
score: 3
upvote count: 3
favorite count: 0
type: Question

http://stackoverflow.com/comment/123494227
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/69637289
has text: The illustration and its color darkness help me understand what `contiguous` means, it means whether indexing all of next number in one row is contiguous or not. BTW, there is a minor typo at `b.t().is_contiguous()`, it might be `a.t().is_contiguous()`, thanks all the same !
type: Comment

http://stackoverflow.com/comment/86275491
type: Comment
score: 0
type: AnswerComment
has text: That helped! Thanks! This is strange because in Spyder/Anaconda it worked in [] but in IDLE it doesnt.
comment on: http://stackoverflow.com/a/49633973

http://stackoverflow.com/comment/86615121
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49789123
has text: @plast1K Probably best to post another question for extended discussion. I can't tell off hand. If it's latching onto an incorrect PID, you might check what the process name is that it's latching onto to see if also matches the name you're giving.
type: Comment

http://stackoverflow.com/comment/86272744
comment on: http://stackoverflow.com/q/49631853
type: QuestionComment
has text: @MaxU: No, I'm not. I know about this one, but similarly to GroupKFold or PredefinedSplit, it deals only with the splitting. But I need to apply some post-processing to the split.
type: Comment
score: 0

http://stackoverflow.com/a/49702724
accepted answer of: http://stackoverflow.com/q/49702352
upvote count: 13
has comment: http://stackoverflow.com/comment/86425162
has body: Nothing is wrong with your set up. Start your worker and celery beat in two separate cmd windows celery -A TwitterApiProxy worker -l info celery -A TwitterApiProxy beat -l info If you are using Celery 4.0+, you have to install eventlet first, then start your worker like this: celery -A TwitterApiProxy worker -l info -P eventlet Task Admin Backend If you want a task admin backend, you can install and use django-celery
answers question: http://stackoverflow.com/q/49702352
type: Answer
has comment: http://stackoverflow.com/comment/113196587
score: 12
has comment: http://stackoverflow.com/comment/105769462
has comment: http://stackoverflow.com/comment/86419249
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/49634701
has answer: http://stackoverflow.com/a/49638480
tagged with: python
has body: I want to make a small AI speaker. It looks like Google Home, Apple Homepod. I installed the Google Assist SDK on my Ubuntu 16.04. I can register an action through gactions. $ pushtotalk.py --device-model-id ~ I can use the Google assistant like this. But the dialogue flow is only on the simulator in the actions on google web page. Can I use it like pushtotalk.py and can I use intents in the dialogue flow?
has title: How can i use Google Assistant SDK + Dialogflow by CLI(Command Line Interface)?
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: dialogflow-es
tagged with: google-assistant-sdk
type: Question
accepted answer: http://stackoverflow.com/a/49638480

http://stackoverflow.com/comment/86273254
type: Comment
type: QuestionComment
has text: What operating system are you on?
comment on: http://stackoverflow.com/q/49632852
score: 0

http://stackoverflow.com/comment/86217599
comment on: http://stackoverflow.com/q/49605319
type: Comment
score: 0
has text: Can you do the math and tell me what it is you want?
type: QuestionComment

http://stackoverflow.com/comment/86486611
type: AnswerComment
comment on: http://stackoverflow.com/a/49733074
type: Comment
has text: Staticmethod shouldn't be used as a decorator but call eg: self.foo10 = staticmethod(foo10) I think. Glad to see that partial fits your need. Don't forget to upvote the answer and the comment so it could help other people too.
score: 0

http://stackoverflow.com/a/49963120
downvote count: 0
has body: This is possibly a duplicate of below SO thread Fastest Way to Delete a Line from Large File in Python In above it's a talk about delete, which is just a manipulation, and yours is more of a modification. So the code would get updated like below def update(filename, lineno, column, text): fro = open(filename, "rb") current_line = 0 while current_line &lt; lineno - 1: fro.readline() current_line += 1 seekpoint = fro.tell() frw = open(filename, "r+b") frw.seek(seekpoint, 0) # read the line we want to update line = fro.readline() chars = line[0: column-1] + text + line[column-1:] while chars: frw.writelines(chars) chars = fro.readline() fro.close() frw.truncate() frw.close() if __name__ == "__main__": update("file.txt", 4, 13, "History ") In a large file it make sense to not make modification till the lineno where the update needs to happen, Imagine you have file with 10K lines and update needs to happen at 9K, your code will load all 9K lines of data in memory unnecessarily. The code you have would work still but is not the optimal way of doing it
answers question: http://stackoverflow.com/q/49742962
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/49651800
type: Answer
answers question: http://stackoverflow.com/q/49627214
has body: Your problem is that your call to Usb is expecting integers, which works if you call it like this Printer = Usb(0x154f,0x0517,0,0x82,0x02) but your database call is returning tuples of hexadecimal values stored as strings. So you need to convert those strings to integers, like this: for row in result: printer_vendor_id = int(row[2],16) printer_product_id = int(row[3],16) input_end_point = int(row[4],16) output_end_point = int(row[5],16) Now if you do print printer_vendor_id,printer_product_id,input_end_point,output_end_point you will get (5455, 1303, 130, 2) which might look wrong, but isn't, which you can check by asking for the integers to be shown in hex format: print ','.join('0x{0:04x}'.format(i) for i in (printer_vendor_id,printer_product_id,input_end_point,output_end_point)) 0x154f,0x0517,0x0082,0x0002 I should point out that this only works because your database table contains only one row. for row in result loops through all of the rows in your table, but there happens to be only one, which is okay. If there were more, your code would always get the last row of the table, because it doesn't check the identifier of the row and so will repeatedly assign values to the same variables until it runs out of data. The way to fix that is to put a where clause in your SQL select statement. Something like "select * from printerdetails where id = '{0}'".format(printer_id) Now, because I don't know what your database table looks like, the column name id is almost certainly wrong. And very likely the datatype also: it might very well not be a string.
accepted answer of: http://stackoverflow.com/q/49627214
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86338293
has comment: http://stackoverflow.com/comment/86345921

http://stackoverflow.com/comment/86291495
type: QuestionComment
comment on: http://stackoverflow.com/q/49641454
score: 0
has text: @zwer Haha! thanks for the advice. Is it because this is too trivial? Probably didn't get the offer anyway :(
type: Comment

http://stackoverflow.com/comment/86514375
comment on: http://stackoverflow.com/a/49749497
score: 0
type: Comment
type: AnswerComment
has text: You have 34 characters just to indent the code? That's a lot (and not a multiple of 4 or 8, btw ;-) One possibility in that case could be to move part of the code in separate functions. Another possibility is to simply ignore the warning, as PEP8 is just a guideline ;)

http://stackoverflow.com/comment/86369982
score: 1
has text: What's wrong with just using `print("half-life is a single token".split())`? There's no point in using `\w+|\$[\d\.]+` if you add the option of `\S+`. [KISS](https://en.wikipedia.org/wiki/KISS_principle)
comment on: http://stackoverflow.com/q/49679128
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49695751
has answer: http://stackoverflow.com/a/49695875
has title: Make a Year-Week column in Python
tagged with: datetime
has body: I have a column with dates. I want a column with Year-Week, for example: 2018-13. Here 13 represents the 13th week of the year for 04.01.2018. Can you help me with the code? Input date sample: 0 04.01.2018 1 04.01.2018 2 04.01.2018 3 04.01.2018 4 05.01.2018 The post Convert a column of timestamps into periods in pandas does not help with extracting year and week simultaneously.
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/23840797
downvote count: 4
upvote count: 1
tagged with: python
score: -3
answer count: 1
accepted answer: http://stackoverflow.com/a/49695875
type: Question
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23840797

http://stackoverflow.com/comment/86226098
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49609811
type: QuestionComment
has text: Here is a similar question https://stackoverflow.com/questions/15528939/python-3-timed-input

http://stackoverflow.com/a/49693223
score: 1
type: AcceptedAnswer
downvote count: 1
has body: import re string = 'D B M LTD' print re.sub("([^ ]) ", r"\1", re.sub(" ([^ ]{2,})", r" \1", string)) Awkward, but it should work. It introduces an additional space in front of LTD and then replaces "D " with "D", "B " with "B" and so on.
has comment: http://stackoverflow.com/comment/86400282
has comment: http://stackoverflow.com/comment/86401591
accepted answer of: http://stackoverflow.com/q/49692941
type: Answer
answers question: http://stackoverflow.com/q/49692941
has comment: http://stackoverflow.com/comment/86400063
upvote count: 2

http://stackoverflow.com/comment/86232651
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49612548
has text: Is that an IAM role / S3 bucket policy that is attached to your S3 bucket?

http://stackoverflow.com/q/49600169
tagged with: python
has title: How to deal with histogram zero count when computing image entropy?
tagged with: entropy
tagged with: matlab
possible better answer: http://stackoverflow.com/a/49600211
has body: I am trying to implement the Matlab function entropy() in Python. Entropy Entropy is a statistical measure of randomness that can be used to characterize the texture of the input image. Entropy is defined as -sum(p.*log2(p)), where p contains the normalized histogram counts returned from imhist. I use openCV to get the normalized histogram counts. What should I do if there are zeroes in the histogram counts?
type: AnsweredQuestion
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/49600211
has comment: http://stackoverflow.com/comment/86207999
accepted answer: http://stackoverflow.com/a/49600247
downvote count: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49600247

http://stackoverflow.com/comment/86420063
comment on: http://stackoverflow.com/a/49703108
score: 0
type: Comment
has text: @Ajax1234 Read his comment on the question: He wants to pair up the strings with the same number, not skip over every other element of the shorter list.
type: AnswerComment

http://stackoverflow.com/a/49746778
has comment: http://stackoverflow.com/comment/86507838
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86529058
answers question: http://stackoverflow.com/q/49746711
has body: Are you looking for? import pandas as pd s=["first","second","third"] a = "; ".join(s) d=pd.DataFrame([{"text": a, "c": 1}]) print(d) Output: c text 0 1 first; second; third

http://stackoverflow.com/a/49709788
type: Answer
answers question: http://stackoverflow.com/q/49709714
has body: Your regular expression is wrong because it has a $ at the end. $ asserts that this is the end of the string. The regex engine matches your string with the regex and after matching the last two digits, expects a $ - end of the string. However, your string still has T12:54:41Z before the end, so the regex does not match. To fix this, remove $: &gt;&gt;&gt; re.match('(\d{4})[/.-](\d{2})[/.-](\d{2})', '2025-03-21T12:54:41Z') &lt;_sre.SRE_Match object; span=(0, 10), match='2025-03-21'&gt;
has comment: http://stackoverflow.com/comment/86433095
has comment: http://stackoverflow.com/comment/86433119
score: 0

http://stackoverflow.com/comment/86475706
type: QuestionComment
has text: I don't understand why you think it should transform into anything. The reason why you don't have this problem with chestPosition is that you don't have an equivalent method to resetShirtPosition that attempts to mutate it.
comment on: http://stackoverflow.com/q/49730152
score: 1
type: Comment

http://stackoverflow.com/q/49607990
answer count: 0
score: 0
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/86268685
tagged with: shutil
has comment: http://stackoverflow.com/comment/86255549
has comment: http://stackoverflow.com/comment/86266016
tagged with: excel
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/49610870
tagged with: python
has title: Python : Copying the data from one excel file to another excel file (template) and save it as new excel file without any data loss
has comment: http://stackoverflow.com/comment/86292872
has body: I have an excel sheet (with the first row having numbers) named template.xlsx.It contains data in the sheet named ‘data’ as follows it also has a graph in the second sheet named graph like this I have a csv file named input.csv which has data in the similar format as template.xlsx but has more columns than it and the first row doesn’t have the numbers. I want to copy the data from input.csv to the first sheet of template.xlsx so that the graph according to the data in input.csv will be generated in second sheet. For this, I am making another excel file output.xlsx which should first take in all the data from template.xlsx, empty itself (since number of columns in template.xlsx and input.csv are different) and copy data from input.csv in it and generate graph accordingly (I need to retain the template.xlsx and dont want to over write it,also, in the output.xlsx I want the first row to be there too). I did this but I am not able to accomplish the required task. import pandas as pd from openpyxl.utils.dataframe import dataframe_to_rows import openpyxl from shutil import copyfile template_file = 'template.xlsx' #Has numbers in row 1 already output_file = 'output.xlsx' #What we are saving the template as copyfile(template_file, output_file) # Read in the data to be pasted into the termplate df = pd.read_csv('input.csv') #to read the csv file wb = openpyxl.load_workbook(output_file) ws = wb.get_sheet_by_name('data') for r in dataframe_to_rows(df, index=False, header=False): ws.append(r) wb.save(output_file)

http://stackoverflow.com/q/49692794
tagged with: python
accepted answer: http://stackoverflow.com/a/49695243
tagged with: c++
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
has title: C++ 17 compatability with Python 2.7
has comment: http://stackoverflow.com/comment/86397815
score: 7
upvote count: 7
tagged with: c++17
has comment: http://stackoverflow.com/comment/86397897
has answer: http://stackoverflow.com/a/49695243
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/20618008
answer count: 1
has body: The most recent version of python 2.7 (2.7.13) includes a header unicodeobject.h that uses the register keyword. My understanding is that C++ 17 has removed this keyword. When compiling against this header using C++ 17, unsurprising a slew of warnings are triggered including: /opt/anaconda/include/python2.7/unicodeobject.h:534:24: warning: ISO C++1z does not allow ‘register’ storage class specifier [-Wregister] register PyObject *obj, /* Object */ ^~~ /opt/anaconda/include/python2.7/unicodeobject.h:553:24: warning: ISO C++1z does not allow ‘register’ storage class specifier [-Wregister] register PyObject *obj /* Object */ ^~~ /opt/anaconda/include/python2.7/unicodeobject.h:575:29: warning: ISO C++1z does not allow ‘register’ storage class specifier [-Wregister] register const wchar_t *w, /* wchar_t buffer */ ^ /opt/anaconda/include/python2.7/unicodeobject.h:593:23: warning: ISO C++1z does not allow ‘register’ storage class specifier [-Wregister] register wchar_t *w, /* wchar_t buffer */ That said, I am still able to compile and run python extensions despite these warnings. Is it safe to continue doing so? Is there any way (besides explicitly ignoring the warnings) to resolve these messages such as upgrading to a different version of 2.7 (though as mentioned the newest version seems to still use the register keyword)?

http://stackoverflow.com/comment/86472072
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49729046
has text: Not sure what exactly you mean by "byte array". A string in Python 2.7 is an array of bytes.

http://stackoverflow.com/comment/86227486
type: QuestionComment
score: 0
has text: Python is case sensitive, so `Cursor` isn't the same thing as `cursor`. And anyway, the best way to find out if something is a class is to use `type(db.cursor)`. It's a method that returns a Cursor object, nothing more.
comment on: http://stackoverflow.com/q/49610464
type: Comment

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/49616402
tags question: http://stackoverflow.com/q/49636443

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/49741836
type: Tag
tags question: http://stackoverflow.com/q/49654856

http://stackoverflow.com/comment/86399010
type: Comment
type: QuestionComment
has text: this one ? `https://stackoverflow.com/questions/10266281/obtain-active-window-using-python` but it also requires a package
score: 0
comment on: http://stackoverflow.com/q/49691828

http://stackoverflow.com/comment/86405455
comment on: http://stackoverflow.com/q/49695960
score: 0
type: Comment
type: QuestionComment
has text: Restarting is automatically done when I update a file within my project.

http://stackoverflow.com/comment/86453787
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate: https://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs
comment on: http://stackoverflow.com/q/49720345

http://stackoverflow.com/comment/87571072
type: Comment
score: 0
type: AnswerComment
has text: I went the route of Selenium. It's really easy to use and I've since been using it for other web scraping tasks.
comment on: http://stackoverflow.com/a/49740303

http://stackoverflow.com/q/49640234
tagged with: numpy
linked to: http://stackoverflow.com/q/11144513
type: Question
upvote count: 2
tagged with: arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/49640529
has comment: http://stackoverflow.com/comment/86288248
has answer: http://stackoverflow.com/a/49640529
score: 2
type: AnsweredQuestion
has body: numpy.linspace is one-dimensional linear gradient. For example: numpy.linspace(0, 3, 4): [0, 1, 2, 3] It is easy to imagine 2-dimensional linear gradient: [[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [1, 1], [2, 1], [3, 1]], [[0, 2], [1, 2], [2, 2], [3, 2]], [[0, 3], [1, 3], [2, 3], [3, 3]]] What I need is 3 or even 4-dimensional linear gradients using numpy. I can easily achieve it using Python code, but it is too slow. %time arr = numpy.array([ [ [ (a, b, c) for a in range(65) ] for b in range(65) ] for c in range(65) ]) Wall time: 177 ms arr.shape (65, 65, 65, 3)
downvote count: 0
answer count: 1
has title: numpy: multidimensional linspace
favorite count: 0

http://stackoverflow.com/comment/86286995
score: 0
type: AnswerComment
has text: Thanks for the simplest Solution. You are great. Thanks
type: Comment
comment on: http://stackoverflow.com/a/49639624

http://stackoverflow.com/a/49696881
score: 2
has comment: http://stackoverflow.com/comment/86408716
downvote count: 0
has comment: http://stackoverflow.com/comment/86408892
answers question: http://stackoverflow.com/q/49696761
has comment: http://stackoverflow.com/comment/86407934
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86409153
has body: It looks like you are taking the log of every value in self.arms and that you know the median value should be around 1.0. So instead of self.arms = df['arms'].iloc[-self.plotlength:] self.armsup = [0 if i &lt; 1.0 else log(i, 10) for i in self.arms] self.armsdn = [0 if i &gt; 1.0 else log(i, 10) for i in self.arms] you could use self.arms = df['arms'].iloc[-self.plotlength:] self.armsup = [1.0 if log(i, 10) &lt; 1.0 else log(i, 10) for i in self.arms] self.armsdn = [1.0 if log(i, 10) &gt; 1.0 else log(i, 10) for i in self.arms] or, similarly, using NumPy: self.arms = df['arms'].iloc[-self.plotlength:] log_arms = np.log(self.arms) threshold = 1 mask = log_arms &gt; threshold armsup = np.where(mask, log_arms, threshold) armsdn = np.where(~mask, log_arms, threshold) np.where has call signature np.where(cond, x, y) where cond is a boolean array, x and y are arrays of the same length as cond, and np.where(cond, x, y) returns values from x where cond is True and from y where cond is False. For example, import numpy as np import matplotlib.pyplot as plt N = 100 arms = np.random.uniform(0.5, 4.0, N) log_arms = np.log(arms) threshold = 1 mask = log_arms &gt; threshold armsup = np.where(mask, log_arms, threshold) armsdn = np.where(~mask, log_arms, threshold) fig, ax = plt.subplots() x = np.arange(N) ax.vlines(x, threshold, armsup, color='g') ax.vlines(x, armsdn, threshold, color='r') plt.show() yields
type: Answer
has comment: http://stackoverflow.com/comment/86407504
accepted answer of: http://stackoverflow.com/q/49696761
upvote count: 2

http://stackoverflow.com/comment/86328285
type: Comment
comment on: http://stackoverflow.com/a/49643922
type: AnswerComment
has text: I think it's best if you post a new question with this problem, since the one asked here originally has been solved.
score: 0

http://stackoverflow.com/comment/86335048
type: AnswerComment
comment on: http://stackoverflow.com/a/49662098
has text: Pardon me, I misread your comment thinking `jq` was a python package. I got the following error: `parse error: Unfinished string at EOF at line 603195, column 263 Error: writing output failed: Invalid argument`
type: Comment
score: 0

http://stackoverflow.com/comment/86350815
comment on: http://stackoverflow.com/a/49669944
score: 0
has text: I forgot, you also need to add: `contentType: 'application/json;charset=UTF-8'`. I updated the answer.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/68527340
answers question: http://stackoverflow.com/q/49699244
score: 0
has body: You probably can use two separate .env-files. The one for your passwords and the one for pipenv somewhere else. You can use a custom path for your pipenv .env-file by setting the PIPENV_DOTENV_LOCATION variable in the environment. It is debateable if you consider this portable, if you have to set the variable first. Anyway, from experience you should not rely too strong on the autoload of .env. If you are using remote/ssh interpeters or having several environments in parallel for testing purposes the cleanest way would be to just add your project path to a *.pth file in the site-packages folder of your Python environment. In conda there is an explicit "develop" comand for this, in pipenv you still have to do it manually though. Still, this is the way, because you create your Python environment explicitly for your project in an arbitrary setup, and then you also should hardwire the project location into this setup.
type: Answer

sensors
type: Tag
tags question: http://stackoverflow.com/q/49724109
tag name: sensors

http://stackoverflow.com/comment/86444308
score: 0
comment on: http://stackoverflow.com/q/49715385
type: QuestionComment
type: Comment
has text: Use `print("Median time of death:",df_time['time_to_death'].median().days) `

http://stackoverflow.com/comment/86303632
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49646895
has text: You don't use `User` or `AUTH_USER_MODEL` anywhere else in that `models.py`, so I really think that moving it to a different app will fix the problem. If doing that gave you an error, at least it should have been a different error.
type: QuestionComment

http://stackoverflow.com/q/49610464
answer count: 0
has comment: http://stackoverflow.com/comment/86227306
has comment: http://stackoverflow.com/comment/86227437
downvote count: 0
has body: I would like to know what do we mean when we write instanceName.className, in Python. Like in PyMySQL:- db = pymysql.connect(...) cursor = db.cursor() &lt;- what does this mean ?
has comment: http://stackoverflow.com/comment/86227610
favorite count: 0
type: Question
has title: What do we mean by Instance.classname() in python?
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86227486
tagged with: python
tagged with: inheritance
tagged with: class
score: 2
tagged with: oop

http://stackoverflow.com/comment/86356372
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49663391
has text: thanks! I'm getting an error message ['dict' object has no attribute 'iteritems'] for [rep = dict((re.escapte(k)...]. is this supposed to be something different when i'm trying to run it through a dataframe? thanks again for any suggestions!
type: Comment

http://stackoverflow.com/comment/86339364
type: AnswerComment
score: 1
type: Comment
has text: Thanks @Filipe, can I please ask you to edit your answer to include an example of using scandir.walk() to perform this? Thanks again...
comment on: http://stackoverflow.com/a/49664695

http://stackoverflow.com/comment/86405347
has text: You probably haven't restarted your server since adding test - as you can see, all the other URLs in that file are available.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49695960
type: Comment

http://stackoverflow.com/comment/86423778
type: Comment
type: QuestionComment
score: 0
has text: Can you rename `local_module` you're pulling from within the `main1.py` path?
comment on: http://stackoverflow.com/q/49705245

http://stackoverflow.com/comment/86468996
has text: Why not putting the connection string in a config.ini? Each of you can then have its own config file depending on your environment
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49727457

http://stackoverflow.com/comment/86514064
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49749699
type: Comment
has text: No I cannot. The site doesn't give me the option to generate a new key sadly.

http://stackoverflow.com/comment/130217150
score: 0
type: AnswerComment
has text: +1: By far the better answer to OP for addressing its requirements, by resorting to metadata-agnostic pixel-level hashing.
comment on: http://stackoverflow.com/a/54053080
type: Comment

http://stackoverflow.com/q/49606509
has comment: http://stackoverflow.com/comment/86242239
accepted answer: http://stackoverflow.com/a/49606574
has comment: http://stackoverflow.com/comment/86219816
has answer: http://stackoverflow.com/a/49606574
tagged with: python
score: -1
type: AnsweredQuestion
has body: i'm using this code to record video with a PS3 camera *the code is in spanish by the way that's why i wrote "camara" and not "camera". i'm using Python 2.7 and opencv 3.4.0.12, i'm assuming that the problem is the version of opencv but i don't think so BUT HONESTLY AT THIS POINT I DON'T KNOW WHAT'S RIGHT OR WRONG, PLEASE HELP. When i run it i get this errors: Traceback (most recent call last): File "C:\Users\carls\OneDrive\Documentos\VIDEO CAMARA PS3.py", line 31, in camara1() File "C:\Users\carls\OneDrive\Documentos\VIDEO CAMARA PS3.py", line 9, in camara1 fourcc = cv2.cv.CV_FOURCC(*"XVID") AttributeError: 'module' object has no attribute 'cv' Also when i run the code instead of recording in the PS3 camera, the camera from my laptop turns on. THIS IS PART OF THE CODE TOO, SORRY! import numpy as np import cv2 import random import time def camara1(): cap = cv2.VideoCapture(0) fourcc = cv2.cv.CV_FOURCC(*"XVID") size1 = (int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) ) out = cv2.VideoWriter('output.avi',fourcc, 20.0, size1) while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0) out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break else: break #Release everything if job is finished cap.release() out.release() cv2.destroyAllWindows() camara1() #THIS IS IN THE CODE TOO, SORRY. THIS IS THE LAST CODE LINE
has comment: http://stackoverflow.com/comment/86219844
upvote count: 2
has title: PYTHON 2.7 AttributeError: 'module' object has no attribute 'cv'
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86623220
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86242364
tagged with: opencv

http://stackoverflow.com/comment/86240012
comment on: http://stackoverflow.com/q/49616500
type: Comment
type: QuestionComment
score: 0
has text: Looks like you've got a list of tuples and you want to only print the first element. Suppose the result of your query is stored in the variable `myResult`, you could do: `print(myResult[0][0])` or loop over all of the results: `for result in myResult: print(result[0])`

http://stackoverflow.com/comment/86386929
score: 0
type: Comment
has text: I'd use a generator instead.
type: AnswerComment
comment on: http://stackoverflow.com/a/49687881

http://stackoverflow.com/comment/104934195
has text: This line `fp = webdriver.FirefoxProfile('specify location to profile .default')` will copy whatever profile you have at that location, paste it to `/tmp/rust_mozprofileasdf123` and then driver will use this copied version of profile.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49817725
type: Comment

http://stackoverflow.com/comment/86506333
has text: This is a very good answer, thanks. However, instead of a list of words, I have something like: """ art goes here """. So I am not able to use that function. EDIT: splitlines() function is just for this. Thanks for the answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/49745894
score: 0
type: Comment

http://stackoverflow.com/q/49757013
tagged with: lxml
score: 1
has comment: http://stackoverflow.com/comment/86533611
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
has body: I am crawling this website, https://www.ntuh.gov.tw/labmed/檢驗目錄/Lists/2015/BC.aspx. It is an aspx so I plan to use selenium to get multiple pages of the table in the same url. However, I cannot extract the table even though I believe I am using the correct xpath. import requests from selenium import webdriver from time import sleep from lxml import etree, html url = "https://www.ntuh.gov.tw/labmed/檢驗目錄/Lists/2015/BC.aspx" browser = webdriver.Chrome() browser.get(url) # The url is visited with Chrome correctly root = etree.fromstring(browser.page_source, etree.HTMLParser()) root.xpath("//table[@class='ms-listviewtable']/tr") # It gives me [] while browser.page_source is a string of html Still, I can use the very same xpath to get (part of the) data successfully - except that only the information on the first page of the table can be crawled, which is undesirable. result = "" while result == "": try: # Certificate is not verified to bypass the SSLError # Not secure though result = requests.get(url, verify = False) break except: sleep(5) continue # Transform it into an element tree root = etree.fromstring(result.content, etree.HTMLParser()) # Parse the information with Xpath root.xpath("//table[@class='ms-listviewtable']/tr") # It gives me many elements of tr tags Why is that and how can I fix it?
favorite count: 0
has title: The same xpath yields different extraction results from the same webpage
type: Question
accepted answer: http://stackoverflow.com/a/50008112
has answer: http://stackoverflow.com/a/50008112
has comment: http://stackoverflow.com/comment/86533833
tagged with: python
tagged with: web-crawler
type: AnsweredQuestion
tagged with: xpath
has comment: http://stackoverflow.com/comment/86534502

http://stackoverflow.com/q/49600526
score: -4
answer count: 1
has body: Python beginner here, I'm modifying a piece of existing code (TwitterSearch on Github) to search Twitter for specific tweets that contain certain keywords using standard search API. I keep getting a Syntax Error, but it points me to blank space at the end of a line. The thing is, the code worked once yesterday (as in I got the output I wanted) and then I tried to use it again and it keeps giving me SyntaxError. At one point the error was at the end of the code - I deleted the last few lines and the error would simply move to whatever the end of the code was (but it always pointed at blank space rather than anything I had typed). Now it's moved to the blank space after the closing brackets following 'created at' (see below) I've been consistently indenting the same way throughout, so I don't think it's an indentation error. For reference, I'm using Jupyter Notebook. These are the last four lines of the code: for tweet in ts.search_tweets_iterable(tso): print:('@%s tweeted: %s' % (tweet['user']['screen_name'], tweet['text']), (tweet['created_at'])) ^ **this is where the Syntax Error points to** except TwitterSearchException as e print:('e') Any help would be much appreciated.
type: Question
type: AnsweredQuestion
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/49600560
tagged with: syntax-error
downvote count: 4
has title: Python Syntax error: blank space at end of line
has answer: http://stackoverflow.com/a/49600560
upvote count: 0
has comment: http://stackoverflow.com/comment/86208092

http://stackoverflow.com/q/49635734
type: UnansweredQuestion
has body: $ cat test_version.py import argparse parser = argparse.ArgumentParser(prog='test_version.py') parser.add_argument("-f", "--file", help="file name", type=str, required=True) parser.add_argument("-v", "--version", help="show program version", action="store_true") args = parser.parse_args() if args.version: print('test version: 3.5.1') $ python test_version.py --version usage: test_version.py [-h] -f FILE [-v] test_version.py: error: the following arguments are required: -f/--file $ python test_version.py --version -f a test version: 3.5.1 Question> Is there a method I can use to enable the following operation? $ python test_version.py --version test version: 3.5.1 As you can see, in this case, I don't have to provide the required parameter.
tagged with: python
linked to: http://stackoverflow.com/q/8521612
answer count: 0
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/86278916
duplicate of: http://stackoverflow.com/q/8521612
downvote count: 1
has title: support version without providing required parameters
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49747339
answers question: http://stackoverflow.com/q/49746175
has comment: http://stackoverflow.com/comment/86509791
has body: __str__ needs to return a string representation of the object. __str__ goal is to be readable, __repr__ goal is to be unambiguous. When you print a list (which is tweet_inst), it iterates over the objects (of Tweet) contained in the list and call their __repr__. You want to add def __repr__(self): return str(self) so they do the same thing, then it will return self.text instead of the object default representation (which is it's location in memory) class Tweet(object): def __init__(self, x): self.x = x def __str__(self): return self.x def __repr__(self): return '__repr__' + str(self.x) &gt;&gt;&gt; t1 = Tweet('t1') &gt;&gt;&gt; t2 = Tweet('t2') &gt;&gt;&gt; list_ = [t1, t2] &gt;&gt;&gt; print(list_) [__repr__t1, __repr__t2] Rather than the default [&lt;__main__.Tweet object at 0x02AFA810&gt;, &lt;__main__.Tweet object at 0x029E2BF0&gt;] Here is a great answer by moshez about the difference between the two.
type: Answer
has comment: http://stackoverflow.com/comment/86509125
score: 0

http://stackoverflow.com/q/49626880
has comment: http://stackoverflow.com/comment/86260792
has comment: http://stackoverflow.com/comment/86261149
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/86261027
has body: I have an instance of a class that needs to be appended to a list. However, upon appending N amount of instances, the values of the list is the last inserted instance. Here is a replication of what I'm trying to do (Original file is big): class SomeParent: listOfObject = [] tempObject = None def addObjects(self): for i in range(10): self.tempObject = Child() self.changeTempObjectX(i) listOfObject.append(self.tempObject) def changeTempObjectX(self, i): self.tempObject.x = i class Child: x = None The Problem: The listOfObject should contain, in theory, 10 instances of Child class with different x attribute (0-9). What is happening is that the values of listOfObject (all of them) are same to the last inserted instance. I was doing my searching and found out that this has to do with mutability and references. What I think is happening is that what is being inserted to the list is a reference to the previous value which will in turn point out to the last inserted value. Tried: Converting listOfObject to tuple and the add operation is like this self.listOfObject = self.listOfObject + (self.tempObject,). I also tried using all types of copy which didn't work. I'm aware of the structure of the application and I don't need changing it as it will require a big amount of effort to refactor the code. It is pretty straightforward, create, edit and save the instance. How can I insert to a list an instance of a class?
has answer: http://stackoverflow.com/a/49627150
answer count: 4
has comment: http://stackoverflow.com/comment/86261045
has answer: http://stackoverflow.com/a/49627771
upvote count: 0
has answer: http://stackoverflow.com/a/49627125
has comment: http://stackoverflow.com/comment/86261031
tagged with: oop
downvote count: 3
has answer: http://stackoverflow.com/a/49627136
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86260869
has title: Adding instance to a list creates similar values
type: UnansweredQuestion

http://stackoverflow.com/q/49633207
has title: Conditional groupby and shift in pandas
tagged with: pandas
linked to: http://stackoverflow.com/q/33261359
has comment: http://stackoverflow.com/comment/86274116
tagged with: python
has answer: http://stackoverflow.com/a/49633518
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: shift
upvote count: 1
has body: I have a dataframe that looks like this, which store the order by order information of an order book. Type N = new order, D = delete order and E = execution. the same order_id might be reused. So basically the problem is that delete and execution does not have a proper price as they should be inferred by the last new order with the same oid. Could someone suggest a method to achieve this? Thank you Input type order_id price 0 N 10 99 1 E 10 0 1 E 10 0 1 D 10 0 0 N 11 98 1 N 10 97 1 D 10 0 Output type order_id price 0 N 10 99 1 E 10 **99** 1 E 10 **99** 1 D 10 **99** 0 N 11 98 1 N 10 97 1 D 10 **97**
downvote count: 1
has comment: http://stackoverflow.com/comment/86274468
favorite count: 0
has answer: http://stackoverflow.com/a/49633569
type: Question

http://stackoverflow.com/comment/86400113
type: AnswerComment
has text: Thanks for the answer! I had one follow up question, that is in regard to line 34. (p.s. you forgot the parenthesis after print :) ) I'm assuming this is the part where I would make it do stuff, like for example, when I click a number, it would be under def click(self, event): that I would make it pull up a text box for comments on that day, right?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49688938

http://stackoverflow.com/comment/86370204
comment on: http://stackoverflow.com/q/49670832
type: Comment
type: QuestionComment
score: 1
has text: Not the root cause here, but the 'w mask' line is wrong. You're selecting the masked entries with `y_test[(x_test[:,N:] == 0).all(axis=2)]`.

http://stackoverflow.com/q/49621903
score: 0
has title: Algorithm to evenly split number with factors while maximizing the lowest weight
has body: Given a number and a list of factors, what is the most efficient way to split this number into its given factors so as to maximize the minimum weight (weight is the multiple of particular factor)? &gt;&gt;&gt; number = 32 &gt;&gt;&gt; given_factors = [1,2,4] &gt;&gt;&gt; evenly_split_a_number_with_factors(number, given_factors) [6,5,4] # note: 6*1 + 5*2 + 4*4 == 32 Another way to think of it as: Given: w1*f1 + w2*f2 + ... + wN*fN = Z Where: given f1,f2,f3...fN are ascending order factors of a given positive number Z Find: w1,w2,w3...wN which are corresponding factors' non-zero positive weights and weights being approximately evenly distributed Example e.g. Given: a + 2b + 4c = 32, find largest together possible a,b,c 1 2 4 a b c 32 00 00 00 16 00 00 00 08 08 04 04 06 05 04 &lt;- should be the outcome of this algorithm
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49622545
type: Question
tagged with: algorithm
answer count: 2
tagged with: math
tagged with: python
accepted answer: http://stackoverflow.com/a/49622545
possible better answer: http://stackoverflow.com/a/49637807
has answer: http://stackoverflow.com/a/49637807
type: AnsweredQuestion

http://stackoverflow.com/a/49693147
has comment: http://stackoverflow.com/comment/86398858
has comment: http://stackoverflow.com/comment/86421408
answers question: http://stackoverflow.com/q/49692996
has comment: http://stackoverflow.com/comment/86407555
score: 1
has comment: http://stackoverflow.com/comment/86398726
downvote count: 0
has comment: http://stackoverflow.com/comment/86406870
upvote count: 1
has comment: http://stackoverflow.com/comment/86406596
has comment: http://stackoverflow.com/comment/86406144
has comment: http://stackoverflow.com/comment/86406459
has body: It's possible you mean something like &gt;&gt;&gt; df.STATUS.astype(str).str.upper().str.contains('RECEIVED') 1 True 2 False 3 False (Your example has a typo, incidentally - 1. has RECEIVED and 3. has RECIEVED.) as isin is the opposite of what is meant by your example.
has comment: http://stackoverflow.com/comment/86408687
type: Answer

http://stackoverflow.com/comment/86513461
score: 0
type: Comment
type: QuestionComment
has text: You want to pad the image?
comment on: http://stackoverflow.com/q/49747969

http://stackoverflow.com/comment/86473458
type: QuestionComment
has text: Does app doen't have __init__.py file ? I belive you import your home ( blueprint or normal views ) to `app>__init__.py` Isn't it ?
score: 0
comment on: http://stackoverflow.com/q/49729918
type: Comment

http://stackoverflow.com/q/49699926
has title: Kombu 4.1.0 - Memory usage increase (leak?) on a worker when using kombu queues
type: Question
tagged with: worker
tagged with: redis
type: UnansweredQuestion
tagged with: memory-leaks
tagged with: python
tagged with: kombu
has comment: http://stackoverflow.com/comment/86413222
score: 0
has comment: http://stackoverflow.com/comment/87342978
answer count: 0
has comment: http://stackoverflow.com/comment/86414139
has body: I have implemented a worker using Kombu's SimpleQueue. The implementation is as given below. When I run this worker for a few hours on a Ubuntu 16.04 system with redis as the backend, I notice a gradual memory build up on the process. When I run this worker for over a day, it ends up consuming all memory on the system and the system ends up being unusable, until the worker is killed. On redis server, I have it configured with a timeout set to 5 seconds and a tcp_keepalive set to 60 seconds. Worker Code: from kombu import Connection myqueue_name = 'test_queue' backendURL = 'redis://127.0.0.1:6379/' def GetConnection(): conn = Connection(backendURL) return conn def dequeue(): conn = GetConnection() with conn: myqueue = conn.SimpleQueue(myqueue_name) item = None try: qItem = myqueue.get(block=True, timeout=2) item = qItem.payload qItem.ack() except Exception as e: qItem = None myqueue.close() conn.close() conn.release() return item if __name__ == '__main__': try: i = 1 while True: print 'Iteration %s: %s' % (i, dequeue()) i = i + 1 except (KeyboardInterrupt, SystemExit): print 'Terminating' Here's a plot of free memory on the system: What is going wrong here? Did I miss anything in the implementation? Any help here will be greatly appreciated.
has comment: http://stackoverflow.com/comment/86414414

http://stackoverflow.com/comment/86460588
type: Comment
has text: Yeah I just tried that and it works for me too :) Thank you!!
type: QuestionComment
comment on: http://stackoverflow.com/q/49723274
score: 0

http://stackoverflow.com/comment/86390509
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49678829
type: QuestionComment
has text: post the solution as answer :)

http://stackoverflow.com/comment/138480702
comment on: http://stackoverflow.com/a/78548247
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: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49736849
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/39120942
type: AnsweredQuestion
tagged with: pca
score: 1
has comment: http://stackoverflow.com/comment/86488566
tagged with: matplotlib
downvote count: 0
answer count: 1
has title: No runtime error, but wrong iris PCA plotting
tagged with: scikit-learn
has body: I am using following code to perform PCA on iris dataset: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # get iris data to a dataframe: from sklearn import datasets iris = datasets.load_iris() varnames = ['SL', 'SW', 'PL', 'PW'] irisdf = pd.DataFrame(data=iris.data, columns=varnames) irisdf['Species'] = [iris.target_names[a] for a in iris.target] # perform pca: from sklearn.decomposition import PCA model = PCA(n_components=2) scores = model.fit_transform(irisdf.iloc[:,0:4]) loadings = model.components_ # plot results: scoredf = pd.DataFrame(data=scores, columns=['PC1','PC2']) scoredf['Grp'] = irisdf.Species sns.lmplot(fit_reg=False, x="PC1", y='PC2', hue='Grp', data=scoredf) # plot point; loadings = loadings.T for e, pt in enumerate(loadings): plt.plot([0,pt[0]], [0,pt[1]], '--b') plt.text(x=pt[0], y=pt[1], s=varnames[e], color='b') plt.show() I am getting following plot: However, when I compare with plots from other sites (e.g. at http://marcoplebani.com/pca/ ), my plot is not correct. Following differences seem to be present: Petal length and petal width lines should have similar lengths. Sepal length line should be closer to petal length and petal width lines rather than closer to sepal width line. All 4 lines should be on the same side of x-axis. Why is my plot not correct. Where is the error and how can it be corrected?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49737963
has comment: http://stackoverflow.com/comment/86488577
has answer: http://stackoverflow.com/a/49737963

http://stackoverflow.com/comment/86482399
has text: Ideally yes. i thought there could be a smart unknown function in python which could handle such cases. but if know i will use different constructs. that is fine for me. it has been just a question...
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49734052

http://stackoverflow.com/a/49609864
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Check my codes: def remove_dup(my_lst): from copy import deepcopy from collections import OrderedDict my_lst = list(reversed(deepcopy(my_lst))) ordred_dict = OrderedDict() for sub_list in my_lst: ordred_dict[tuple(sub_list[1:])] = sub_list return list(ordred_dict.values()) def main(): results = {'example': [['london', '5.123', '-3.123'], ['bham', '5.123', '-3.123'], ['manc', '51.23', '-3.453']]} nduplicates = {k: remove_dup(v) for k, v in results.items()} print(nduplicates) if __name__ == "__main__": main() and you got: {'example': [['manc', '51.23', '-3.453'], ['london', '5.123', '-3.123']]} The codes about reverse the list guarantees that if a duplicate is found, keep the first element.
type: Answer
answers question: http://stackoverflow.com/q/49609445
accepted answer of: http://stackoverflow.com/q/49609445

http://stackoverflow.com/comment/86245082
comment on: http://stackoverflow.com/a/49619005
type: Comment
type: AnswerComment
has text: I like it but the second ValueError should raise an error I'd say.
score: 0

http://stackoverflow.com/comment/86247231
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49620100
has text: Yes, if I use that then I get the "can't pickle lambda functions" =/

http://stackoverflow.com/comment/86368123
has text: how can i attached a log out button on my original code?
type: Comment
comment on: http://stackoverflow.com/a/49638169
type: AnswerComment
score: 0

http://stackoverflow.com/a/49722251
has body: Uninstall the dependent library one by one and try reinstalling this library. conda uninstall &lt; dependent >
answers question: http://stackoverflow.com/q/49722143
has comment: http://stackoverflow.com/comment/86495784
type: Answer
has comment: http://stackoverflow.com/comment/86457832
score: 0
has comment: http://stackoverflow.com/comment/86458146

http://stackoverflow.com/a/49654236
type: AcceptedAnswer
type: Answer
has body: In Jinja2 (unlike for example Django template language) you can use methods with parameters, so you can use the dictionary .get method: {{ result.get(header) }}
accepted answer of: http://stackoverflow.com/q/49654198
score: 0
answers question: http://stackoverflow.com/q/49654198

http://stackoverflow.com/q/49733850
has comment: http://stackoverflow.com/comment/86482691
has comment: http://stackoverflow.com/comment/86481610
linked to: http://stackoverflow.com/q/438844
has comment: http://stackoverflow.com/comment/86481561
has comment: http://stackoverflow.com/comment/86481860
has comment: http://stackoverflow.com/comment/86481772
has comment: http://stackoverflow.com/comment/86482503
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/49734052
downvote count: 4
upvote count: 2
type: UnansweredQuestion
answer count: 1
has body: I have typically an outer loop with an inner loop in it. Now I would like to modify the code that way that in some situation the outer loop shall not be executed but just the inner loop. There are no data need from outer loop in the inner loop. for i in list_a: # do sth in list_a for j in list_b: #do sth in list_b Could this be done in ONE construct or shall i write two different loop constructs like: if (conditionA): for i in list_a: # do sth in list_a for j in list_b: #do sth in list_b if (conditionB): for j in list_b: #do sth in list_b
has comment: http://stackoverflow.com/comment/86481975
has comment: http://stackoverflow.com/comment/86481576
tagged with: loops
favorite count: 0
has title: Outer and inner loop by condition
type: Question

http://stackoverflow.com/comment/86405211
score: 0
type: Comment
has text: I can't delete it
type: AnswerComment
comment on: http://stackoverflow.com/a/49695988

http://stackoverflow.com/comment/86520945
comment on: http://stackoverflow.com/q/49753012
has text: Thanks @toheedNiaz, this solved the problem instantly. appreciate a bunch. What about the json passed?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86362289
comment on: http://stackoverflow.com/q/49675419
type: QuestionComment
type: Comment
has text: TypeError: image is not a numpy array, neither a scalar
score: 0

http://stackoverflow.com/comment/86357218
score: 7
comment on: http://stackoverflow.com/q/49673345
type: QuestionComment
has text: `df = df[df['my_col'].notnull()]` ?
type: Comment

http://stackoverflow.com/a/49638494
has comment: http://stackoverflow.com/comment/86301430
has comment: http://stackoverflow.com/comment/86284823
has comment: http://stackoverflow.com/comment/86285030
has comment: http://stackoverflow.com/comment/86284768
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49638372
upvote count: 1
has comment: http://stackoverflow.com/comment/86285009
has body: Try defining the rule first: def color_chocolate_red(val): color = 'red' if val == 'chocolate' else 'black' return 'color: {}'.format(color) Then apply it: result = df.style.applymap(color_chocolate_red) For entire row you can use this: def highlight_row(x): df = x.copy() mask = df['column'] == 'chocolate' df.loc[mask, :] = 'color: red' df.loc[~mask,:] = 'color: black' return df
has comment: http://stackoverflow.com/comment/86284699
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49638372

http://stackoverflow.com/a/49619811
has body: You can print the current time with: import datetime print(datetime.datetime.now())
type: Answer
answers question: http://stackoverflow.com/q/49619741
score: 0

http://stackoverflow.com/comment/86383340
comment on: http://stackoverflow.com/a/49685833
type: Comment
score: 0
type: AnswerComment
has text: how can I modify this if i dont want to use the entire line as key i.e I just want to use www_1 to be used as the key instead of the whole url

http://stackoverflow.com/comment/86505900
comment on: http://stackoverflow.com/q/49743238
type: Comment
has text: Somewhere you loaded an encoded file (maybe utf-8, utf-16 or a Windows code page) into pandas and this happens when you try to write it out again. I don't know ML Workbench. Can you specify the input or output encodings? Much better, does this environment support python 3? We are approaching python 3's 10 anniversary and should be preferred when possible.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86286016
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49639101
has text: Thank you! I will try doing this. (New to using xarray and pandas so still learning how to do anything beyond the basics)

http://stackoverflow.com/comment/86485653
score: 0
comment on: http://stackoverflow.com/q/49735311
type: Comment
type: QuestionComment
has text: Specifying version is [mentioned in the docs](https://conda.io/docs/user-guide/tasks/manage-pkgs.html#installing-packages), e.g. `conda install user-agents=1.1.0`

http://stackoverflow.com/q/49604146
score: 1
tagged with: dataframe
tagged with: python
has body: I'm trying to read several XLS files into a Panda's dataframe. They appear to read in correctly - but when I trying and display(df), df.info() or df.head() the dataframe is empty. All data is in subfolder named data1. xls sheets are named a.xls and b.xls. The data sets are as follows: a.xls Account Description Final Adjustment Adj Final 324 Testing1 2342 0 2342 232 Essential 5678 0 5678 35 Options 2345 0 2345 634 Working 45 5675 5720 23 Time 45774 0 45774 52 Styling 67 0 67 b.xls Account Description Final Adjustment Adj Final 343 Visual 345 0 345 576 IO Tools 34543 0 34543 6567 Options 6356 0 6356 8675 Pickling 7456 5675 13131 345 Clipboard 5678 0 5678 6365 Flat 2355 645 3000 Code: import pandas as pd import os from IPython.display import display, HTML df = pd.DataFrame() for filename in os.listdir('data1'): if filename.endswith(".xls"): print(f'appending {filename}') data = pd.read_excel(os.path.join("data1", filename), sheet_name=0) display(data) df.append(data) display(df) else: print(f'skipping {filename}, wrong data type') The Output: appending a.xls Account Description Final Adjustment Adj Final 0 324 Testing1 2342 0 2342 1 232 Essential 5678 0 5678 2 35 Options 2345 0 2345 3 634 Working 45 5675 5720 4 23 Time 45774 0 45774 5 52 Styling 67 0 67 ___ appending b.xls Account Description Final Adjustment Adj Final 0 343 Visual 345 0 345 1 576 IO Tools 34543 0 34543 2 6567 Options 6356 0 6356 3 8675 Pickling 7456 5675 13131 4 345 Clipboard 5678 0 5678 5 6365 Flat 2355 645 3000 ___ The display(data) produces the tables above, but the display(df) produces the ___. So, somehow I'm reading the excel file into data, but it isn't appending it to the df. df.info() produces: &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 0 entries Empty DataFrame My question is how to append the data into a single dataframe (df) for multiple excel workbooks.
has comment: http://stackoverflow.com/comment/86215392
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49604304
downvote count: 0
answer count: 1
upvote count: 1
tagged with: excel
favorite count: 0
type: AnsweredQuestion
has title: Appending a Pandas .read_excel dataframe to a new dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/49604304

http://stackoverflow.com/q/49715505
has comment: http://stackoverflow.com/comment/86444336
has title: Scrapy save data to mongoDB TypeError: list indices must be integers or slices, not str
score: 0
has answer: http://stackoverflow.com/a/49715922
tagged with: scrapy
answer count: 1
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86444550
has comment: http://stackoverflow.com/comment/86444489
has comment: http://stackoverflow.com/comment/86444531
has comment: http://stackoverflow.com/comment/86444700
tagged with: mongodb
has body: I am new into Python/Scrapy and facing TypeError issue. I want to store the crawler parse data to MongoDB as an object. Here is my code. alertentry = {'website': host, '_id': doc['_id'], 'event': 'website_up', 'alert_id': '', 'main_website_id': doc['main_website_id']} Alerts.add(alertentry, 'Website Up:' + doc[0]['website_url'], 2) From above code I am getting " alertentry = {'website': host, '_id': doc['_id'], 'event': 'website_up', 'alert_id': '', TypeError: list indices must be integers or slices, not str" If change alertentry to list as below, I am getting same error. alertentry = [host, doc['_id'], 'website_up', '', doc['main_website_id']] Alerts.add(alertentry, 'Website Up:' + doc[0]['website_url'], 2) I also tried with: alertentry = [self.host, self.doc['_id'], 'website_up', '', self.doc['main_website_id']] But no luck. Here Alerts.add() function inserts the data into MongoDB. I am using Scrapy 1.5 with Python 3.5. Can somebody help me please. Thanks in advance.

http://stackoverflow.com/comment/86407995
type: Comment
comment on: http://stackoverflow.com/q/49682576
type: QuestionComment
has text: You may want to check out Dask (https://dask.pydata.org/en/latest/), it may be more applicable to your situation and is very easy to setup.
score: 0

http://stackoverflow.com/q/49753612
tagged with: python-3.6
has title: Why is dill slow?
tagged with: dill
has body: From https://github.com/uqfoundation/dill/blob/master/dill/dill.py#L43: from pickle import _Pickler as StockPickler, Unpickler as StockUnpickler This means dill inherits from pickle._Pickler which is a pure Python implementation. However, _pickle.Pickler is an alternative implementation of pickle and is a much faster version. Why doesn't dill extend from it?
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49816096
type: Question
tagged with: cpython
tagged with: pickle
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/49655812
type: UnansweredQuestion
tagged with: physics
tagged with: python
has comment: http://stackoverflow.com/comment/86321208
has comment: http://stackoverflow.com/comment/86322954
has body: I am trying to make a rudimentary model for the a coronal hole in my mathematics thesis. I am looking to create a plot where the radial direction of the cylinder increases with proportionally with the height and then I would like to add twists in the $(\theta, z)$ direction either explicitly or with lines and arrows along the surface. Currently I have only been able to produce a normal cylinder. import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Cylinder x=np.linspace(-1, 1, 100) z=np.linspace(-2, 2, 100) Xc, Zc=np.meshgrid(x, z) Yc = np.sqrt(1-Xc**2) # Draw parameters rstride = 20 cstride = 10 ax.plot_surface(Xc, Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride) ax.plot_surface(Xc, -Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride) ax.set_xlabel("X") #ax.set_ylabel("Y") fig.gca().set_ylabel(r'$\theta$') ax.set_zlabel("Z") plt.figure(figsize=(200,70)) #sets the size of the plot #plt.show()
answer count: 0
score: 1
tagged with: matplotlib
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86330964
favorite count: 0
has comment: http://stackoverflow.com/comment/86321450
type: Question
has title: Draw a truncated-cone-based vortex in matplotlib
tagged with: fluid-dynamics

http://stackoverflow.com/comment/111937215
score: 1
type: Comment
type: AnswerComment
has text: @Snow, `counts` is a `pd.Series` object. `counts < 5` returns a Boolean series. We filter the `counts` series by the Boolean `counts < 5` series (that's what the square brackets achieve). We then take the index of the resultant series to find the cities with < 5 counts. Remember a series is a mapping between index and value. The index does not necessarily contain unique values, but with `value_counts` this is guaranteed.
comment on: http://stackoverflow.com/a/49735808

http://stackoverflow.com/comment/86257922
type: Comment
has text: @mehrdad-pedramfar what is mysql package or how can i get mysql package info ? Thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/49624954
score: 0

http://stackoverflow.com/comment/86462967
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49719695
type: Comment
has text: You can set them to be in the center of their parent by using: `pos_hint: {"center_x":0.5, "center_y":0.5}`

http://stackoverflow.com/q/49717876
type: Question
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/59519984
possible better answer: http://stackoverflow.com/a/59519984
type: AnsweredQuestion
answer count: 2
tagged with: pytorch
score: 1
downvote count: 0
upvote count: 1
has body: This question mainly concerns the return value of __getitem__ in a pytorch Dataset which I've seen as both a tuple and a dict in the source code. I have been following this tutorial for creating a dataset class within my code, which is following this tutorial on transfer learning. It has the following definition of a dataset. class FaceLandmarksDataset(Dataset): """Face Landmarks dataset.""" def __init__(self, csv_file, root_dir, transform=None): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.landmarks_frame = pd.read_csv(csv_file) self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.landmarks_frame) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.landmarks_frame.iloc[idx, 0]) image = io.imread(img_name) landmarks = self.landmarks_frame.iloc[idx, 1:].as_matrix() landmarks = landmarks.astype('float').reshape(-1, 2) sample = {'image': image, 'landmarks': landmarks} if self.transform: sample = self.transform(sample) return sample As you can see, __getitem__ returns a dictionary with two entries. In the transfer learning tutorial, the following calls are made to transform a dataset: data_transforms = { 'train': transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), } data_dir = 'hymenoptera_data' image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']} dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4, shuffle=True, num_workers=4) for x in ['train', 'val']} dataset_sizes = {…
has answer: http://stackoverflow.com/a/49727504
has title: Error Utilizing Pytorch Transforms and Custom Dataset
accepted answer: http://stackoverflow.com/a/49727504
favorite count: 0

http://stackoverflow.com/a/49696395
downvote count: 0
has comment: http://stackoverflow.com/comment/86405815
answers question: http://stackoverflow.com/q/49696270
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86405624
has comment: http://stackoverflow.com/comment/86405691
has comment: http://stackoverflow.com/comment/86405934
has body: There is collections.Sized for that: def n_and_list(x: collections.Sized): return len(x), [y for y in x] Or for your case, since you want it to have __len__ and to be iterable: import typing import collections def n_and_list(x: typing.Union[collections.Sized, collections.Iterable]): return len(x), [y for y in x] Sadly, as the comments bellow mentioned, there is no typing.Intersection as of yet to guarantee the presence of both.
has comment: http://stackoverflow.com/comment/86406010
has comment: http://stackoverflow.com/comment/86405935

http://stackoverflow.com/comment/86506825
comment on: http://stackoverflow.com/a/49738110
score: 0
type: Comment
has text: I did the changes but still the pywin error persists,
type: AnswerComment

http://stackoverflow.com/comment/86299678
has text: `queue` is a class. `queue()` is an instance of the class. `buffer` is an attribute of an _instance_.
score: 0
comment on: http://stackoverflow.com/q/49645703
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49694895
type: Question
has comment: http://stackoverflow.com/comment/86403131
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49696677
tagged with: python
has comment: http://stackoverflow.com/comment/86403192
has answer: http://stackoverflow.com/a/49696677
tagged with: statistics
has body: I have created box and whisker plots using matplotlib. My question is how to ensure that the calculated statistics which appear in the chart match those I would calculate via a built-in function like .mean() of a column. From what I can tell, if outliers are found then the 75, 50, 25 quartiles will reflect this (calculated without outliers) and will therefore not match statistics inclusive of outliers. My guess is that if I do a 1.5 IQR filter and then run my stats such as .mean() they will match. Any way to directly peak at the stats being used by the matplotlib box-whisker plot? Thanks!
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86402923
answer count: 1
linked to: http://stackoverflow.com/q/18861075
has title: matplotlib box and whisker underlying stats

http://stackoverflow.com/comment/86284690
has text: As a follow up question, how exactly does the * return inp == ' ' * allow the deletion of that last character? I'm a bit fuzzy on that.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49634276

http://stackoverflow.com/a/49716745
accepted answer of: http://stackoverflow.com/q/49716307
type: AcceptedAnswer
has body: Some of your errors are due to wrong keys being used ("name" is not in the dictionary). But beside that, collecting the plain dictionary is probably the most appropriate way to do this (see note at bottom). d1=rdd.filter(lambda x: x['actor']=='brad').first() d2=rdd.filter(lambda x: x['actor']=='tom').first() With a list of predefined keys: keys = ['good', 'bad', 'average'] You can make the resulting dictionary using comprehension: {key: d1[key] - d2[key] for key in keys} # outputs: {'average': -1, 'bad': -1, 'good': 1} The sum can then be simply calculated over all dictionary values: print(sum([v for v in dc.values()])) #-1 You can even do this over multiple dictionaries if they're collected in parallel lists (assuming you know exactly that the 2 RDDs are collected in orders allowing index by index operation) [{key: d1[key] - d2[key] for key in keys}\ for d1,d2 in zip(dicRdd1.collect(), dicRdd2.collect())] You can test this logic using (your example dictionaries): [{key: d1[key] - d2[key] for key in keys}\ for d1,d2 in zip([d1], [d2])] Note: You should avoid performing subtraction in Spark's distributed reduce operations. This is simply because subtraction is not commutative and that would cause unpredictable results.
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49716307
type: Answer

http://stackoverflow.com/a/49676843
answers question: http://stackoverflow.com/q/49676246
score: 2
type: Answer
upvote count: 2
has body: You can use combine_first df2.set_index('User_ID').Code_2.combine_first(df1.set_index('User_ID').Code_1) User_ID 123 ert 345 nad 567 cewr
downvote count: 0

http://stackoverflow.com/comment/86451719
has text: Based on the actual question at hand, I am not the one making the additional assumptions here :) but I see your point.
type: AnswerComment
comment on: http://stackoverflow.com/a/49718970
score: 0
type: Comment

http://stackoverflow.com/comment/86497321
type: Comment
type: QuestionComment
has text: The `split` method throws away all the delimiters. If you want to keep track of the delimiters, you have to use something different—the `partition` method, or a regexp, or explicit iteration of the string (maybe using the `find` method rather than going character by character, so it's still as fast as `split`), etc.
comment on: http://stackoverflow.com/q/49741337
score: 1

http://stackoverflow.com/comment/86216263
score: 0
comment on: http://stackoverflow.com/q/49604549
has text: `split` can only be called on a string, not a number. Also, it splits strings into words by spaces; there are no spaces in `9119` even if you turn it into the string `'9119'`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49613045
tagged with: background
has answer: http://stackoverflow.com/a/49613251
favorite count: 0
tagged with: timer
has body: I'm making a client/server program and on the client I want a clock on the GUI that displays the running time. Now there's plenty of tutorials on here on how to make a clock/timer and I think I have that part down. The issue is making one that runs in the background while the rest of the code executes. At the moment I have a loop for my timer that the code doesn't move past, so it just starts counting the timer then doesn't do anything else after that. At least until the timer is stopped anyway. I'm guessing I need to find a way to make it run in the background, but I don't know how and I can't find the answer. It has been suggested to me that I should use threading/multithreading, but that looks kinda complicated and I can't quite figure it out. Is there a better way to do it or is threading the way to go?
tagged with: python
has title: Creating a timer that runs in the background
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49613732
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
upvote count: 1
tagged with: loops
score: 1

http://stackoverflow.com/comment/86298398
comment on: http://stackoverflow.com/a/49638076
type: AnswerComment
has text: Don't really think so @orsonady , I tried to proof your theory with training and re-training several models, but it starts from scratch every single time.
score: 0
type: Comment

http://stackoverflow.com/comment/86478711
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49732538
has text: Could you also provide the code that actually inserts the list `solutions` into the DataFrame `df`?
score: 1

http://stackoverflow.com/q/49732534
has title: Creating a checklistbox in LibreOffice from Python
type: Question
type: UnansweredQuestion
tagged with: python
has body: I'm working on a LibreOffice extension where the Options dialog has to have a list of checkboxes that are created programmatically, since they depend on what extra data files (custom settings for a spelling/grammar checker) the user has installed. It's easy enough to add some checkboxes manually in the macro organizer dialog editor that I can export to a .xdl file and load from Python, but I haven't found any sort of "container" that I can add checkboxes to so I can get automatic positioning and scrolling. I can add entries programmatically to a ListBox that I've made in a dialog.xdl using boxC = windowC.getControl("toggleIds") boxM = boxC.getModel() entries = ("some", "checkbox", "entries") uno.invoke(boxM, "setPropertyValue", ("StringItemList", uno.Any("[]string", entries))) but multiselection in a listbox requires ctrl-clicking, which is not very intuitive. I can programmatically add a single checkbox to the dialog window (the "main part" of the extension's Options tab) using windowM = windowC.getModel() ctx = uno.getComponentContext() cb1 = ctx.ServiceManager.createInstanceWithContext("com.sun.star.form.component.CheckBox", ctx) cb1.Label = "some label" cb1.State = 1; windowM.insertByName("mycb1", cb1) which puts it at the very top, but then it seems I'd have to manually do all the scrolling-code, positioning etc. If I do insertByName multiple times here, it adds them all at the same position, I haven't yet figured out how to add them below one another. I see there is C++ code which uses SvxCheckListBox, e.g. optcomp.cxx, but this seems like a newer development, at least I can't find anything referring to it in the old Java AWT docs. TL;DR: Is there a simple way to programmatically make a list of checkboxes from Python extensions to LibreOffice?
tagged with: awt
tagged with: user-interface
downvote count: 0
tagged with: libreoffice
upvote count: 1
score: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49739756
tagged with: uno

http://stackoverflow.com/comment/86468294
type: QuestionComment
has text: Do you mean the index when you say `as int`?
comment on: http://stackoverflow.com/q/49727251
score: 0
type: Comment

http://stackoverflow.com/comment/86234510
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49605789
type: QuestionComment
has text: @HaiLang, thanks for the information. I'm starting to wonder if this is a PostgreSQL issue (possibly with the library I'm using to connect to the DB).

http://stackoverflow.com/q/49687811
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: plot
has answer: http://stackoverflow.com/a/49689319
tagged with: pandas
score: 1
answer count: 1
has title: Pandas plot 22 series in 11 plots in 1 Figure
favorite count: 0
has body: I can plot 11 Series in 11 Graphs and in 1 Figure: NG = [1,2,3,4,5,6,7,8,9,10,11] serieslist = [] for n in NG: l = [1,2,3,4,5,6] df = pd.DataFrame(l) serieslist.append(df) df = pd.concat(serieslist, axis = 1) df.plot(grid = 1, subplots = True, layout = (6,2), sharey = True) How do I plot 22 series (of which 2 shall always be in one plot) in 1 Figure? So that means 22 plots in 11 Graphs. The code below only gives 22 graphs: NG = [1,2,3,4,5,6,7,8,9,10,11] serieslist = [] for n in NG: l = [1,2,3,4,5,6] df = pd.DataFrame(l) serieslist.append(df) serieslist.append(df) df = pd.concat(serieslist, axis = 1) df.plot(grid = 1, subplots = True, layout = (12,2), sharey = True) Edit: This is not 100% the solution I want but it looks a bit prettier: import pandas as pd NG = [1,2,3,4,5,6,7,8,9,10,11] dflist1 = [] dflist2 = [] l = [1,2,3,4,5,6] b = [6,5,4,3,2,1] for n in NG: df = pd.DataFrame(l) dflist1.append(df) df = pd.concat(dflist1, axis = 1) df2 = pd.DataFrame(b) dflist2.append(df2) df2 = pd.concat(dflist2, axis = 1) df.plot(grid = 1, subplots = True, layout = (12,1), sharey = True) df2.plot(grid = 1, subplots = True, layout = (12,1), sharey = True) Output: 2 figure. Now how to combine the plots into 1 figure?
type: Question

http://stackoverflow.com/q/49621420
has comment: http://stackoverflow.com/comment/86249837
has title: Python figureCanvasTkAgg animation
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86254354
has comment: http://stackoverflow.com/comment/86266687
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86330681
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86251163
tagged with: animation
tagged with: python
has body: I'm using Python 3.6 on Ubuntu 17.10. This is an MVC that I tried to do for my actually long code. I have to make an animated graph of the convolution of two signals, but when I graph, the screen turns gray and the graph just appears. from tkinter import * from tkinter import ttk import matplotlib matplotlib.use("TkAgg") from matplotlib import style style.use("ggplot") from matplotlib import pyplot as plt import matplotlib.animation as animation from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import numpy as np from scipy import signal as sn import time tim = np.arange(0,10) tim1 = np.arange(0,10) root = Tk() root.geometry('1280x700') root.resizable(width = False, height = False) root.configure(bg = fondo) root.title('Convolusión') f2 = Figure(figsize=(3,2), dpi=100) k2 = f2.add_subplot(1, 1, 1) plot = FigureCanvasTkAgg(f2, root) plot.show() plot.get_tk_widget().place(x=50,y=470) k3.clear() ycc = sn.convolve(s1,s2,mode="full") t = np.arange(min(tim)+min(tim1),max(tim)+max(tim1)+1) i=0 tim = [0]*len(t) y = [0]*len(t) for x in t: tim[i] = t[i] y[i] = ycc[i] k3.clear() k3.plot(tim,y) plot = FigureCanvasTkAgg(self.f3, self.root) plot.show() plot.get_tk_widget().place(x=450,y=470) i=i+1 plt.pause(0.1)
score: 0
answer count: 0
tagged with: matplotlib

http://stackoverflow.com/q/49633798
has body: I am using pyqtgraph to make a plot with a few subplots and shared X axes. However, when the tick labels have different lengths, the Y axes do not line up with each other. How can I make the plots line up properly, despite differences in the size of tick labels or axis labels? from pyqtgraph import QtGui, QtCore import pyqtgraph as pg import numpy as np # Make up some data ---------- x = np.linspace(0, 80, 81) y1 = np.sqrt(x) y2 = 10*x**2 # Set up the plot ---------- # Switch to using white background and black foreground pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') app = QtGui.QApplication([]) pw = pg.GraphicsWindow(title="plot test") gv = pw layout_ = pg.GraphicsLayout() gv.setCentralItem(layout_) gv.show() layout = layout_.addLayout(colspan=1) layout.setContentsMargins(10, 10, 10, 10) # Top row: title layout.addLabel('title', colspan=2) # Next row: main plot with y axis label layout.nextRow() layout.addLabel('y1', angle=-90, rowspan=1) p1 = layout.addPlot() # Next row: secondary plot layout.nextRow() layout.addLabel('y2', angle=-90, rowspan=1) p2 = layout.addPlot() # Bottom row: X axis label layout.nextRow() layout.addLabel("x", col=1, colspan=1) # Share X axes p2.setXLink(p1) # Add data to plot --------- p1.plot(x, y1, pen=pg.mkPen((255, 0, 0, 255), width=3)) p2.plot(x, y2, pen=pg.mkPen((0, 0, 255, 255), width=3)) # Start Qt event loop to keep the window open if __name__ == '__main__': if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): app.exec_() # Start QApplication event loop ***
tagged with: plot
has answer: http://stackoverflow.com/a/71158709
upvote count: 3
has comment: http://stackoverflow.com/comment/86789975
tagged with: python-2.7
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/70746637
has title: How can I control the alignment of y axes in multiple subplots with pyqtgraph when the tick labels have different lengths?
tagged with: pyqtgraph
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
tagged with: python

plotly
tags question: http://stackoverflow.com/q/49697846
tag name: plotly
type: Tag
tags question: http://stackoverflow.com/q/49630427
tags question: http://stackoverflow.com/q/49740343
tags question: http://stackoverflow.com/q/49746015
tags question: http://stackoverflow.com/q/49628849
tags question: http://stackoverflow.com/q/49677428
tags question: http://stackoverflow.com/q/49614653
tags question: http://stackoverflow.com/q/49699189

http://stackoverflow.com/comment/86288663
has text: @hpaulj Sure, but we're not looking for the "better" constructor here, we're looking for the one that we can trick into throwing an exception. I believe `array` does look for `bf.getbuffer` (see `np.array(memoryview(b'abc'))` for example—you don't get a single `|S3` element as with `b'abc'` used directly, or an `object`, you get 3 `uint8`s).
type: QuestionComment
comment on: http://stackoverflow.com/q/49639414
type: Comment
score: 0

http://stackoverflow.com/a/49645742
answers question: http://stackoverflow.com/q/49645478
has body: To answer shortly, there is no such way. Once you have declared your pool, you cannot change the number of workers without first closing the pool and recreating it. There is also no way to make the pool feed tasks slower than the maximum speed to workers. You have a couple of (not so optimal) choices. One is to add sleep based on global variable to the worker. Then you can use task completed callbacks to measure actual speed and adjust the variable accordingly. But if sleeping is out of question, this does not work. The better, albeit more onerous, way is to write the task manager yourself. In this version you do not use pool but write a class that manages worker processes. You spawn "enough" workers, and the workers listen to a queue for tasks. You will feed this queue from your manager in your desired speed. You will set your queue to have a very low maximum size, and if your manager detects the queue is full, it spawns another worker. But there is no built-in functionality to do what you want, which means some work is needed or you need to redesign your program so that you will not feed all of your tasks to the pool in one go but do some throttling there.
type: Answer
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49645478
type: AcceptedAnswer

http://stackoverflow.com/comment/86457409
has text: Glad to hear. Regards.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49721803
type: Comment

http://stackoverflow.com/comment/86518640
comment on: http://stackoverflow.com/a/49750123
score: 1
type: Comment
has text: Thanks, that is exactly it.
type: AnswerComment

http://stackoverflow.com/comment/86500118
type: Comment
has text: Thank you for the elaborate answer. It does seem that I would have to read stdin separately. However, the only thing I would need to handle is to prevent the script from blocking (unnecessarily) if no input was given via the pipe.
type: AnswerComment
comment on: http://stackoverflow.com/a/49709285
score: 0

http://stackoverflow.com/a/49711599
upvote count: 1
has body: df_a = df[df["mycol"]=='a'] I believe this should work, unless by 'mask' you mean you want to actually zero out the values that don't have a
accepted answer of: http://stackoverflow.com/q/49711567
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49711567
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49664036
score: 0
has title: Getting file errors after creating python script titled ssl.py
answer count: 1
has answer: http://stackoverflow.com/a/49664259
tagged with: pyopenssl
has body: Traceback (most recent call last): File "ssl-common.py", line 14, in s = ctx.wrap_socket(s, server_hostname=dst[0]) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 363, in wrap_socket _context=self) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 611, in init self.do_handshake() File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 840, in do_handshake self._sslobj.do_handshake() socket.error: [Errno 54] Connection reset by peer I am getting the above errors when I try to run the below script on my Mac. I have reinstalled openssl through homebrew, as well as through pip import socket import ssl import OpenSSL.crypto as crypto dst = ('1.2.3.4',443) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ret = s.connect_ex(dst) if ret == 0 : ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE s = ctx.wrap_socket(s, server_hostname=dst[0]) # get certificate cert_bin = s.getpeercert(True) x509 = crypto.load_certificate(crypto.FILETYPE_ASN1,cert_bin) print(x509.get_subject().CN) else : print "socket.connect_ex returned ", ret
linked to: http://stackoverflow.com/q/1434451
tagged with: ssl
tagged with: python
tagged with: macos
type: Question
tagged with: openssl
type: UnansweredQuestion

http://stackoverflow.com/comment/86239587
type: Comment
type: QuestionComment
has text: How do you formally define the frequency value for an individual row? How do you plan to compute it based on Date values in the previous and the following rows?
comment on: http://stackoverflow.com/q/49615438
score: 0

http://stackoverflow.com/comment/86396403
has text: but isn't like telling the interpreter to `print something` or `evaluate other stuff`? how can this be a valid syntax?
type: Comment
comment on: http://stackoverflow.com/a/49692094
type: AnswerComment
score: 0

http://stackoverflow.com/q/49696580
type: Question
has answer: http://stackoverflow.com/a/49696934
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86406061
has comment: http://stackoverflow.com/comment/86407028
has title: Downloading a xml file using an API URL in python
has body: I am trying to download data which is returned in an xml file from an api with the following url URL='http://oasis.caiso.com/oasisapi/SingleZip?queryname=PRC_FUEL&fuel_region_id=ALL&startdatetime=20130919T07:00-0000&enddatetime=20130928T07:00-0000&version=1' When I use the url in my web browser the xml file downloaded looks like this <?xml version="1.0" encoding="UTF-8"?> <OASISReport xmlns="http://www.caiso.com/soa/OASISReport_v1.xsd"> 2018-04-06T15:17:51-00:00 <Source>OASIS v20131201 <MessagePayload> <RTO> CAISO <REPORT_ITEM> <REPORT_HEADER> OASIS PPT PRC_FUEL US$ ENDING <SEC_PER_INTERVAL>3600</SEC_PER_INTERVAL> </REPORT_HEADER> <REPORT_DATA> <DATA_ITEM>FUEL_PRC</DATA_ITEM> <RESOURCE_NAME>CISO</RESOURCE_NAME> <OPR_DATE>2013-09-19</OPR_DATE> <INTERVAL_NUM>24</INTERVAL_NUM> However, when I download using a python script it is something very different. Python script: r=requests.get(URL) r.encoding="UTF-8" with open ('data.xml','wb') as file: file.write(r.content) Downloaded file: PKEL520130919_20130928_PRC_FUEL_N_20180406_08_44_40_v1.xmlíÝïOÇ¹àïþ+Pt¤ó)ÝåQ*SdJ§_,âlMÿþÇK{Í£yV{í;ï¶vRâ¹XÞÌ<÷=»ûþ×?lü<sy}õ§Ï&O·>Û_½»þöòê»?}öõ¿|þì³?<Ù?}q~rþzþÓõûÛ»ÿÇÕÍ>ûþöö§/67ùå§ï..o®¾»þqóæúbsáï}ûóäé¿n¾ýìî+¼ßÜ\|7ÿëüâÛùû»_¿¹üqþòâv~0Ý<û|kûó­Ý7/¶·¿ØÞú|kë­­ýÍ?þ'ûç×ÿ|ÿn~ðákïoþþ«'ûûíO~ðóÝWMîþcóão=Ùßü÷æï¿>»øõëoï~ãõÓ»ÿ¼ºøq~pøâäütóÃÿ¾ûGg§¯ß¼=ysôêÓ¯þzôâåÑëû?Ìÿßÿß~u·¤¿½¹ûcÿýÿÏÁÙëÃ·ùúèËýÍßãÉþ×§¯¾>ÿ¯ýÍûÿñdÿä«7G¯ÿöâË£¯^|u¼¿ùÇoÜýß½~ûÇoÍvï]þã·|üòþ¿ÿúå7/î~uÿ_¿­æþóöîOµ¿ùé÷îÿîóÓ¯_½ýêÅ«£Ãïî5pöúþËÝÇfo=ÿ|ò|óßü´·_}ýê`ºýi!~cá¯¿yq÷';~õæ¯4Ýz³µûÅïúÇïýÿów/|;«ÿø{|ïÝ«åÅ_l?Ý¹ûÃýö¿?Áýµj¶Ym§í1÷ubDÔ&Ï­T©ÝgPFÕ[tµÚó¨~BK®Ul @-ô¯Ò¢«Õ&PÛª=¶èjµéÔv£j-ºZm6µ½¨Úc®VÛÚ³¨Úc®V{lÃ·NjÏ£jM»Üû/0]îV­éLuÿp¦DO®ºm§Iôxðèª«Ùp<DÏ®ºm:óÁ$z@xtÕÕlC8 L¢'GW]Í6Â$zDxtÕÕlC8"L¢gGW]=Ä³-tH(­ºmÏ¶Ð)¡´êj¶!<Û¦¡SBiÕÕlCx¶MC§Òª«Ù0ÿN ¥UW³¥@>þòaÂÛiÞ{v|4óÞU°u\&¨uÁ%¨uÁ%¨uÁ%¨uÁ%¨uÁ%¨uÁ%¨uÁeì×:à2Ø:à2Ø:à2Ø:à2Ø:à2Ø:à2Ø:à2Ø:à2Ø:à2Ø:à2áFplFplkÁ­­Ã«vlÑìÅ¸46æ½ßòóÃ£É®¥üð$¨Ñ~VX5:¸dÕèU£¬½bÕèÊ«f÷ó\6úè²Ñ# ¹lô¸e³û.%¹ltpé²Ñ1¹ËF2\6ºä²Ñ3®7ºltÖe£«Û,}Oàqµ1ï}ø2t]sº¬A·5]5yêªÉPWMÞºjòÔUw ¬¼eÑäz…
answer count: 2
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49697009
upvote count: 1
tagged with: python-requests
favorite count: 0

http://stackoverflow.com/a/49740127
has comment: http://stackoverflow.com/comment/86507371
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49692402
has body: You need to implement a copy_relations method on your plugin. The documentation is here, but essentially the functionality works like this; class ArticlePluginModel(CMSPlugin): title = models.CharField(max_length=50) def copy_relations(self, oldinstance): # Before copying related objects from the old instance, the ones # on the current one need to be deleted. Otherwise, duplicates may # appear on the public version of the page self.associated_item.all().delete() for associated_item in oldinstance.associated_item.all(): # instance.pk = None; instance.pk.save() is the slightly odd but # standard Django way of copying a saved model instance associated_item.pk = None associated_item.plugin = self associated_item.save() class AssociatedItem(models.Model): plugin = models.ForeignKey( ArticlePluginModel, related_name="associated_item" )
accepted answer of: http://stackoverflow.com/q/49692402

http://stackoverflow.com/a/49751701
type: Answer
has body: You can try this:- words = ['a','b','c','d'] table = [['','',''],['','',''],['','',''],['','','']] ls = [list(x)+y[1:] for x,y in zip(words,table)] print(ls) Output [['a', '', ''], ['b', '', ''], ['c', '', ''], ['d', '', '']]
answers question: http://stackoverflow.com/q/49751550
score: 0
has comment: http://stackoverflow.com/comment/86524167

http://stackoverflow.com/comment/86502578
has text: Can you modify your question to include the actual traceback you are getting. Your title indicates that the error is coming from the show_all route, but you mention the problem is in the Show_Multi route.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49743742
type: Comment

http://stackoverflow.com/a/49698061
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49697940
has comment: http://stackoverflow.com/comment/86409749
answers question: http://stackoverflow.com/q/49697940
has body: You can doing with IntervalIndex and .loc B.index=pd.IntervalIndex.from_arrays(B['start'],B['end'],closed='both') A['Yourcolumn']=B.animal.loc[A.Number].values A Out[1577]: Number Yourcolumn 0 1 CAT 1 1 CAT 2 2 CAT 3 2 CAT 4 3 CAT .. ... ... 6 4 DOG 7 5 DOG 8 6 DOG 9 6 DOG 10 7 COW [11 rows x 2 columns] Update B.index=pd.IntervalIndex.from_arrays(B['start'],B['end'],closed='both') s=sum([list(range(x,y+1)) for x,y in zip(B.start,B.end)],[]) v=A.Number[A.Number.isin(s)] A.loc[v.index,'Yourcolumns']=B.loc[v].animal.values A Out[1652]: Number Yourcolumns 0 1 CAT 1 1 CAT 2 2 CAT 3 2 CAT 4 3 CAT .. ... ... 7 5 DOG 8 6 DOG 9 6 DOG 10 7 COW 11 8 NaN [12 rows x 2 columns]
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86409029
has comment: http://stackoverflow.com/comment/86409403
has comment: http://stackoverflow.com/comment/86409721
has comment: http://stackoverflow.com/comment/86409344
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86409488

http://stackoverflow.com/q/49601031
tagged with: sat-solvers
has answer: http://stackoverflow.com/a/49617866
tagged with: bit-manipulation
answer count: 1
has comment: http://stackoverflow.com/comment/86247961
has title: Why Z3 falling at this?
tagged with: z3py
type: Question
tagged with: z3
has body: i'm trying to solve this using z3-solver but the proplem is that it gives me wrong values i tried to replace the &gt;&gt; with LShR the values changes but non of them is corrent however i know the value of w should be 0x41414141 in hex i also tried to set w to 0x41414141 and it said that it's unsat from z3 import * def F(w): return ((w * 31337) ^ (w * 1337 &gt;&gt; 16)) % 2**32 s = Solver() w = BitVec("w",32) s.add ( F(w) == F(0x41414141)) while s.check() == sat: print s.model() s.add(Or(w != s.model()[w]))
tagged with: python
linked to: http://stackoverflow.com/q/49281487
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49617866

http://stackoverflow.com/comment/86533553
comment on: http://stackoverflow.com/a/49758402
has text: I am actually adding in a bias into my MLP class now, and am already seeing results from using the bias in the forward pass, without having implemented the backprop bias calculations yet. Thanks for the help.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49616485
has comment: http://stackoverflow.com/comment/86239895
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86240008
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86239969
answer count: 1
has title: append values in python.How?
type: Question
score: 0
has body: I am getting the FixVersion value for each my JIRA issue in below format from the below code and then I am trying to append the value using append method in python but not getting the desired results for version in issue["fields"]["fixVersions"]: cacheData = json.dumps(version) jsonToPython = json.loads(cacheData) #lines = jsonToPython.items() if jsonToPython['name'][:8] == "Clignra ": Fixversionmatch = re.findall(r"(\d+\.\d+)\.\d+\.\d+", jsonToPython['name']) match = Fixversionmatch[0] print match for i in range(match): allModules.append(i) print allModules from the above code I get the below error for i in range(match): TypeError: range() integer end argument expected, got unicode. If I remove the below code and just do print match for i in range(match): allModules.append(i) print allModules then I get the below output after remove and get no unicode: Processing TTPT-2 1.4 2.4 2.5 Processing TTPT-1 2.4 The output which I am trying to achieve is below Processing TTPT-2 [1.4, 1.4, 1.5] Processing TTPT-1 [1.4]
has comment: http://stackoverflow.com/comment/86240029
tagged with: python
has comment: http://stackoverflow.com/comment/86240141
has answer: http://stackoverflow.com/a/49616680

http://stackoverflow.com/comment/86498281
score: 3
comment on: http://stackoverflow.com/q/49741823
has text: This feels like an [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) to me. As a way to solve your *actual* problem: can you pre-sort the file data and then read it into Python knowing that it is sorted? Something like `sort foo.txt -o foo.txt && python my_prog foo.txt` in bash.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49742393
type: Question
has body: I'm struggling to deploy a flask-app to AWS with Elastic Beanstalk. It deploys fine locally but kicks an error when I try to push to EB. After reading joshmcode's answer here, I changed my flask application name from the conventional app to application, changed my file name to application.py, and made sure the Elastic Beanstalk config file matched. This didn't solve the problem. The relevant part of my eb config file: aws:elasticbeanstalk:container:python: NumProcesses: '1' NumThreads: '15' StaticFiles: /static/=static/ WSGIPath: application.py My File Structure: In a folder FlaskAWS, I have the root flask directory ("flask-chatterbot") and the virtual environment, like: venv flask-chatterbot -requirements.txt -application.py Templates -index.html Static css -styles.css js -dynam.js Commands before error: After successfully deploying locally, I froze the package requirements with pip freeze > requirements.txt Then deactivted the virtual environment deactivate Initialized the CLI repository with the eb init command eb init -p python example-chatbot At this point, I choose the version of Python and set up the SSH keys without any problems. 4) After this I ran eb create flask-environ I receive the following error: MacBook-Air:flaskaws patrickharris$ eb create flask-environ Creating application version archive "app-180409_132356". Uploading flask-app/app-180409_132356.zip to S3. This may take a while. Upload Complete. Environment details for: flask-environ Application name: flask-app Region: us-west-1 Deployed Version: app-180409_132356 Environment ID: xxxidxxx Platform: arn:aws:elasticbeanstalk:us-west-1::platform/Python 2.6 running on 64bit Amazon Linux/2.6.6 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2018-04-09 20:23:59.312000+00:00 Printing Status: INFO: createEnvironment is starting. INFO: Using elasticbeanstalk-us-west-1-814752048877 as Amazon S3 storage bucket for environment data. INFO: Created security group named: sg-0f84dd5f7959f932f INFO: Created s…
has comment: http://stackoverflow.com/comment/86499531
type: UnansweredQuestion
tagged with: python
tagged with: amazon-web-services
tagged with: flask
answer count: 0
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/31169260
has comment: http://stackoverflow.com/comment/101928962
downvote count: 0
has comment: http://stackoverflow.com/comment/86499560
tagged with: amazon-elastic-beanstalk
has title: Deploying a Flask Application to AWS Elastic Beanstalk: "ERROR: Your WSGIPath refers to a file that does not exist."
favorite count: 0

http://stackoverflow.com/comment/86261027
has text: Your example works as expected... Thoughj it is missing a `self.` before `listOfObject`.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49626880

http://stackoverflow.com/q/49640452
has comment: http://stackoverflow.com/comment/86288992
has title: Anaconda PyCulib and CUDA Issues
downvote count: 1
has body: I'm trying to use PyCulib for GPU calculations and Anaconda 5.1 with Python 3.6 in an Amazon Web Services Windows instance, I have PyCulib installed and CUDA 9.1.85_win10 installed but when ever I use an import relying on CUDA I get the following error: Traceback (most recent call last): File "findGPUs.py", line 4, in &lt;module&gt; prng = curand.PRNG(rndtype=curand.PRNG.XORWOW) File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\devices.py", line 211, in _require_cuda_context get_context() File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\devices.py", line 194, in get_context return _runtime.get_or_create_context(devnum) File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\devices.py", line 162, in get_or_create_context return self.push_context(self.gpus[devnum]) File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\devices.py", line 40, in __getitem__ return self.lst[devnum] File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\devices.py", line 26, in __getattr__ numdev = driver.get_device_count() File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\driver.py", line 334, in get_device_count self.cuDeviceGetCount(byref(count)) File "C:\ProgramData\Anaconda3\lib\site- packages\numba\cuda\cudadrv\driver.py", line 272, in __getattr__ self.initialization_error) numba.cuda.cudadrv.error.CudaSupportError: Error at driver init: CUDA driver library cannot be found. If you are sure that a CUDA driver is installed, try setting environment variable NUMBAPRO_CUDA_DRIVER with the file path of the CUDA driver shared library. : The offending code is: import numpy as np from pyculib import rand as curand prng = curand.PRNG(rndtype=curand.PRNG.XORWOW) rand = np.empty(100000) prng.uniform(rand) print(rand[:10]) I think my main issue is that I just don't know where the CUDA driver shared lirary is. My Path is: %USERPROFILE%\AppData\Local\Microsoft\WindowsApps C:\Program Files\NVIDIA GPU…
has comment: http://stackoverflow.com/comment/86314889
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86289467
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/86291600
answer count: 1
has answer: http://stackoverflow.com/a/49699070
accepted answer: http://stackoverflow.com/a/49699070
tagged with: amazon-web-services
tagged with: cuda
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86316706
tagged with: anaconda
tagged with: gpu

http://stackoverflow.com/q/49604079
score: 0
has comment: http://stackoverflow.com/comment/86216813
has body: I am using keras to create a model using the url https://github.com/tensorflow/workshops/blob/master/extras/keras-bag-of-words/keras-bow-model.ipynb as the reference/guide. The only difference in the approach between the one mentioned in the above URL and my approach is in encoding. My vocabulary has only 35 words. So, I do a one hot encoding for each word like below [0000001000.....00] //column length is 35 So, my sentence with 3 words after encoded will look like [[[0 0 0 ... 0 0 0 1]] [[0 0 0 ... 0 1 0 0]] [[0 0 0 ... 0 0 1 0]]] and the shape looks like this (3, 1, 36) I wish to pass thousands of encoded sentence for training and each of the sentence has different size of words. When I print the shape of the encoded sentence, I got (3, 1, 36) (4, 1, 36) (7, 1, 36) (4, 1, 36) (9, 1, 36) (3, 1, 36) . . . . (5, 1, 36) Now, I need to pass this to the model I created a model as below batch_size = 32 epochs = 2 max_words = 1000 # Build the model model = Sequential() model.add(Dense(512, input_shape=(max_words,))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # model.fit trains the model # The validation_split param tells Keras what % of our training data should be used in the validation set # You can see the validation loss decreasing slowly when you run this # Because val_loss is no longer decreasing we stop training to prevent overfitting history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1, validation_data=(x_test, y_test)) After running this, I got an error message Error when checking input: expected dense_71_input to have 2 dimensions, but got array with shape (3, 1, 36) I am sure I am doing something fundamentally wrong. But not sure how to fix this as I am a novice user and extensive search too didnt help me. Any help in resolving this will be a huge he…
answer count: 0
has comment: http://stackoverflow.com/comment/86216726
tagged with: keras
has comment: http://stackoverflow.com/comment/86216796
has title: Unable to create a keras model. Error message expected dense_67_input to have 2 dimensions, but got array with shape (3, 1, 36)
has comment: http://stackoverflow.com/comment/86217505
has comment: http://stackoverflow.com/comment/86218261
type: Question
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/86216773
tagged with: python
type: UnansweredQuestion
tagged with: keras-2
has comment: http://stackoverflow.com/comment/86216710

partial-application
type: Tag
tag name: partial-application
tags question: http://stackoverflow.com/q/49724663

http://stackoverflow.com/a/49734151
accepted answer of: http://stackoverflow.com/q/49734080
upvote count: 2
answers question: http://stackoverflow.com/q/49734080
downvote count: 0
type: Answer
score: 2
type: AcceptedAnswer
has body: Convert it to a list and update the values. And the you can change it back to tuple. Ex: tup = [('a', '10', 0xA), ('b', '9', 0x9)] res = [] for i in tup: val = list(i) val[-1] = 0x99 res.append(tuple(val)) print(res)

joystick
type: Tag
tags question: http://stackoverflow.com/q/49707878
tag name: joystick

http://stackoverflow.com/a/49722008
answers question: http://stackoverflow.com/q/49721738
has body: Spark doesn't support Python-slice slicing with negative indices. You could from pyspark.sql import functions as F df.withColumn("Year", df.Date[F.length(df.Date)-3:F.length(df.Date)]) but it might be easier to just split df.withColumn("Year", F.split(df.Date, "/")[2]) or parse (assuming day/month/year format): df.withColumn("Year", F.year(F.to_date(df.Date, "dd/MM/yyyy")))
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86263222
type: Comment
score: 0
type: AnswerComment
has text: The problem is in the third command, I have a lftp -c with another command and the single quote inside it.
comment on: http://stackoverflow.com/a/49628099

http://stackoverflow.com/comment/86330890
has text: Running `np.where(pd.isnull(df))` returns `(array([], dtype=int32), array([], dtype=int32))`; so i think it's ok
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49660359

http://stackoverflow.com/q/49691395
score: 0
downvote count: 1
tagged with: python
tagged with: pythonanywhere
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/32597390
answer count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86399066
has title: Getting Proxy error 'Name or service not found' when using PythonAnywhere server
tagged with: python-requests
tagged with: flask
has comment: http://stackoverflow.com/comment/86398719
has body: I am using Python3/flask. When I am trying to access a url it says 'Name or service not found'. But I am able to access the url when I try to do it using my local editor Pycharm. I know PythonAnywhere only allows whitelisted urls else it gives a 403 forbidden error. Here in my case I am getting 'service not found' error so it is not a case where PythonAnywhere is restricting the access. My code as follows (Cannot share the credentials because of security issues) line = 1 try: USERNAME = "******" PASSWORD = "******" URI = "https://jofa9908cdf9.hana.ondemand.com/ibass/IBASS_1/IOT_DASHBOARD/SERVICES/IOT_DASHBOARD.xsjs?CMD=equip_dev_health&amp;IP_PLANT=1000&amp;IP_PLANT=1" USER_AGENT = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17" proxies = {"http": "http://&lt;username&gt;:&lt;password&gt;@rb-proxy-apac.bosch.com:8080","https": "https://&lt;username&gt;:&lt;password&gt;@rb-proxy-apac.bosch.com:8080"} CERT_FILE = False requests.packages.urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) requests.packages.urllib3.disable_warnings(urllib3.exceptions.HTTPError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.ConnectionError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.PoolError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.ProxySchemeUnknown) requests.packages.urllib3.disable_warnings(urllib3.exceptions.HTTPWarning) requests.packages.urllib3.disable_warnings(urllib3.exceptions.MaxRetryError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.ProxyError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.SecurityWarning) requests.packages.urllib3.disable_warnings(urllib3.exceptions.SSLError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.NewConnectionError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.ClosedPoolError) requests.packages.urllib3.disable_warnings(urllib3.exceptions.RequestError) line …
favorite count: 0
has comment: http://stackoverflow.com/comment/86409233

http://stackoverflow.com/q/49699310
type: Question
has title: Convert bytearray representation to string
has comment: http://stackoverflow.com/comment/86411874
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/86411977
has body: I have the following string I am reading from a file: bytearray(b'\x03\x05\n') Whats the easiest way to convert this to a 3-character string (or 3-element list)? (To be clear: There is a file a.txt, whose contents are "bytearray(b'\x03\x05\n')")
has answer: http://stackoverflow.com/a/49699361
accepted answer: http://stackoverflow.com/a/49699361
answer count: 1

http://stackoverflow.com/comment/86503852
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49744330
has text: Try `gdal.UseExceptions()` before `gdal.Open()` to see what's wrong.
type: Comment

http://stackoverflow.com/q/49749695
downvote count: 0
has body: I've been using pytest for a while and learnt to love parametrization and fixtures. For the first time, I want to test a number of classes with a branched inheritance structure. Naturally, I would like to reuse test cases for child classes. Say I have the following package structure: mock ├── pkg │ ├── child.py │ ├── grandchild.py │ └── parent.py └── tests ├── test_child.py ├── test_grandchild.py └── test_parent.py As outlined in this SO question I can use a fixture to provide an instance of the class being tested. However, when I import a test class from one test module in another it (a) feels like it's not the pytest way and (b) pytest will run all test methods of the imported class plus run them again as part of the inherited test class. Say for example the file test_child.py contained the following: from test_parent import TestParent class TestChild(TestParent): def test_foo(self): pass def test_bar(self): pass this causes pytest to run the test methods in TestParent once (due to being imported in the module) plus another time as part of TestChild (due to its methods being inherited). So I see two ways: (1) Do not inherit the base test class but just create a fixture so that the current instance is used both for TestParent and TestChild, essentially: import pytest from pkg.child import Child from test_parent import TestParent @pytest.fixture(scope="class") def instance(): return Child() class TestChild(object): def test_foo(self, instance): pass def test_bar(self, instance): pass (2) The other way I see is to not import any test classes but just create a parametrized fixture in test_parent.py that would insert instances of all relevant classes into those test methods. Something like: import pytest from pkg.parent import Parent from pkg.child import Child from pkg.grandchild import GrandChild @pytest.fixture(scope="class", params=[Parent, Child, GrandChild]) def instance(request): return request.param() class TestParent(object): def test_base(self, instance): pas…
answer count: 1
tagged with: inheritance
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pytest
linked to: http://stackoverflow.com/q/46040478
tagged with: python
has answer: http://stackoverflow.com/a/49782596
accepted answer: http://stackoverflow.com/a/49782596
has title: How to test a class hierarchy in pytest?
upvote count: 2
score: 2

http://stackoverflow.com/a/49622782
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49621503
accepted answer of: http://stackoverflow.com/q/49621503
type: AcceptedAnswer
downvote count: 0
has body: I think you actually want to replace the control character: Code print(s.replace("\x01", ".01")) # бекслеш .018 на точку Details It is clear that the programming language interprets the backslash as a control character. Actually the control character includes the escape character (\) and the adjacent code (01). Let's see how Python looks at each character: print(list(s)) # ['б', 'е', 'к', 'с', 'л', 'е', 'ш', ' ', '\x01', '8', ' ', 'н', 'а', ' ', 'т', 'о', 'ч', 'к', 'у'] Notice \x01 is one character, not the backslash alone. You have to replace this entire character. Addendum Therefore, a general approach can be to iterate each character and substitute any that belong to the control character category with a new string. This new string should be formatted to mirror the value of the character it replaces. Otherwise, return a normal character. from unicodedata import category "".join(".{:02d}".format(ord(char)) if category(char).startswith("C") else char for char in s) # 'бекслеш .018 на точку' See also a list of unicode categories and this related post. See also this post on removing control characters.
upvote count: 2

http://stackoverflow.com/comment/86216489
has text: it possible to `split` a number @abarnert
score: 0
comment on: http://stackoverflow.com/q/49604549
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49689115
has comment: http://stackoverflow.com/comment/86390338
has comment: http://stackoverflow.com/comment/86389752
has comment: http://stackoverflow.com/comment/86390792
has comment: http://stackoverflow.com/comment/86390431
has comment: http://stackoverflow.com/comment/86389902
downvote count: 1
has comment: http://stackoverflow.com/comment/86389968
favorite count: 0
has answer: http://stackoverflow.com/a/49734838
tagged with: multiprocessing
type: Question
answer count: 2
upvote count: 0
type: UnansweredQuestion
has body: I have writtern small multiprocess program and was expecting that order will following way. hello number ls -l &lt;output&gt; But It did not work. So I believe parent process is not aware of child process. How main process can wait to finish child process. or I am missing very basic concept of multiprocessing #!/usr/bin/env python import multiprocessing import subprocess def run_command(): pipe = subprocess.Popen("ls -l", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = pipe.communicate() pipe.wait() print out, err def msg(number): print "hello %s" %(number) run_command() def main(): print "yes" procs = [] for i in range(0, 100, 1): process = multiprocessing.Process(target=msg, args=(i,)) procs.append(process) for proc in procs: proc.start() for proc in procs: proc.join() if __name__ == "__main__": main() Expected code: hello 0 total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py hello 1 total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py etc Getting output: python check_process.py yes hello 0 hello 1 hello 2 hello 3 hello 4 total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py total 4 -rw-rw-r-- 1 goswamia &lt;#&gt; 682 Apr 6 02:51 check_process.py
has title: communicattion between process and subprocess
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86390532
linked to: http://stackoverflow.com/q/31429849
has answer: http://stackoverflow.com/a/49689752
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86391736
has comment: http://stackoverflow.com/comment/86389716

http://stackoverflow.com/q/49725629
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has body: Ye with Pandas Perspicacity, I'm attempting to update a simple dataframe with another dataframe, and I'm running into trouble. I have a master dataframe that I would like to update: Master_df: color tastey name Apples Red Always Avocados Black Sometimes Anise Brown NaN I have some new data that I would like to update this dataframe with. It might append new columns, add new rows, or update old values: New_df: color tastey price name Bananas Yellow NaN Medium Apples Red Usually Low Berries Red NaN High I would like to merge these two dataframes such that an updated dataframe looks like: Desired_df: color tastey price name Apples Red Always Low Avocados Black Sometimes NaN Anise Brown NaN NaN Bananas Yellow NaN Medium Berries Red NaN High I've played with many different commands, but I'm still struggling to: Not lose the index values I join on. Have common columns form one tastey column, rather than tastey_x and tastey_y. Have new data from new rows. Not have to hardcode the names of the new columns or new rows. Finally, (while not shown in this example) I need to join on multiple columns. i.e. I need to use 3 columns to form my unique key. (Though I'm sure a solution to the above example would expand to that case.) I sincerely appreciate any help or pointers! I hope the example above is clear. Cheers, A Pandas Pinhead. edit1: I believe this question is different than previously asked questions because when I use combine_first I get this: &gt;&gt;&gt; Master_df.combine_first(New_df) color tastey name Apples Red Always Avocados Black Sometimes Anise Brown NaN Edit2: OK, I'm getting closer, but not there yet! I don't want to generate _x and _y columns. I want them to be one column, taking data from New_df when there's a conflict. &gt;&gt;&gt; updated = pd.merge(Master_df, New_df, how="outer", on=["name"]) name color_x tastey_x color_y tastey_y price 0 Apples Red Always Red Usually Low 1 Avocados Black Sometimes NaN NaN NaN 2 Anise Brown NaN NaN NaN NaN 3 Bananas NaN NaN…
answer count: 1
favorite count: 0
has title: Updating a pandas dataframe with a new dataframe
type: Question
accepted answer: http://stackoverflow.com/a/49729071
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/49729071
linked to: http://stackoverflow.com/q/29973074
tagged with: dataframe
tagged with: python
tagged with: merge

http://stackoverflow.com/comment/86537258
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49711687
has text: You mean that it autoscales to the lines presented in each frame? I am not sure this is possible with ArtistAnimation. And there might be [some drawbacks with this approach in 3D](https://stackoverflow.com/q/16143493/8881141). But imho the worst problem would be a perception problem. If all elements, objects and reference frame, change dramatically, it might be difficult to understand, what we see. This wouldn't be of course the case, if we have 100 frames with only marginal changes - in this case the zoom effect would probably look rather appealing.
type: AnswerComment

http://stackoverflow.com/q/49617651
tagged with: python
tagged with: web-services
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86242476
has comment: http://stackoverflow.com/comment/86242791
has comment: http://stackoverflow.com/comment/86242427
has title: how to implement http server push?
has comment: http://stackoverflow.com/comment/86242437
has comment: http://stackoverflow.com/comment/86242937
has body: I'm trying to implement a server push service (preferably in Python). Regardless of whether it will be implemented using long polling, websockets, etc, all the examples I've seen have the form def controller(request): while True: wait() when new_data_is_available(): send_to_client(new_data) The question is: how does the method know when new data is available? Especially in a language like Python, which, as far as I know, does not have a standardized event system??
type: Question
has comment: http://stackoverflow.com/comment/86242571
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86242304

http://stackoverflow.com/comment/86469756
comment on: http://stackoverflow.com/q/49727251
has text: Possible duplicate of [Accessing the index in Python 'for' loops](https://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86268088
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49630276
type: Comment
has text: i think my all database is on same server.. does JOIN do better performance that UNION ALL?? Yes u r right i will have to redesign it later and i willing to redesign it now that's why i posted the question and search only in one database then join the result will help. OK, it will somewhat get faster as i only wanted to fetch 18 products at a time but fetching next 18 will take lots of job done. I am thinking this as my last solution.

http://stackoverflow.com/q/49709479
has title: Reverse {% url %}: Reverse for '"' not found. '' is not a valid view function or pattern name
has answer: http://stackoverflow.com/a/49710492
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86433826
has comment: http://stackoverflow.com/comment/86432524
has comment: http://stackoverflow.com/comment/86433661
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/86432872
tagged with: python
has comment: http://stackoverflow.com/comment/86433063
has body: I've been stuck on this for a while, can't seem to fix the error. I do not use reverse() anywhere in the view. urls.py urlpatterns = [ url(r"^book/", include("bookings.urls")), ] bookings.urls.py from django.conf.urls import url from . import views app_name = 'bookings' urlpatterns = [ url(r'^charge/$', views.charge, name='charge'), url(r'^booking/$', views.booking, name='booking'), ] views.py def booking(request): # some code render(request, 'bookings/template.html', {'listing': listing,}) def charge(request): # some code template.html &lt;form action="{% url 'bookings:charge' %}" method="post"&gt; I tried all different alterations and namespaces, e.g. trying to use just charge, different namespaces in urls.py etc. When I render the book/booking/, I get the following error: Reverse for 'charge' not found. 'charge' is not a valid view function or pattern name.
has comment: http://stackoverflow.com/comment/86433105
has comment: http://stackoverflow.com/comment/86432560
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/46795690
upvote count: 3
has comment: http://stackoverflow.com/comment/86433797
answer count: 1
accepted answer: http://stackoverflow.com/a/49710492
has comment: http://stackoverflow.com/comment/86432639

geocoding
tags question: http://stackoverflow.com/q/49737760
tag name: geocoding
tags question: http://stackoverflow.com/q/49756355
tags question: http://stackoverflow.com/q/49640197
type: Tag

http://stackoverflow.com/comment/86245075
comment on: http://stackoverflow.com/q/49618808
type: Comment
type: QuestionComment
score: 0
has text: Thank you for that @JacobIRR. I actually tried that its how I know the array is empty I just didnt include it in code. Great tip usually though, Thanks.

http://stackoverflow.com/q/49687742
answer count: 3
has comment: http://stackoverflow.com/comment/86386678
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/49687954
has answer: http://stackoverflow.com/a/49688073
tagged with: jupyter-notebook
favorite count: 0
type: Question
has body: `example suppose this is a json dictionary- how to make this into the dictionary shown below anybody there dictionary={ "actions": [ { "action_type": "comment", "value": "1" }, { "action_type": "like", "value": "18" }, { "action_type": "post", "value": "4" }, { "action_type": "post_reaction", "value": "268" }, { "action_type": "video_view", "value": "198245" }, { "action_type": "page_engagement", "value": "198536" }, { "action_type": "post_engagement", "value": "198518" } ], "date_start": "2018-03-30", "date_stop": "2018-03-30" } how can i get this into this i tried the iterator, making function and other method but i am stuck now dictionary={ "comment": "1" "like": "18" "post": "4" "post_reaction": "268" "video_view": "198245" "page_engagement": "198536" "post_engagement": "198518" "date_start": "2018-03-30", "date_stop": "2018-03-30" }`
has answer: http://stackoverflow.com/a/49688248
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/86386607
has title: how to access dictionary under a dictionary in python
tagged with: python
tagged with: dictionary
upvote count: 0
downvote count: 2

http://stackoverflow.com/q/49628202
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49643116
score: 1
has comment: http://stackoverflow.com/comment/86300505
answer count: 1
has answer: http://stackoverflow.com/a/49643116
favorite count: 0
has title: read plist files in non-XML format using python
type: Question
has comment: http://stackoverflow.com/comment/86264480
tagged with: plist
tagged with: python
has comment: http://stackoverflow.com/comment/86264829
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86288910
has body: I am reading MacOS data that is in plist (propertly list) format that is not in the XML format, not in the binary format, but in the other ascii format. For example: addr= { City = "San Francisco Bay Area"; } I am trying to parse this into a Python dictionary. Unfortunately, plistlib.loads returns InvalidFileException() when I try to parse it: import plistlib plist=b""" addr= { City = "San Francisco Bay Area"; } """ print( plistlib.loads( plist ) ) Produces: Traceback (most recent call last): File "x.py", line 9, in &lt;module&gt; print( plistlib.loads( plist ) ) File "/Users/simsong/anaconda/lib/python3.6/plistlib.py", line 1024, in loads fp, fmt=fmt, use_builtin_types=use_builtin_types, dict_type=dict_type) File "/Users/simsong/anaconda/lib/python3.6/plistlib.py", line 1009, in load raise InvalidFileException() plistlib.InvalidFileException: Invalid file What's the correct way to do this?

http://stackoverflow.com/a/49725612
upvote count: 0
answers question: http://stackoverflow.com/q/49725522
downvote count: 1
has body: If parsed value True its calling the function class MySpider(object): def parse(self, response): # do some stuff parsed = True if parsed: self.cleanup() return else: print 'parsed is False/None' def cleanup(self): # do some stuff print "called" MySpider().parse('response') Output: called
has comment: http://stackoverflow.com/comment/86465125
has comment: http://stackoverflow.com/comment/86465001
type: Answer
score: -1

http://stackoverflow.com/q/49626599
tagged with: discord
has comment: http://stackoverflow.com/comment/86269081
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86260274
has comment: http://stackoverflow.com/comment/86260354
has comment: http://stackoverflow.com/comment/86303335
has comment: http://stackoverflow.com/comment/86260502
tagged with: discord.py
has comment: http://stackoverflow.com/comment/86261488
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86261284
has comment: http://stackoverflow.com/comment/86260492
has comment: http://stackoverflow.com/comment/86261492
score: 0
has comment: http://stackoverflow.com/comment/86263943
answer count: 0
has comment: http://stackoverflow.com/comment/86264625
has comment: http://stackoverflow.com/comment/86303404
has comment: http://stackoverflow.com/comment/86263884
has body: if i wanna use indexing i got a error: Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\Robson1608\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "C:\Users\Robson1608\Desktop\Nowy folder\run.py", line 79, in on_message await cmds.get(invoke).ex(args, message, client, invoke) File "C:\Users\Robson1608\Desktop\Nowy folder\commands\cmd_play.py", line 7, in ex await Music().play(client, message, message.author.voice.voice_channel, link) File "C:\Users\Robson1608\Desktop\Nowy folder\core\discordmusic.py", line 11, in play self.players[int(message.server.id)] = await voice.create_ytdl_player(link, use_avconv=False) IndexError: cannot fit 'int' into an index-sized integer Code here: def __init__(self): self.players = [] async def play(self, client, message, channel, link): voice = await client.join_voice_channel(channel) voice.encoder_options(sample_rate=48000, channels=2) self.players[int(message.server.id)] = await voice.create_ytdl_player(link, use_avconv=False) self.players[int(message.server.id)].start() def pause(self, message): self.players[int(message.server.id)].pause() Any idea to resolve this problem? ;v I dont know what is problem i search google but dont see any solution
has title: cannot fit 'int' into an index-sized integer

http://stackoverflow.com/comment/86465467
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49687487
has text: No one has any source of answer to this question?

http://stackoverflow.com/comment/86443505
type: Comment
comment on: http://stackoverflow.com/q/49714068
score: 0
has text: You might want to elaborate the rules for assigning a Boolean value. Seemingly nobody understands them.
type: QuestionComment

http://stackoverflow.com/comment/86229055
type: AnswerComment
comment on: http://stackoverflow.com/a/49611223
type: Comment
has text: Could u please help me debug my code?
score: 0

http://stackoverflow.com/q/49650369
has comment: http://stackoverflow.com/comment/86309816
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49651367
has answer: http://stackoverflow.com/a/49650959
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/86308947
has body: I'm trying to extract contents from this post "https://community.diabetes.org/discuss/viewtopic/3/13319" and to iterate over post pages to continue scraping, but the next pages rendered by some JS code. Any ideas how to solve it? import requests url = 'https://community.diabetes.org/discuss/viewcategory/3/13319' r = requests.get(url) text = r.text from bs4 import BeautifulSoup soup = BeautifulSoup(text,"lxml") Title = [] title = soup.find_all("h3",{"class":"forum-post-subject"}) for i in title: Title.append(i.text.strip())
has title: Trying to extract contents from the website by iterating over pages using Python's BeautifulSoup
tagged with: python
possible better answer: http://stackoverflow.com/a/49650959
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86308834
answer count: 3
has answer: http://stackoverflow.com/a/49651135
score: 0
accepted answer: http://stackoverflow.com/a/49651367

http://stackoverflow.com/q/49685032
accepted answer: http://stackoverflow.com/a/49702551
favorite count: 0
type: Question
tagged with: stanford-nlp
score: 0
linked to: http://stackoverflow.com/q/44742809
answer count: 2
has body: I want to parse a sentence to a binary parse of this form (Format used in the SNLI corpus): sentence:"A person on a horse jumps over a broken down airplane." parse: ( ( ( A person ) ( on ( a horse ) ) ) ( ( jumps ( over ( a ( broken ( down airplane ) ) ) ) ) . ) ) I'm unable to find a parser which does this. note: This question has been asked earlier(How to get a binary parse in Python). But the answers are not helpful. And I was unable to comment because I do not have the required reputation.
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50745280
has answer: http://stackoverflow.com/a/49702551
type: AnsweredQuestion
has title: How to get a parse in a bracketed format (without POS tags)?
possible better answer: http://stackoverflow.com/a/50745280
tagged with: python
tagged with: nlp

http://stackoverflow.com/comment/86451148
comment on: http://stackoverflow.com/q/49716147
type: Comment
type: QuestionComment
score: 0
has text: I'm not a Python programmer, but what happens if you increase 4096 to something bigger? 8192, 16384, ...? Perhaps Python can't process packets fast enough and your buffer is too small for the packet flow rate? Looking quickly at the timestamps, there seem to be a lot of packets all arriving within a very short time of each other.

http://stackoverflow.com/comment/86485426
score: 0
comment on: http://stackoverflow.com/q/49735426
type: Comment
has text: So, again, which attributes are they? If they are regular ASCII strings that just happen to be `unicode` objects, there's no problem.
type: QuestionComment

http://stackoverflow.com/comment/86512495
has text: i tried that but i still have that weird problem that sometimes the script adding the user is working, and sometimes not..
type: QuestionComment
comment on: http://stackoverflow.com/q/49738455
type: Comment
score: 0

http://stackoverflow.com/comment/86330515
type: QuestionComment
comment on: http://stackoverflow.com/q/49627957
score: 0
has text: Possible duplicate of [Difference between subprocess.Popen and os.system](https://stackoverflow.com/q/4813238/608639) and [How does subprocess.call differ from os.system](https://stackoverflow.com/q/6220157/608639), Maybe even [Calling an external command in Python](https://stackoverflow.com/q/89228/608639).
type: Comment

http://stackoverflow.com/a/49647841
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49647606
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86304377
answers question: http://stackoverflow.com/q/49647606
has comment: http://stackoverflow.com/comment/86304543
has comment: http://stackoverflow.com/comment/86309743
has comment: http://stackoverflow.com/comment/86308934
has comment: http://stackoverflow.com/comment/86338196
type: Answer
has comment: http://stackoverflow.com/comment/86307935
has body: If you want to use a custom estimator - it should be inherited from sklearn.base.BaseEstimator and it should implement methods fit() and predict(). If you want to be able to pass parameters to your estimator you should also implement __init__() method. Example from sklearn docs: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn.base import BaseEstimator, RegressorMixin &gt;&gt;&gt; from sklearn.utils.validation import check_X_y, check_array, check_is_fitted &gt;&gt;&gt; from sklearn.utils.multiclass import unique_labels &gt;&gt;&gt; from sklearn.metrics import euclidean_distances &gt;&gt;&gt; class TemplateClassifier(BaseEstimator, RegressorMixin): ... ... def __init__(self, demo_param='demo'): ... self.demo_param = demo_param ... ... def fit(self, X, y): ... ... # Check that X and y have correct shape ... X, y = check_X_y(X, y) ... # Store the classes seen during fit ... self.classes_ = unique_labels(y) ... ... self.X_ = X ... self.y_ = y ... # Return the classifier ... return self ... ... def predict(self, X): ... ... # Check is fit had been called ... check_is_fitted(self, ['X_', 'y_']) ... ... # Input validation ... X = check_array(X) ... ... closest = np.argmin(euclidean_distances(X, self.X_), axis=1) ... return self.y_[closest] PS please be aware that the example above shows how to create a custom classifier, so it might contain a code, which is not quite appropriate for regressors
has comment: http://stackoverflow.com/comment/86307214
has comment: http://stackoverflow.com/comment/86308371
score: 2
upvote count: 2

uipath
tags question: http://stackoverflow.com/q/49688476
type: Tag
tag name: uipath

http://stackoverflow.com/comment/86363668
type: QuestionComment
has text: @galfisher The output of my code is the entire first column of my first file
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49676180

http://stackoverflow.com/comment/86435332
type: QuestionComment
type: Comment
has text: Am not stress-testing, just would like to see benchmark results on couchbase in that scenario.
score: 0
comment on: http://stackoverflow.com/q/49706042

http://stackoverflow.com/q/49718241
has comment: http://stackoverflow.com/comment/86455925
has comment: http://stackoverflow.com/comment/86450564
type: Question
has comment: http://stackoverflow.com/comment/86454718
upvote count: 3
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86454392
has comment: http://stackoverflow.com/comment/86449892
tagged with: django
has comment: http://stackoverflow.com/comment/86454519
favorite count: 0
has answer: http://stackoverflow.com/a/49721396
tagged with: docker
accepted answer: http://stackoverflow.com/a/49721396
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86450480
tagged with: docker-compose
has body: I am stuck with deploying my Django project which uses mySQL database using docker containers. I am able to create the two containers but the web container exits with code 1 as soon as it is created with the error -- Not able to find tg_db database. My understanding is that when I run docker-compose up -d to start both the containers, it uses MYSQL_DATABASE=tg_db environment variable to create the database named tg_db, which is used and identified by django settings. Or, I can run command docker-compose run web python3 manage.py migrate to run docker-compose which will create database and migrations on it. Please let me know, if this is not true. Below are the files used: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tg_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '3306', 'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'} },} Dockerfile: # Start with a python image FROM python:3 # Some stuff that everyone has been copy-pasting # since the dawn of time. ENV PYTHONUNBUFFERED 1 # Install things RUN apt-get update # Make folders and locations for project RUN mkdir /code COPY . /code WORKDIR /code/project/t_backend # Install requirements RUN pip install -U pip RUN pip install -Ur requirements.txt Woking directory is set to WORKDIR /code/project/t_backend as my manage.py sits there and Dockerfile and docker-compose.yml files lives at the same place as project folder. docker-compose.yml: version: '3' services: db: image: mysql:latest restart: always environment: - MYSQL_DATABASE=tg_db - MYSQL_ROOT_PASSWORD=password volumes: - ./dbdata:/var/lib/mysql web: build: . command: bash -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db Thank's in advance!
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/86454675
has title: Create mysql database with Django using Docker

pyqt4
tags question: http://stackoverflow.com/q/49745456
tags question: http://stackoverflow.com/q/49609259
tags question: http://stackoverflow.com/q/49644530
tags question: http://stackoverflow.com/q/49615844
tags question: http://stackoverflow.com/q/49744088
tags question: http://stackoverflow.com/q/49670460
type: Tag
tags question: http://stackoverflow.com/q/49633248
tags question: http://stackoverflow.com/q/49621152
tags question: http://stackoverflow.com/q/49679827
tag name: pyqt4
tags question: http://stackoverflow.com/q/49750746

http://stackoverflow.com/a/49700500
score: 1
has comment: http://stackoverflow.com/comment/86414627
has comment: http://stackoverflow.com/comment/86414772
downvote count: 0
upvote count: 1
has body: You can zip the two lists togather, and compare the values: &gt;&gt;&gt; list1 = [100, 223, 335, 143, 218] &gt;&gt;&gt; list2 = [75, 245, 400, 86, 500] &gt;&gt;&gt; &gt;&gt;&gt; for i, j in zip(list1, list2): print i, j, i &lt; j ... 100 75 False 223 245 True 335 400 True 143 86 False 218 500 True To filter the larger values from list1, use list comprehension: &gt;&gt;&gt; [i for i, j in zip(list1, list2) if i &gt;j] [100, 143]
type: Answer
answers question: http://stackoverflow.com/q/49700443
has comment: http://stackoverflow.com/comment/86414430
has comment: http://stackoverflow.com/comment/86414336
has comment: http://stackoverflow.com/comment/86415593

http://stackoverflow.com/q/49706062
tagged with: parallel-processing
tagged with: buffer
has comment: http://stackoverflow.com/comment/86425417
downvote count: 3
linked to: http://stackoverflow.com/q/49782358
tagged with: python
has body: I'm using a basler camera to take images and also using pypylon to interface camera software(pylon) with python I want to create two parts grab images (i.e 1000 or 2000)with some specific exposure time and shutter speed. and save it parallelly without disturbing fps. Or is there any way to save them in a buffer and use it afterward which won't affect fps? Right now my concern is to save images without affecting fps Thanks Following is my code import pypylon pypylon.pylon_version.version available_cameras = pypylon.factory.find_devices() available_cameras cam = pypylon.factory.create_device(available_cameras[0]) cam.opened cam.open() cam.properties['AcquisitionFrameRateEnable'] = True cam.properties['AcquisitionFrameRate'] = 1000 cam.properties['ExposureTime'] cam.properties['ExposureTime'] = 1000 #import matplotlib.pyplot as plt from scipy.misc import imsave count=0 for image in cam.grab_images(30): count +=1 a=str(count) b=str('I:/'+ a+'.png') imsave(b,image)
score: -1
tagged with: image-processing
accepted answer: http://stackoverflow.com/a/49716983
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86436399
tagged with: frame-rate
has title: Is there any way to write a for loop in python which will grab images from camera and save it parallelly?
answer count: 1
has answer: http://stackoverflow.com/a/49716983
favorite count: 0
type: Question

http://stackoverflow.com/q/49659035
tagged with: xml-parsing
answer count: 0
tagged with: cron-task
has comment: http://stackoverflow.com/comment/86364574
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/86842535
type: Question
type: UnansweredQuestion
tagged with: python
has title: python script launch with cron fails when parsing XML
has body: I try to do domotic on 2 different devices with python script on my raspberry py.The script runs several tasks: Launch external command to get some informations on serial port on device 1 get string as a response parse result to build a dictionary Launch external command to get get informations by mbus on device 2 get XML string as a response parse this string add couple of informations to initial dictionary send the dictionary as a post JSON request over to a web server If I launch the script manually, everything go fine. If I launch the script with cron, script get freeze on parsing XML string come from device 2. I launch the script with absolute path : python /home/&lt;user&gt;/script/dom.py If I remove device 2 parsing (step 6 &amp; 7), cron runs fine I have tried to parse string with DOM and SAX way, same freeze at parsing stage XML string is about 80 lines long. Is XML parsing process too slow ? How can I work this around? I really wants to avoid writing to a file, since rewriting is no good for the SD card... Thanks here is the function freezing: nv = {} id ='' def pw3_parseDOM( XMLstr): tree = ET.ElementTree(ET.fromstring(XMLstr)) root = tree.getroot() root.tag root.attrib for child in root: if (child.tag == CONST_XML_DATARECORD): Val = '' Nam = '' for value in child: if value.tag == CONST_XML_VALUE: Val = value.text elif value.tag == CONST_XML_UNIT: Nam = Shortcut.get(value.text, 'None') if(Nam == 'pw3_temp_in' or Nam == 'pw3_temp_out'): nv[Nam] = str(Val).decode('utf-8') elif(Nam == 'pw3_temp_delta'): nv[Nam] = str(Val).decode('utf-8') elif (child.tag == CONST_XML_INFO): for c in child: if(c.tag == CONST_XML_ID): id = c.text and a typical xml string passed to pw3_parseDOM(): &lt;MBusData&gt; &lt;SlaveInformation&gt; &lt;Id&gt;13745998&lt;/Id&gt; &lt;Manufacturer&gt;ITR&lt;/Manufacturer&gt; &lt;Version&gt;24&lt;/Version&gt; &lt;ProductName&gt;&lt;/ProductName&gt; &lt;Medium&gt;Heat: Outlet&lt;/Medium&gt; &lt;AccessNumber&gt;39&lt;/AccessNumber&gt; &lt;Statu…
has comment: http://stackoverflow.com/comment/86328464
score: 0

http://stackoverflow.com/comment/86299125
comment on: http://stackoverflow.com/a/49645323
score: 0
type: AnswerComment
type: Comment
has text: You haven't reacted to the question and suggestion in the above answer. We need to know if it is your getText that is being run, or something else.

game-physics
tags question: http://stackoverflow.com/q/49600583
tag name: game-physics
type: Tag

http://stackoverflow.com/comment/86393830
type: AnswerComment
score: 0
has text: @A.Queue Could you please look into the link [here](https://github.com/python-pillow/Pillow/issues/3079#event-1560370122)
type: Comment
comment on: http://stackoverflow.com/a/49652654

http://stackoverflow.com/comment/86223213
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49607623
has text: Thank you, This worked for me. Wanted to know, if this is the only possible way, as this is kind of hardcoding things. What if I want something like expecting a set of integer before NA, or expecting a set of strings before NA in the columns I have?

http://stackoverflow.com/a/60781395
downvote count: 1
has body: "Read the source, Luke!" -- Obi-one Codobi The source for ayncio.queue is pretty short. the number of unfinished tasks goes up by one when you put to the queue. it goes down by one with you call task_done join() awaits there being no unfinished tasks. This makes join useful if and only if you are calling task_done(). Using the classic bank analogy: people come in the doors and get in line; door is a producer doing a q.put() when a teller is idle and a person is in line, they go to the teller window. teller does a q.get(). When the teller has finished helping the person, they are ready for the next one. teller does a q.task_done() at 5 p.m., the doors are locked door task finishes you wait until both the line is empty and each teller has finished helping the person in front of them. await q.join(tellers) then you send the tellers home, who are now all idling with an empty queue. for teller in tellers: teller.cancel() Without the task_done(), you cannot know every teller is done with people. You cannot send a teller home while they have a person at his or her window.
upvote count: 20
has comment: http://stackoverflow.com/comment/121869597
score: 19
answers question: http://stackoverflow.com/q/49637086
type: Answer

http://stackoverflow.com/comment/86404968
comment on: http://stackoverflow.com/a/49676551
has text: Hi djangoliv, thanks for your answer. But I have a little problem that I havent sloved. Actually I'm working on nested json data( about 24000 json data). I tried to apply your answer on it. like that :
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50859000
type: Answer
has body: You can download the appropriate wheel package and pip install it, or the .gz file and run python setup.py install though you will need CMAKE installed
score: 0
answers question: http://stackoverflow.com/q/49757615

http://stackoverflow.com/comment/86383906
has text: @wwii: usage of it in given context is considered ugly and non-Pythonic
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49685988
score: 0

http://stackoverflow.com/comment/86327644
has text: I don't agree. I think it means [Dependency Injection Container](http://php-di.org/doc/understanding-di.html) (php link but still applicable).
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49659003

http://stackoverflow.com/comment/86255405
type: Comment
comment on: http://stackoverflow.com/q/49619732
type: QuestionComment
has text: Or [`(REST).*?HAB:\s*([^\s\d]*\d\S*)`](https://regex101.com/r/kN7hvR/3)
score: 0

http://stackoverflow.com/a/49799890
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86615197
type: Answer
has body: Back in the days I've built a class, wrapping the package "HyperOpt" to suit my needs. I'll try to quickly minimize it for you, so you can use it. Here's the code with some notes in the end, to help you solve your problem: import numpy as np from hyperopt import fmin, tpe, hp, STATUS_OK, Trials import xgboost as xgb max_float_digits = 4 def rounded(val): return '{:.{}f}'.format(val, max_float_digits) class HyperOptTuner(object): """ Tune my parameters! """ def __init__(self, dtrain, dvalid, early_stopping=200, max_evals=200): self.counter = 0 self.dtrain = dtrain self.dvalid = dvalid self.early_stopping = early_stopping self.max_evals = max_evals self.tuned_params = None def score(self, params): self.counter += 1 # Edit params print("Iteration {}/{}".format(self.counter, self.max_evals)) num_round = int(params['n_estimators']) del params['n_estimators'] watchlist = [(self.dtrain, 'train'), (self.dvalid, 'eval')] model = xgb.train(params, self.dtrain, num_round, evals=watchlist, early_stopping_rounds=self.early_stopping, verbose_eval=False) n_epoach = model.best_ntree_limit score = model.best_score params['n_estimators'] = n_epoach params = dict([(key, rounded(params[key])) if type(params[key]) == float else (key, params[key]) for key in params]) print "Trained with: " print params print "\tScore {0}\n".format(score) return {'loss': 1 - score, 'status': STATUS_OK, 'params': params} def optimize(self, trials): space = { 'n_estimators': 2000, # hp.quniform('n_estimators', 10, 1000, 10), 'eta': hp.quniform('eta', 0.025, 0.3, 0.025), 'max_depth': hp.choice('max_depth', np.arange(1, 9, dtype=int)), 'min_child_weight': hp.choice('min_child_weight', np.arange(1, 10, dtype=int)), 'subsample': hp.quniform('subsample', 0.3, 1, 0.05), 'gamma': hp.quniform('gamma', 0.1, 20, 0.1), 'colsample_bytree': hp.quniform('colsample_bytree', 0.5, 1, 0.25), 'eval_metric': 'map', 'objective': 'rank:pairwise', 'silent': 1 } fmin(self.score, space, algo=tpe.suggest, trials=trials, max_evals=se…
has comment: http://stackoverflow.com/comment/86615020
has comment: http://stackoverflow.com/comment/86615101
answers question: http://stackoverflow.com/q/49756461

http://stackoverflow.com/q/49735807
tagged with: python-docx
has answer: http://stackoverflow.com/a/49740570
answer count: 1
has comment: http://stackoverflow.com/comment/86488567
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86486703
has body: I am getting this error while importing nsprefixes from docx library. from docx import nsprefixes Any idea on How to resolve this issue?
has comment: http://stackoverflow.com/comment/86488397
has comment: http://stackoverflow.com/comment/86486767
type: Question
has comment: http://stackoverflow.com/comment/86485678
has comment: http://stackoverflow.com/comment/86485547
accepted answer: http://stackoverflow.com/a/49740570
has title: ImportError: cannot import name 'nsprefixes' Python 3.5
tagged with: python
has comment: http://stackoverflow.com/comment/86488463
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86488292

http://stackoverflow.com/q/49755826
answer count: 1
downvote count: 0
tagged with: recurrent-neural-network
tagged with: keras
tagged with: tensorflow
favorite count: 0
has body: I'm trying to hand code a trained stateful RNN Keras model, with tensorflow backend, in pure Numpy. My model is built as: model = Sequential() num_layers_first_stage = 64 model.add(GRU(num_layers_first_stage, stateful=True, name=input_node_name, batch_input_shape=(1,1,4), return_sequences=True)) model.add(GRU(64, stateful=True, name='gru_layer_1', return_sequences=True)) model.add(GRU(64, stateful=True, name='gru_layer_2', return_sequences=True)) model.add(Dense(2, activation='softmax', name=output_node_name)) model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy']) return model After training, I save the model and then load it again in a different session. The code I am using to build my pure Numpy model looks something like this: def hard_sigmoid(x): return np.clip(x * 0.2 + 0.5, 0.0, 1.0) class MyKerasGRULayer(object): def __init__(self, keras_layer): self.num_units = keras_layer.units self.W_z = keras_layer.cell.kernel_z.eval(session=K.get_session()) self.W_r = keras_layer.cell.kernel_r.eval(session=K.get_session()) self.W_h = keras_layer.cell.kernel_h.eval(session=K.get_session()) self.U_z = keras_layer.cell.recurrent_kernel_z.eval(session=K.get_session()) self.U_r = keras_layer.cell.recurrent_kernel_r.eval(session=K.get_session()) self.U_h = keras_layer.cell.recurrent_kernel_h.eval(session=K.get_session()) self.b_z = keras_layer.cell.input_bias_z.eval(session=K.get_session()) self.b_r = keras_layer.cell.input_bias_r.eval(session=K.get_session()) self.b_h = keras_layer.cell.input_bias_h.eval(session=K.get_session()) self.input_shape = keras_layer.input_shape self.h = np.zeros((1, self.num_units), dtype=np.float32) def forward_pass(self, x): z = hard_sigmoid(np.dot(x, self.W_z) + np.dot(self.h, self.U_z) + self.b_z) r = hard_sigmoid(np.dot(x, self.W_r) + np.dot(self.h, self.U_r) + self.b_r) h_ = np.tanh(np.dot(x, self.W_h) + np.dot(np.multiply(r, self.h), self.U_h) + self.b_h) self.h = np.multiply((1-z), self.h) + np.multiply(z, h_)…
type: Question
tagged with: numpy
has title: Implementing a stateful GRU in pure Numpy based on a trained Keras Model
has answer: http://stackoverflow.com/a/49761397
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3

http://stackoverflow.com/comment/86400575
type: Comment
type: QuestionComment
has text: well i am new to python so i saw many people suggest to use regex (although it is not compulsory to use regex only)
comment on: http://stackoverflow.com/q/49693758
score: 0

http://stackoverflow.com/q/49753411
has answer: http://stackoverflow.com/a/49754051
score: 0
has comment: http://stackoverflow.com/comment/86521709
has answer: http://stackoverflow.com/a/49753897
answer count: 4
has answer: http://stackoverflow.com/a/49754429
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86522098
has comment: http://stackoverflow.com/comment/86521473
type: UnansweredQuestion
has body: Could someone suggest some ways to Optimise the below code? First Method board =[ {"Pakistan": 123}, {"Pakistan": 27}, {"India": 3}, {"India": 71}, {"Australia": 31}, {"India": 22}, {"Pakistan": 81}, {"India": 171}, {"India": 171}, ] country = {} for item in board: for team,value in item.items(): try: country[team].append(value) except KeyError: country[team] = [value] print(country) avg={} for key, value in country.iteritems(): avg[key]= sum(value)/len(value) print(avg) def maximum(team): d3={v:k for k,v in team.items()} return d3[max(d3)] print(maximum(avg)) Second Method avgDict = {} for k,v in [(key,d[key]) for d in board for key in d]: if k not in avgDict: avgDict[k]=[v] else: avgDict[k].append(v) print(avgDict) Just to get the name and list of scores. Thanks in Advance.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86521424
has comment: http://stackoverflow.com/comment/86521712
downvote count: 1
has comment: http://stackoverflow.com/comment/86521459
has answer: http://stackoverflow.com/a/49753699
has title: Python Code Optimisation for list of dict

http://stackoverflow.com/a/49740862
has body: shlex.split does exactly what you're looking for: import shlex s = """"'quick', 'brown fox'", 'jumps over the "lazy dog"'""" toks = shlex.split(s) print(toks) result: ["'quick', 'brown fox',", 'jumps over the "lazy dog"'] (I must say I'm pleasantly surprised to see that it can cope with single or double quotes, I only used it to split according to double quotes, but that one tries hard to emulate Unix-like command line tokenizing) EDIT: the question has been modified in the meantime. To get rid of the first unquoted chars, I've added a regex to remove all chars until the first quote: import shlex,re s = """ The "'quick', 'brown fox'", 'jumps over the "lazy dog"' """ toks = shlex.split(re.sub('^[^\'"]*',"",s)) output: ["'quick', 'brown fox',", 'jumps over the "lazy dog"']
upvote count: 2
has comment: http://stackoverflow.com/comment/86496625
downvote count: 1
answers question: http://stackoverflow.com/q/49740784
has comment: http://stackoverflow.com/comment/86496512
score: 1
type: Answer

http://stackoverflow.com/comment/86388514
type: Comment
comment on: http://stackoverflow.com/a/49685430
type: AnswerComment
has text: thanks, may I know if i set n = 9 what would happen to groups with less than 9 row?
score: 0

http://stackoverflow.com/comment/86293695
score: 0
comment on: http://stackoverflow.com/q/49641112
has text: @drum. Then How can I solve this?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49614797
downvote count: 0
upvote count: 1
has body: The thing is, whether in Python 2.2, 2.3, or later, these are all new-style classes. There are 3 method resolution schemes here, not 2: Classic class method resolution. Python 2.2 new-style class method resolution. Python 2.3+ C3 linearization. Schemes 2 and 3 would produce the same MRO for the given example. If you want to see the (now almost completely irrelevant) Python 2.2 method resolution scheme, the most complete documentation is probably a blog post from Guido's old Python history blog. There's also an old archived draft of documentation for Python 2.2, which mostly describes it but fails to mention a special case.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49614553
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49614553

http://stackoverflow.com/a/49644217
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86296730
has comment: http://stackoverflow.com/comment/86296136
upvote count: 1
answers question: http://stackoverflow.com/q/49643751
score: 1
accepted answer of: http://stackoverflow.com/q/49643751
type: Answer
has comment: http://stackoverflow.com/comment/86296148
has body: You can use list comprehension with filter only numpy arrays and then convert columns to correct types if necessary: L = [pd.DataFrame(x) for x in master if isinstance(x,(np.ndarray, np.generic))] df = pd.concat(L, ignore_index=True) df.columns = ['A','B','C','D','E','DATE'] df'B','C','E' = df'B','C','E'.astype(int) df['D'] = df['D'].astype(float) df['DATE'] = pd.to_datetime(df['DATE']) print (df.head()) A B C D E DATE 0 ANDAMAN &amp; NICOBAR ISLANDS 4 0 0.000000 0 2016-11-01 1 ANDHRA PRADESH 13161 107 0.008130 0 2016-11-01 2 ARUNACHAL PRADESH 8 0 0.000000 0 2016-11-01 3 ASSAM 1317 6 0.004556 0 2016-11-01 4 Army Postal Service 10 0 0.000000 0 2016-11-01 print (df.dtypes) A object B int32 C int32 D float64 E int32 DATE datetime64[ns] dtype: object
has comment: http://stackoverflow.com/comment/86296499

http://stackoverflow.com/q/49646334
has comment: http://stackoverflow.com/comment/86307703
score: 0
answer count: 0
type: UnansweredQuestion
has body: Apologies if the question is not relevant to this forum, but i have read comments around turning certain flags on/off during compiling from source which makes opencv Faster. Is there some truth to this
type: Question
tagged with: opencv
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/86303408
has title: Is OpenCV compiled from sources faster than OpenCV installed using pip
has comment: http://stackoverflow.com/comment/86301819
tagged with: python
tagged with: unix

http://stackoverflow.com/comment/97740744
type: AnswerComment
score: 0
type: Comment
has text: In my case the command is converting to `<class 'function'>` even after using `@wraps`.
comment on: http://stackoverflow.com/a/52858746

http://stackoverflow.com/q/49611488
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86230777
tagged with: django-views
has title: How to create a decorator that works on class-based views function and class?
answer count: 1
accepted answer: http://stackoverflow.com/a/49612109
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49612109
has body: I have some decorators that can be used on top of class-based views like below : @method_decorator(auth0_login_required, name='dispatch') class MyClass(DetailView): ... I'd like to also be able to use it on top of functions inside class-based views like so : class MyClass2(DetailView): ... def get(self, request, *args, **kwargs): ... @auth0_login_required def post(self, request, *args, **kwargs): ... The problem is that the decorator doesn't work the same for these two use case, I'd like to avoid creating two decorators that does the same work. Here's what the decorator looks like : def auth0_login_required(function): def wrap(request, *args, **kwargs): if request.user.is_authenticated or request.user.is_staff: ... ... return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap For the second use case I have to add self as parameter right before request. I was wondering if there was a way to make it work both ways with one decorator?
has comment: http://stackoverflow.com/comment/86231171

http://stackoverflow.com/q/49657153
has comment: http://stackoverflow.com/comment/86323528
score: 2
has comment: http://stackoverflow.com/comment/86323934
linked to: http://stackoverflow.com/q/1373164
tagged with: python
has comment: http://stackoverflow.com/comment/86323405
has comment: http://stackoverflow.com/comment/86323433
answer count: 1
has title: Python equivalent of R's deparse(substitute())
has comment: http://stackoverflow.com/comment/86323522
has comment: http://stackoverflow.com/comment/86323693
type: Question
tagged with: pandas
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/49660384
has comment: http://stackoverflow.com/comment/86323985
downvote count: 1
has body: I want to score a model on a pandas DataFrame and then create a column with that model's predictions in the same DataFrame. The new column should be named so that it references the appropriate model so this can be done multiple times with multiple models. I can do this in R using deparse and substitute like so: df &lt;- data.frame(a=1:5+rnorm(1:5), b=6:10+rnorm(1:5), y=11:15+rnorm(1:5)) ols &lt;- lm(df$y ~ df$a + df$b) func &lt;- function(df, model){ new_col &lt;- paste0(deparse(substitute(model)), '_predictions') df[, new_col] &lt;- predict(model, df) return(df) } func(df, ols) a b y ols_predictions 1 1.569142 7.735250 11.90998 12.99388 2 0.828704 4.468299 12.16632 12.01042 3 2.270323 8.135620 14.25781 13.51283 4 1.847564 9.602450 13.76106 13.46148 5 5.776140 10.723743 16.08072 16.19727 What would be the equivalent of this in Python?
favorite count: 0
has answer: http://stackoverflow.com/a/49660384
has comment: http://stackoverflow.com/comment/86323965

http://stackoverflow.com/comment/137907567
has text: There are three ways to introduce input masks in Keras models: 1. Add a `keras.layers.Masking` layer. 2. Configure a `keras.layers.Embedding` layer with mask_zero=True. 3. Pass a mask argument manually when calling layers that support this argument (e.g. RNN layers). [Propagation a mask](https://www.tensorflow.org/guide/keras/understanding_masking_and_padding) to `Lambda` layer require a proper `mask` signature.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49670832

http://stackoverflow.com/a/49639387
type: Answer
answers question: http://stackoverflow.com/q/49639135
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49639135
has body: You have to iterate to get the QModelIndex associated with each cell, and use the QItemSelection to invert the selection of each cell. def invertSelectionRemoveSelected(self): model = self.view.model() for i in range(model.rowCount()): for j in range(model.columnCount()): ix = model.index(i, j) self.view.selectionModel().select(ix, QItemSelectionModel.Toggle) # delete rows for ix in reversed(self.view.selectionModel().selectedRows()): model.removeRow(ix.row()) Another Solution: From your request I understand that you want to eliminate the unselected rows, and deselect all the others afterwards. So the next solution does it directly. def invertSelectionRemoveSelected(self): model = self.view.model() rows_selected =[ix.row() for ix in self.view.selectionModel().selectedRows()] [model.removeRow(i) for i in reversed(range(model.rowCount())) if i not in rows_selected] self.view.clearSelection()

http://stackoverflow.com/a/49657575
type: Answer
has body: This can be done by disabling all unchecked CheckButtons when the maximum number of CheckButtons is checked. Disabling the CheckButtons improves the user-friendlyness, because it gives the user a visual clue that no more buttons can be checked. If we didn't disable the CheckButtons, the user might be confused why nothing happens when he tries to click a CheckButton. For the implementation of this feature, we have to connect a callback function to each CheckButton. The callback functions counts how many buttons are checked, and disables or enables the other buttons accordingly. The first thing we have to do is to rewrite the __init__ method. The Checkbar needs a new parameter how many Checkbuttons can be checked at the same time. We also have to connect the callback function to each CheckButton. I used functools.partial to bind the checkbutton's variable to the callback function. def __init__(self, parent=None, picks=[], maxselect=1, side=tk.LEFT, anchor=tk.W): super().__init__(parent) self.maxselect = maxselect # store all variables and checkbuttons; the callback function # needs access to them self._vars = [] self._checkbuttons = [] for pick in picks: var = tk.IntVar() # bind the callback function to each checkbutton chk = tk.Checkbutton(self, text=pick, variable=var, command=partial(self._var_toggled, var)) chk.pack(side=side, anchor=anchor, expand=tk.YES) self._vars.append(var) self._checkbuttons.append(chk) Now all that's left is to implement the callback function. It simply needs to count how many checkbuttons are checked, and enable or disable them accordingly: def _var_toggled(self, var): # count how many checkbuttons are checked num = sum(v.get() for v in self._vars) if num == self.maxselect: # if we're at maxselect, disable all unchecked checkbuttons for var, chk in zip(self._vars, self._checkbuttons): if not var.get(): chk['state'] = tk.DISABLED else: # otherwise, re-enable all checkbuttons for chk in self._checkbuttons: chk['state'] = tk.NORMAL (The var p…
score: 0
answers question: http://stackoverflow.com/q/49656013

http://stackoverflow.com/a/49669474
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49668991
has body: arr1 = [(7, 0.78, 7920), (8, 0.9, 9000)] arr2 = [(7, 1.68, 8460)] arr1.sort(key=lambda x:x[0]) arr2.sort(key=lambda x:x[0]) from itertools import zip_longest new_list = [] for value1, value2 in zip_longest(arr1, arr2): if value2: _id1, val3, val4 = value1 _id2, val5, val6 = value2 if _id1 == _id2: diff1 = val5 - val3 diff2 = val6 - val4 new_list.append((_id1, diff1, diff2)) else: new_list.append(value1) print(new_list) &gt;&gt;&gt;[(7, 0.8999999999999999, 540), (8, 0.9, 9000)]

http://stackoverflow.com/comment/86507371
comment on: http://stackoverflow.com/a/49740127
score: 0
type: Comment
type: AnswerComment
has text: Thanks for the reply. I got the result. I made a small mistake.

http://stackoverflow.com/comment/86231778
comment on: http://stackoverflow.com/q/49612579
type: Comment
type: QuestionComment
has text: use [sympy](http://docs.sympy.org/latest/tutorial/basic_operations.html)
score: 0

http://stackoverflow.com/comment/86255072
has text: It's probably because on subsequent calls an **exception** is being raised. You are just swallowing the exception. Does it not print that exception message?
score: 0
comment on: http://stackoverflow.com/q/49624014
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86285885
score: 12
comment on: http://stackoverflow.com/q/49639126
type: QuestionComment
type: Comment
has text: *why* do you want to do this?

http://stackoverflow.com/comment/86291493
type: Comment
type: QuestionComment
score: 0
has text: the http it's putted but idont know why it doesnt copied
comment on: http://stackoverflow.com/q/49641855

http://stackoverflow.com/comment/86329866
has text: @ayhan thanks it works and I have solved the problem !
type: QuestionComment
comment on: http://stackoverflow.com/q/49659348
type: Comment
score: 0

http://stackoverflow.com/q/49628442
type: AnsweredQuestion
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/49628543
has comment: http://stackoverflow.com/comment/86263937
has answer: http://stackoverflow.com/a/49628546
has comment: http://stackoverflow.com/comment/86264115
has comment: http://stackoverflow.com/comment/86263909
favorite count: 0
has title: Filter list of dictionaries contains same key, value
has comment: http://stackoverflow.com/comment/86263868
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49628711
has comment: http://stackoverflow.com/comment/86267434
score: -2
has body: I have a list of dictionaries like: l = [ {'a': 123, 'b': 456}, {'a': 322, 'b': 44454}, {'a': 123, 'b': 134} ] I want to filter list based upon key a of each dictionary. If key, value 'a': 123 exist in any other dictionary of list then remove any one of these two and I want filtered result like: [ {'a': 123, 'b': 456}, {'a': 3222, 'b': 44454} ] # 1st and 3rd dict have same 'a': 123 so remove 3rd dictionary, don't care about value of 'b'. # or [ {'a': 3222, 'b': 44454}, {'a': 123, 'b': 134} ] # 1st and 3rd dict have same 'a': 123 so remove 1st dictionary. Don't care about value of 'b'. I have tried different ways but all are successful in case if list of dictionaries have all keys and values same. import itertools, operator, pprint from operator import itemgetter l = [ {'a': 123, 'b': 456}, {'a': 322, 'b': 44454}, {'a': 123, 'b': 134} ] getvals = operator.itemgetter('a', 'b') l.sort(key=getvals) result = [] for k, g in itertools.groupby(l, getvals): result.append(g.next()) l[:] = result pprint.pprint(l) But result is [{'a': 123, 'b': 134}, {'a': 123, 'b': 456}, {'a': 322, 'b': 44454}] How I can filter my list ?
tagged with: python
has comment: http://stackoverflow.com/comment/86265142
possible better answer: http://stackoverflow.com/a/49628543
accepted answer: http://stackoverflow.com/a/49628711

http://stackoverflow.com/q/49602095
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49602647
has body: I am working on code in Visual Basic 2015 that is calling a Python 2.7 program. Right now I am trying to pass a variable, "arg1= 1" from VB to Python. This is the VB code: Private Sub FWHM_Click(sender As Object, e As EventArgs) Handles FWHM.Click Dim pythonProcess As New Process() Dim arg1 As New Integer arg1 = 1 With pythonProcess .StartInfo.FileName = "pythonw.exe" .StartInfo.WorkingDirectory = "C:\Users\...\" .StartInfo.Arguments = ("HelloWorld.py" &amp; arg1) .StartInfo.RedirectStandardOutput = True .StartInfo.UseShellExecute = False .StartInfo.CreateNoWindow = True .Start() End With End Sub As you can see the code activates when the I click a button in my form. The button works fine when I don't try to pass "arg1", as the python code shows me a window with a sinusoidal graph. arg1's value will change the period of the sinusoidal graph. This is the Python code, and it is pretty simple. I am just starting to learn to use Python. I am not in the process of learning Python, just for learning it. I just need Python to perform some mathematical libraries that will be eventually used in the VB program: from sys import argv script = argv import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np msg= script msg= "Hello Wolrd" print(msg) arg1= 1 x = np.linspace(0, 20, 100) plt.plot(x, np.sin(x*arg1)) plt.show() I eventually want to pass a pointer to Python as I am going to pass an array, and I assume and array is easier to pass as a pointer if it is about 100x100 floats.
tagged with: visual-studio-2015
tagged with: vb.net
has title: Passing Variables between Visual Basic 2015 and Python
score: 2
has comment: http://stackoverflow.com/comment/86212289
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49608573
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/61803263
tagged with: systemd
score: 3
tagged with: linux
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/66879066
favorite count: 0
has title: systemd service not executing notify-send
type: Question
has body: I want to generate pop-ups for certain events in my python script. I am using 'notify-send' for that purpose. subprocess.Popen(['notify-send', "Authentication", "True/False"]) The above command executes fine on terminal but when I run it from systemd-service it does not generate any pop-up. When I see logs there are no errors.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49617812
tagged with: notify-send

http://stackoverflow.com/a/49617446
score: 1
type: Answer
downvote count: 0
has body: referred from datascience.stackexchange. Modified code: while True: frame=stream.read() frame = cv2.resize(frame, (299, 299), interpolation=cv2.INTER_CUBIC) numpy_frame = np.asarray(frame) numpy_frame = cv2.normalize(numpy_frame.astype('float'), None, -0.5, .5, cv2.NORM_MINMAX) numpy_final = np.expand_dims(numpy_frame, axis=0) text=run_graph(numpy_final, labels, FLAGS.input_layer, FLAGS.output_layer) cv2.putText(frame,text,topLeftCornerOfText,font,fontScale,fontColor,lineType) cv2.imshow("Frame",frame) key = cv2.waitKey(1) &amp; 0xFF fps.update() if key == ord('q'): break
answers question: http://stackoverflow.com/q/49613059
upvote count: 1

http://stackoverflow.com/a/49716983
has comment: http://stackoverflow.com/comment/86489146
has comment: http://stackoverflow.com/comment/86480808
score: 0
has comment: http://stackoverflow.com/comment/86475674
has comment: http://stackoverflow.com/comment/86579989
has comment: http://stackoverflow.com/comment/86489201
has comment: http://stackoverflow.com/comment/86489727
has body: First things first: scipy's imsave has been deprecated, and is scheduled to be removed. Use imageio's imwrite instead. Now for the code. There are a few ways of doing this. I'll move from fewest modifications to most modifications. Fix up code I'm just going to make some changes to your program, to make it easier to modify later and so that it won't break in the future: import pypylon from imageio import imwrite available_cameras = pypylon.factory.find_devices() cam = pypylon.factory.create_device(available_cameras[0]) cam.open() cam.properties['AcquisitionFrameRateEnable'] = True cam.properties['AcquisitionFrameRate'] = 1000 cam.properties['ExposureTime'] = 1000 for count, image in enumerate(cam.grab_images(30)): filename = str('I:/{}.png'.format(count)) imwrite(filename, image) Future modifications will be based on this. I recommend looking up what some of these do, like 'ExposureTime', since it looks like you blindly copied these from the example. Buffer In order to store these images in a buffer, we can simply read them all straight away by converting the iterable into a tuple (a read-only list). Once we're done with the buffer we can delete it to free up some memory. import pypylon from imageio import imwrite available_cameras = pypylon.factory.find_devices() cam = pypylon.factory.create_device(available_cameras[0]) cam.open() cam.properties['AcquisitionFrameRateEnable'] = True cam.properties['AcquisitionFrameRate'] = 1000 cam.properties['ExposureTime'] = 1000 buffer = tuple(cam.grab_images(30)) for count, image in enumerate(buffer): filename = str('I:/{}.png'.format(count)) imwrite(filename, image) del buffer Asynchronous saving I need to do something with multiprocessing. Oh, look, there's a Python module called multiprocessing. I've never used this before, but by reading it I can create this: import pypylon from imageio import imwrite from multiprocessing import Pool def save_image(pair): count, image = pair # pair is actually two values filename = str('I:/{…
has comment: http://stackoverflow.com/comment/86475797
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86475631
has comment: http://stackoverflow.com/comment/86475877
has comment: http://stackoverflow.com/comment/86563808
has comment: http://stackoverflow.com/comment/86579572
has comment: http://stackoverflow.com/comment/86489234
accepted answer of: http://stackoverflow.com/q/49706062
type: Answer
has comment: http://stackoverflow.com/comment/86576891
has comment: http://stackoverflow.com/comment/86489087
has comment: http://stackoverflow.com/comment/86488738
has comment: http://stackoverflow.com/comment/86579538
answers question: http://stackoverflow.com/q/49706062
has comment: http://stackoverflow.com/comment/86480665

http://stackoverflow.com/a/49805458
type: Answer
answers question: http://stackoverflow.com/q/49743797
score: 0
has body: The root of your problem is that you're limiting your results to only one post. In reality, what you want is every post since the last one you saw. Try something like this: while True: for post in reddit.subreddit(query_list).new(): if not newLastProcessed: newLastProcessed = post if post == lastProcessed: break # Do something lastProcessed = newLastProcessed newLastProcessed = None time.sleep(30) Another alternative that's not quite as fragile in regards to ordering is to store the ids of processed posts, for instance in an SQLite database, and then query that for every post you're considering processing.

http://stackoverflow.com/a/49614777
has comment: http://stackoverflow.com/comment/86239624
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86241174
has comment: http://stackoverflow.com/comment/86262001
has comment: http://stackoverflow.com/comment/86240643
has body: Maybe you're missing the cuda toolkit or it doesn't work properly with your PyTorch installation. Can you first check if this function torch.cuda.is_available() returns true. If not, you should check if the cuda toolkit works and the PyTorch version you are using is the correct one for your cuda installation.
has comment: http://stackoverflow.com/comment/86238302
type: Answer
has comment: http://stackoverflow.com/comment/86256023
answers question: http://stackoverflow.com/q/49613268

http://stackoverflow.com/a/49625470
answers question: http://stackoverflow.com/q/49625407
upvote count: 2
has comment: http://stackoverflow.com/comment/86257898
has comment: http://stackoverflow.com/comment/86259013
downvote count: 0
has comment: http://stackoverflow.com/comment/86258253
has comment: http://stackoverflow.com/comment/86257873
has comment: http://stackoverflow.com/comment/86258042
type: Answer
has body: If I understand correctly, your data are: vars = ['age','balance','day','duration','campaign','pdays','previous','job_admin.','job_blue-collar'] and indexes are: idx = [1, 5, 7] Then you can do: &gt;&gt;&gt; [vars[i] for i in idx] ['balance', 'pdays', 'job_admin.']
has comment: http://stackoverflow.com/comment/86259117
score: 2

http://stackoverflow.com/comment/86350663
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49650990
has text: Try to uninstall and install package, maybe it can't be imported because it's incomplete.

http://stackoverflow.com/comment/86390235
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49688707
has text: the same as before, datetime is datetime64 and value is float64

http://stackoverflow.com/q/49675419
has comment: http://stackoverflow.com/comment/86362289
linked to: http://stackoverflow.com/q/14134892
tagged with: python
score: 0
has body: I'm trying to locate the facial land marks of an image using openCV by getting the image using a URL, The code bellow gets the image using the url and converts it from a image to a list and then from a list to a string as before did this I got the error 'TypeError: expected string or Unicode object, list found', I am currently getting: Blockquote : Traceback (most recent call last): File "C:\Users\matth\Desktop\testmctest.py", line 52, in cv2.imshow('Result',annotate_landmarks(im,get_landmarks(im))) File "C:\Users\matth\Desktop\testmctest.py", line 31, in get_landmarks x,y,w,h =rects[0] IndexError: tuple index out of range def get_landmarks(im): rects = cascade.detectMultiScale(im, 1.3,5) x,y,w,h =rects[0] rect=dlib.rectangle(x,y,x+w,y+h) return numpy.matrix([[p.x, p.y] for p in predictor(im, rect).parts()]) def annotate_landmarks(im, landmarks): im = im.copy() for idx, point in enumerate(landmarks): pos = (point[0, 0], point[0, 1]) cv2.putText(im, str(idx), pos, fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale=0.4, color=(0, 0, 255)) cv2.circle(im, pos, 3, color=(0, 255, 255)) return im URL = "http://static-23.sinclairstoryline.com/resources/media/d368a1cb-f6af-4a04-83d0-ebc66e984ab2-large16x9_BIOPIC.jpg?1456517822862" from PIL import Image import urllib2 im = Image.open(urllib2.urlopen(URL)) o = str(im) img =[unicode(o, encoding="UTF-8")] string = ''.join(map(str, img)) im=cv2.imread(string) cv2.imshow('Result',annotate_landmarks(im,get_landmarks(im)))
has comment: http://stackoverflow.com/comment/86362287
answer count: 0
tagged with: url
has comment: http://stackoverflow.com/comment/86362311
type: Question
tagged with: opencv
has title: IndexError: tuple index out of range cv2 using a url
has comment: http://stackoverflow.com/comment/86361982
has comment: http://stackoverflow.com/comment/86368933
has comment: http://stackoverflow.com/comment/86362090
type: UnansweredQuestion

http://stackoverflow.com/comment/86433700
type: QuestionComment
comment on: http://stackoverflow.com/q/49620757
score: 0
has text: what is `ds_by_month` `ds`?
type: Comment

http://stackoverflow.com/a/49645546
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86299541
has body: As I mentioned in my comment, you seem to be importing the module that you are executing. The code example in https://automatetheboringstuff.com/chapter13/ (somewhere in the middle) looks exactly like your getText() function and is mentioned to be saved to a file readDocx.py While importing, all the code in the imported module is executed. The import line already executes your file, including the print(). Please try it without the readDocx in the import statement and consider familiarizing yourself with the aforementioned __name__ == '__main__' blocks
answers question: http://stackoverflow.com/q/49644926
has comment: http://stackoverflow.com/comment/86299274
downvote count: 0
type: Answer

http://stackoverflow.com/comment/93688991
type: QuestionComment
has text: Shakya RDN, @PiotrK, I am also in similar situation :D Were you able to find the solution? If so, it would be really appreciative, if you could share the solution.
type: Comment
comment on: http://stackoverflow.com/q/49737231
score: 0

http://stackoverflow.com/q/49630010
type: Question
tagged with: python-3.x
has body: I have an issue than is invariably more complex that what I'm about to show, but it's concept will be similar: I am writing 100's of new files, each name based on a specific datetime and they all have the same 'template'... I am using the 'string' library to build such a template. with open(New_FileTemplate) as FileTemplate: FileTemplate = string.Template(FileTemplate.read()) (Yes I know I its bad coding practise for using the same names, but it's easier for showing my issue). The simplified txt file template has the following form: ${datetime1} instruction1 ${datetime2} instruction2 ${datetime3} instruction3 ${StartLocation} ${datetime4} instruction4 ${StartOffset} My StartLocation variable initially starts at 0 and ranges from 0 - 1000 and my StartOffset variable initially starts at 0 and ranges from 0-300 The StartLocation specifies which memory block and the StartOffset specifies where in the memory block to start. So once StartOffset reaches 300, then StartLocation then goes to value 1 and it's offset goes back to 0 etc... Lets say I am trying to create 100 files with this template. For each file, the offset will increase by 10. How can I incorporate this into my architecture? I created a function: def MemoryUsed(StartLocation, StartOffset): ImageSize = 10 if StartOffset + ImageSize &lt;=300: StartLocation = StartLocation StartOffset = StartOffset + ImageSize return StartLocation, StartOffset if StartOffset + ImageSize &gt; 300: StartLocation +=1 Offset = 0 + ImageSize return StartLocation, StartOffset So this function will return a tuple of StartLocation and StartOffset I then would write into the template as follows: for i in range(1, 100): fout = open(DirectoryforFiles + 'filedate.txt' % filedate, 'w') fout.write(template.substitute(StartLocation=MemoryUsed(0, 0)[0], StartOffset=MemoryUsed(0,0)[1]) So this would initially write 0 to each variable for 100 files.. But I want it to increase after each file based on the rules outlined earlier! I hope I've explai…
type: UnansweredQuestion
tagged with: python
tagged with: string
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/49630673
has title: Increment template.substitute variable on specified rules in a loop
answer count: 1
tagged with: templates

http://stackoverflow.com/comment/86322361
comment on: http://stackoverflow.com/a/49649290
type: Comment
type: AnswerComment
has text: Instead of checking `if titles['href'] is not None`, you can use `find_all('a', href=True)`.
score: 1

http://stackoverflow.com/comment/86419685
comment on: http://stackoverflow.com/q/49703016
has text: Hi could you elaborate a bit more on what is not working? what is the intended function of your code?
type: QuestionComment
score: 1
type: Comment

http://stackoverflow.com/a/49738560
score: 0
has body: I am thinking about lookup, but it it fail since KeyError: 'One or more row labels was not found' #df1.lookup(df2.PN,df2.Date,na_action='ignore') result = [] for x,y in zip(df2.PN, df2.Date): try: result.append(df1.get_value(x, y)) except: result.append(np.nan) df2['V']=result
type: Answer
answers question: http://stackoverflow.com/q/49737588

http://stackoverflow.com/q/49718737
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86450342
type: UnansweredQuestion
answer count: 1
type: Question
has title: python match chromosome number ignore X, Y, and MT
has body: I am working with python3 on a linux cluster. I am having trouble working with chromosome numbers in a table. I have the following csv (example.csv) 1,2,x 3,4,mt 5,6,9 7,8,y I would like to print all lines containing a value of 9 in column #3. Here is my attempt import csv with open('example.csv', 'rb') as f: for line in csv.reader(f): if 9 == int(line[2]): print(line) If I include the int it fails due to the presence of MT, Y and X values. But if I exclude int it does not find the 9. Any assistance or clarification on how to query through columns of mixed integers and characters in python is much appreciated.
has answer: http://stackoverflow.com/a/49718796
tagged with: http://stackoverflow.com/tag/csv
tagged with: genetics

http://stackoverflow.com/a/49692066
has comment: http://stackoverflow.com/comment/86395995
has body: I would try extracting the tar file first (See here) import tarfile tar = tarfile.open("xxx.tar.gz") tar.extractall() tar.close() and then use the os.walk() method (See here) import os for root, dirs, files in os.walk('.\\xxx\\'): txt_files = [path for path in files if path[:-4] == '.txt'] OR use the glob package to gather the txt files as suggested by @alper in the comments below: txt_files = glob.glob('./**/*.txt', recursive=True) This is untested, but should get you pretty close And obviously move them once you get the list of text files new_path = ".\\extracted\\" for path in txt_files: name = path[path.rfind('\\'):] os.rename(path, new_path + name)
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/86396187
accepted answer of: http://stackoverflow.com/q/49691737
upvote count: 4
answers question: http://stackoverflow.com/q/49691737
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86409376
score: 0
type: Comment
type: QuestionComment
has text: each iteration np.std only generate one data point.
comment on: http://stackoverflow.com/q/49698020

http://stackoverflow.com/q/49685877
tagged with: aws-lambda
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: Is there any way to install the pdftotext command via poppler-utils in aaws-lambda
score: 2
tagged with: pdftotext
answer count: 0
tagged with: poppler
has body: WHy pdftotext command is not working in aws-lambda python 2.7 where as it working in local ubuntu system.

http://stackoverflow.com/comment/86291604
type: AnswerComment
has text: Check your output, it's not exactly what the OP wanted (unless I missed something)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49641986

http://stackoverflow.com/a/49666606
has comment: http://stackoverflow.com/comment/86343310
type: Answer
has comment: http://stackoverflow.com/comment/86342995
has comment: http://stackoverflow.com/comment/86343095
has body: for i in a[:-1]: if i[0]==b: a.remove(i) What about this? The output is [[1, 2], [5, 6], [7, 8]]
score: 1
has comment: http://stackoverflow.com/comment/86343027
downvote count: 0
answers question: http://stackoverflow.com/q/49666523
upvote count: 1
has comment: http://stackoverflow.com/comment/86343221

http://stackoverflow.com/comment/86424308
type: QuestionComment
has text: @zwer, 1st, Python does not support unloading modules. 2nd, I don't know what modules are being loaded in `main2.py` =). 3rd, I swtich back to main1 when main2 has been completed.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49705245

http://stackoverflow.com/comment/86260669
comment on: http://stackoverflow.com/q/49610780
score: 2
has text: You seem to establish an ANSI-mode session (in Teradata mode it's autocomitted by default) and set *autocommit=False*. `SET SESSION` is considered a DDL statement, which must be commited. Adding `COMMIT;` should resolve the issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86472156
type: Comment
type: AnswerComment
score: 0
has text: I can help you more if you can update your question with specific requirement , as you have mentioned that you want to do further analysis on data . if you can add details about the output you want that will help us solve it for you
comment on: http://stackoverflow.com/a/49727305

http://stackoverflow.com/a/49736288
has comment: http://stackoverflow.com/comment/86494645
has comment: http://stackoverflow.com/comment/86509524
has comment: http://stackoverflow.com/comment/105004701
answers question: http://stackoverflow.com/q/49735187
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49735187
has body: Assuming your data is always an image, you need to use a library to get the image back from the base64 encoded string. For example with OpenCV: retval, buffer = cv2.imencode('.jpg', test_image) jpg_as_text = base64.b64encode(buffer) nparr = np.fromstring(base64.b64decode(jpg_as_text), np.uint8) img2 = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
score: 7

http://stackoverflow.com/comment/86495835
type: AnswerComment
has text: That's a surprise, considering that even explicitly constructing `dtype('<i4')` will produce a `byteorder` of `'='` if native is little-endian. I would consider this a bug.
comment on: http://stackoverflow.com/a/49740663
type: Comment
score: 0

http://stackoverflow.com/a/49638727
has body: Several ways you can do the same. In this very case the better approach is to put the last page number as it's highest range. The webpage displays documents in three different pages and the highest number of page is 3. However, if you search for https://www.congress.gov/members?q=%7B%22congress%22%3A%22115%22%7D&amp;pageSize=250&amp;page=5, you can see that the webpage still shows the data whereas the stock of data have been exhausted in page 3. So, defining the last page number (plus 1) is what you should do here. import requests from bs4 import BeautifulSoup my_url = "https://www.congress.gov/members?q=%7B%22congress%22%3A%22115%22%7D&amp;pageSize=250&amp;page={}" for link in [my_url.format(page) for page in range(1,4)]: res = requests.get(link,headers={"User-Agent":"Mozilla/5.0"}) soup = BeautifulSoup(res.text, "lxml") for item in soup.select(".expanded"): name = item.select_one(".result-heading a").text print(name)
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49638285

http://stackoverflow.com/q/49650604
tagged with: for-loop
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/49651601
tagged with: python
has title: conditional within four units
has comment: http://stackoverflow.com/comment/86310815
has body: I'm not using my conditional statements correctly and don't know if I need a while loop or for loop instead of what I am attempting. What my code wishes to do is to look at the tl or bl value the previous four rows and if tl &gt; Upper or bl &lt; Lower then we need to make sure that (current_row['difference'] &gt; 0) &amp; (row_minus1['difference'] &lt; 0). First step is to check the or statements, meaning row_minus1['tl'] &gt; Upper or...row_minus4['tl'] &gt; Upper...or row_minus4['bl'] &lt; Lower, and then check the (current_row['difference'] &gt; 0) &amp; (row_minus1['difference'] &lt; 0) condition. for i in range(len(data)): # do something current_row = data.iloc[i,:] row_minus1 = data.iloc[i-1,:] row_minus2 = data.iloc[i-2,:] row_minus3 = data.iloc[i-3,:] row_minus4 = data.iloc[i-4,:] if ((current_row['difference'] &gt; 0) &amp; (row_minus1['difference'] &lt; 0)) &amp; (((row_minus1['tl'] &gt; Upper) or (row_minus1['bl'] &lt; Lower) )) or ((row_minus2['tl'] &gt; Upper) or (row_minus2['bl'] &lt; Lower) )) or ((row_minus3['tl'] &gt; Upper) or (row_minus3['bl'] &lt; Lower) )) or ((row_minus4['top_line'] &gt; Upper) or (row_minus4['bl'] &lt; Lower) ))) :
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86309636
answer count: 1
has comment: http://stackoverflow.com/comment/86309299
has comment: http://stackoverflow.com/comment/86310083
has comment: http://stackoverflow.com/comment/86309957
accepted answer: http://stackoverflow.com/a/49651601
type: Question

http://stackoverflow.com/a/49700607
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86485166
has body: Your i = 1 After else should not be there, it keeps setting i to 1 thus always making i's value in to a 2, try to have it outside of the for statements
type: Answer
answers question: http://stackoverflow.com/q/49700561

http://stackoverflow.com/comment/86506996
score: 0
type: AnswerComment
has text: Yes cat will not return true in the above example
comment on: http://stackoverflow.com/a/49746200
type: Comment

http://stackoverflow.com/a/49752802
type: AcceptedAnswer
type: Answer
score: 4
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49750220
has comment: http://stackoverflow.com/comment/86520656
has body: class MySpider(scrapy.Spider): name = "myspidername" host = 'localhost' user = 'root' password = 'test123' db = 'scraping_db' def __init__(self): self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db,use_unicode=True, charset="utf8") self.cursor = self.connection.cursor() def insert(self, query,params): try: self.cursor.execute(query,params) self.connection.commit() except Exception as ex: self.connection.rollback() def __del__(self): self.connection.close() then in your Pipeline do this spider.cursor to access cursor and perform any MySQL operation. class LinkPipeline(object): def process_item(self, item, spider): query="""INSERT INTO links (title, location,company_name,posted_date,status,company_id,scraped_link,content,detail_link,job_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)""" params=(item['title'], item['location'], item['company_name'], item['posted_date'], item['status'], item['company_id'], item['scraped_link'], item['content'], item['detail_link'],item['job_id']) spider.cursor.insert(query,params) return item
answers question: http://stackoverflow.com/q/49750220

http://stackoverflow.com/comment/86260375
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49626753
has text: I was using request.post earlier but getting same result
type: Comment

http://stackoverflow.com/q/49609501
answer count: 1
has comment: http://stackoverflow.com/comment/86225666
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49609595
tagged with: python
has comment: http://stackoverflow.com/comment/86225552
has title: Difference between two list
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49609595
has comment: http://stackoverflow.com/comment/86225442
downvote count: 0
has body: I have the following text file: text1 text2 # text2 text3 text4 # text5 text4 text6 text 3 text 4 # .... ... I would like to have a array list like the following, where fu dict[function([text1, text2])] = [[text2, text3, text4], [text5, text4, text6]]. The idea is to open the file, read line by line dict = {} inputfile = open("text.txt","r") for line in inputfile: l=line.split() if not line.startswith("#"): #create a new key else: dict[key] = l However, the problem is that I cannot assign other element if I go to the next line. Do you know how to solve this issue? "Function"is just a function which I defined elsewhere and that takes as an input a list of strings.
score: 1
upvote count: 1

http://stackoverflow.com/comment/86455160
type: Comment
type: QuestionComment
has text: Sorry if I sound idiot, I'm really just beginning. There is no error message per say, but I got a syntax error for "install"... I don't really get it
score: 0
comment on: http://stackoverflow.com/q/49720878

http://stackoverflow.com/a/49604304
answers question: http://stackoverflow.com/q/49604146
accepted answer of: http://stackoverflow.com/q/49604146
type: Answer
score: 2
has body: You never reassign the variable df, then your dataframe is empty. You should do: df = df.append(data)
has comment: http://stackoverflow.com/comment/86216700
upvote count: 2
has comment: http://stackoverflow.com/comment/86216520
has comment: http://stackoverflow.com/comment/86216591
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86531495
type: AnswerComment
comment on: http://stackoverflow.com/a/49757949
score: 2
type: Comment
has text: Thanks you @etene for teaching me something new. I have made suitable changes.

http://stackoverflow.com/q/49750367
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49756011
tagged with: deep-learning
has body: I'm trying to fit a time series to an LSTM with Keras and I have some issues with the input shape. In this article : https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ , the autor choose the shape : (trainX.shape[0], 1, trainX.shape[1]) But the input of an LSTM should be : (samples, timesteps, features) So shouldn't he have chosen this shape : (1 , trainX.shape[0] , trainX.shape[1]) ? Since it's a single serie with multiple steps over time I tried to do that with my own time series but it does not work, so what did I miss ? My situation is exactly the same than the article. It works when I reshape like the autor did but It does not work my way. Thanks.
answer count: 1
tagged with: keras
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49756011
score: 1
has title: Input Shape LSTM for a time series
downvote count: 1
tagged with: python
tagged with: lstm

http://stackoverflow.com/comment/86394176
has text: Could you edit your question to show what you have right now and where it fails? The code I wrote works on [tio.run](https://tio.run) until the actual posting part as the hostname doesn't resolve there so it's not clear where your issue lies.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49689239

http://stackoverflow.com/a/49659527
accepted answer of: http://stackoverflow.com/q/49658100
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49658100
has comment: http://stackoverflow.com/comment/86332896
type: Answer
score: 4
upvote count: 4
has body: Just launch it in application mode by adding next argument: chrome_options.add_argument("--app=https://www.google.com") This url (https://www.google.com) is just an example so use one you have.
has comment: http://stackoverflow.com/comment/86329417

http://stackoverflow.com/q/49678297
has comment: http://stackoverflow.com/comment/86368229
has title: Controlling Pandas plot layout
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/86368131
downvote count: 0
upvote count: 1
tagged with: plot
has body: I am creating some plots and put them in one figure: import pandas as pd l1 = [1,2,3,4,5,6] df1 = pd.DataFrame(l1) l2 = [1,2,3,4,5,6] df2 = pd.DataFrame(l2) l3 = [1,2,3,4,5,6] df3 = pd.DataFrame(l3) l4 = [1,2,3,4,5,6] df4 = pd.DataFrame(l4) l5 = [1,2,3,4,5,6] df5 = pd.DataFrame(l5) l6 = [1,2,3,4,5,6] df6 = pd.DataFrame(l6) l7 = [1,2,3,4,5,6] df7 = pd.DataFrame(l7) l8 = [1,2,3,4,5,6] df8 = pd.DataFrame(l8) l9 = [1,2,3,4,5,6] df9 = pd.DataFrame(l9) l10 = [1,2,3,4,5,6] df10 = pd.DataFrame(l10) l11 = [1,2,3,4,5,6] df11 = pd.DataFrame(l11) df = pd.concat([df1,df2,df3,df4,df5,df6,df7,df8,df9,df10,df11], axis = 1) df.plot(grid = 1,subplots = True, sharey = True) Output: By modifying the code I can change the plot layout to this: df.plot(grid = 1,subplots = True, layout = (6,5), sharey = True) or this: df.plot(grid = 1,subplots = True, layout = (5,6), sharey = True) Is there a way to change the layout further? For these graphs this layout would be handy: 5/6 rows, 2 columns IIIII IIIII IIIII IIIII IIIII IIIII IIIII IIIII IIIII IIIII IIIII
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/comment/86467092
comment on: http://stackoverflow.com/a/49726484
has text: If assert is a statement why does it allow open and close parenthesis after it?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49716504
favorite count: 0
has title: Access Arrays by index
tagged with: indexing
type: AnsweredQuestion
score: 3
tagged with: python
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49717771
has answer: http://stackoverflow.com/a/49717771
upvote count: 3
tagged with: arrays
answer count: 1
downvote count: 0
has body: I want to access arrays like in the example code below, this is quite slow. Is it possible to create a vector from i ans f_s and access the arrays by that index? def calc(self, length): for i in range(int(f_s*length*6)): t = i / f_s self.data[i] = (numpy.multiply(sinTable512[int(t*f_carrier)%512], self.Signal[int(t*f_prn)%1023])) I imagine the code to look something like this: def calc(self,length): t = numpy.arange(0, f_s*length*6, 1/f_s) t_sin = t * f_carrier %512 t_sig = t * f_prn % 1023 self.data[i] = (numpy.multiply(sinTable512[t_sin], self.Signal[t_sig])) Are there any other ways to do somethink like that? From what I remember the vector operations are a lot faster than for loops, at least in MatLab, is that the same for Python or is there another method to speed this operation up?

http://stackoverflow.com/comment/86490878
type: QuestionComment
has text: What is the expected result?
comment on: http://stackoverflow.com/q/49738220
type: Comment
score: 0

http://stackoverflow.com/comment/86359330
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49674272
score: 2
has text: You aren't even using the mixin. Have you tried inheriting from it?

http://stackoverflow.com/q/49757660
linked to: http://stackoverflow.com/q/312443
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/312443
has comment: http://stackoverflow.com/comment/86530333
type: Question
tagged with: python-itertools
accepted answer: http://stackoverflow.com/a/49757687
tagged with: python
has answer: http://stackoverflow.com/a/49757687
has body: I want to break a list into sub-lists of n elements. I could convert the list (after adding appropriate padding) to a numpy array, e.g.: n = 20 L = [x for x in range(93)] Lnp = np.array(L+[0]*7).reshape(-1,n) Lgrouped = [g for g in Lnp] but this is sub-optimal. What would be a good way to do this without numpy? (itertools comes to mind, but didn't seem to find a straightforward function...)
tagged with: list
has title: "reshaping" a list to a list of sub-lists
type: AnsweredQuestion

http://stackoverflow.com/comment/86214722
type: AnswerComment
comment on: http://stackoverflow.com/a/49603782
type: Comment
has text: I'd like to point out this answer brings up an important (and previously unfamiliar to me) attribute **`.str`** of a `Series` - and which distinguishes it from a `DataFrame`
score: 0

http://stackoverflow.com/a/49666184
score: -1
has body: or you can first convert m to text and add a 0 depending on the number and then concat to url.
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49665969
type: Answer

http://stackoverflow.com/comment/86425343
comment on: http://stackoverflow.com/a/49705139
score: 0
type: Comment
has text: And I have another question if you can help me :) I want to make numpy array and make copy of trainer list in it, line by line but without "\n" because I want to use its parameter for math function, how can I do this?
type: AnswerComment

http://stackoverflow.com/comment/86319932
type: QuestionComment
comment on: http://stackoverflow.com/q/49654856
has text: @9000 yes, my shebang is correct: `#!/usr/bin/env python3`. Bash doesn't find anything, because I use autocompletion: ./mysc+<tab> returns nothing
score: 0
type: Comment

http://stackoverflow.com/comment/86478433
has text: There is no error message you can copy/paste in the page in the browser?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49732220
score: 0

http://stackoverflow.com/comment/86371775
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49679349
type: Comment
has text: block[0] is 0.000ms, block[1] is 37.903 and block[2] is 0. All this in turn means that between 0.000ms and 37.903ms in the audio file I am working with, there is no singing. I understand about your suggestion.

http://stackoverflow.com/q/49658348
has comment: http://stackoverflow.com/comment/86326567
has comment: http://stackoverflow.com/comment/86326921
accepted answer: http://stackoverflow.com/a/49684065
possible better answer: http://stackoverflow.com/a/49660880
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49684065
has answer: http://stackoverflow.com/a/49660880
has comment: http://stackoverflow.com/comment/86326664
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/13793399
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86326845
has title: Reading large tables into Pandas, is there a intermediate step?
has comment: http://stackoverflow.com/comment/86328797
has body: I have a data-analysis script that I am putting together. This script connects to Teradata, Select * from the table, and loads that into the pandas dataframe. import teradata import pandas as pd with udaExec.connect(method="xxx", dsn="xxx", username="xxx", password="xxx") as session: query = "Select * from TableA" # read in records df = pd.read_sql(query, session) # misc pandas tests below... This works great for tables with 100k records or less, but the problem is that many tables have far more records than that (millions and millions of records), and it just tends to run indefinitely. Is there some intermediate step I can take? I've been researching and I see something about copying the DB table to a .csv file or .txt file or something first, and then loading the pandas dataframe from that(instead of loading from the table itself), but I can't make sense of it. Any advice would be appreciated! Thanks.
answer count: 2
has comment: http://stackoverflow.com/comment/86329188
has comment: http://stackoverflow.com/comment/86379711
tagged with: python
score: 4

http://stackoverflow.com/q/49713526
has comment: http://stackoverflow.com/comment/86440785
has comment: http://stackoverflow.com/comment/86473148
has title: Brute forcing the private key
favorite count: 0
has body: I need to find x from the below equation h = pow(g,x,p) I have the values of h = 400 digit number g = 400 digit number p = 400 digit number I need to find the value of x. All the values are very big. I have incomplete x with 10 missing digits in it and they are not continuous missing digits.Index of all the missing digits is different. I am using 10 for loops to replace that value every time to get H.It is taking too much time in python to do that.Is there anyway in which I can do it faster.
type: Question
tagged with: brute-force
has answer: http://stackoverflow.com/a/49717135
has comment: http://stackoverflow.com/comment/86440456
tagged with: python
tagged with: cryptography
has comment: http://stackoverflow.com/comment/86477750
upvote count: 2
has comment: http://stackoverflow.com/comment/86442210
has comment: http://stackoverflow.com/comment/86453311
tagged with: private-key
downvote count: 5
type: UnansweredQuestion
score: -3
answer count: 1

system
tag name: system
tags question: http://stackoverflow.com/q/49733535
type: Tag

http://stackoverflow.com/a/49659620
score: 0
has comment: http://stackoverflow.com/comment/86332537
answers question: http://stackoverflow.com/q/49659474
has comment: http://stackoverflow.com/comment/86381032
has body: What you see with a browser's developer tools doesn't correspond to what's in the HTML returned by the webserver. Look at the source code in your web browser and you will see that all of the webpage's content is generated with JavaScript from the JSON contained in the &lt;script&gt; tags. This makes your life a lot easier, since you don't have to worry much about parsing the HTML and only extract the data from the JSON: import json from bs4 import BeautifulSoup ... soup = BeautifulSoup(page.text) # Find the `script` tag with no `src` and 'window.jsonData' in its text script = soup.find('script', src=None, text=lambda text: 'window.jsonData' in text).get_text() # The JSON is part of script, so just remove the extra stuff script = script.strip().replace('window.jsonData = ', '').rstrip(';') # Now parse it data = json.loads(script)
has comment: http://stackoverflow.com/comment/86330589
type: Answer
has comment: http://stackoverflow.com/comment/86378987

http://stackoverflow.com/comment/86497436
comment on: http://stackoverflow.com/a/49740663
type: Comment
type: AnswerComment
score: 1
has text: @miradulo: I'd expect `newbyteorder` to produce `'='` when the resulting byte order is the same as the native byte order. (The fact that explicit `dtype('<i4')` produces `'='` when native is little-endian is documented, while the `newbyteorder` behavior isn't.)

http://stackoverflow.com/q/49736006
favorite count: 0
has comment: http://stackoverflow.com/comment/86487419
has comment: http://stackoverflow.com/comment/86487343
tagged with: python-3.x
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49736079
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49736714
tagged with: geojson
has comment: http://stackoverflow.com/comment/86486328
has title: How to remove unwanted double quotes when converting CSV to GeoJSON
has comment: http://stackoverflow.com/comment/86486273
type: Question
upvote count: 3
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86486708
has comment: http://stackoverflow.com/comment/86486125
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I'm getting started with Python3 and I'm working on a script to convert a CSV file into a GeoJSON one. The conversion works but I still have a problem with the coordinates, that are not taking the right format. I need to remove the double quotes, but it's not working. Here is part of my code: def readCsvFile(): features=[] geoJson={} with open('resources/data_export.csv',newline= '') as csvfile: csvReader = csv.DictReader(csvfile,delimiter=',',quotechar='|') for row in csvReader: features.append({'type': 'Feature', 'geometry': { 'type': 'Point', "coordinates" : [str(row['longitude']), str(row['latitude'])]}, 'properties': {'id': decodeString(row['id']), 'field1': decodeString(row['field1']), 'field2': decodeString(row['field2'])}) geoJson = {'type': 'FeatureCollection', 'features': features} return json.dumps(geoJson) I'm getting that result: {"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": ["16.394564", "48.246426"]}, "properties": {"id": "0", ... While I'm supposed to get: {"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.394564, 48.246426]}, "properties": {"id": "0",

http://stackoverflow.com/comment/97968410
score: 0
comment on: http://stackoverflow.com/a/49751075
type: Comment
type: AnswerComment
has text: (This can replace the other 3 `ax.xaxis` statements in the question.)

http://stackoverflow.com/comment/86308351
type: Comment
has text: use "if i in userInputList"...will work here since length differ here what you are referring in loop
comment on: http://stackoverflow.com/q/49650028
score: 0
type: QuestionComment

http://stackoverflow.com/a/49711333
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49711153
answers question: http://stackoverflow.com/q/49711153
has body: Your transcription of the code image is missing the last line, which is pretty key. Inside the loop, it's calling subprocess.Popen on the output of the line lambda function: subprocess.Popen(line(block)).wait() The getblocks function reads from a redacted website (probably not jstor) to get a list of pdf files to download. This allows the script to be remotely controlled. The line lambda function produces a list of command line arguments that will be used by Popen to call the curl command line utility program, which does the actual downloading. The cookie mentioned in the quotation your "additional notes" section gets produced in the lambda (it generates a random number, converts it to a string, and slices all but the first three characters to get the cookie value).
type: Answer

http://stackoverflow.com/comment/86331746
has text: This won't work for the admin views, as you need to order the queryset, not a list.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49660569
score: 1

http://stackoverflow.com/a/49636121
downvote count: 0
upvote count: 1
has body: Using the file path as parameter you can select the id for each line and save it on a dict. import re import sys ref = dict() with open(sys.argv[1], 'r') as f: for line in f.readlines(): m = re.search(".*id:(\w*),", line) if m is not None and m.group(1) is not None: ref[m.group(1)] = line.strip() for i in ref: print(ref[i])
has comment: http://stackoverflow.com/comment/86313759
accepted answer of: http://stackoverflow.com/q/49635495
type: Answer
has comment: http://stackoverflow.com/comment/86303458
answers question: http://stackoverflow.com/q/49635495
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86320757
score: 0
type: Comment
has text: @abarnert: I want to break only the inner loop to check the other keys as well.
type: QuestionComment
comment on: http://stackoverflow.com/q/49655375

http://stackoverflow.com/a/49677390
type: AcceptedAnswer
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/49677110
upvote count: 5
type: Answer
has body: It appears that click passes keywords arguments. This should work. I think it needs to be the first decorator, i.e. it is called after all of the click methods are done. def capitalise_input(f): def wrapper(**kwargs): kwargs['name'] = kwargs['name'].upper() f(**kwargs) return wrapper @click.command() @click.option('--count', default=1, help='Number of greetings.') @click.option('--name', prompt='Your name', help='The person to greet.') @capitalise_input def hello(count, name): .... You could also try something like this to be specific about which parameter to capitalize: def capitalise_input(key): def decorator(f): def wrapper(**kwargs): kwargs[key] = kwargs[key].upper() f(**kwargs) return wrapper return decorator @capitalise_input('name') def hello(count, name):
answers question: http://stackoverflow.com/q/49677110
has comment: http://stackoverflow.com/comment/86369450

http://stackoverflow.com/q/49750705
has title: Cannot import name 'faster_rcnn_pnas_feature_extractor'
has body: I have installed the newest tensorflow version 1.7. I have also added slim and models to my env variables. But I see this error when I try to run - model_builder_test.py Please help.
score: 0
linked to: http://stackoverflow.com/q/3555107
has answer: http://stackoverflow.com/a/49888583
answer count: 1
tagged with: tensorflow
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: object-detection

http://stackoverflow.com/a/49778570
answers question: http://stackoverflow.com/q/49752788
score: 3
has body: It looks like your problem is you are requiring two params in your predicate - PT-31 and PT-32 - which would match a path of /trends?param1=PT-31&amp;param1=PT32 but not /trends?param1=PT-31. A couple other suggestions, in the hopes that they're useful: Because you're using deepEquals, it won't even match /trends?param1=PT-31&amp;param1=PT-32&amp;param1=PT-33. It requires an exact match. If you want to be a bit more flexible, I'd suggest using equals instead The outermost "and" predicate is unnecessary. All predicates within a single operator (the "deepEquals") are automatically ANDed together.
type: Answer
has comment: http://stackoverflow.com/comment/86621527
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86576198

http://stackoverflow.com/q/49694574
has comment: http://stackoverflow.com/comment/86412495
tagged with: postgresql
score: 0
answer count: 0
tagged with: flush
has body: I have a form where a user can upload images/videos. I create a unique image/video name for the files, to make sure the name is unique I am using the id of the image/video object. To get the id before the commit() I am using flush(). def profile_add_user_post(): form = AddUserPostForm() if form.validate_on_submit(): new_post = Post(title=form.title.data.strip(), description=form.description.data, created_on=datetime.today(), updated_on=datetime.today(), created_by_user_id=current_user.id) if form.visible_to_tier_id.data and form.visible_to_tier_id.data != "0": setattr(new_post, "visible_to_tier_id", form.visible_to_tier_id.data) if form.post_image.data: new_image_post = PostImage(path=get_random_code(15), created_on=datetime.today()) new_post.image_belongs_to_post_addresses.append(new_image_post) # multiple add db_session.add(new_post) db_session.flush() image_name = str(new_image_post.id) + "-post-image." + form.post_image.data.filename.split(".")[-1] upload_to_aws(image_name, "images/", form.post_image.data) setattr(new_image_post, "path", image_name) if form.post_video.data: new_video_post = PostVideo(path=get_random_code(15), created_on=datetime.today()) new_post.video_belongs_to_post_addresses.append(new_video_post) # multiple add db_session.add(new_post) db_session.flush() video_name = str(new_video_post.id) + "-post-video." + form.post_video.data.filename.split(".")[-1] upload_to_aws(video_name, "videos/", form.post_video.data) setattr(new_video_post, "path", video_name) if form.send_category.data: category_list_for_post = form.send_category.data.split(",") for cat in category_list_for_post: new_cat_post = PostBelongsCategory(category_id=cat) new_post.children_PostBelongsCategory.append(new_cat_post) # multiple add db_session.add(new_post) db_session.commit() flash("Beitrag erfolgreich hinzugefügt","success") return redirect(url_for('profile')) return render_template('profile_add_post.html', form=form) It works great, but couldn't this lead to problems with I…
linked to: http://stackoverflow.com/q/2095917
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/86413872
type: UnansweredQuestion
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/86413340
has title: Sqlalchemy using flush() to retrieve primary key (id) smart here?

http://stackoverflow.com/q/49737354
tagged with: python
score: 10
has answer: http://stackoverflow.com/a/65127317
accepted answer: http://stackoverflow.com/a/49737694
has title: Collecting prometheus metrics from a separate port using flask and gunicorn with multiple workers
has body: I run a small flask application with gunicorn and multiple worker processes on kubernetes. I would like to collect metrics from this application with prometheus, but the metrics should only be accessible cluster internally on a separate port (as this required in our current setting). For one gunicorn worker process I could use the start_http_server fucntion from the python client library to expose metrics on a different port than the flask app. A minimal example may look like this: from flask import Flask from prometheus_client import start_http_server, Counter NUM_REQUESTS = Counter("num_requests", "Example counter") app = Flask(__name__) @app.route('/') def hello_world(): NUM_REQUESTS.inc() return 'Hello, World!' start_http_server(9001) To start the app do the following: gunicorn --bind 127.0.0.1:8082 -w 1 app:app However this only works for one worker process. In the documentation of the client library is also a section on how to use prometheus and gunicorn with multiple worker processes by specifying a shared directory for the worker processes as an environment variable where metrics are written to (prometheus_multiproc_dir). So following the documentation the above example for multiple workers would be: A gunicorn config file: from prometheus_client import multiprocess def worker_exit(server, worker): multiprocess.mark_process_dead(worker.pid) The application file: import os from flask import Flask from prometheus_client import Counter NUM_REQUESTS = Counter("num_requests", "Example counter") app = Flask(__name__) @app.route('/') def hello_world(): NUM_REQUESTS.inc() return "[PID {}]: Hello World".format(os.getpid()) To start the app do: rm -rf flask-metrics/ mkdir flask-metrics export prometheus_multiproc_dir=flask-metrics gunicorn --bind 127.0.0.1:8082 -c gunicorn_conf.py -w 3 app:app However in this setting I don't really know how to accesses the metrics stored in flask-metrics on a separate port. Is there way to get this done? I am a bit new to these things…
answer count: 2
tagged with: prometheus
has comment: http://stackoverflow.com/comment/98383886
downvote count: 0
possible better answer: http://stackoverflow.com/a/65127317
upvote count: 10
tagged with: flask
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49737694
tagged with: gunicorn
tagged with: kubernetes

http://stackoverflow.com/a/53701209
has body: None of the answers currently given will solve your problem. Your socket() construction is fine with default parameters, and the number of sends and receives doesn't matter at all. The real answer is this: When you recv(1024), you're going to get at least one, and at most 1024 bytes. You probably know the latter, but the former might be a surprise. It is a consequence of how network works. recv must block (unless the socket is in nonblocking mode) until it gets something, and that something will be at least one byte. So if there's nothing to read, recv will hang. It can't detect the difference between that situation and the network simply being slow. If you have further questions, feel free to ask.
score: 0
answers question: http://stackoverflow.com/q/49695334
type: Answer

http://stackoverflow.com/comment/86208693
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49600560
has text: try adding `:` after `as e`, if it won't works, check out the code in my updated post

http://stackoverflow.com/comment/86484707
type: QuestionComment
comment on: http://stackoverflow.com/q/49734949
has text: The code is confused as to who actually owns the pointer. Both the python wrapper for `Test*` and `Changer` think they own the pointer and so both call free, thus causing the seg fault. See this question on who to deal with ownership correctly. https://stackoverflow.com/questions/4112561/boost-python-ownership-of-pointer-variables
score: 0
type: Comment

http://stackoverflow.com/comment/86404982
type: QuestionComment
comment on: http://stackoverflow.com/q/49694837
type: Comment
has text: This ValueError is produced when you use a boolean array in a context that expects a simple scalar True/False. An `if` statement is most likely. Doing comparisons on numpy arrays produces boolean arrays.
score: 0

http://stackoverflow.com/a/60781433
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/130698121
has body: I don't know where your alist and blist variables are coming from, but you could do something like this. import concurrent.futures def func(a, b): return (func2(a),func3(3)) def parallel_func(alist, blist): processes = [] with concurrent.futures.ThreadPoolExecutor(max_workers=None) as executor: processes.append(executor.submit(func, alist, blist)) for _ in concurrent.futures.as_completed(processes): print('Result: ', _.result())
has comment: http://stackoverflow.com/comment/130688914
has comment: http://stackoverflow.com/comment/132250687
score: 7
type: Answer
answers question: http://stackoverflow.com/q/49690198
has comment: http://stackoverflow.com/comment/130648715

http://stackoverflow.com/q/49618479
possible better answer: http://stackoverflow.com/a/49622832
has answer: http://stackoverflow.com/a/49622832
type: AnsweredQuestion
score: 5
answer count: 3
has answer: http://stackoverflow.com/a/49618870
downvote count: 0
has body: I am parsing an HTMl page and am having a hard time figuring out how to pull a certain 'p' tag without a class or on id. I am trying to reach the tag of 'p' with the lat and long. Here is my current code: import bs4 from urllib import urlopen as uReq #this opens the URL from bs4 import BeautifulSoup as soup #parses/cuts the html my_url = 'http://www.fortwiki.com/Battery_Adair' print(my_url) uClient = uReq(my_url) #opens the HTML and stores it in uClients page_html = uClient.read() # reads the URL uClient.close() # closes the URL page_soup = soup(page_html, "html.parser") #parses/cuts the HTML containers = page_soup.find_all("table") for container in containers: title = container.tr.p.b.text.strip() history = container.tr.p.text.strip() lat_long = container.tr.table print(title) print(history) print(lat_long) Link to website: http://www.fortwiki.com/Battery_Adair
accepted answer: http://stackoverflow.com/a/49621421
has answer: http://stackoverflow.com/a/49621421
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: HTML Parsing using bs4
upvote count: 5
tagged with: python

geometry-surface
tag name: geometry-surface
tags question: http://stackoverflow.com/q/49630410
type: Tag

http://stackoverflow.com/comment/86311186
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49651244
type: AnswerComment
has text: Nice, no problem!

http://stackoverflow.com/comment/86311532
comment on: http://stackoverflow.com/a/49643273
score: 0
type: AnswerComment
has text: I have indeed edited my code with the parameters you already gave, but unfortunately it didn't give me the same result you got (your image). And to be honest py playing with the parameters and especially with the height and width, I could get a good result. For example in the original code of the tutorial, he uses 300*300 which doesn't give good results. I will post my answer about 'giving feedback' in a new comment.
type: Comment

http://stackoverflow.com/q/49710850
has comment: http://stackoverflow.com/comment/86436070
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86435980
has comment: http://stackoverflow.com/comment/86436831
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49711459
has body: My Django URLs.py isn't working it returns a 404. forums/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.forums, name='forums'), url('topics/&lt;int:id&gt;/', views.topics, name='topics'), ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('announcements.urls')), path('faq/', include('FAQ.urls')), path('', include('account.urls')), path('forum/', include('forums.urls')), ] I am trying to go to the URL /forum/topics/4
has title: Django URL's not working
has answer: http://stackoverflow.com/a/49711459
tagged with: django
tagged with: python

http://stackoverflow.com/q/49665757
has answer: http://stackoverflow.com/a/51860964
accepted answer: http://stackoverflow.com/a/49675283
has title: How to add report_tensor_allocations_upon_oom to RunOptions in Keras
score: 30
linked to: http://stackoverflow.com/q/53885356
has answer: http://stackoverflow.com/a/49675283
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72634264
downvote count: 0
possible better answer: http://stackoverflow.com/a/51860964
tagged with: keras
has answer: http://stackoverflow.com/a/70954964
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 30
answer count: 5
tagged with: gpu
has answer: http://stackoverflow.com/a/64231036
tagged with: python
has body: I'm trying to train a neural net on a GPU using Keras and am getting a "Resource exhausted: OOM when allocating tensor" error. The specific tensor it's trying to allocate isn't very big, so I assume some previous tensor consumed almost all the VRAM. The error message comes with a hint that suggests this: Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. That sounds good, but how do I do it? RunOptions appears to be a Tensorflow thing, and what little documentation I can find for it associates it with a "session". I'm using Keras, so Tensorflow is hidden under a layer of abstraction and its sessions under another layer below that. How do I dig underneath everything to set this option in such a way that it will take effect?

http://stackoverflow.com/q/49663908
has comment: http://stackoverflow.com/comment/86337709
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I wonder if there is a way to search a list of keywords using Python. I am able to search though my data using PostgreSQL. Here is my PostgreSQL code SELECT distinct ON (id) id, year, cost, description FROM mydata WHERE description similar to'%((hotel)||(travel)|(taxi)|(food))%'; I don't know if Python is the best way to do it, but the work that I am replicating uses Python and would like to stick with Python. I was able to search one keyword but am not sure how to do multiple. import csv with open('mydata.csv', 'r') as f: for line in f.readlines(): if 'food' in line: print(line) I need help with 1) searching using multiple keywords 2) way to export the data back to csv
tagged with: python
has title: Keyword search in a large CSV file using Python
linked to: http://stackoverflow.com/q/38185688
has answer: http://stackoverflow.com/a/49665159
tagged with: postgresql
score: 0
answer count: 1

http://stackoverflow.com/comment/86445206
has text: @Azure in which case you should accept the answer. There's a little check box by the side of the answer to do that
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49703256

http://stackoverflow.com/a/58452252
upvote count: 15
downvote count: 0
score: 15
has body: I found another tool which perfectly matches this question: Sourcetrail, which officially supports C/C++/Java/Python in 2019. The text down below comes from its official doc: Sourcetrail is an interactive source explorer that simplifies navigation in existing source code. Sourcetrail's aim is to give answers to all your questions about your source code. Sourcetrail first indexes your code and gathers data about its structure and then provides you a simple interface consisting of three interactive views, each playing a key role in getting information. Update: Sourcetrail is officially open source as well. Github link. Update before 2021 ends: Sourcetrail is now officially discontinued. Here is the blog link on this decision (For the record, it still works well on my Windows 11 Home Insider Preview with OS build 22523.1000; date: 2021-12-21).
type: Answer
answers question: http://stackoverflow.com/q/49647160

http://stackoverflow.com/comment/86323230
type: Comment
type: AnswerComment
score: 0
has text: But clearly [U+1f941](http://www.unicode.org/emoji/charts/full-emoji-list.html#1f941) does.
comment on: http://stackoverflow.com/a/49656963

http://stackoverflow.com/comment/86428081
has text: Does order matter in this list?
comment on: http://stackoverflow.com/q/49707401
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86349656
type: Comment
type: QuestionComment
has text: Thank you for your answer and for your edit. Sorry for swapping the outputs.
comment on: http://stackoverflow.com/q/49654085
score: 0

http://stackoverflow.com/comment/86289388
type: Comment
comment on: http://stackoverflow.com/a/49629851
has text: I have another problem that t is make _.csv_ file with 90273 columns in any range of _**i**_ and _**j**_.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50185257
score: 18
type: Answer
has body: If you want to show it, you can use img/255. Or np.array(img,np.int32) The reason is that if the color intensity is a float, then matplotlib expects it to range from 0 to 1. If an int, then it expects 0 to 255. So you can either force all the numbers to int or scale them all by 1/255.
answers question: http://stackoverflow.com/q/49643907
downvote count: 0
upvote count: 18

http://stackoverflow.com/comment/86458156
comment on: http://stackoverflow.com/q/49722389
score: 0
has text: Can you give an example?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49636659
has comment: http://stackoverflow.com/comment/86285728
has comment: http://stackoverflow.com/comment/86280880
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49636788
has body: def computes(text): file=open(text) line=file.readlines() for i in range(0,len(line)): print(str(line[i][1])) Output [4, 4, 3, 4, 0] [9, 7, 6, 8, 0] [6, 6, 4, 2, 2] [9, 10, 6, 8, 6] [12, 9, 6, 9, 2] [12, 12, 2, 4, 1] [5, 6, 3, 4, 16] [24, 21, 14, 16, 0] [3, 2, 2, 5, 0] [10, 10, 10, 0, 9] 4 9 6 9 1 1 5 2 3 1 What I'm trying to do, is loop through a text that has an array of lists inside and I am trying to print the number 12 but is only printing the first number, I am not sure where to go from here. How can I correct this?
linked to: http://stackoverflow.com/q/15197673
has comment: http://stackoverflow.com/comment/86280952
answer count: 3
has comment: http://stackoverflow.com/comment/86281157
upvote count: 3
has title: Trying to print the number 12 but it only prints the number 1
tagged with: python
has answer: http://stackoverflow.com/a/49636698
type: Question
score: 2
has answer: http://stackoverflow.com/a/49637016
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86281430

http://stackoverflow.com/q/49620498
has title: How to resolve json.load encoding error in python?
has body: I'm trying to convert a JSON text file into a python object (and also print the text to the console) I'm getting an error to do with encoding characters. I'm using Python 3.6.5 and Windows Powershell to execute the script. The Python code: import json f = open("z.txt", "r", encoding='utf-8') test = f.readline() testa = json.loads(test) print(testa) test = f.readline() testb = json.loads(test) print(testb) f.close() The Powershell code to execute the script: python tweetsentiment.py The text file with JSON test: {"created_at":"Mon Apr 02 18:54:15 +0000 2018","id":980881109440331776,"id_str":"980881109440331776","text":"@MyOtterName @OBrienslife @mikefarb1 Agree. The hate, judgment &amp;amp; self-righteousness was what Jesus preach against m\u2026 https:\/\/t.co\/v40MxsR6Ul","display_text_range":[37,140],"source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":980136581217402880,"in_reply_to_status_id_str":"980136581217402880","in_reply_to_user_id":836670766368219136,"in_reply_to_user_id_str":"836670766368219136","in_reply_to_screen_name":"MyOtterName","user":{"id":4808517884,"id_str":"4808517884","name":"LHAinColorado","screen_name":"LeslieArnoldH2O","location":"Colorado Springs, CO","url":null,"description":"CO Mother of 4 daughters who've turned out amazing &amp; hilarious despite my best attempts! Politics is my porn-I'm a CO St delegate, marketing GOP to Millennials","translator_type":"none","protected":false,"verified":false,"followers_count":488,"friends_count":369,"listed_count":10,"favourites_count":8311,"statuses_count":6498,"created_at":"Sun Jan 24 17:21:46 +0000 2016","utc_offset":null,"time_zone":null,"geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"1DA1F2"…
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/5419
linked to: http://stackoverflow.com/q/27092833
has comment: http://stackoverflow.com/comment/86248583
tagged with: unicode
favorite count: 0
duplicate of: http://stackoverflow.com/q/5419
duplicate of: http://stackoverflow.com/q/27092833
type: Question
has comment: http://stackoverflow.com/comment/86249191
tagged with: encoding
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86249129
tagged with: python

http://stackoverflow.com/a/49648808
has body: chs = "This is a Test Ab Here here big" get_all_captial = [val for val in chs.split() if val[0].isupper()] &gt;&gt;&gt;get_all_captial ['This', 'Test', 'Ab', 'Here']
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49648682
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/86512058
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49748278
score: 0
has text: @SlipFist thanks. Could you upload or paste your script somewhere? I guess we're missing something (e.g. is the shebang exactly on the first line of your script?).

http://stackoverflow.com/q/49624029
tagged with: scikit-learn
has title: SKlearn reshape warning for X and Y
favorite count: 0
type: Question
has body: I'm new to Machine Learning and working on a project using python(3.6), pandas, Numpy and SKLearn. My DataFrame is: discount tax total subtotal productid 3 0 20 13 002 10 3 106 94 003 46.49 6 21 20 004 Here's how I have performed the classification: df_full = pd.read_excel('input/Potential_Learning_Patterns.xlsx', sheet_name=0) df_full.head() #for convert to numeric df_full['discount'] = pd.to_numeric(df_full['discount'], errors='coerce') df_full['productdiscount'] = pd.to_numeric(df_full['discount'], errors='coerce') df_full['Class'] = ((df_full['discount'] &gt; 20) &amp; (df_full['tax'] == 0) &amp; (df_full['productdiscount'] &gt; 20) &amp; (df_full['total'] &gt; 100)).astype(int) print (df_full) # Get some sample data from entire dataset data = df_full.sample(frac = 0.1, random_state = 1) print(data.shape) data.isnull().sum() # Convert excel data into matrix columns = "invoiceid locationid timestamp customerid discount tax total subtotal productid quantity productprice productdiscount invoice_products_id producttax invoice_payments_id paymentmethod paymentdetails amount Class(0/1) Class".split() X = pd.DataFrame.as_matrix(data, columns=columns) Y = data.Class # temp = np.array(temp).reshape((len(temp), 1) Y = Y.values.reshape(Y.shape[0], 1) X.shape X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.06) X_test, X_dev, Y_test, Y_dev = train_test_split(X_test, Y_test, test_size = .5) # Check if there is Classification Values - 0/1 in training set and other set np.where(Y_train == 1) np.where(Y_test == 1) np.where(Y_dev == 1) # Determine no of fraud cases in dataset Fraud = data[data['Class'] == 1] Valid = data[data['Class'] == 0] # calculate percentages for Fraud &amp; Valid outlier_fraction = len(Fraud) / float(len(Valid)) print(outlier_fraction) print('Fraud Cases : {}'.format(len(Fraud))) print('Valid Cases : {}'.format(len(Valid))) # Correlation matrix corrmat = data.corr() fig = plt.figure( figsize = (12, 9)) sns.heatmap(corrmat, vmax = .8,…
accepted answer: http://stackoverflow.com/a/49624690
tagged with: python
has comment: http://stackoverflow.com/comment/86255518
has answer: http://stackoverflow.com/a/49624690
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34757653
tagged with: pandas
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86255570
tagged with: arrays
answer count: 1
linked to: http://stackoverflow.com/q/49839270
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/comment/86489970
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49737541
score: 0
has text: do you want to blend two images or merge them?

http://stackoverflow.com/comment/86272941
score: 0
has text: @Victor - Give me a sec.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49631535

http://stackoverflow.com/comment/86288978
type: Comment
type: QuestionComment
has text: Fix your indentation.
score: 2
comment on: http://stackoverflow.com/q/49640637

http://stackoverflow.com/a/49608234
type: Answer
answers question: http://stackoverflow.com/q/49608160
has body: A more pythonic way: sorted([b for b in a if b[0]=='x']) + sorted([c for c in a if c[0]!='x']) First we separate the list into two lists, those starting with X and those that don't. then we sort and join them together.
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49743838
answer count: 2
score: 5
has title: Predict single Image after training model in tensorflow
downvote count: 0
tagged with: machine-learning
possible better answer: http://stackoverflow.com/a/75042425
has body: I have trained model in tensorflow as follows : batch_size = 128 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weights = tf.Variable( tf.truncated_normal([image_size * image_size, num_labels])) biases = tf.Variable(tf.zeros([num_labels])) # Training computation. logits = tf.matmul(tf_train_dataset, weights) + biases loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits)) # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax( tf.matmul(tf_valid_dataset, weights) + biases) test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases) num_steps = 3001 with tf.Session(graph=graph) as session: tf.global_variables_initializer().run() print("Initialized") for step in range(num_steps): # Pick an offset within the training data, which has been randomized. # Note: we could use better randomization across epochs. offset = (step * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_data = train_dataset[offset:(offset + batch_size), :] batch_labels = train_labels[offset:(offset + batch_size), :] # Prepare a dictionary telling the session where to feed the minibatch. # The key of the dictionary is the placeholder node of the graph to be fed, # and the value is the numpy array to feed to it. feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} _, l, predictions = session.run( [optimizer, loss, train_prediction], feed_dict=feed_dict) if…
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/75042425
accepted answer: http://stackoverflow.com/a/49791466
upvote count: 5
has answer: http://stackoverflow.com/a/49791466
tagged with: python
type: AnsweredQuestion
tagged with: prediction

http://stackoverflow.com/comment/86514687
type: AnswerComment
has text: You can choose the padding, just pad with 0s or NaNs, boolean values make no difference
type: Comment
comment on: http://stackoverflow.com/a/49749664
score: 0

http://stackoverflow.com/comment/86421567
score: 0
comment on: http://stackoverflow.com/q/49704105
type: QuestionComment
type: Comment
has text: Possible duplicate of [Python: How can I execute a jar file through a python script](https://stackoverflow.com/questions/7372592/python-how-can-i-execute-a-jar-file-through-a-python-script)

http://stackoverflow.com/comment/86226867
comment on: http://stackoverflow.com/a/49609551
type: Comment
has text: pip _doesn't work_, so why you are recommending calling it? Also it's `python3`, not `python`.
score: 2
type: AnswerComment

http://stackoverflow.com/a/51724360
answers question: http://stackoverflow.com/q/49651279
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: You do not seem to have started a starting a hyperopt-mongo-worker to listen and respond to your requests as given in https://github.com/hyperopt/hyperopt/wiki/Parallelizing-Evaluations-During-Search-via-MongoDB hyperopt-mongo-worker --mongo=localhost:1234/test_trial --poll-interval=0.1 Hope this solves the issue.

http://stackoverflow.com/q/49674965
answer count: 1
downvote count: 0
upvote count: 1
has body: I have shared weights between two layers by the use of reuse property but I found that this actually shares the initial values of the variable. Optimizer updates the weights but that update is not reflected in the other layer. with tf.variable_scope('conv1'): layer1 = conv2d(x,output_features=out_features,kernel_size=kernel_size,padding=padding,strides=strides) with tf.variable_scope('conv1', reuse=True): layer1 = conv2d(x_shaped,output_features=out_features,kernel_size=kernel_size,padding=padding,strides=strides) how can I reflect the updates on both of the layers?
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/49675353
score: 1
tagged with: python
type: Question
type: UnansweredQuestion
has title: weight update between shared variables in Tensorflow

http://stackoverflow.com/comment/86285578
comment on: http://stackoverflow.com/a/49638802
type: Comment
has text: At the server: client_socket.send('Hello ' + client_name) TypeError: a bytes-like object is required, not 'str'. At the client: print('The server sent: ' + data) TypeError: must be str, not bytes.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86500333
score: 0
comment on: http://stackoverflow.com/q/49728460
has text: Again, this depends on the requirements (and I guess you can't afford to just scale out to deal with the amount of data)... but perhaps an SQL database (or at least one storing such small records individually) is not the best storage solution for a system like this. But that's not to say PostgreSQL (I haven't experience with MySQL) is inflexible, for many years I've dealt with a DB for 1.4 billion accounts, tens of millions online at a time, where we had stored procedures that parsed and generated binary compressed blobs -- using functions implemented in C++ :) ).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52749421
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49749981
has body: I had a case where the method was implemented in a base class and Pycharm couldn't find it. I solved it by importing the base class into the module I was having trouble with.

http://stackoverflow.com/q/49690256
tagged with: neural-network
tagged with: machine-learning
tagged with: python
tagged with: keras
has answer: http://stackoverflow.com/a/49690528
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49690747
has body: I wan't to train a simple multilayer perceptron with Keras. My input (x_train) is a np.array where every data point is represented by an 300 dimensional vector. My output should be a class 0,1 or 2. Shapes: x_train: (5708, 300) y_train: (5708,) shape: (300,) shape = x_train[0].shape model = Sequential() model.add(Dense(32, input_shape=shape)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(num_classes)) model.add(Activation('softmax')) model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x_train, y_train, epochs=5) After calling model.fit I get this error: ValueError: Error when checking target: expected activation_3 to have shape (None, 3) but got array with shape (5708, 1) What is wrong and what which layer is activation_3?
has title: Keras: expected activation_3 to have shape (None, 3) but got array with shape (5708, 1)
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/49690422
accepted answer: http://stackoverflow.com/a/49690422
type: Question
possible better answer: http://stackoverflow.com/a/49690528

http://stackoverflow.com/a/49665491
downvote count: 0
answers question: http://stackoverflow.com/q/49665291
type: Answer
score: 4
upvote count: 4
has body: Another solution: print([el2 for el2 in list2 if any(el1 in str(el2).split() for el1 in list1)])

http://stackoverflow.com/comment/86410518
type: QuestionComment
has text: Your strings look strange, what exactly are you showing there?
comment on: http://stackoverflow.com/q/49698551
score: 1
type: Comment

http://stackoverflow.com/a/49722962
has body: At first, the function read_csv was used incorrectly to read the input file. The columns are separated by spaces, not tab, thus sep should be '\s+' instead of '\t'. Also, there is no index column in the input file, thus the parameter index_col should not be set to 0. After having correctly read the input file into a DataFrame, we can convert it to a networkx graph using the function from_pandas_edgelist. import networkx as nx import pandas as pd df = pd.read_csv('protein.txt', sep='\s+') g = nx.from_pandas_edgelist(df, 'A', 'B')
score: 0
answers question: http://stackoverflow.com/q/49722640
type: Answer

http://stackoverflow.com/comment/86273753
type: QuestionComment
has text: @zwer What do you mean with "simple straight concatenation"? Just `+`/`sum`?
score: 0
comment on: http://stackoverflow.com/q/49631326
type: Comment

http://stackoverflow.com/comment/86328797
score: 1
comment on: http://stackoverflow.com/q/49658348
type: QuestionComment
type: Comment
has text: It sounds like you are asking pandas to do a lot of things that are pretty straightforward to do with SQL in the database itself. Maybe you could just use pandas to retrieve lots of little results sets? e.g., `df = pd.read_sql('select count * from TableA', session)`. Alternatively, if you must retrieve a large table in its entirety, it will probably be faster to use a command (specific to your database software) to do a bulk copy to a local CSV file, then use pandas to read in the CSV. Let me know if you want example code. Pandas is incredibly quick at reading CSV files but slow for SQL.

http://stackoverflow.com/comment/86404018
score: 2
comment on: http://stackoverflow.com/q/49695647
type: Comment
type: QuestionComment
has text: `if text in ['whole', 'sentence']` will always be false, because `text` is not set to `'whole'` or `'sentence'`.

http://stackoverflow.com/q/49712542
type: AnsweredQuestion
score: 0
has body: Why does file mode differ when using open() versus gzip.open() from the official gzip module? Python 2.7 on Linux. Same thing happens when using GzipFile on already open filehandle. I was thinking it's supposed to be transparent, so why do I see numeric modes and not rb / wb? Test script #!/usr/bin/env python """ Write one file to another, with optional gzip on both sides. Usage: gzipcat.py &lt;input file&gt; &lt;output file&gt; Examples: gzipcat.py /etc/passwd passwd.bak.gz gzipcat.py passwd.bak.gz passwd.bak """ import sys import gzip if len(sys.argv) &lt; 3: sys.exit(__doc__) ifn = sys.argv[1] if ifn.endswith('.gz'): ifd = gzip.open(ifn, 'rb') else: ifd = open(ifn, 'rb') ofn = sys.argv[2] if ofn.endswith('.gz'): ofd = gzip.open(ofn, 'wb') else: ofd = open(ofn, 'wb') ifm = getattr(ifd, 'mode', None) ofm = getattr(ofd, 'mode', None) print('input file mode: {}, output file mode: {}'.format(ifm, ofm)) for ifl in ifd: ofd.write(ifl) Test script output $ python gzipcat.py /etc/passwd passwd.bak input file mode: rb, output file mode: wb $ python gzipcat.py /etc/passwd passwd.bak.gz input file mode: rb, output file mode: 2 $ python gzipcat.py passwd.bak.gz passwd.txt input file mode: 1, output file mode: wb $ python gzipcat.py passwd.bak.gz passwd.txt.gz input file mode: 1, output file mode: 2 Secondary question: Is there any good reason behind that, or is it just an omission / unhandled case in gzip module? Background My actual use case is with Google BigQuery loader which requires the mode to be rb before using it as data source. Traceback below. But I prepared minimum test case above, to make this question more readable. # python -c 'import etl; etl.job001()' Starting job001. Processing table: reviews. Extracting reviews, time range [2018-04-07 17:01:38.172129+00:00, 2018-04-07 18:09:50.763283) Extracted 24 rows to reviews.tmp.gz in 2 s (8 rows/s). Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "etl.py", line 920, in wf_dimens…
has title: python open() vs gzip.open() and file mode
has comment: http://stackoverflow.com/comment/86570398
answer count: 1
downvote count: 1
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/86570131
has answer: http://stackoverflow.com/a/50116166
type: Question
upvote count: 1
tagged with: gzip
tagged with: python
accepted answer: http://stackoverflow.com/a/50116166
favorite count: 0
has comment: http://stackoverflow.com/comment/86485449

http://stackoverflow.com/comment/86284065
has text: just removed that line and run the code with evaluation of model after 10 epochs: original: 0.6359964006149502 retrained: 0.002937551016101346 :/
comment on: http://stackoverflow.com/a/49638076
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49653264
has body: You could use a CSV file as the output and have the delimiter set as a tab. import csv import xlrd import urllib.request csv_file = open('output.csv', 'wb') writer = csv.writer(csv_file , delimiter='\t') path= 'F:/4480/ASSIGNMENT.xlsx' data = xlrd.open_workbook(path) table = data.sheets()[0] writer.writerow(('image URL', 'not url')) for x in table.col_values(0): try: response = urllib.request.urlopen(x) # Write normal row writer.writerow((x, response.getheader('ETag'))) except: # Write invalid row writer.writerow((x, "not url")) # Finally close the file csv_file.close() Of course you can tweak it and use a comma(delimiter=',') as your delimiter if you want a normal CSV file. Edit: Changed sample code to use posters excel read feature
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49652560

http://stackoverflow.com/comment/86326811
score: 0
comment on: http://stackoverflow.com/q/49650449
type: QuestionComment
has text: I have fixed the indentation. You also don't need to explicitly close each file in the end. The `with` statement does that for you automatically.
type: Comment

http://stackoverflow.com/comment/86281302
type: Comment
has text: can you put some example data?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49636819

http://stackoverflow.com/a/49695683
has body: (Spyder maintainer here) This certainly looks like a bug. Please open an issue in our issues tracker, posting the above code so we can investigate what's happening in this case.
has comment: http://stackoverflow.com/comment/86520264
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49690523

http://stackoverflow.com/q/49625148
has body: Given a dataframe structured like: rule_id | ordering | sequence_id 1 | 0 | 12 1 | 1 | 13 1 | 1 | 14 2 | 0 | 1 2 | 1 | 2 2 | 2 | 12 I need to transform it into: rule_id | sequences 1 | [[12],[13,14]] 2 | [[1],[2],[12]] that seems like easy groupby into groupby to list operation - I can not however make it work in pandas. df.groupby(['rule_id', 'ordering'])['sequence_id'].apply(list) leaves me with rule_id ordering 1 0 [12] 1 [13,14] 2 0 [1] 1 [2] 2 [12] How does one apply another groupBy operation to furtherly concat results into one list?
has title: Pandas group by on groupby to list of lists
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49625165
upvote count: 17
has answer: http://stackoverflow.com/a/49625165
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
score: 17

http://stackoverflow.com/comment/86218687
type: Comment
score: 0
type: QuestionComment
has text: They are the same things, just aliases, I'm guessing they exist to keep backward compatibility.
comment on: http://stackoverflow.com/q/49605958

http://stackoverflow.com/comment/86463726
score: 0
comment on: http://stackoverflow.com/a/49724667
type: Comment
has text: No idea. This solution worked well. I guess those suggested after are more concise? But I don't think people should downvote this as it worked well.
type: AnswerComment

http://stackoverflow.com/comment/86401421
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49694084
type: QuestionComment
has text: @SmokeyBaxter let me check it out. I hope I can also login via Selenium.

http://stackoverflow.com/comment/86213397
comment on: http://stackoverflow.com/a/49602508
score: 0
has text: This is exactly what I was looking! Thanks a lot!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86369939
has text: @AntonvBR ... Indeed, if dates is not an index, boolean indexing with a mask would be needed. Let's await OP's confirmation.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49678838
type: Comment

http://stackoverflow.com/q/49632380
has comment: http://stackoverflow.com/comment/86272329
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/86271830
linked to: http://stackoverflow.com/q/364802
answer count: 1
has comment: http://stackoverflow.com/comment/86277337
has comment: http://stackoverflow.com/comment/86271856
has answer: http://stackoverflow.com/a/49634205
type: Question
has title: Syntax: Compacted For Loop in python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86272193
has body: What is going on here? with open('contractors.txt','r') as in_file: stripped = (line.strip() for line in in_file) lines = (line for line in stripped if line) Is this a syntactic equivalent to: for line in in_file: stripped = line.strip() for line in stripped: lines = line

http://stackoverflow.com/a/49657489
type: Answer
answers question: http://stackoverflow.com/q/49652081
score: 2
has body: I tried using the on_show event, but was not successful, so I used the on_draw event instead. Here is your code with the on_pos references removed and the on_draw implemented: from kivy.app import App from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder class KivyGuiApp(App): def build(self): return root_widget ''' interface for global widget access ''' global_widgets = {} def register_widget(self, widget_object): print(widget_object.gid) def print_widgets(self): for w in self.global_widgets: print(w) class MyBox(BoxLayout): pass root_widget = Builder.load_string(""" MyBox: gid: "4" name: 'screen_manager' SimpleLayout: &lt;SimpleLayout@BoxLayout&gt;: gid: "1" name: 'simple_layout_rule' TextInput: gid: "inputB" TextInput: gid: "inputC" TextInput: gid: "inputD" """) def on_draw(*args): app = App.get_running_app() for widget in root_widget.walk(): app.register_widget(widget) if __name__ == '__main__': Window.bind(on_draw=on_draw) KivyGuiApp().run()
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86343398

http://stackoverflow.com/comment/86378940
has text: Have you made sure that the ISBN column doesn't have hidden characters that could make the value in the row with the same ISBN number not match? Without having a sample of the data to test things it's hard to be able to help.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49683262
type: Comment

http://stackoverflow.com/comment/86361012
score: 1
has text: That error is very descriptive. That is invalid syntax. Just look at how to declare variables in python to see that.
comment on: http://stackoverflow.com/q/49675048
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49701229
answers question: http://stackoverflow.com/q/49700534
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Is there a way I can do this similar to my original method? Yes; two ways about this would be to use map() or a list comprehension. &gt;&gt;&gt; s = "Hi there" &gt;&gt;&gt; list(map(list, s)) [['H'], ['i'], [' '], ['t'], ['h'], ['e'], ['r'], ['e']] &gt;&gt;&gt; [[i] for i in s] # or: [list(i) for i in s] [['H'], ['i'], [' '], ['t'], ['h'], ['e'], ['r'], ['e']] Also, why does my original method not do what I want it to do? The problem lines are here: for i in string_list: i = list(i) As you can read more about in this question, assinging to i within the loop does not affect the elements of string_list themselves. To be specific, for i in string_list creates a new variable i at each turn of the loop, the last of which will still exist after the loop terminates. In short, it is good practice to avoid trying to modify the container (string_list) over which you're looping.
accepted answer of: http://stackoverflow.com/q/49700534
score: 1
type: Answer

http://stackoverflow.com/comment/86462736
score: 0
type: Comment
type: AnswerComment
has text: @stuntmachine you could just as easily use a normal function
comment on: http://stackoverflow.com/a/49724192

http://stackoverflow.com/q/49643206
tagged with: youtube
linked to: http://stackoverflow.com/q/40713268
tagged with: video
linked to: http://stackoverflow.com/q/68945080
has comment: http://stackoverflow.com/comment/86294077
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61492831
downvote count: 3
has answer: http://stackoverflow.com/a/49643669
possible better answer: http://stackoverflow.com/a/61492831
favorite count: 0
has title: AttributeError: 'YouTube' object has no attribute 'get_videos'
score: 9
type: Question
upvote count: 12
linked to: http://stackoverflow.com/q/49185538
answer count: 2
tagged with: pytube
tagged with: download
accepted answer: http://stackoverflow.com/a/49643669
tagged with: python
has body: While trying to download a YouTube video from python, I come across this error AttributeError: 'YouTube' object has no attribute 'get_videos'. Last line causes the error. import pytube link = "" yt = pytube.YouTube(link) videos = yt.get_videos() Thanks!

http://stackoverflow.com/q/49691845
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86396728
has body: I am using thorns and cochlea to generate a spiketrain. The result is in the form of a pandas.DataFrame in the form, that the column 'spikes' contains the array of spiketimes that I need. DataFrame generated by thorns When I try to extract it with a = df.as_matrix(['spikes']) the resulting matrix will always look like this: a = [[array([1,2,3])][array([4,5,6])]] to further use the data, i need the form: a= [[1,2,3][4,5,6]] how can I delete the array() part? This is the code I use: import cochlea import thorns.waves as wv #generating the spiketrain sound = wv.ramped_tone(fs=100e3,freq=500,duration=0.3,dbspl=60) spiketrain=cochlea.run_zilany2014(sound,fs=100e3,anf_num=(2,0,0),cf=500,seed=0,species='human') print spiketrain #trying to extrakt spiketime information a = spiketrain.as_matrix(['spikes']) print 'a=' print a
tagged with: arrays
tagged with: python
has title: Extracting an array from a dataframe column that contains an array
has comment: http://stackoverflow.com/comment/86397540
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/49692597
has comment: http://stackoverflow.com/comment/86396996
tagged with: pandas
has comment: http://stackoverflow.com/comment/86397074
has answer: http://stackoverflow.com/a/49692597
answer count: 1
has comment: http://stackoverflow.com/comment/86395616
has comment: http://stackoverflow.com/comment/86397587

http://stackoverflow.com/q/49616864
favorite count: 0
has body: I've been trying to get my line length hard limited to 80 characters in Atom. I have found in the setting the "max screen line length" but I cannot set a value there. I've set the soft wrap but this doesn't seem to work either. I checked packages and nothing from a specific language is driving it either. I found the autoflow package but it doesn't give a clear indication of how to drive it to 80 characters. Any advice on how to implement this would be helpful. I understand that 80 characters is the PEP 8 standard and I don't want to start off with issues.
tagged with: atom-editor
type: Question
type: UnansweredQuestion
tagged with: pep8
answer count: 1
downvote count: 0
score: 16
tagged with: python
has answer: http://stackoverflow.com/a/49993558
has title: Limiting line length in Atom
upvote count: 16

http://stackoverflow.com/comment/86289116
comment on: http://stackoverflow.com/q/49640641
score: 0
type: Comment
type: QuestionComment
has text: Sorry, I am stuck at somewhere and I can't change the whole code just to use subprocess, I didn't accept because there was this red message popping each time I tried to accept. Why are you angry? sorry...

http://stackoverflow.com/q/49606715
tagged with: python
has comment: http://stackoverflow.com/comment/86220146
score: 0
has comment: http://stackoverflow.com/comment/86220147
answer count: 0
duplicate of: http://stackoverflow.com/q/4599016
type: Question
has body: I use globals() to get the all the variable and functions, but could not find function abs. So wondering which namespace is in for this kind of global python functions ?
has title: Which namespace is python global functions in
linked to: http://stackoverflow.com/q/4599016
type: UnansweredQuestion

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/49723274
tag name: kivy-language
tags question: http://stackoverflow.com/q/49656005

http://stackoverflow.com/a/49619218
answers question: http://stackoverflow.com/q/49607111
score: 0
accepted answer of: http://stackoverflow.com/q/49607111
has body: So I got it working by removing all djcelery instances and upgrading Django from 1.11 to 2.0.3 By the way I'm using Celery 4.1.0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/86238643
type: Comment
type: QuestionComment
has text: how can I make it better?
score: 0
comment on: http://stackoverflow.com/q/49615290

http://stackoverflow.com/comment/86481167
score: 0
type: AnswerComment
has text: array indexing starts at 0, so you are accessing 2nd row, 2nd col and 3rd element
comment on: http://stackoverflow.com/a/49733565
type: Comment

http://stackoverflow.com/comment/86425714
score: 0
type: Comment
type: QuestionComment
has text: i'm sorry if it is, but i would like a comprehensive answer on this query
comment on: http://stackoverflow.com/q/49706231

http://stackoverflow.com/q/49748266
tagged with: design-patterns
downvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31155388
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/49752066
tagged with: algorithm
possible better answer: http://stackoverflow.com/a/49748478
has answer: http://stackoverflow.com/a/49928284
has answer: http://stackoverflow.com/a/49752066
tagged with: python
has title: Algorithms to achieve reasonable result with most economic efforts
has body: Suppose that there are six kinds of problems to be handled when reading a book, I illustrate the details as follow: while True: if encounter A : handle A #during handling the problem, it might spawn new problems of #A, B, C, D, E, produce (A,B..E or null) continue if B occurs: handle B #during hanlding the problem, it might spwan new problems #A, B, C, D, E, produce (A,B..E or null) continue if C happens: handle C produce (A,B..E or null) continue ... if there are no problmes: break Assume I have 3 problems, the above program might endless loop on first one and never touch the second. Take an example that I am reading a book, 'Problem A' is defined as encounter a 'new word', handle it is to look up dictionary. When looking up, I might come acorss another new word, another and another. In this case, I will never end up reading one sentence of a book. As a solution, I introduce a container to collect problems, value-weighted them then determine to execute which one. def solve_problems(problems) problem_backet = list(problems) while True: if problem_backet not is null: #value-weighted all the problem #and determine one to implement value_weight problems problem = x if problem == A: handle A problem_backet.append(new_problem) continue if problem == B: handle B problem_backet.append(new_problem) continue ... if problem_backet is null: return I tried alternatively to seek inspiration and improve efficiency. def solve_problems(problems): global problem_backet problem_backet = list(problems) value_weight problems problem = x if problem == A: handle A problem_backet.append(new_problem) solve_problems(problem_backet) if problem == B: handle B problem_backet.append(new_problem) solve_problems(problem_backet) if problem == C: handle C problem_backet.append(new_problem) solve_problems(problem_backet) ... if problem_backet is null: return Again, the value_weighted process consume huge efforts and time. How to solve such a problem in a proper algorithms?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49748478
upvote count: 1

http://stackoverflow.com/a/49668755
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86347663
has comment: http://stackoverflow.com/comment/86347527
upvote count: 1
answers question: http://stackoverflow.com/q/49668709
has body: You can. Here's a list comprehension to do it. You really cannot vectorize this due to the inherent nature of this problem. df['values'] = [ list(range(x, y + 1)) for x, y in zip(df['min'], df['max']) ]
accepted answer of: http://stackoverflow.com/q/49668709
type: Answer
has comment: http://stackoverflow.com/comment/86347545
has comment: http://stackoverflow.com/comment/86347854
has comment: http://stackoverflow.com/comment/86347434
score: 1

http://stackoverflow.com/a/49631500
downvote count: 0
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49631178
has comment: http://stackoverflow.com/comment/86270398
has body: Functions aren't mutable in general; but they may have references to data that is. In your snippet, this reference is a little unclear, but i only occurs once in the function body, as a read. It therefore reads from some outer scope, typically the function or module your for loop is contained within. Because this happens to be a shared context, every addi function will end up with the same i. Another issue is that you're using the name addi on every iteration, and the function never appeared under another name. So whatever addi functions were defined earlier are lost. This leads us to the third question; why would you want to create names (such as function names) dynamically? It's almost always better to use a collection, such as the d dictionary in jpp's answer. Otherwise, what code would even refer to the functions you created? All that said, it is still possible to do what you asked for, albeit very strange. Here's one way: def addfunc(n): def addn(x): return x+n return addn for i in range(1,10): globals()['add{}'.format(i)] = addfunc(i) This abuses globals to inject dynamically created names into the module's namespace, and nests each of these functions within another to create the namespaces holding their individual n values. Another classic hack was using a default argument, and partial application of operator.add is a neater functional style.

http://stackoverflow.com/a/49721329
has comment: http://stackoverflow.com/comment/86460765
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49720956
type: Answer
accepted answer of: http://stackoverflow.com/q/49720956
has comment: http://stackoverflow.com/comment/86456772
has body: The first error occurs because you pass distributed object into db.mynewcollection.insert_one. The second error occurs because you initalize database connection on the driver, and in general, connection objects cannot be serialized. While there exist a number of Spark / MongoDB connectors you should take a look at (Getting Spark, Python, and MongoDB to work together) a generic pattern is to use foreachPartition. Define helper def insert_partition(xs): connection = pymongo.MongoClient('....',...) db = connection['twitter1'] db.authenticate('..','...') db.mynewcollection.insert_many(xs) and then: def to_dict(s): return ... # Convert input to a format acceptable by `insert_many`, for example with json.loads tweets.map(to_dict) \ .foreachRDD(lambda rdd: rdd.foreachPartition(insert_partition))
has comment: http://stackoverflow.com/comment/86528802
has comment: http://stackoverflow.com/comment/86458126
has comment: http://stackoverflow.com/comment/86456574
score: 0
has comment: http://stackoverflow.com/comment/86471143
has comment: http://stackoverflow.com/comment/86475044

http://stackoverflow.com/q/49663474
has comment: http://stackoverflow.com/comment/86658641
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86338215
has answer: http://stackoverflow.com/a/49711804
has title: OpenCV Python: cv2.VideoCapture can only find 2 of 3 cameras, Windows Camera app finds all
has comment: http://stackoverflow.com/comment/86658575
has comment: http://stackoverflow.com/comment/86542433
type: UnansweredQuestion
score: 18
has body: I'm trying to create 3 real-time capture frames with webcams into a USB hub into my laptop. Using the "camera" app on Windows, I can change the camera source one at a time and confirm that all 3 webcams are working. However, my OpenCV Python code can only ever find two. (Quick notes on the USB - it's a USB 3.0 hub, laptop port is USB 3, and I even have an active USB female-to-male cable going into the laptop, so given this and the Windows app working, I generally trust the hardware.) Below I did some raw testing of cv2.VideoCapture(src) with the results below: cams_test = 10 for i in range(0, cams_test): cap = cv2.VideoCapture(i) test, frame = cap.read() print("i : "+str(i)+" /// result: "+str(test)) That first argument, test, returns True/False depending on if the frame can be read. Results: i : 0 /// result: True i : 1 /// result: True i : 2 /// result: False i : 3 /// result: False i : 4 /// result: False i : 5 /// result: False i : 6 /// result: False i : 7 /// result: False i : 8 /// result: False i : 9 /// result: False As with other sample code I tested, only 2 webcams can be registered and show frames in Python. And the Windows 10 camera app lets me scroll between all 3 working and connected webcam feeds. I know I can create multiple, like 3+, cv2.imshow() frames if I use the caps that work. My project involves doing this to show realtime USB webcam feeds on the laptop from multiple cameras. Any help and advice appreciated; also potentially interested in (Python-based) alternative solutions. Cheers.
has comment: http://stackoverflow.com/comment/86524842
tagged with: python
has comment: http://stackoverflow.com/comment/86525091
has comment: http://stackoverflow.com/comment/87031092
answer count: 4
tagged with: opencv
upvote count: 19
has comment: http://stackoverflow.com/comment/86382698
has answer: http://stackoverflow.com/a/49976672
tagged with: camera
linked to: http://stackoverflow.com/q/21792909
has comment: http://stackoverflow.com/comment/86541474
has answer: http://stackoverflow.com/a/49833728
downvote count: 1
has answer: http://stackoverflow.com/a/49901961

http://stackoverflow.com/a/49619521
answers question: http://stackoverflow.com/q/49619443
downvote count: 0
has body: Previous solution: You could use .str.split() and do this: df.mill = df.mill.str.split(' –').str[0]. Update: Seeing you got a few constraints you could build up your own returning function (called func below) and put any logic you want inside there. This will loop through all strings split by - and if Mill is in the first word you return. In other case I recommend Wen's solution. import pandas as pd df = pd.DataFrame({'id': ["1", "2", "3","4","5"], 'mill': ["Company A Palm Oil Mill – Special Company A of CC Ltd", "Company X POM – Company X Ltd","DDDD Mill – Company New and Old Ltd", "Company Not Special – R Mill","Greatest Company – Great World POM"]}) def func(x): #Split array ar = x.split(' – ') # If length is smaller than 2 return value if len(ar) &lt; 2: return x # Else loop through and apply logic here for ind, x in enumerate(ar): if x.lower().endswith(('mill', 'pom')): return x # Nothing found, return x return x df.mill = df.mill.apply(func) print(df) Returns: id mill 0 1 Company A Palm Oil Mill 1 2 Company X POM 2 3 DDDD Mill 3 4 R Mill 4 5 Great World POM
upvote count: 1
has comment: http://stackoverflow.com/comment/86246155
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86246136

http://stackoverflow.com/comment/88137675
has text: Thank you! I'm not using transactions as i need to make sure in the best way possible that everything is written on the db, if it fails i want the least number of objects to not be created. Example, i'm sniffing packets and storing them.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49760990

http://stackoverflow.com/a/49652835
downvote count: 0
type: Answer
has body: Maybe using min df['indicator']=(df[columns]!=0).min(axis=1).astype(bool)
answers question: http://stackoverflow.com/q/49652404
upvote count: 2
score: 2

http://stackoverflow.com/comment/86531084
has text: Further investigation shows the that virtual environment was previously being created as a sub of the project folder, where now it is being created in a separate folder. Not sure how to adjust that nor whether it will be impactful.
comment on: http://stackoverflow.com/q/49755639
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49706655
type: Question
has comment: http://stackoverflow.com/comment/86427922
has comment: http://stackoverflow.com/comment/86428523
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86427737
answer count: 1
tagged with: python
has body: I am creating a simple scrapy project to better understand how to use it, and what I intend to do is crawl the questions page for StackOverflow. My spider is called first and here's the content of the file. # -*- coding: utf-8 -*- import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class FirstSpider(CrawlSpider): name = 'first' allowed_domains = ['stackoverflow.com'] start_urls = ['https://stackoverflow.com/questions'] rules = ( Rule(LinkExtractor(allow=['/questions/\?page=\d&amp;sort=newest']), callback='parse_item', follow=True), ) def parse_item(self, response): item = scrapy.Item() selector_list = response.css('.question-summary') for selector in selector_list: item['question'] = selector.css('h3 a::text').extract() item['votes'] = selector.css('.vote-count-post strong::text').extract() item['answers'] = selector.css('.status strong::text').extract() item['views'] = selector.css('.views::text').extract() item['username'] = selector.css('.user-details a::text').extract() item['user-link'] = selector.css('.user-details a::attr(href)').extract() return item It should then traverse the pages of the questions gathering the info. I can get the data from the shell but fail when I try to crawl or save the output. Here's the output of scrapy crawl first: 2018-04-07 13:57:06 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: scraper) 2018-04-07 13:57:06 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9 .5, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 2.7.14 ( v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)], pyOpenSS L 17.5.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.2.2, Platform Windows-XP- 5.1.2600-SP3 2018-04-07 13:57:06 [scrapy.crawler] INFO: Overridden settings: {'NEWSPIDER_MODU LE': 'scraper.spiders', 'SPIDER_MODULES': ['scraper.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'scraper'} 2018-04-07 13:57:06 [scrapy.middleware] INFO: Enabled extensions: […
score: 0
has comment: http://stackoverflow.com/comment/86428332
has comment: http://stackoverflow.com/comment/86428464
has title: Scrapy crawl: Crawled 0 pages
linked to: http://stackoverflow.com/q/21788939
tagged with: scrapy
has answer: http://stackoverflow.com/a/49721484
has comment: http://stackoverflow.com/comment/86428487

http://stackoverflow.com/a/49658504
has comment: http://stackoverflow.com/comment/86331511
downvote count: 0
has body: When running your example I was not able to replicate your results. Instead I observe the desired behavior. Below are the settings I used. firstTest.robot *** Settings *** Library String *** Test Cases *** TC [Tags] TestCLI Log ${my_vars} @{list_of_vars} Split String ${my_vars} Log @{list_of_vars}[0] Log @{list_of_vars}[1] The additional command line variables -v my_vars:one,two -E space:, need to be set on the run configuration. This then results in the following message log: Starting test: RunWithVars.firstTest.TC 20180404 20:45:06.445 : INFO : one two 20180404 20:45:06.447 : INFO : @{list_of_vars} = [ one | two ] 20180404 20:45:06.448 : INFO : one 20180404 20:45:06.449 : INFO : two Ending test: RunWithVars.firstTest.TC And console log. I've seperated the command into seperate lines and removed some of the --listener folder path for readability. Command: C:\Python\RF_P27\Scripts\python.exe -m robot.run --listener C:\Users\..\TestRunnerAgent.py:51805 -s RunWithVars.FirstTest -v my_vars:one,two -E space:, C:\TA\W\StackOverflow\RunWithVars Suite Executor: Robot Framework 3.0.2 (Python 2.7.13 on win32) ============================================================================== RunWithVars ============================================================================== RunWithVars.firstTest ============================================================================== TC | PASS | ------------------------------------------------------------------------------ RunWithVars.firstTest | PASS | 1 critical test, 1 passed, 0 failed 1 test total, 1 passed, 0 failed ============================================================================== RunWithVars | PASS | 1 critical test, 1 passed, 0 failed 1 test total, 1 passed, 0 failed ============================================================================== Output: C:\TA\W\StackOverflow\RunWithVars\output.xml Log: C:\TA\W\StackOverflow\RunWithVars\log.html Report: C:\TA\W\StackOverflow\RunWithVars\report.html
has comment: http://stackoverflow.com/comment/86327608
answers question: http://stackoverflow.com/q/49654291
has comment: http://stackoverflow.com/comment/86328989
upvote count: 1
has comment: http://stackoverflow.com/comment/86328574
type: Answer
has comment: http://stackoverflow.com/comment/86331424
has comment: http://stackoverflow.com/comment/86357723
has comment: http://stackoverflow.com/comment/86329199
score: 1
has comment: http://stackoverflow.com/comment/86340646

http://stackoverflow.com/comment/103303216
score: 1
has text: This response does not mention anything about the a `/resources` option best practice in then python context.
type: Comment
comment on: http://stackoverflow.com/a/49677691
type: AnswerComment

http://stackoverflow.com/comment/86453011
has text: In short, pipes and processes and signals are confusing. Gotcha. I didn't understand half of that, but I appreciate the explanation nonetheless, thanks. I guess I have some reading on wikipedia to do.
score: 0
comment on: http://stackoverflow.com/q/49719673
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86297056
type: QuestionComment
has text: Please if you see ^M because of some reason I always use `Ctrl + J` instead of `Enter`
comment on: http://stackoverflow.com/q/49643773
score: 1
type: Comment

http://stackoverflow.com/q/49600944
has body: For times series prediction I am using pandas. this is a some sample of my data frame: Close Price DateTime 2017-01-02 23:00:00 1.04630 2017-01-02 23:30:00 1.04575 2017-01-03 00:00:00 1.04672 2017-01-03 00:30:00 1.04662 2017-01-03 01:00:00 1.04766 ...... in my X matrix for sklearn prediction I want to have something like this: use 3 past row as input for making a new row X: ClosePrice ClosePrice-1 ClosePrice-2 ClosePrice-3 2017-01-03 00:30:00 1.04662 1.04672 1.04575 1.04630 2017-01-03 01:00:00 1.04766 1.04662 1.04672 1.04575 ... what is the best method? is there a way to use pandas function to do this?
score: 0
tagged with: pandas
type: Question
has title: Time series prediction, make new X, new row from some past rows
tagged with: time-series
has answer: http://stackoverflow.com/a/49601390
type: UnansweredQuestion
answer count: 1
tagged with: python

http://stackoverflow.com/a/49628737
upvote count: 3
has comment: http://stackoverflow.com/comment/86727156
has body: I suppose it is a bug (or behavior) introduced in the very last version of PyCharm. Indeed, it has been happening to me since the last update I recently installed. However, I temporary ignored these unresolved references in PyCharm to avoid the annoying and misleading warnings. To do so, if you are importing os.path this way (e.g.): from os.path import join Go to PyCharm preferences -> Editor -> Inspections Then, look for "Unresolved references" under "Python" and add the following entries: os.path join Hope this helps, Giuliano
answers question: http://stackoverflow.com/q/49617465
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/a/49735597
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86529972
type: Answer
has body: Cleaning up the code This code is pretty good; there's not much cleaning up to do. You shouldn't return self from __enter__ if the context manager isn't designed to be used with the as keyword. is should be used when checking classes, since they are singletons... but you should prefer issubclass to properly emulate exception handling. Implementing these changes gives: from celery.exceptions import SoftTimeLimitExceeded class Manager: def __enter__(self): pass def __exit__(self, error_type, error, tb): if issubclass(error_type, SoftTimeLimitExceeded): logger.info('job killed.') # swallow the exception return True @task def do_foo(): with Manager(): run_task1() run_task2() run_task3() Debugging I created a mock environment for debugging: class SoftTimeLimitExceeded(Exception): pass class Logger: info = print logger = Logger() del Logger def task(f): return f def run_task1(): print("running task 1") raise SoftTimeLimitExceeded def run_task2(): print("running task 2") def run_task_3(): print("running task 3") Executing this and then your program gives: &gt;&gt;&gt; do_foo() running task 1 job killed. This is the expected behaviour. Hypotheses I can think of two possibilities: Something in the chain, probably run_task1, is asynchronous. celery is doing something weird. I'll run with the second hypothesis because I can't test the former. I've been bitten by the obscure behaviour of a combination between context managers, exceptions and coroutines before, so I know what sorts of problems it causes. This seems like one of them, but I'll have to look at celery's code before I can go any further. Edit: I can't make head nor tail of celery's code, and searching hasn't turned up the code that raises SoftTimeLimitExceeded to allow me to trace it backwards. I'll pass it on to somebody more experienced with celery to see if they can work out how it works.
answers question: http://stackoverflow.com/q/49688481
has comment: http://stackoverflow.com/comment/86530933

http://stackoverflow.com/comment/86476553
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49731391
has text: If you get `WAIT_TIMEOUT`, you have a correct handle (although the conversions look fishy). Had you passed an invalid handle, you'd get an error instead. The real question now is: Why do you expect to *not* receive a timeout?

http://stackoverflow.com/q/49632311
has answer: http://stackoverflow.com/a/49644271
type: AnsweredQuestion
has body: Suppose the following minimal code: x = input("Numeral: ") y = input("Numeral: ") if x &lt; y: print(f'{x} is less than {y}.') if x &gt; y: print(f'{x} is greater than {y}.') else: print(f'{x} is equal to {y}.') I feed it and come by $ python3 draft.py Numeral: 1 Numeral: 0 1 is greater than 0. It runs properly, then change the order to input: $ python3 draft.py Numeral: 0 Numeral: 1 0 is less than 1. 0 is equal to 1. The else branch was executed. Does else branch only pair to its nearest 'if'? What's the mechanism behind it?
has answer: http://stackoverflow.com/a/49632426
possible better answer: http://stackoverflow.com/a/49632426
has answer: http://stackoverflow.com/a/49632375
has comment: http://stackoverflow.com/comment/86271663
score: -6
answer count: 4
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/86271973
has answer: http://stackoverflow.com/a/49632338
has title: `else` branch only pair to its nearest 'if'
tagged with: python
downvote count: 6
linked to: http://stackoverflow.com/q/49627409
accepted answer: http://stackoverflow.com/a/49632375
has comment: http://stackoverflow.com/comment/86271996

http://stackoverflow.com/q/49619685
tagged with: python-3.x
has title: Tracing Entry that uses a StringVar has no effect on Label
tagged with: python
has body: Learning to use Tkinter and following an online tutorial. This is an example given where text is entered and then label will update accordingly to the input text field. I'm trying it in Python3 on Mac and on Raspberry Pi and I don't see the effect of trace, hence the label doesn't get modified by the Entry. Any help would be appreciate (or any other simple example of how to use Entry and Trace together) Thanks. from tkinter import * class HelloWorld: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button( frame, text="Hello", command=self.button_pressed ) self.button.pack(side=LEFT, padx=5) self.label = Label(frame, text="This is a label") self.label.pack() a_var = StringVar() a_var.trace("w", self.var_changed) self.entry = Entry(frame,textvariable=a_var) self.entry.pack() def button_pressed(self): self.label.config(text="I've been pressed!") def var_changed(self, a, b, c): self.label.config(text=self.entry.get()) def main(): root = Tk() root.geometry("250x150+300+300") ex = HelloWorld(root) root.mainloop() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/86246547
accepted answer: http://stackoverflow.com/a/49620233
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: tkinter
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86246441
tagged with: raspberry-pi3
tagged with: macos
has answer: http://stackoverflow.com/a/49620233
favorite count: 0
has comment: http://stackoverflow.com/comment/86246461
type: Question

http://stackoverflow.com/a/56449062
has body: for i in range(2,number//2): if(number%i==0): return False return True def rotations(num): count=0 rotation_lst=[] num=str(num) while(count&lt;len(num)): num=num[1:]+num[0] count+=1 rotation_lst.append(int(num)) rotation_lst1=sorted(rotation_lst,key=int) return rotation_lst1 def get_circular_prime_count(limit): count=0 for i in range(1,limit+1): a=rotations(i) for j in a: if(check_prime(j)): count+=1 return count print(get_circular_prime_count(1000) ```
score: 0
answers question: http://stackoverflow.com/q/49663638
type: Answer

http://stackoverflow.com/q/49654377
has body: I have a function in Python Flask to add my data in MongoDB. Date data being collected from form is in text format but I want to save it in date format in MongoDB. So I am converting the format before inserting it to Mongo. @app.route('/addtaskdb/', methods=["GET","POST"]) def addtaskdb(): try: print("***********entered in addtaskdb function ") if request.method == 'POST': data = request.form.to_dict() print(type(data)) month,day, year = map(int, data['deliverydate'].split("/")) print(month) dbdate = datetime.date(year, month, day) data['deliverydate1'] = dbdate db.tasks.insert(data) return redirect(url_for('dashboard')) except Exception as e: flash(e) return redirect(url_for('dashboard')) I am getting following error. builtins.TypeError TypeError: Object of type 'InvalidDocument' is not JSON serializable Traceback (most recent call last) File "C:\New folder\lib\site-packages\flask\app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "C:\New folder\lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "C:\New folder\lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "C:\New folder\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\New folder\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\New folder\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request return self.finalize_request(rv) File "C:\New folder\lib\site-packages\flask\app.py", line 1632, in finalize_request response = self.process_response(response) File "C:\New folder\lib\site-packages\flask\app.py", line 1858, in process_response self.save_session(ctx.session, response) File "C:\New folder\lib\site-packages\flask\app.py", line 924, in save_session return self.session_interface.save_session(self, session, response) File "C:\New folder\lib\site-packages\flask\sessions.py", line 363, in s…
type: UnansweredQuestion
tagged with: python
tagged with: flask
score: -1
has comment: http://stackoverflow.com/comment/86317693
has comment: http://stackoverflow.com/comment/86319736
has title: Add dictionary to MongoDB from Flask
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49662076
type: Question
tagged with: mongodb

http://stackoverflow.com/comment/86356693
type: Comment
has text: Of course, but you've seen the sort of mess we get with on SO with overuse of `global`. I've used `global` maybe twice in my entire development history. Beginners tend to use it if they know about it because they find it conceptually easy, but it causes a lot of problems they don't anticipate so I tend not to even tell them it exists unless surrounded by a lot of warnings.
type: AnswerComment
comment on: http://stackoverflow.com/a/49672949
score: 1

http://stackoverflow.com/comment/86411959
score: 0
has text: Does `pd.read_json` not do the trick? https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html
comment on: http://stackoverflow.com/q/49697737
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/124673380
comment on: http://stackoverflow.com/a/55694571
score: 1
type: Comment
type: AnswerComment
has text: You mean `self.classifier(u)`?

http://stackoverflow.com/a/49639423
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49619412
has body: So, the issue is the program could not find the compiler.js file. I had to made few changes to incorporate this file in the PyInstaller executable. Under ..\bokeh\util the compiler.py file is present. In this file under the nodejs_compile function, def nodejs_compile(code, lang="javascript", file=None): compilejs_script = join(bokehjs_dir, "js", "compiler.js") ... ... it is using bokehjs_dir, which is already defined in the file as bokehjs_dir = settings.bokehjsdir() bokehjs_dir is a variable which is eventually appended by other variables and makes the path for the program to reach compiler.js file ) so the value of bokehjs_dir is set as an absolute path to the bokeh directory, which caused the problem as the generated executable could not access that. so just comment out that line and add the code snippet as shown below, import bokeh #bokehjs_dir = settings.bokehjsdir() if getattr(sys, 'frozen', False): # we are running in a bundle temp_dir = sys._MEIPASS else: # we are running in a normal Python environment temp_dir = os.path.dirname(bokeh.__file__) bokehjs_dir = temp_dir + '\\server\\static' As mentioned in the already referenced post, what it does is when the code is frozen, it redirects the program to look into sys._MEIPASS (temporary folder created by PyInstaller to unpack the bundle). Now all that needs to be done is the inclusion of ..\bokeh\server\static\ folder in the bundle with the same name as static. This can be done by editing the pyinstaller .spec file. The edited .spec file looks like the follwing, a = Analysis(['module1.py'], pathex=['C:\\Users\\user_name\\Desktop\\PythonFiles'], binaries=[], datas=[(r'C:\Python27\Lib\site-packages\bokeh\core\_templates', '_templates'), (r'C:\Python27\Lib\site-packages\bokeh\server', 'server')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) By editing this we made sure that the required compiler.js got bundled in the…
has comment: http://stackoverflow.com/comment/89789292
type: Answer

http://stackoverflow.com/q/49689780
tagged with: python
has answer: http://stackoverflow.com/a/49690123
score: 0
tagged with: pandas-groupby
has title: Cartesian Product on Pandas Groupby
has body: I have a dataframe df: col1 col2 col3 JHGK B name1 JHGK B name2 JHGK C name3 OPDR B name4 ERTH B name5 ERTH C name6 After doing a groupby on col1, I would like to do cartesian product between( distinct col3 values where col2 = B and distinct col3 values where col2 = C) Result dataframe: final: col1 n1 n2 JHGK name1 name3 JHGK name2 name3 ERTH name5 name6
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: cartesian-product

http://stackoverflow.com/q/49601155
has comment: http://stackoverflow.com/comment/86213822
tagged with: python
has title: How to login and get data using python request?
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86213760
tagged with: python-requests
tagged with: https
type: Question
has body: I am trying to make a script which will login to a url and then get data from it. The webpage is built using jsp, The sample login page looks like this.. Login Username Password so now i want to login and want to get data from the page after login. So i tried using request as follows; import requests from lxml import html USERNAME = "example_user" PASSWORD = "example_password" LOGIN_URL = "https://www.loginurl.com" def main(): session_requests = requests.session() result = session_requests.get(LOGIN_URL) tree = html.fromstring(result.text) payload = { "userid": USERNAME, "password": PASSWORD, "submit":"Login" } result = session_requests.post(LOGIN_URL, data = payload, headers = dict(referer = LOGIN_URL)) # Scrape url result = session_requests.get(URL, headers = dict(referer = URL)).text # tree = html.fromstring(result.content) print result if __name__ == '__main__': main() but this code gets only the login page source html, I tried using selenium in which it works fine, but snce i have to put this in a server, I wont be able to use selenium. I am using python 2.7 and request to do it. I dont know what i am doing wrong. Can someone help me out with this
type: UnansweredQuestion

http://stackoverflow.com/a/49714859
has body: You can filter the columns names with .filter method, then apply your conversion and finally rename: import pandas as pd df = pd.DataFrame({'Height (mm)':[16,12,17,20,14],'Temperature(°F)':[27,30,32,23,43]}) print('before conversion',df) for x in df.filter(like='°F',axis=1).keys(): df[x] = (df[x] - 32) * 5/9 df.rename(columns={x:x.replace('°F','°C')}, inplace=True) for x in df.filter(like='(mm)',axis=1).keys(): df[x] = df[x] * 0.0393701 df.rename(columns={x:x.replace('(mm)','(In)')}, inplace=True) print('After conversion',df) output looks like: before conversion Height (mm) Temperature(°F) 0 16 27 1 12 30 2 17 32 3 20 23 4 14 43 After conversion Height (In) Temperature(°C) 0 0.629922 -2.777778 1 0.472441 -1.111111 2 0.669292 0.000000 3 0.787402 -5.000000 4 0.551181 6.111111
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86494976
accepted answer of: http://stackoverflow.com/q/49696794
type: Answer
answers question: http://stackoverflow.com/q/49696794
score: 0

http://stackoverflow.com/q/49691923
tagged with: dataframe
tagged with: python
has title: Pandas string filtering by position with variable lengths
favorite count: 0
possible better answer: http://stackoverflow.com/a/49692428
type: Question
accepted answer: http://stackoverflow.com/a/49692040
has answer: http://stackoverflow.com/a/49692428
has answer: http://stackoverflow.com/a/49692040
downvote count: 0
upvote count: 1
tagged with: string
has body: I have a pandas dataframe with a string column. The strings are either 2 or 3 characters long, and I have to filter out string whose third character is 'W'. So far I have df[df.col_name.str[2] == 'W'] This works as long as df.col_name has strings with both 2 and 3 characters in them. However, when df.col_name only contains strings with 2 characters, the code crashes with the error: TypeError: invalid type comparison Is there any way to make this work for both cases?
type: AnsweredQuestion
answer count: 3
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/49692051

http://stackoverflow.com/a/49694304
has body: I got the issue. Actually, I was trying index data with multithreading. Because of this, i didn't get any error while running. Finally, I had fixed by passing charset and use_unicode as parameter in mysqldb.connect function.
answers question: http://stackoverflow.com/q/49673859
type: Answer
score: 0

http://stackoverflow.com/comment/86357244
comment on: http://stackoverflow.com/a/49673206
type: Comment
score: 0
type: AnswerComment
has text: Yep I know about the option ambiguity='explicit', but that's pretty heavy to interpret the tree. As you said, I'm looking for a way to choose between the two, or to change my grammar to not be ambiguous. Thanks

http://stackoverflow.com/a/49736240
answers question: http://stackoverflow.com/q/49735956
score: 0
has body: I have never done this before, but i would hazard a guess that it may be due to the wrong function structure, it should read: def test() return sys.argv[1]
type: Answer

http://stackoverflow.com/comment/86324833
type: QuestionComment
score: 4
type: Comment
comment on: http://stackoverflow.com/q/49657732
has text: In general, parameters can only be used where expressions are allowed. You can't use them for table or column names.

http://stackoverflow.com/comment/86254352
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49610780
has text: @dnoeth, I will definitely test and see if I can do that with SQLAlchemy. Thank you

http://stackoverflow.com/a/49746037
downvote count: 0
has body: gTTS only saves the bytes directly without doing any conversion, and these bytes are encoded in mp3, you can verify it by checking the source code: .... with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=InsecureRequestWarning) r = requests.get(self.GOOGLE_TTS_URL, params=payload, headers=headers, proxies=urllib.request.getproxies(), verify=False) if self.debug: print("Headers: {}".format(r.request.headers)) print("Request url: {}".format(r.request.url)) print("Response: {}, Redirects: {}".format(r.status_code, r.history)) r.raise_for_status() for chunk in r.iter_content(chunk_size=1024): # write the bytes directly fp.write(chunk) ...
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49745456
score: 2
accepted answer of: http://stackoverflow.com/q/49745456
type: AcceptedAnswer

http://stackoverflow.com/comment/86211231
type: QuestionComment
has text: Is there a reason you need to use the shell here? You're not using any shell features, just executing a command with some arguments, so you're just trying to figure out how to fight with two layers of quoting instead of none this way…
score: 0
comment on: http://stackoverflow.com/q/49601829
type: Comment

http://stackoverflow.com/q/49743961
has answer: http://stackoverflow.com/a/52129548
type: UnansweredQuestion
downvote count: 0
tagged with: pip
tagged with: python
answer count: 6
score: 34
linked to: http://stackoverflow.com/q/49748063
has answer: http://stackoverflow.com/a/60412921
has body: I'm trying to update pip using pip install --upgrade pip, but I get a "requirement satisfied" error and an "outdated version" message at the same time $ pip install --upgrade pip Requirement already up-to-date: pip in /Users/user/Envs/proj/lib/python2.7/site-packages You are using pip version 9.0.1, however version 9.0.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. How do I update?
has comment: http://stackoverflow.com/comment/86502805
upvote count: 34
has title: Cannot upgrade pip 9.0.1 to 9.0.3 - requirement already satisfied
has answer: http://stackoverflow.com/a/53109045
tagged with: upgrade
has answer: http://stackoverflow.com/a/49758204
has answer: http://stackoverflow.com/a/64530399
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51313697

http://stackoverflow.com/q/49631518
answer count: 3
has answer: http://stackoverflow.com/a/49770459
possible better answer: http://stackoverflow.com/a/49636500
tagged with: image-processing
has answer: http://stackoverflow.com/a/49631786
has body: I applied some operations on the image to remove the white background(color clustering), but the issue is that the result is not smooth on the contours as you can see here: https://i.sstatic.net/pf0Pi.jpg. What's your advice for smoothing the contours without blurring the entire image? Thanks in advance!
has comment: http://stackoverflow.com/comment/86270318
type: Question
has title: Smooth image contours using python
accepted answer: http://stackoverflow.com/a/49770459
has answer: http://stackoverflow.com/a/49636500
tagged with: python
tagged with: opencv
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86270236
tagged with: image-segmentation

http://stackoverflow.com/a/49666443
has body: I think need to_datetime: pq.index = pd.to_datetime(pq.index) print (pq) col 1970-01-01 00:00:00.000000000 203 1970-01-01 00:00:00.000000001 250 1970-01-01 00:00:00.000000002 318 1970-01-01 00:00:00.000000003 786 1970-01-01 00:00:00.000000004 321 1970-01-01 00:00:00.000000005 135 Also there is nice parameter origin for define start datetime (pandas 0.20.0+): pq.index = pd.to_datetime(pq.index, origin=pd.Timestamp('2000-01-01'), unit='d') print (pq) col 2000-01-01 203 2000-01-02 250 2000-01-03 318 2000-01-04 786 2000-01-05 321 2000-01-06 135 For check max index is possible use Series.idxmax: print (pq['col'].idxmax()) 2000-01-04 00:00:00 EDIT: For lower versions is possible use: pq.index = pd.Timestamp('2000-01-01') + pd.to_timedelta(pq.index, unit='d') print (pq) col 2000-01-01 203 2000-01-02 250 2000-01-03 318 2000-01-04 786 2000-01-05 321 2000-01-06 135
answers question: http://stackoverflow.com/q/49666419
has comment: http://stackoverflow.com/comment/86346542
has comment: http://stackoverflow.com/comment/86342723
has comment: http://stackoverflow.com/comment/86346362
type: Answer
has comment: http://stackoverflow.com/comment/86346768
score: 4
has comment: http://stackoverflow.com/comment/86345931
upvote count: 4
has comment: http://stackoverflow.com/comment/86351266
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86342739
downvote count: 0
has comment: http://stackoverflow.com/comment/86346697
accepted answer of: http://stackoverflow.com/q/49666419
has comment: http://stackoverflow.com/comment/86346915
has comment: http://stackoverflow.com/comment/86346997
has comment: http://stackoverflow.com/comment/86350568
has comment: http://stackoverflow.com/comment/86346320

http://stackoverflow.com/a/49644243
downvote count: 0
answers question: http://stackoverflow.com/q/49644188
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49644188
has body: You need define order in DataFrame constructor, because dict under python 3.6 are not orderable: frame = pandas.DataFrame(data_final, columns=['Case index','Similarity', 'Case description']) writer = pandas.ExcelWriter(rooter + '\\Final_Score_Result.xlsx') frame.to_excel(writer, 'Results', index = False) writer.save() Sample: data_final = {'Case index':[1,2,3], 'Similarity':[6,7,8], 'Case description':['asa','def','gth']} frame = pandas.DataFrame(data_final, columns=['Case index','Similarity', 'Case description']) print (frame) Case index Similarity Case description 0 1 6 asa 1 2 7 def 2 3 8 gth
type: AcceptedAnswer

http://stackoverflow.com/a/49691738
upvote count: 1
score: 1
has body: here is the screen picture, the class is like-btn
answers question: http://stackoverflow.com/q/49690564
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86484384
type: AnswerComment
score: 0
has text: I already tried this and it doesn't help at all. Is it possible that it's a problem with the rights or something like this?
type: Comment
comment on: http://stackoverflow.com/a/49735211

http://stackoverflow.com/a/49690506
type: Answer
has body: Generally this problem "local variable 'my_number' referenced before assignment" comes when you have 'my_number' variable in code and you had not initialized that variable at top of your code or before using that variable do one thing . Declare my_number=0 and then do your calculation on my_number variable .
has comment: http://stackoverflow.com/comment/86392969
answers question: http://stackoverflow.com/q/49690443
score: 0

http://stackoverflow.com/comment/86488239
score: 1
has text: So I have to call `qServer.execute("START TRANSACTION")` everytime I change something? Or is that just an example for a query?
comment on: http://stackoverflow.com/a/49736623
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49738798
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86505878
type: Answer
answers question: http://stackoverflow.com/q/49738508
has comment: http://stackoverflow.com/comment/86505834
score: 0
has body: ... couchdb starts without a pre-set admin (I mean i can do everything without login) ... That's called The Admin Party which is the default configuration if you don't modify the security configurations of CouchDB. It will start to make sense if you take a look at the documentation.

http://stackoverflow.com/q/49691737
has title: moving files from an unknown folder to other
has comment: http://stackoverflow.com/comment/86395653
downvote count: 1
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/86395794
has comment: http://stackoverflow.com/comment/86395538
favorite count: 0
type: Question
upvote count: 3
has answer: http://stackoverflow.com/a/49692066
linked to: http://stackoverflow.com/q/31163668
has comment: http://stackoverflow.com/comment/86395528
has body: I am extracting .tar.gz files which inside there are folders (with files with many extensions). I want to move all the .txt files of the folders to another, but I don't know the folders' name. .txt files location ---> my_path/extracted/?unknown_name_folder?/file.txt I want to do ---> my_path/extracted/file.txt My code: os.mkdir('extracted') t = tarfile.open('xxx.tar.gz', 'r') for member in t.getmembers(): if ".txt" in member.name: t.extract(member, 'extracted') ###
accepted answer: http://stackoverflow.com/a/49692066

http://stackoverflow.com/a/49689239
has comment: http://stackoverflow.com/comment/86390753
has comment: http://stackoverflow.com/comment/86392554
accepted answer of: http://stackoverflow.com/q/49688476
score: 1
has comment: http://stackoverflow.com/comment/86391296
type: Answer
answers question: http://stackoverflow.com/q/49688476
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86390851
downvote count: 0
has comment: http://stackoverflow.com/comment/86403284
upvote count: 1
has comment: http://stackoverflow.com/comment/86393172
has body: Creating a dictionary in VB.net https://www.dotnetperls.com/dictionary-vbnet: Dim payload2 As New Dictionary(Of String, String&gt; payload2.add("auth_token", "&lt;token&gt;") .... Then post the dictionary as JSON: Dim params As String = JsonConvert.SerializeObject(payload2, Formatting.None) Dim Uri As New Uri(String.Format("http://localhost:3030/widgets/hot"+indeks)) Dim webClient As New WebClient() Dim resByte As Byte() Dim resString As String Dim reqString() As Byte webClient.Headers("content-type") = "application/json" Dim senddata As Object = JsonConvert.SerializeObject(New With {Key .param = params}).ToString() reqString = Encoding.Default.GetBytes(senddata) resByte = webClient.UploadData(Uri, "post", reqString) resString = Encoding.Default.GetString(resByte) Edit: You are missing at least the import for System.Net that has the WebClient class. I'm not sure where/how you import the Newtonsoft.Json as I don't see it in your imports but based on the errors it is imported somewhere. For the ambiguous import, see this answer for resolving ambiguous imports.
has comment: http://stackoverflow.com/comment/86394176

http://stackoverflow.com/comment/86571805
has text: @user3667018, there is no need to train your model again - `gs` will contain a __trained__ model, you can simply use `gs.predict()`, `gs.score()`, `gs.best_estimator_`, etc. I would suggest you to open a new question with a small reproducible sample data set and ask there a new question...
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49758787

http://stackoverflow.com/comment/86433135
has text: I already use Euclid's method. But it's not problem. problem is different. I wrote above.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49709833
type: Comment

http://stackoverflow.com/comment/86489727
has text: @Rishabhsharma You're welcome! If you are ever really stuck again, feel free to give me a link to your question. I can't promise I'll be able to help, but I'll have a look.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49716983

http://stackoverflow.com/comment/86263666
type: QuestionComment
has text: I think problem is in quesiton's title
type: Comment
comment on: http://stackoverflow.com/q/49628218
score: 0

http://stackoverflow.com/q/49669492
answer count: 1
downvote count: 0
has body: I have 2 dataframes, the [Trade] column in first dataframe has 3 NaN values, I need to fill them with a referenc dataframe, which you might see below this the first df. You can use various methods to populate NaN value. Join, merge, concat, replace, whatever that works easily. thank you Trade ID Toy_company 0 D255/FE 192 Duplo 1 L217/SN 255 Duplo 2 NaN 195 Lego 3 NaN 256 Duplo 4 D255/FE 192 Duplo 5 D255/FE 192 Duplo 6 D250/AT 192 Duplo 7 D250/AT 192 Duplo 8 L195/AE 195 Lego 9 NaN 195 Lego 10 L256/PE 256 Lego reference dataframe: Trade_ID Item Company 0 D255/FE 192 Duplo 1 D217/SN 255 Duplo 2 L12A/BA 195 Lego 3 L999/CC 256 Lego Requirement: 1. Only fill NaN value according to the info in reference dataframe, on TWO keys: Item+Company. Leave it NaN if can't be referenced. 2. Do not correct any exsiting info, only impact on NaN values So the final result should be: Trade ID Toy_company 0 D255/FE 192 Duplo 1 L217/SN 255 Duplo 2 L12A/BA 195 Lego 3 NaN 256 Duplo 4 D255/FE 192 Duplo 5 D255/FE 192 Duplo 6 D250/AT 192 Duplo 7 D250/AT 192 Duplo 8 L195/AE 195 Lego 9 L12A/BA 195 Lego 10 L256/PE 256 Lego
has title: pandas reference NaN value with multiple keys
favorite count: 0
type: Question
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49669764
tagged with: pandas
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/49669764

http://stackoverflow.com/comment/86518211
has text: Thank you so much! This also seems like a useful tip for future programming! But also here: how can this help me? What is the difference in using PumpAmount1 - a variable i declared before and have to copy and paste - to using PumpAmount[0]? Don´t I need to copy PumpAmount[0] also over and over again? Or can I use a variable (for example X) inside what you´ve proposed? Like PumpAmount[X]
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49737199
type: Comment

http://stackoverflow.com/comment/86345939
type: QuestionComment
comment on: http://stackoverflow.com/q/49667924
type: Comment
has text: Should `mlp_functions` have a `ChosenFunction` already?
score: 0

http://stackoverflow.com/a/58282014
type: Answer
answers question: http://stackoverflow.com/q/49621331
has body: Although this is not a function, it helped me: digits = "12345678901234567890" digit_sum = sum(map(int, digits)) print("The equation is: ", '+'.join(digits)) print("The sum is:", digit_sum) (This prints: The equation is: 1+2+3+4+5+6+7+8+9+0+1+2+3+4+5+6+7+8+9+0 The sum is: 90 )
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/86245469
type: Comment
type: QuestionComment
has text: @Tsyvarev I copied the library from 'build' directory one up where the CMakeLists.txt is (this is where the install command puts the library).
score: 0
comment on: http://stackoverflow.com/q/49603690

http://stackoverflow.com/q/49706803
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86432709
tagged with: python
has body: I am new in both python and opencv and trying to develop a simple object tracking GUI by using opencv tracking API. I am using my webcam to test it. My purpose is selecting the target object in the current frame. For this, I plot a rectangle in the center of the window and select the target object with reference to the rectangle. Since the rectangular shape may fail the tracking operation I want to select the target object from the original frame. In the code I create two different frames which are called rawInp and outImage. rawInp is the input video. outImage is the final outcome and I want all the shapes are plotted in this image. I use an external function to plot the rectangle. I show also the rawInp to check it. However, I see the rectangular shape also in this output. How is it possible and how can I solve this problem? Also, how can I use only rawInp variable for both operations? Because copying the same the same variable is not a good way to handle. I am adding the related part of my code but if you want to see the whole code I can add. Thank you in advance for any of your answers. import sys import cv2 import numpy as np from PyQt5 import QtCore from PyQt5.QtCore import pyqtSlot, QTimer from PyQt5.QtGui import QImage, QPixmap from PyQt5.QtWidgets import QDialog, QApplication, QFileDialog, QMainWindow from PyQt5.uic import loadUi cap = cv2.VideoCapture(0) if not cap.isOpened(): print ("Could not open video") ,sys.exit() ok, frame = cap.read(0) height, width, channels = frame.shape upper_left = (3*int(width/8), 3*int(height/8)) bottom_right = (5*int(width/8), 5*int(height/8)) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) class trackingApp(QMainWindow): def __init__(self): super(trackingApp,self).__init__() loadUi('tracking_ui.ui',self) self.rawInp = None self.outImage = None self.stBtclk = False self.trckBtclk = False self.startButton.clicked.connect(self.start_webcam) self.trackingButton.clicked.connect(self.tracking_clicked) @pyqtSlot() def st…
tagged with: opencv
has comment: http://stackoverflow.com/comment/86445429
tagged with: qt-designer
has comment: http://stackoverflow.com/comment/86431076
has title: Same plot in two different output images
tagged with: pyqt5
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86431377

http://stackoverflow.com/comment/86489141
comment on: http://stackoverflow.com/q/49729340
type: Comment
type: QuestionComment
has text: @ymonad It's a pretty old computer with broken wifi. I have been copying files via usb stick.
score: 0

http://stackoverflow.com/a/49734505
has comment: http://stackoverflow.com/comment/86509215
has comment: http://stackoverflow.com/comment/86509513
type: Answer
has comment: http://stackoverflow.com/comment/86509148
has comment: http://stackoverflow.com/comment/86509042
has comment: http://stackoverflow.com/comment/86510364
has comment: http://stackoverflow.com/comment/86509642
has comment: http://stackoverflow.com/comment/86510168
has comment: http://stackoverflow.com/comment/86508184
score: 0
answers question: http://stackoverflow.com/q/49734227
has comment: http://stackoverflow.com/comment/86509350
has body: Try this Library out : https://pypi.python.org/pypi/json2html json2html.convert - The module’s convert method accepts the following arguments: Argument Description json a valid JSON; This can either be a string in valid JSON format or a python object that is either dict-like or list-like at the top level. table_attributes e.g. pass id=”info-table” or class=”bootstrap-class”/data-* to apply these attributes to the generated table clubbing turn on[default]/off clubbing of list with same keys of a dict / Array of objects with same key encode turn on/off[default] encoding of result to escaped html, compatible with any browser escape turn on[default]/off escaping of html tags in text nodes (prevents XSS attacks in case you pass untrusted data to json2html)

http://stackoverflow.com/q/49746787
answer count: 0
upvote count: 2
tagged with: pandas
type: UnansweredQuestion
score: 1
downvote count: 1
favorite count: 0
type: Question
has title: Changing matplotlib boxplot styling
linked to: http://stackoverflow.com/q/35160956
has comment: http://stackoverflow.com/comment/86511812
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86530556
tagged with: dataframe
tagged with: python
has body: I have a pandas dataframe and I am trying to create boxplot using Matplotlib. I am able to get the boxplot but it looks like styling for boxplot (color for boxplot components) is not working. I am trying to learn plotting charts but somewhat confused how all elements come together. Any guidance will be highly appreciated. import matplotlib.pyplot as plt import numpy as np %matplotlib inline fig, ax = plt.subplots(figsize=(20,6)) ax.set_title('Height Distribution') ax.set_xlabel('PANEL') ax.set_ylabel('Height (um)') # Define styling for each boxplot component medianprops = {'color': 'magenta', 'linewidth': 2} boxprops = {'color': 'black', 'linestyle': '-'} whiskerprops = {'color': 'red', 'linestyle': '-'} capprops = {'color': 'green', 'linestyle': '-'} flierprops = {'color': 'yellow', 'marker': 'x'} concatenated_df.boxplot(ax=ax, column='HEIGHT',by=['Label'],rot=90,fontsize=15,medianprops=medianprops, boxprops=boxprops, whiskerprops=whiskerprops, capprops=capprops, flierprops=flierprops) # Save figure fig.savefig("filename.jpg")

http://stackoverflow.com/comment/86501816
type: Comment
type: QuestionComment
has text: Please provider the _complete_ error message.
score: 0
comment on: http://stackoverflow.com/q/49743363

http://stackoverflow.com/a/49723708
answers question: http://stackoverflow.com/q/49721259
has body: Telethon library provides full access to the Telegram API. You can scan official documentation and find necessary method. There are two places where you can get an answer: Accessing the Full API account.updateProfile method Then you can check Telethon API helper site which will give you desired python method from telethon.tl.functions.account import UpdateProfileRequest
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49721259
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/comment/86389615
score: 1
type: Comment
type: QuestionComment
has text: Can you add views.py and urls.py files content?
comment on: http://stackoverflow.com/q/49688967

http://stackoverflow.com/comment/86543785
has text: `ax.set_ylim(np.array([-dy, dy])+y0), ax.set_xlim(np.array([-dx, dx])+x0)` where you can set dx and dy to be what ever you want and x0 and y0 are where you want the view of the plot centred...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49757799

http://stackoverflow.com/comment/86319229
comment on: http://stackoverflow.com/q/49652648
score: 0
has text: I was talking about all lists.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86471026
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49728484
type: Comment
has text: You can use a dynamic variable name in an `assign` statement by passing a dictionary and using ** on it: `df.assign(**{x: 1})` for example, assuming the content of `x` is a valid Python identifier.

http://stackoverflow.com/a/49741381
answers question: http://stackoverflow.com/q/49712457
type: Answer
score: 0
has body: class1: import sqlite3 from driver import Driver from sqlitte import error def create(): try: conn = sqlite3.connect(':memory:') except error as e: print (e) c = conn.cursor() c.excute("""CREATE TABLE users( price real, discount real )""") conn.commit() conn.close() and class 2(saved in the same directory as driver.py): class Driver: def __init__(self, online_id): self.online_id = online_id def get_online_id(): return self.online_id

http://stackoverflow.com/q/49641899
has title: how to export two columns to csv in python
type: Question
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49641967
tagged with: python
has answer: http://stackoverflow.com/a/49642028
accepted answer: http://stackoverflow.com/a/49641951
has body: I am not familiar with how to export the list to the csv in python. Here is code for one list: import csv X = ([1,2,3],[7,8,9]) Y = ([4,5,6],[3,4,5]) for x in range(0,2,1): csvfile = "C:/Temp/aaa.csv" with open(csvfile, "w") as output: writer = csv.writer(output, lineterminator='\n') for val in x[0]: writer.writerow([val]) And I want to the result: Then how to modify the code(the main problem is how to change the column?)
has answer: http://stackoverflow.com/a/49641951
type: AnsweredQuestion
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/49641967

http://stackoverflow.com/comment/100423009
has text: Explain why it will solve the issue at hand and also where the author went wrong
comment on: http://stackoverflow.com/a/56941261
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50501056
has body: if you want help with python objects in dash then just use: help(html.Div) to get a list of argument parameters. If you want to know what can be placed in the style parameter the answer is any and all css can be generated. You can customize the look anyway you want here is the syntax... style={ 'border':'1px solid #333', 'margin':'10px', 'padding':'10px', 'background-color':'#888', 'position':'absolute', }, The style parameter excepts a dictionary object. In order for your CSS to be rendered it needs to be in the syntax above, which will create a python dictionary object.
answers question: http://stackoverflow.com/q/49730967
score: 0
type: Answer

http://stackoverflow.com/a/49720597
answers question: http://stackoverflow.com/q/49715458
score: 1
downvote count: 0
upvote count: 1
has body: Qt Designer creates a class that is used to fill another widget, it is not a widget, so it is recommended to create a class that inherits from the appropriate widget and fills in using the Ui_Form class. For more information read the following: http://pyqt.sourceforge.net/Docs/PyQt5/designer.html Going to the point, you must use the showMinimized() method. # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) self.btn_name = QtWidgets.QPushButton(Form) self.btn_name.setGeometry(QtCore.QRect(300, 30, 98, 33)) self.btn_name.setObjectName("btn_name") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.btn_name.setText(_translate("Form", "PushButton")) class Form(QtWidgets.QWidget, Ui_Form): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.setupUi(self) self.btn_name.clicked.connect(self.minimize) def minimize(self): self.showMinimized() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) w = Form() w.show() sys.exit(app.exec_())
type: Answer

http://stackoverflow.com/comment/100620734
has text: Many people who come here for help doesn't go through comments much. So it will be really helpful if you can add that up in your answer.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/56941261

http://stackoverflow.com/comment/86503676
has text: Okay sorry change it to Offender2.query.get(BookingNumber) and I get a blank template no data.. this is what im using in the template to test the data being passed... {{ offenders.Name }}
score: 0
comment on: http://stackoverflow.com/a/49744262
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49602040
has comment: http://stackoverflow.com/comment/86235119
has comment: http://stackoverflow.com/comment/86235035
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86235304
has comment: http://stackoverflow.com/comment/86221560
has comment: http://stackoverflow.com/comment/86240086
has body: OK, shot in the dark: I would drop shell=True and use a argument list to pass to subprocess. The quoting will be handled automatically: cmd = ['Reg.exe','add',r'HKCR\7-Zip.zip\shell\open\command','/ve','/t','REG_SZ','/d',r'"C:\Program Files\7-Zip\7zFM.exe" "%1"','/f'] rc = subprocess.call(cmd) also check the return code of subprocess.call If you want to process several commands like this "automatically", I'd suggest to use shlex.split, I'm not saying that it will solve everything, but it does a fine job with the quotes (protecting the quoted arguments, with quote nesting): import shlex text = r"""Reg.exe add "HKCR\7-Zip.zip\shell\open\command" /ve /t REG_SZ /d "\"C:\Program Files\7-Zip\7zFM.exe\" \"%%1\"" /f""" print([x.replace("%%","%") for x in shlex.split(text)]) # %% =&gt; % in listcomp, add more filters if needed result: ['Reg.exe', 'add', 'HKCR\\7-Zip.zip\\shell\\open\\command', '/ve', '/t', 'REG_SZ', '/d', '"C:\\Program Files\\7-Zip\\7zFM.exe" "%1"', '/f'] same thing with raw prefix would be: ['Reg.exe', 'add', r'HKCR\7-Zip.zip\shell\open\command', '/ve', '/t', 'REG_SZ', '/d', r'"C:\Program Files\7-Zip\7zFM.exe" "%1"', '/f'] pretty close right? :)
answers question: http://stackoverflow.com/q/49601829
type: Answer

http://stackoverflow.com/comment/86233062
type: QuestionComment
comment on: http://stackoverflow.com/q/49613228
score: 0
type: Comment
has text: what library are you using to connect? the problem is with how you are inserting the table name but I can't help until I know the library you're using

http://stackoverflow.com/comment/86237616
type: QuestionComment
has text: You might need to tell jQuery that the response is in JSON format, it's probably being interpreted as a string.
score: 0
comment on: http://stackoverflow.com/q/49615349
type: Comment

http://stackoverflow.com/q/49738715
has body: How to get all values ​​from OptionMenus with one button. I would like to get a similar effect as in the WWW form. I was able to collect values ​​in a very unprofessional way (for each individual).It hurts my eyes :D def funcUser(value): add_item(listaUser, value) mies = OptionMenu(root, value, *list,command=func)
score: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/49783107
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/86495547
has title: How to get all values from OptionMenus with one button
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86492019

http://stackoverflow.com/a/50183170
downvote count: 0
type: AcceptedAnswer
has body: The key is giving another linemargin in LAParams: LAParams(line_margin=0.1) My line looks now like this: device = TextConverter(resource_manager, string_writer, codec='utf-8', laparams=LAParams(line_margin=0.1)) Credits to Tim
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49722754
type: Answer
answers question: http://stackoverflow.com/q/49722754
score: 5

http://stackoverflow.com/comment/86408708
type: Comment
score: 0
type: QuestionComment
has text: 1) `with` makes the call to `close` unnecessary. 2) In Python a loop over an iterable is done using `for item in a:`. The index `i` is not Pythonic.
comment on: http://stackoverflow.com/q/49697476

http://stackoverflow.com/q/49713196
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86439998
has comment: http://stackoverflow.com/comment/86440063
accepted answer: http://stackoverflow.com/a/49713352
tagged with: python
has answer: http://stackoverflow.com/a/49713352
has body: Trying to figure out how to only replace a portion of a word using Lists, For loops and .replace(). I am also in the midst of figuring out how to extract an integer from the code in order to +1 and return the number. So far my code is as follows: dictZero = [ "zero", "none", "nil", "null" ] dictOne = [ "one", "won", "juan" ] dictTwo = [ "two", "to", "too", "tu" ] dictThree = [ "three" ] dictFour = [ "four", "for", "fore" ] userInput = input ( "Enter your sentence to inflate: " ) for i in userInput.split(): for e in dictFour: if e in i: userInput = userInput.replace ( i, "five" ) for d in dictThree: if d in i: userInput = userInput.replace ( i, "four" ) for c in dictTwo: if c in i: userInput = userInput.replace ( i, "three" ) for b in dictOne: if c in i: userInput = userInput.replace ( i, "two" ) for a in dictZero: if a in i: userInput = userInput.replace ( i, "one" ) #This seems to work but not sure how to assign it back into the Input if int(i): i = int(i) + 1 print (i) print ( userInput) Example: Input = "Before I go to bed at 1630" Output = "Befifth I go three bed at 1631" So the code works as I want it to for the most part. If you enter a word in the list it will replace it with the corresponding word. BUT! I cannot for the life of me figure out how to break apart the userInput one step further to replace a word such as "before" and have the outcome as "befifth" rather than fifth. Maybe a further if statement with .split() then .join()? Any help or suggestions would be appreciated. Thank you for your time.
type: AnsweredQuestion
has title: How to .replace() only a portion of a word? And extracting integer from string?
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49721621
tagged with: python
accepted answer: http://stackoverflow.com/a/49721698
tagged with: recursion
has body: I am new to Python and I plan on having a list inside a recursive function such as def myRecursion(a): A = [0,1,2] #Rest of code here myRecursion(a-1) My question is will having A inside the recursion create many instances of it and eat up my resources? I should also note that the contents of the list is always the same.
has answer: http://stackoverflow.com/a/49721698
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86457949
downvote count: 0
upvote count: 1
score: 1
tagged with: memory
answer count: 1
has comment: http://stackoverflow.com/comment/86456421
favorite count: 0
tagged with: resources
has title: Having a list inside recursive function's impact on memory/resources
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86458011
type: Question
has comment: http://stackoverflow.com/comment/86459694

http://stackoverflow.com/q/49705002
has body: https://github.com/pgbrodrick/ensemblePLSR. I have downloaded python code and sample data from the link mentioned above. I am novice in programming/coding. while running the code, I am getting error: Traceback (most recent call last): File "C:\SOME_PATH\ensemble_plsr.py", line 167, in sf = read_settings_file.settings(sys.argv1) IndexError: list index out of range
favorite count: 0
has comment: http://stackoverflow.com/comment/86423717
downvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49705161
type: Question
upvote count: 0
has title: error in ensemble PLSR (Partial Least Square Regression) code
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/49719784
has comment: http://stackoverflow.com/comment/86452678
answers question: http://stackoverflow.com/q/49719404
downvote count: 0
upvote count: 1
has body: Use copy.deepcopy. Whenever you doing appending and poping all operation performing on list so after lastoperation whatever the list have values its printing the same In [10]: path=[1,2,3,4] In [11]: path2=path In [12]: path.pop() Out[12]: 4 In [13]: path2 Out[13]: [1, 2, 3] In [14]: #using deepcopy In [15]: import copy In [16]: path=[1,2,3,4] In [17]: path2=copy.deepcopy(path) In [18]: path.pop() Out[18]: 4 In [19]: path2 Out[19]: [1, 2, 3, 4] Modified your code : import copy list = [2,1,3,0] my_list = [] #take the inly list my_list.append(copy.deepcopy(list)) list.pop() list.pop() list.append(9) my_list.append(copy.deepcopy(list)) list.append(5) my_list.append(copy.deepcopy(list)) print(my_list) result: [[2, 1, 3, 0], [2, 1, 9], [2, 1, 9, 5]]
has comment: http://stackoverflow.com/comment/86452660
score: 1
type: Answer

http://stackoverflow.com/comment/86216909
score: 0
type: Comment
has text: [official site](https://www.tensorflow.org/install/install_windows#requirements_to_run_tensorflow_with_gpu_support)
type: QuestionComment
comment on: http://stackoverflow.com/q/49604784

http://stackoverflow.com/q/49656013
tagged with: tkinter
has answer: http://stackoverflow.com/a/49657764
has comment: http://stackoverflow.com/comment/86321783
has comment: http://stackoverflow.com/comment/86322757
tagged with: items
upvote count: 0
tagged with: user-interface
tagged with: python
tagged with: checkbox
has comment: http://stackoverflow.com/comment/86322354
downvote count: 1
type: AnsweredQuestion
has title: certain number of choices in TKinter
answer count: 3
possible better answer: http://stackoverflow.com/a/49657575
has body: I made a checkbar in Tkinter with many items but I want the user can only choose the equal or less than a certain number of items. This is my current code: from tkinter import * class Checkbar(Frame): def __init__(self, parent=None, picks=[], side=LEFT, anchor=W): Frame.__init__(self, parent) self.vars = [] for pick in picks: var = IntVar() chk = Checkbutton(self, text=pick, variable=var) chk.pack(side=side, anchor=anchor, expand=YES) self.vars.append(var) def state(self): return [var.get() for var in self.vars] root = Tk() lng = Checkbar(root, range(10)) lng.pack(side=TOP, fill=BOTH) root.mainloop()
score: -1
has answer: http://stackoverflow.com/a/49657575
accepted answer: http://stackoverflow.com/a/49657354
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49657354

http://stackoverflow.com/comment/86697387
type: Comment
type: QuestionComment
has text: See https://stackoverflow.com/q/49838872/901925 for newer similar question. Seems that poster wanted a structured array, not simply a list of tuples.
comment on: http://stackoverflow.com/q/49757471
score: 0

http://stackoverflow.com/a/49610210
has comment: http://stackoverflow.com/comment/86227038
type: Answer
answers question: http://stackoverflow.com/q/49610154
score: 2
upvote count: 2
has body: Your question is not clear. You don't have "another loop". However this is the wrong way to do this - it is terribly inefficient. Instead, loop through the students in each class. Assuming Student has a ForeignKey to Class: {% for class in classList %} {% for student in class.student_set.all %} ...
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49610154

http://stackoverflow.com/q/49603734
tagged with: python
has title: Python3.x, How to focus on newly opened webpage
has body: Ok, here's the deal. I use: driver = webdriver.Firefox(firefox_profile=profile) driver.get = ('http://google.com') to open a new webpage. After opening the new webpage, I use pyautogui to do some clicking and scrolling and whatnot, and then close the browser, and then do the same thing over again as the program iterates through a list of proxies. But when the webpage opens, it isn't in focus. I can see it and see that it opened, but it's not in focus. So I originally implemented a simple click command on the webpage, and that usually focuses the new browser. But after the first browser is opened and closed, the next browser that is opened using a new proxy from the list isn't in focus, and for whatever reason, the click doesn't bring it into focus. So because the browser isn't in focus, my scroll code doesn't happen, it just acts like it skips over it. So I guess my question is, is there some command I can use to make my program focus on the new browser? I've searched extensively on here for the answer to my question and have tried a bunch of different things, but none have worked. Most answers on here pertain to newly opened tabs, and that isn't my issue. Any helpful comments or ideas would be much appreciated. I'm using Mac OS X, and the most recent version of python. Thank you.
type: AnsweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86230570
score: 1
answer count: 1
tagged with: macos
favorite count: 0
tagged with: macos-high-sierra
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49640846
accepted answer: http://stackoverflow.com/a/49640846

http://stackoverflow.com/comment/86344226
has text: @masan welcome. don't be afraid of downvotes :)
comment on: http://stackoverflow.com/q/49636870
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49707874
has answer: http://stackoverflow.com/a/49709694
accepted answer: http://stackoverflow.com/a/49709694
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has title: PyQt5, how to restart operations running through threads
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
has body: So I have been trying to create a GUI which works on multiple threads to perform each operation. Each operation actually has loops running on it and so I decided to use threads to run each operation simultaneously. Here's some piece of code which describes the work flow. Below there's a function called cvfeed1 which starts a thread when a button is pressed on the GUI using ( self.pushButton_3.clicked.connect(self.cvfeed1) ). When the threads starts it calls a function called colour_detect. The problem that I am facing is that I can only use this thread once, i.e I can only click the button once. When the operation in the functions is finished and I click the button again, the program crashes. What do I need to do to again make the thread work? class MyWindowClass(QMainWindow, form_class): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.startButton.clicked.connect(self.start_clicked) self.pushButton.clicked.connect(self.printer) # Here is the command when the button is clicked. self.pushButton_3.clicked.connect(self.cvfeed1) self.window_width = self.ImgWidget.frameSize().width() self.window_height = self.ImgWidget.frameSize().height() self.ImgWidget = OwnImageWidget(self.ImgWidget) self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.update_frame) self.timer.start(1) # This function starts the detect_1_thread def cvfeed1(self): detect_1_thread.start() #self.pushButton_3.setEnabled(False) def printer(self): global running1 running1=True printer_thread.start() def start_clicked(self): global running running = True capture_thread.start() self.startButton.setEnabled(False) self.startButton.setText('Starting...') def update_frame(self): if not q.empty(): self.startButton.setText('Camera is live') frame = q.get() img = frame["img"] img_height, img_width, img_colors = img.shape scale_w = float(self.window_width) / float(img_width) scale_h = float(self.window_height) / float(img_height) scale = min([scale_w, scale_h]) i…
tagged with: python-multithreading
tagged with: python

http://stackoverflow.com/a/49708506
downvote count: 0
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49706501
has body: BinaryFillHoles might not work because your "holes" are not holes topologically. They might be thin "tubes" that extend all the way to the "outside" of the object and thus topologically not being holes. But they would mostly appear as holes when looking at individual slices. What you might try then is BinaryMorphologicalClosing in ITK or SimpleITK. Just make sure to SetRadius() to a value greater than your biggest "hole".
has comment: http://stackoverflow.com/comment/86443128
score: 4

http://stackoverflow.com/a/49601297
answers question: http://stackoverflow.com/q/49601248
score: 3
upvote count: 3
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49601248
has comment: http://stackoverflow.com/comment/86238313
has comment: http://stackoverflow.com/comment/86237815
type: AcceptedAnswer
has body: df = pd.DataFrame({'d1': d1, 'd2': d2, 'd3': d3, 'd4': d4}) df.reindex(pd.to_datetime(df.index)).plot()

http://stackoverflow.com/comment/86252303
type: Comment
type: QuestionComment
has text: It'll require root permissions, but see various solutions here (not sure about the accepted answer myself) https://stackoverflow.com/questions/23013274/shutting-down-computer-linux-using-python
score: 2
comment on: http://stackoverflow.com/q/49622575

http://stackoverflow.com/comment/86463858
has text: @DyZ, I put this in "test.csv" `a,b,c \ 1,, \ ,-1, \ 2,1, \ 1,1,1` and then ran this: `df = pd.read_csv("test.csv") \ binary_df = pd.get_dummies(df)` You can see `binary_df` is the same as `df`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49724908
type: QuestionComment

http://stackoverflow.com/q/49630143
tagged with: python
tagged with: optimization
type: AnsweredQuestion
tagged with: adam
answer count: 1
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49631423
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49631423
has title: How does the ADAM optimizer output a specific value for v_t in keras?
has body: I want to look at the results of each iteration of the ADAM algorithm that computes v_t, so I added the following code to the Adam class in the keras\optimizers.py file: sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) I want to get every numeric value in this shape, similar to the form of a matrix. But the output below is not what I expected: v_t: Tensor("training/Adam/add_2:0", shape=(8, 512), dtype=float32) v_t: Tensor("training/Adam/add_5:0", shape=(128, 512), dtype=float32) This line of code is part of the Adam class itself, and the next line adds its own: v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g) print('v_t:',v_t)# This is my added code I made the following attempts but would report the error as follows: InvalidArgumentError (see above for traceback): Shape [-1,1,8] has negative dimensions [[Node: lstm_1_input = Placeholderdtype=DT_FLOAT, shape=[?,1,8], _device="/job:localhost/replica:0/task:0/cpu:0"]] This is my model: model = Sequential() model.add(LSTM(128, input_shape=(train_X.shape[1], train_X.shape[2]))) model.add(Dense(1)) model.compile(loss='mae', optimizer='adam',metrics=['mae']) I just want to output every value in this shape.

http://stackoverflow.com/comment/86307244
comment on: http://stackoverflow.com/q/49649470
has text: If the code has multiple problems, it’s beyond the scope of this site to fix them all. I have no problem with closing as a duplicate to fix the most obvious problem.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49754113
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: See OpenGL 4.6 API Compatibility Profile Specification; 10.3.3 Specifying Arrays for Fixed-Function Attributes; page 402 The commands void VertexPointer( int size, enum type, sizei stride, const void *pointer ); void NormalPointer( enum type, sizei stride, const void *pointer ); void ColorPointer( int size, enum type, sizei stride, const void *pointer ); void SecondaryColorPointer( int size, enum type, sizei stride, const void *pointer ); void IndexPointer( enum type, sizei stride, const void *pointer ); void EdgeFlagPointer( sizei stride, const void *pointer ); void FogCoordPointer( enum type, sizei stride, const void *pointer ); void TexCoordPointer( int size, enum type, sizei stride, const void *pointer ); specify the location and organization of arrays to store vertex coordinates, normals, colors, secondary colors, color indices, edge flags, fog coordinates. ... An individual array is enabled or disabled by calling one of void EnableClientState( enum array ); void DisableClientState( enum array ); with array set to VERTEX_ARRAY, NORMAL_ARRAY, COLOR_ARRAY, SECONDARY_COLOR_ARRAY, INDEX_ARRAY, EDGE_FLAG_ARRAY, FOG_COORD_ARRAY, or TEXTURE_COORD_ARRAY, for the vertex, normal, color, secondary color, color index, edge flag, fog coordinate, or texture coordinate array, respectively. This means that vertex coordinates can be specified by glVertexPointer and enabled by glEnableClientState(GL_VERTEX_ARRAY) glVertexPointer(3, GL_FLOAT, 0, None) glEnableClientState(GL_VERTEX_ARRAY) And texture cooridantes can be specified by glTexCoordPointer and enabled by glEnableClientState(GL_TEXTURE_COORD_ARRAY) glTexCoordPointer(3, GL_FLOAT, 0, None) glEnableClientState(GL_TEXTURE_COORD_ARRAY)
accepted answer of: http://stackoverflow.com/q/49749956
answers question: http://stackoverflow.com/q/49749956
score: 1

http://stackoverflow.com/comment/86291222
type: Comment
type: QuestionComment
has text: Hi @zwer I think any modification on magic_debug is okay. I think somefunc is fixed and shouldn't be changed.
comment on: http://stackoverflow.com/q/49641454
score: 0

http://stackoverflow.com/a/49750418
has comment: http://stackoverflow.com/comment/128867491
score: 24
upvote count: 24
answers question: http://stackoverflow.com/q/49750067
accepted answer of: http://stackoverflow.com/q/49750067
has comment: http://stackoverflow.com/comment/109459551
type: Answer
has body: First install PyCall package in Julia by running Pkg.add("PyCall") in Julia REPL. Next you need to install julia for Python: $ pip install julia should work. Here is the output from my console (you should see something similar): $ pip install julia Collecting julia Downloading julia-0.1.5-py2.py3-none-any.whl (222kB) 100% |████████████████████████████████| 225kB 1.1MB/s Installing collected packages: julia Successfully installed julia-0.1.5 Now assume you have the following file test.jl in your working directory: for i in 1:10 println(i) end 1+2 (it should print numbers from 1 to 10, and return value 3 which is the result of sum of 1 and 2). Now you start Python REPL and use julia package as follows to run a custom Julia script: &gt;&gt;&gt; import julia &gt;&gt;&gt; j = julia.Julia() &gt;&gt;&gt; x = j.include("test.jl") 1 2 3 4 5 6 7 8 9 10 &gt;&gt;&gt; x 3 And as you can see you have the return value of Julia script assigned to variable x in Python. You can find more details here: https://github.com/JuliaPy/pyjulia.
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49653836
tagged with: python
has body: Sorry if this is a silly question but I'm streaming data from a server and trying to pull specific values by keys, and they are only working if I first check if the key is present JSON Example {"time_exchange":"2018-04-04T14:29:53.0847306Z","time_coinapi":"2018-04-04T14:29:53.0847306Z","ask_price":117.1,"ask_size":158.30616728,"bid_size":102.60064,"bid_price":117.09,"symbol_id":"COINBASE_SPOT_LTC_USD","sequence":25388355,"type":"quote"} It prints correctly if I do this: data = json.loads(ws.recv()) if 'ask_size' in data: print data['ask_size'] But if I do just: data = json.loads(ws.recv()) print data['ask_size'] I get a key error: KeyError: 'ask_size'
type: Question
has title: json value priting by key within if in, but not without
has comment: http://stackoverflow.com/comment/86316841
has comment: http://stackoverflow.com/comment/86316482
accepted answer: http://stackoverflow.com/a/49654520
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86316590
has comment: http://stackoverflow.com/comment/86317942
has comment: http://stackoverflow.com/comment/86317509
upvote count: 1
has answer: http://stackoverflow.com/a/49654520
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86317229
has comment: http://stackoverflow.com/comment/86317524
has comment: http://stackoverflow.com/comment/86317690
has comment: http://stackoverflow.com/comment/86318030
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86316383
has comment: http://stackoverflow.com/comment/86316613

http://stackoverflow.com/a/49653317
downvote count: 0
answers question: http://stackoverflow.com/q/49653107
upvote count: 1
score: 1
type: Answer
has body: Little example with a predifined index with value 34: l = ["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"] index=34 print(l[index%len(l)]) # result 'I'

http://stackoverflow.com/q/49612908
tagged with: cntk
answer count: 1
tagged with: neural-network
has title: How to use scikit-learn metrics in CNTK?
downvote count: 1
favorite count: 0
type: Question
has body: I wish to use classification metrics like matthews_corrcoef as a metric to a neural network built with CNTK. The way I could find as of now was to evaluate the value by passing the predictions and label as shown matthews_corrcoef(cntk.argmax(y_true, axis=-1).eval(), cntk.argmax(y_pred, axis=-1).eval()) Ideally I'd like to pass the metric to the trainer object while building my network. One of the ways would be to create own custom metric and pass that to the trainer object. Although possible, it'll be better to be able to reuse the already existing metrics present in other libraries.
type: UnansweredQuestion
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49613345
upvote count: 2

http://stackoverflow.com/comment/86414198
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49700443
has text: Yes, you mean ***"compare lists pairwise"***. Are they guaranteed to have the same length? Do you want it in native Python, or pandas, or both?

http://stackoverflow.com/comment/86407504
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49696881
has text: That was the first thing I tried. Here is the result with the data in its original base one form. https://imgur.com/a/ltBGN What I'd like is bars rising and falling from one.
type: Comment

spyder
tags question: http://stackoverflow.com/q/49736915
tag name: spyder
tags question: http://stackoverflow.com/q/49684669
tags question: http://stackoverflow.com/q/49740290
tags question: http://stackoverflow.com/q/49704486
tags question: http://stackoverflow.com/q/49716523
tags question: http://stackoverflow.com/q/49749808
tags question: http://stackoverflow.com/q/49650449
type: Tag
tags question: http://stackoverflow.com/q/49633725
tags question: http://stackoverflow.com/q/49690523
tags question: http://stackoverflow.com/q/49657742
tags question: http://stackoverflow.com/q/49713475
tags question: http://stackoverflow.com/q/49741469

http://stackoverflow.com/comment/86444868
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49715881
has text: @SergeyDylda: you can safely ignore that comment, it makes zero sense.
score: 0

http://stackoverflow.com/comment/86400537
type: AnswerComment
has text: Oh right, I use python 2.7 and only changed back the import statements. The `click` function is indeed the place to put the code you want to be executed when a date is clicked. You can use `event.widget.cget('text')` to find which day has been clicked. In combination with `self.month.get()` and `self.year.get()` this gives you the exact date.
comment on: http://stackoverflow.com/a/49688938
type: Comment
score: 0

http://stackoverflow.com/comment/86257157
type: Comment
type: AnswerComment
score: 0
has text: This was my first idea, but I tought maybe there is simpler way, like for IP address `ip = socket.gethostbyname(socket.gethostname())`.
comment on: http://stackoverflow.com/a/49625033

http://stackoverflow.com/a/49687674
answers question: http://stackoverflow.com/q/49654008
has comment: http://stackoverflow.com/comment/92767026
type: AcceptedAnswer
has body: Solved it by adding my_op = tf.load_op_library('/path/to/.so/') also in import.py before loading the graph
downvote count: 0
has comment: http://stackoverflow.com/comment/92795126
upvote count: 2
has comment: http://stackoverflow.com/comment/92764900
type: Answer
accepted answer of: http://stackoverflow.com/q/49654008
score: 2

http://stackoverflow.com/comment/86343099
type: QuestionComment
has text: @abarnert It is clear to me. I'm just pointing that the `O(m * 2k/m * 1) = O(mk)` equation in the first comment is misleading in the first place, that's all. _It can not simplify to `O(mk)`_.
score: 0
comment on: http://stackoverflow.com/q/49665799
type: Comment

http://stackoverflow.com/a/54948332
score: 0
has body: assuming s is equal to your dataframe : Try this: def file(): styled = df.style.apply(highlight_rows, axis = 0) f = open('new_file.html', 'w') html = (styled.render()) f.write(html) f.close() def highlight_rows(s): if s.my_column == 'some_text': return ['background-color: green'] * s.size elif s.my_column == 'somedifferent_text': return ['background-color: blue'] * s.size
type: Answer
answers question: http://stackoverflow.com/q/49677112

http://stackoverflow.com/comment/86428666
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49707469
has text: What do you want to achieve? Check this: https://pypi.python.org/pypi/pyspeedtest

http://stackoverflow.com/comment/86362037
type: Comment
type: AnswerComment
has text: https://riverbankcomputing.com/pipermail/pyqt/2016-December/038428.html
score: 0
comment on: http://stackoverflow.com/a/49675526

http://stackoverflow.com/comment/86485344
comment on: http://stackoverflow.com/q/49735569
score: 0
type: Comment
type: QuestionComment
has text: @chrisz where should I find this standard library?

http://stackoverflow.com/a/49770041
accepted answer of: http://stackoverflow.com/q/49755719
answers question: http://stackoverflow.com/q/49755719
type: Answer
has body: I think the following strategy satisfies your requirements: import hypothesis.strategies as st @st.composite def unique_pair_lists(draw): data = draw(st.lists(st.integers(), unique=True) if len(data) % 2 != 0: data.pop() result = [data[i:i+2] for i in range(0, len(data), 2)] for pair in result: pair.sort() return result The idea here is that we generate something that gives the right elements, and then we transform it into something of the right shape. Rather than trying to generate pairs of lists of integers, we just generate a list of unique integers and then group them into pairs (we drop the last element if there's an odd number of integers). We then sort each pair to ensure it's in the right order.
has comment: http://stackoverflow.com/comment/86618250
upvote count: 3
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86575076
downvote count: 0

http://stackoverflow.com/q/49627084
has comment: http://stackoverflow.com/comment/86314722
has answer: http://stackoverflow.com/a/49627316
tagged with: python
has title: pandas read_json reads large integers as strings incorrectly
upvote count: 3
tagged with: pandas
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
favorite count: 0
has body: I'm trying to read tweets which are stored as json files. I'm using pandas to load the data. But found some strange behaviour in the read_json function. It I'm providing an mcve below: json_content=""" { "1": { "tid": "9999999999999998", }, "2": { "tid": "9999999999999999", }, "3": { "tid": "10000000000000001", }, "4": { "tid": "10000000000000002", } } """ df=pd.read_json(json_content, orient='index', # read as transposed convert_axes=False, # don't convert keys to dates ) print(df.info()) print(df) Which outputs the following on my PC: &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 4 entries, 1 to 4 Data columns (total 1 columns): tid 4 non-null int64 dtypes: int64(1) memory usage: 64.0+ bytes None tid 1 9999999999999998 2 10000000000000000 3 10000000000000000 4 10000000000000002 Which is not storing the correct values for tid column, why is this happening? Note: There shouldn't be an overflow case. The tid column is being stored as int64, which has a limit about 10 times higher than the tid I originally tested with(see below): import sys # original problem tid_0 = 956677215197970432 print(sys.maxsize,tid_0,sys.maxsize/tid_0) # &lt; 1 if overflow possible # minimal case tid = 10000000000000001 print(sys.maxsize,tid,sys.maxsize/tid) # &lt; 1 if overflow possible #Output 9223372036854775807 956677215197970432 9 9223372036854775807 10000000000000001 922 Update : It is reading correctly on explictly specifying the argument dtype=int, but I don't understand why. What changes when we specify the dtype?
type: Question
tagged with: python-3.x
score: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/86446327
comment on: http://stackoverflow.com/q/49716403
has text: @usr2564301, I'm still trying to solve and will also try your suggestion. Thanks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49711650
has answer: http://stackoverflow.com/a/49713491
has comment: http://stackoverflow.com/comment/86440256
tagged with: python
favorite count: 0
has title: How to detect the outlines of cells of a pillbox in opencv in python?
accepted answer: http://stackoverflow.com/a/49713491
answer count: 1
downvote count: 0
has body: So I am trying to make an opencv program that can detect which cells of a pillbox have pills in them. My initial idea was to: find all the edges using canny Run hough transform to find the borders of the cells see which of the 14 cells have white pixels greater than a certain threshold. However, in practice, I can't really seem to find good edges using canny, since the camera is a poor quality raspberry pi camera. Does anybody have any suggestions of how I can go about finding the outlines of the 14 cells? UPDATE: So I've put masking tape on the edges of the walls, and through some processing, am able to obtain images like the following Now, how do I get the 14 masks of the interiors of the 14 cells? I tried doing a hough transform on this image, but it's still creating spurious lines it shouldn't, and not creating lines it should
upvote count: 1
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/86440141
type: Question
tagged with: opencv
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/86434362
comment on: http://stackoverflow.com/q/49710411
type: Comment
score: 1
has text: Python globals are global to _each module_, not to the entire program.
type: QuestionComment

http://stackoverflow.com/comment/86268349
type: QuestionComment
has text: @mkrieger1 thank you, it was stupid question
comment on: http://stackoverflow.com/q/49630683
score: 0
type: Comment

http://stackoverflow.com/q/49724413
answer count: 1
type: Question
type: AnsweredQuestion
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49724632
tagged with: index-error
has body: I've been working to place a string variable "revenue" into a pandas dataframe df1. As you can see, I used df.ait. More details about the code: It's about finding the specific date row, by m counting loop. My issue occurs at the .iat. if info[1] == "1": #Get Kikko1 listofdates = df.Date.tolist() m = 0 for i in listofdates: if i != date: #Counting the rows m = m+1 elif i == date: #Select the row with the matched date df.iat[m, 9] = "revenue" break The error says: IndexError: index 36 is out of bounds for axis 0 with size 31
tagged with: python
has title: Place Variable into a Specific Location [row,column] Pandas Python
accepted answer: http://stackoverflow.com/a/49724632

http://stackoverflow.com/comment/86240504
score: 0
comment on: http://stackoverflow.com/q/49616162
has text: @LutzHorn i just edited the question hopefully its clearer now
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87071622
comment on: http://stackoverflow.com/a/49657885
type: Comment
score: 2
has text: As I understand, when we create an Interceptor and send credentials in metadata, server check first metadata on first RPC call. Can I add metadata during channel creation on a client side and if credentials are invalid - close the channel?
type: AnswerComment

http://stackoverflow.com/q/49620585
has comment: http://stackoverflow.com/comment/86250882
has comment: http://stackoverflow.com/comment/86252219
has answer: http://stackoverflow.com/a/49707992
has comment: http://stackoverflow.com/comment/86248845
score: 1
has comment: http://stackoverflow.com/comment/86252268
has comment: http://stackoverflow.com/comment/86257611
favorite count: 0
has comment: http://stackoverflow.com/comment/86251165
linked to: http://stackoverflow.com/q/26980713
type: Question
has title: response to preflight doesn't pass access control check
tagged with: cors
has comment: http://stackoverflow.com/comment/86251064
type: UnansweredQuestion
has body: I have a simple flask server import pdb from flask import Flask, jsonify, abort, make_response, request, send_from_directory from flask_cors import CORS, cross_origin from pprint import pprint import argparse from mylib.mylib_rest_api import ProcessRestApiRequest DEBUG=True app = Flask(__name__) CORS(app) parser = argparse.ArgumentParser(description='Run the server') parser.add_argument('--ip-address', default='127.0.0.1', help='Server IP Address. Default: %(default)s') parser.add_argument('--port', type=int, default=8081, help='Server port') args = parser.parse_args() @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) def do_pre_serve_actions(): if not request.json: abort(400) # Extract the data dictReq = request.get_json(force=True) if DEBUG: pprint('dictReq: '+str(dictReq)) return dictReq def do_post_serve_actions(dictResp): if DEBUG: pprint("dictResp: "+str(dictResp)) dictJSONResp = jsonify(dictResp) objRespADF = make_response(dictJSONResp) return objRespADF @app.route('/&lt;target&gt;', methods=['POST']) def serve(target): dictReq = do_pre_serve_actions() dictResp = ProcessRestApiRequest(dictReq, target) return do_post_serve_actions(dictResp) if __name__ == '__main__': app.run(debug=DEBUG, host=args.ip_address, port=args.port) This is how a request looks like: makeRequestAndSendData(xhr, dict) { dict['Interface'] = this.getChipInterface(); var data = JSON.stringify(dict); var url = this.server.getUrl(); console.log("url: "+url); console.log("Request Dictionary:"); console.log(dict); xhr.open("POST", url, true); xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); xhr.setRequestHeader("Access-Control-Allow-Headers","*"); xhr.setRequestHeader("Access-Control-Allow-Credentials", "true"); xhr.setRequestHeader("Content-type","application/json"); xhr.send(data); } Here is what I'm getting: Failed to load http://192.168.0.132:8084/mychip: Response to preflight request doesn't pass access control check: The 'Acc…
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86257689
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86252296
tagged with: flask

http://stackoverflow.com/comment/86250640
score: 0
comment on: http://stackoverflow.com/a/49618930
type: Comment
has text: Ok, I'll complete it.
type: AnswerComment

http://stackoverflow.com/comment/86533684
type: Comment
comment on: http://stackoverflow.com/q/49757496
type: QuestionComment
has text: File "C:\Users\playe\Anaconda3\lib\site-packages\discord\client.py", line 2163, in create_channel data = yield from self.http.create_channel(server.id, name, str(type), permission_overwrites=perms) File "C:\Users\playe\Anaconda3\lib\site-packages\discord\http.py", line 196, in request raise Forbidden(r, data) discord.errors.Forbidden: FORBIDDEN (status code: 403): Missing Permissions
score: 0

http://stackoverflow.com/q/49656005
answer count: 2
has answer: http://stackoverflow.com/a/49657382
linked to: http://stackoverflow.com/q/36680693
linked to: http://stackoverflow.com/q/40705889
tagged with: python
has answer: http://stackoverflow.com/a/62692616
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/42610635
tagged with: kivy
possible better answer: http://stackoverflow.com/a/62692616
linked to: http://stackoverflow.com/q/20872598
accepted answer: http://stackoverflow.com/a/49657382
type: Question
has body: I have a kivy app, which I was able to create with a white background using Window.clearcolor in the python file, as suggested in kivy: change background color to white . I then added a tabbed panel, which has caused the background to go back to black. I attempted to use canvas and canvas.before, and background_color to make it go back to white, but it still renders black (or rather dark grey). Reproducible Toy Example import kivy from kivy.lang import Builder from kivy.core.window import Window kivy.require('1.1.0') from kivy.app import App presentation = Builder.load_file("works.kv") class TestApp(App): def build(self): Window.clearcolor = (1, 1, 1, 1) return presentation if __name__ == '__main__': TestApp().run() with kv file: #:kivy 1.10.0 GridLayout: cols: 2 Label: text:'just to force spacing' Button: text: 'Hello World' but when I add a tabbed panel to the kv file, like the following, the background appears to be black (screenshots below): #:kivy 1.10.0 BoxLayout: TabbedPanel: do_default_tab: False background_color: (1, 1, 1, 1) TabbedPanelItem: text: 'Main' GridLayout: cols: 2 Label: text:'just to force spacing' Button: text: 'Hello World' TabbedPanelItem: text: 'Tab 2' SCREENSHOTS: Before adding panels: After adding panels (I would like the panel to have a white background, in this toy example the text would be white on white, but I have that handled in my app): Tried &lt;Main&gt;: name: 'mscreen' canvas.before: Color: rgba: 1, 1, 1, 1 Rectangle: pos: self.pos size: self.size TabbedPanel: do_default_tab: False TabbedPanelItem: text: 'Main' GridLayout: ... and similarly &lt;Main&gt;: name: 'mscreen' canvas: Color: rgba: 1, 1, 1, 1 Rectangle: pos: self.pos size: self.size TabbedPanel: do_default_tab: False TabbedPanelItem: text: 'Main' GridLayout:... If I'm reading Kivy's documentation on TabbedPanels correctly, I should be able to use background_color, but this also doesn't work: TabbedPanel: do_default_tab: False TabbedPanelItem: text: 'Main' background_colo…
tagged with: kivy-language
has title: Kivy Tabbed Panel won't change background color

http://stackoverflow.com/q/49719655
has comment: http://stackoverflow.com/comment/86464142
tagged with: python
favorite count: 0
score: 1
has title: To invert a ttk.progressbar()
type: Question
has body: I am trying to make a simple GUI based game with tkinter where I use ttk.Progressbar as a way to show the remaining health of my characters. However, when I use ttk.Progressbar.step(-x), it can only decrease the health of the character from the right to the left. Is there any way to 'invert' the progressbar so that the health decreases from left to right?
tagged with: tkinter
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/87109981
has text: @pradhyo I went under "Applications" and opened JupyterHub via the dropdown option in "Development." I also opened the port 9999 for all inbound traffic. This seemed to work.
type: QuestionComment
comment on: http://stackoverflow.com/q/49603966
score: 0
type: Comment

http://stackoverflow.com/q/49729810
score: 0
tagged with: list
upvote count: 1
answer count: 1
downvote count: 1
tagged with: arrays
has body: I have an ode equation which produces a list like below: u=[array([ 2.06642033, -0.03448756]), array([ 2.03964994, -0.18737285]), array([ 1.99884859, -0.21461016]), array([ 1.95476809, -0.2254584 ]), array([ 1.90875336, -0.23472173]), array([ 1.86082857, -0.24471069]), ... ] I want to plot u[0] and u[1] based on time. I try to access all first and second elements of u in two list with l1=u[0:len(u)-1][0] and l2=u[0:len(u)-1][1], but it gives me only the first item from list. Does anyone have a solution for it? Thanks
favorite count: 0
has comment: http://stackoverflow.com/comment/86473289
has answer: http://stackoverflow.com/a/49729908
type: AnsweredQuestion
has title: How to access the first items in a list of arrays without for loop in Python 3?
has comment: http://stackoverflow.com/comment/86473249
tagged with: python
type: Question
tagged with: numpy
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49729908

http://stackoverflow.com/a/50596844
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49745307
type: Answer
has body: I managed to achieve this with the help of a Singleton class. This is what I have done. This is the parent class. class Parent(object): ''' Class for Parent ''' def __init__(self, host, user, password): self.host = host self.user = user self.password = password def helper_method1(): // Implementation Then I've created a singleton class class ParentObjMgr(object): ''' A Singleton that stores the objects of different child classes. The child class needs to be instantiated here. This class needs to be instantiated in the caller. ''' __metaclass__ = Singleton def __init__(self, host, user, password): self._host = host self._user = user self._password = password self._child1 = None self._child2 = None def get_child1(self): if not self._child1: self._child1 = Child1(self._host, self._user, self._password) return self._child1 def get_child2(self): if not self._child2: self._child2 = Child2(self._host, self._user, self._password) return self._child2 Now I will implement child classes class Child1(Parent): // Implementation class Child2(Parent): // Implementation self.helper_method1() Now in the caller, I would do this parent_object_mgr=ParentObjMgr(self.host, self.user, self.password) child1=parent_object_mgr.get_child1() child2=parent_object_mgr.get_child2() This is how I have managed to access all the child class objects with the help of a single class object. Now, I don't have to instantiate the child classes, wherever they are being called and that is what I was looking for. Please let me know if it is an efficient solution (or) is there anything I need to do to improve it. Thanks
score: 0
accepted answer of: http://stackoverflow.com/q/49745307

http://stackoverflow.com/q/49664947
has answer: http://stackoverflow.com/a/49665331
has answer: http://stackoverflow.com/a/62401073
upvote count: 1
tagged with: python
score: 0
has title: How to fix the error: The array return by func must be one-dimensional, but got ndim=2
has body: Here is my code: import numpy as np from scipy.integrate import odeint import math y0=np.array([1,3,2,3,5]) b=np.array([[1],[3],[4],[2],[5]]) '''generate matrix''' B=np.dot(b,b.T) def g(t,y,B): return np.exp(np.dot(y,B)) t=np.linspace(0,1,100) y= odeint(g, y0, t, args=(B,)) The error is "The array return by func must be one-dimensional, but got ndim=2."
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86339601

http://stackoverflow.com/q/49731841
type: Question
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86478363
type: UnansweredQuestion
has body: I'm trying to jump to the next page without scraping and on the next page start scraping. This is my code. import scrapy import re class ProductSpider(scrapy.Spider): name = 'product' start_url = ['https://www.google.nl/search?client=opera&amp;biw=1880&amp;bih=1008&amp;output=search&amp;tbm=shop&amp;q=738678181690&amp;oq=738678181690&amp;gs_l=products-cc.12...0.0.0.2438282.0.0.0.0.0.0.0.0..0.0....0...1ac..64.products-cc..0.0.0....0.65SJMExjNxE#spd=0'] start_url = response.css('.MCpGKc &gt; a::attr(href)').extract_first() if start_url: start_url = response.urljoin(start_url) yield scrapy.Request(url=next_page_url, callback=self.parse) Here I start scraping, the problem is above. def parse(self, response): self.log('Bla Bla Bla:' + response.url) for product in response.css(".os-main-table"): item ={ "all_sellers": product.css(".os-seller-name-primary &gt; a::text").extract(), "all_prices": product.css("td.os-total-col::text").re("\d+\,\d{1,2}"), } for item in zip(all_prices,all_sellers): scraped_info = { 'all_sellers' : item[0], 'all_prices': item[1], } yield scraped_info next_page_url = response.css('.pag-prev-next-links &gt; a:last-child::attr(href)').extract_first() if next_page_url: next_page_url = response.urljoin(next_page_url) yield scrapy.Request(url=next_page_url, callback=self.parse)
tagged with: scrapy
downvote count: 1
has title: Jump to next page without scraping
favorite count: 0
score: 1
has comment: http://stackoverflow.com/comment/86478228
tagged with: python
has comment: http://stackoverflow.com/comment/86477367

http://stackoverflow.com/q/49735127
accepted answer: http://stackoverflow.com/a/49735650
downvote count: 0
has title: Subsampling an unbalanced dataset in tensorflow
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49735650
linked to: http://stackoverflow.com/q/47236465
answer count: 2
score: 5
upvote count: 5
tagged with: python
tagged with: tensorflow-datasets
favorite count: 0
has body: Tensorflow beginner here. This is my first project and I am working with pre-defined estimators. I have an extremely unbalanced dataset where positive outcomes represent roughly 0.1% of the total data and I suspect this imbalance to considerably affect the performance of my model. As a first attempt to solve the issue, since I have tons of data, I would like to throw away most of my negatives in order to create a balanced dataset. I can see two ways of doing it: preprocess the data to keep only a thousandth of the negatives then save it in a new file before passing it to tensorflow, for example with pyspark; and asking tensorflow to use only one negative out of a thousand it finds. I tried to code this last idea but didn't manage. I modified my input function to read like def train_input_fn(data_file="../data/train_input.csv", shuffle_size=100_000, batch_size=128): """Generate an input function for the Estimator.""" dataset = tf.data.TextLineDataset(data_file) # Extract lines from input files using the Dataset API. dataset = dataset.map(parse_csv, num_parallel_calls=3) dataset = dataset.shuffle(shuffle_size).repeat().batch(batch_size) iterator = dataset.make_one_shot_iterator() features, labels = iterator.get_next() # TRY TO IMPLEMENT THE SELECTION OF NEGATIVES thrown = 0 flag = np.random.randint(1000) while labels == 0 and flag != 0: features, labels = iterator.get_next() thrown += 1 flag = np.random.randint(1000) print("I've thrown away {} negative examples before going for label {}!".format(thrown, labels)) return features, labels This, of course, doesn't work because iterators don't know what's inside them, so the labels==0 condition is never satisfied. Also, there is only one print in the stdout, meaning that this function is only called once (and meaning that I still don't understand how tensorflow really works). Anyways, is there a way to implement what I want? PS: I suspect that the previous code, even if it worked as intended, would return less than a thous…
has answer: http://stackoverflow.com/a/68593137
possible better answer: http://stackoverflow.com/a/68593137
type: AnsweredQuestion

http://stackoverflow.com/q/49604997
answer count: 2
has answer: http://stackoverflow.com/a/49607287
downvote count: 0
tagged with: process
favorite count: 0
tagged with: daemon
type: Question
accepted answer: http://stackoverflow.com/a/49607291
has title: Why child process (daemon=True) not exiting when main process exit in python?
has answer: http://stackoverflow.com/a/49607291
has comment: http://stackoverflow.com/comment/86221122
has body: Here is the official explanation of daemon flag in python multiprocessing: When a process exits, it attempts to terminate all of its daemonic child processes. By my understanding, the parent process will kill its children whose daemon flag is set to be True when it exits. Below is the code I used to prove my guess. But the result is different. import multiprocessing def child(): while True: pass for x in xrange(1, 4): proc = multiprocessing.Process(target=child, args=()) proc.daemon=True proc.start() while True: pass The above starts 4 child processes and one main process. I killed the main process but the 4 children did not exit. So why are they not terminated by main since the daemon is set to be true?
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86219567
possible better answer: http://stackoverflow.com/a/49607287
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/86296546
comment on: http://stackoverflow.com/a/49617812
has text: My service require root privileges to perform some operations so I cannot change it. I need a way to generate pop-up from root.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49737945
answer count: 2
has title: GAE Can not use cloudstorage on dev environment
type: Question
has answer: http://stackoverflow.com/a/49759628
has answer: http://stackoverflow.com/a/49789260
type: UnansweredQuestion
tagged with: google-app-engine
has body: I'm using the dev build of GAE to upload some zip files, unzip and the edit them on the screen, as of now i'm just trying to see if the files can be opened after the upload and unzip. If I try to open it any other place them on a background tasks i get the following error: Traceback (most recent call last): File "/home/ricardo/workspace/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/wsgiserver/wsgiserver2.py", line 1302, in communicate req.respond() File "/home/ricardo/workspace/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/wsgiserver/wsgiserver2.py", line 831, in respond self.server.gateway(self).respond() File "/home/ricardo/workspace/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/wsgiserver/wsgiserver2.py", line 2115, in respond response = self.req.server.wsgi_app(self.env, self.start_response) File "/home/ricardo/workspace/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 292, in __call__ return app(environ, start_response) File "/home/ricardo/workspace/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/request_rewriter.py", line 314, in _rewriter_middleware response_body = iter(application(environ, wrapped_start_response)) File "/home/ricardo/workspace/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/request_handler.py", line 148, in __call__ environ[http_runtime_constants.REQUEST_ID_ENVIRON]) KeyError: 'HTTP_X_APPENGINE_DEV_REQUEST_ID' Here's the code: class ExportConfiguration(blobstore_handlers.BlobstoreUploadHandler): def post(self, store_id): # upload_files = self.get_uploads('file') bucket = '/' + BUCKET upload = self.get_uploads()[0] # write_retry_params = cloudstorage.RetryParams(backoff_factor=1.1) file = zipfile.ZipFile(upload.open()) # logging.info(file) for name in file.namelist(): outfile = file.read(name) outfile_list = name.split('/') for idx, path in enumerate(outfil…
tagged with: python
tagged with: google-cloud-storage
score: 0

http://stackoverflow.com/comment/86244473
type: QuestionComment
has text: Can you try closing the file first `filedata.close()` and then reading again before decoding like this - `file_data = open("path/to/file/",'rb')`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49618233

http://stackoverflow.com/q/49603083
has title: Boto3 client upload_fileobj throws error NoSuchBucket
tagged with: boto3
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86213724
answer count: 2
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49603512
has answer: http://stackoverflow.com/a/49603249
possible better answer: http://stackoverflow.com/a/49603249
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86214098
has body: I am trying to upload a file to my bucket i.e. test-bucket... So, I specified a constant AWS_S3_BUCKET="test-bucket" and defined the next function (from a some tutorial or forum): import boto3 from config import AWS_S3_LOCATION s3 = boto3.client('s3') def upload_file_to_s3(file, bucket_name, acl="public-read"):#bucket_name=AWS_S3_BUCKET try: s3.upload_fileobj( file, bucket_name, file.filename, ExtraArgs={ "ACL": acl, "ContentType": file.content_type } ) except Exception as e: print("Something Happened: ", e) return e return "{}{}".format(AWS_S3_LOCATION, file.filename) My config.py: import os AWS_S3_BUCKET = os.environ['AWS_S3_BUCKET'] AWS_S3_LOCATION = 'http://{}.s3.amazonaws.com/'.format(AWS_S3_BUCKET) DEBUG = True PORT = 5000 I have installed AWS Cli where I setup aws_access_key, aws_secret_access_key and region (eu-west-1). But when I try to upload a file I get an error: An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist {'Error': {'Code': 'NoSuchBucket', 'Message': 'The specified bucket does not exist', 'BucketName': 'test-bucket'}, 'ResponseMetadata': {'RequestId': 'blah-blah', 'HostId': 'blah-blah', 'HTTPStatusCode': 404, 'HTTPHeaders': {'x-amz-request-id': 'blah-blah', 'x-amz-id-2': 'blah-blah', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'date': 'Sun, 01 Apr 2018 21:59:44 GMT', 'connection': 'close', 'server': 'AmazonS3'}, 'RetryAttempts': 0}} What can be wrong? ADDED Uploading from the terminal using AWS CLI works: aws s3api put-object --bucket test-bucket --key test.txt --body test.txt ADDEDv2 I didn't understand what happened but after I sent a file from the terminal, my app became to work too. I chose a same file like before.
tagged with: python
accepted answer: http://stackoverflow.com/a/49603512

http://stackoverflow.com/comment/86407141
score: 2
type: AnswerComment
has text: You can hide the loop using `map`: `df.withColumn("NewColumn", F.array(map(F.lit, a)))`
comment on: http://stackoverflow.com/a/49684836
type: Comment

http://stackoverflow.com/comment/121855452
comment on: http://stackoverflow.com/a/49646093
score: 2
has text: Nice solution, you saved my time.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49701495
has comment: http://stackoverflow.com/comment/86417005
type: Answer
score: 6
downvote count: 1
answers question: http://stackoverflow.com/q/49701446
upvote count: 7
has comment: http://stackoverflow.com/comment/95389481
has body: You can create functions by calling the types.FunctionType constructor. Keep in mind however that this constructor is undocumented and implementation specific. In CPython, we can figure out the constructor arguments by calling help(types.FunctionType): class function(object) | function(code, globals[, name[, argdefs[, closure]]]) | | Create a function object from a code object and a dictionary. | The optional name string overrides the name from the code object. | The optional argdefs tuple specifies the default argument values. | The optional closure tuple supplies the bindings for free variables. To create a code object, we can use compile: code = compile('print(5)', 'foo.py', 'exec') function = types.FunctionType(code, globals()) function() # output: 5
has comment: http://stackoverflow.com/comment/86416827

http://stackoverflow.com/comment/86706897
type: AnswerComment
has text: That will still give me some polygons which do not occur in the original image.
comment on: http://stackoverflow.com/a/49603871
score: 0
type: Comment

http://stackoverflow.com/a/49671919
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/102626044
has body: You can use concat with dict comprehension with pop for extract column, remove second level and join to original: df1 = (pd.concat({i: pd.DataFrame(x) for i, x in df_actions.pop('actions').items()}) .reset_index(level=1, drop=True) .join(df_actions) .reset_index(drop=True)) What is same as: df1 = (pd.concat({i: json_normalize(x) for i, x in df_actions.pop('actions').items()}) .reset_index(level=1, drop=True) .join(df_actions) .reset_index(drop=True)) print (df1) type value id 0 a 17 12 1 b 19 12 2 a 1 15 3 b 3 15 4 c 5 15 Another solution if performance is important: L = [{**{'i':k, **y}} for k, v in df_actions.pop('actions').items() for y in v] df_actions = df_actions.join(pd.DataFrame(L).set_index('i')).reset_index(drop=True) print (df_actions) id type value 0 12 a 17 1 12 b 19 2 15 a 1 3 15 b 3 4 15 c 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49671693
answers question: http://stackoverflow.com/q/49671693
has comment: http://stackoverflow.com/comment/86354791
type: Answer
has comment: http://stackoverflow.com/comment/98824515
score: 25
has comment: http://stackoverflow.com/comment/86354844
upvote count: 25

http://stackoverflow.com/a/59390391
upvote count: 2
answers question: http://stackoverflow.com/q/49706746
downvote count: 0
has body: If You are using logging.config.fileConfig('someFile.conf'), make sure that You use disable_existing_loggers=False argument, so it will be: logging.config.fileConfig('someFile.conf', disable_existing_loggers=False) Documentation here: https://docs.python.org/3.7/library/logging.config.html#logging.config.fileConfig Otherwise access logs are suppressed. Leaving existing loggers alive might lead to appearing of other logs, for example, from requests or urllib3 library. Do not worry, just disable at the next line, if You do not need them: logging.getLogger("urllib3").setLevel(logging.WARNING)
type: Answer
score: 2

http://stackoverflow.com/a/49755137
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49755027
has body: You need not use pd.DataFrame.apply here. Instead, you can access the cat.codes property of a categorical column directly. In addition, you can use pd.DataFrame.pipe to run ("pipe") your dataframe through a function. Below is a verified example. def ChangeDatatypes(df): df['Name'] = df['Name'].astype('category').cat.codes df['Character'] = df['Character'].astype('category').cat.codes return df df = pd.DataFrame({'Name': ['a', 'b', 'c', 'd'], 'Character': ['e', 'f', 'g', 'h']}) df = df.pipe(ChangeDatatypes) print(df) # Character Name # 0 0 0 # 1 1 1 # 2 2 2 # 3 3 3 print(df.dtypes) # Character int8 # Name int8 # dtype: object
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49755027

http://stackoverflow.com/a/49617695
has comment: http://stackoverflow.com/comment/86242378
downvote count: 3
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86243146
has body: No libraries/built-ins to do that. Easiest way would be to convert the file into a CSV (either yourself by removing all commas then replacing whitespaces with commas or use a program if possible) Then you can use the DictReader class from the csv package to convert the file into a dictionary, then use the json module to dump it into a json string. pseudo-code e.g. after converting to csv. import json from csv import DictReader COLUMN_NAMES = ['your', 'column', 'names,', '...'] #Or the first row will be the column #(and the resulting key in the dictionary ) names jsonCollection = {} with open("your_csv_file.csv") as csvFile: #fieldnames is optional here reader = DictReader(csvFile, fieldnames=COLUMN_NAMES) for row in reader: for colName, rowVal in row.items(): jsonCollection.setdefault(colName, []).append(rowVal) json.dumps(jsonCollection) #should get you what you want
upvote count: 2
answers question: http://stackoverflow.com/q/49617178
has comment: http://stackoverflow.com/comment/86242446

http://stackoverflow.com/comment/86311790
score: 0
comment on: http://stackoverflow.com/q/49651501
type: Comment
type: QuestionComment
has text: You could also wrap the assignments in your for loop in a try-except block, catching IndexError specifically and print row in case an IndexError shows up. Then you can see which line(s) cause the issue and find ways to work around them.

http://stackoverflow.com/comment/86461102
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49723272
has text: About the .join .... you should only call tkinter on the main thread. If you don't join the threads it has the side effect that `turtle.done()` is called before the threads start. I can't explain why this seems to make tkinter happy with calling from other threads, but if you join, you get an error about calling tkinter in the wrong thread. The upshot is that although you could do calculations in the background, its not safe to call turtle itself from other threads.

http://stackoverflow.com/comment/86288411
type: Comment
comment on: http://stackoverflow.com/q/49640197
type: QuestionComment
score: 2
has text: pandas `apply` method is making too many requests at once using the `geopy` backbone, you can see here in the documentation you can make at most, 1 request a second, https://operations.osmfoundation.org/policies/nominatim/

http://stackoverflow.com/q/49683200
type: Question
has title: Extract data from HTML in sequence
answer count: 1
accepted answer: http://stackoverflow.com/a/49686598
downvote count: 0
upvote count: 1
has body: How do I extract all table contents and preceding data from a Wikipedia page e.g https://en.wikipedia.org/wiki/List_of_birds_of_Trinidad_and_Tobago where the data is in this repeated format, Order : Passeriformes Family : Passeridae Sparrows are small passerine birds ... Common name Binomial Status House sparrow Passer domesticus Trinidad only - Introduced species The output format desired is, Order, Family, Description, Name, Binomial, Status.
tagged with: html-parsing
has answer: http://stackoverflow.com/a/49686598
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/comment/107471859
type: AnswerComment
comment on: http://stackoverflow.com/a/54507446
has text: Maybe it's just me, but I was confused into thinking that contiguity is the deciding factor between when reshape does and does not share data. From my own experiments, it seems that this is not the case. (Your `x` and `y` above are both contiguous). Perhaps this can be clarified? Perhaps a comment on _when_ reshape does and does not copy would be helpful?
score: 3
type: Comment

http://stackoverflow.com/q/49724778
accepted answer: http://stackoverflow.com/a/75285522
has comment: http://stackoverflow.com/comment/86463490
score: 10
upvote count: 10
tagged with: python
has comment: http://stackoverflow.com/comment/86463679
tagged with: python-typing
answer count: 2
has comment: http://stackoverflow.com/comment/107255949
downvote count: 0
has body: I'd like to type hint a function like this: from types import Iterable def func(thing: Iterable[str]) -&gt; None: for i in range(10): for x in thing: do_thing(x) PyCharm will (correctly) let me get away with passing in a generator to this function, but I want to type hint it in a way that it won't allow me to, while still accepting other iterables. Using Sequence[str] isn't an option, iterables like KeyView aren't sequences, but I would still like to be able to include them. Someone mentioned using a Union with a Sequence + KeyView, which would work, but I was wondering if there was a more elegant and universal solution Of course, I could just convert thing to a list no matter what, but I'd rather just have this function type hinted correctly. Using Python 3.7
has comment: http://stackoverflow.com/comment/107255874
possible better answer: http://stackoverflow.com/a/79214899
favorite count: 0
type: Question
has title: Type hinting a non-generator (non-consumable) iterable
has comment: http://stackoverflow.com/comment/86463493
has answer: http://stackoverflow.com/a/79214899
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75285522

http://stackoverflow.com/comment/86494783
type: QuestionComment
has text: The question is: Do you want to manage your database with Django or not? If not, simply use `managed = False` in the `Meta` class of the object and don't mage migrations. If you want Django to "take over" the management, it is possible, but a little tricky.
score: 0
comment on: http://stackoverflow.com/q/49739795
type: Comment

http://stackoverflow.com/comment/86524973
has text: `Counter` object from `collections` module perfectly fits that purpose, and is part of standard library.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49755002

http://stackoverflow.com/q/49634577
tagged with: django-file-upload
tagged with: django
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has title: Unzipping file submission without storage in Django
favorite count: 0
type: Question
has body: I'm currently building an application that will be used and maintained by another developer shortly in the future. What I want is the ability to upload a zip file, unzip and process the contents, and discard the file without ever actually storing it in the Django file storage system. These are the relevant parts of what I have right now: views.py: def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] if str(myfile.name).endswith('.zip'): ## THIS STORES THE FILE -- NOT WHAT I WANT #fs = FileSystemStorage() #filename = fs.save(myfile.name, myfile) uploaded_file_url = str(myfile.name) return render(request, 'webapp/upload.html', { 'uploaded_file_url': uploaded_file_url }) file_error = "There was an error processing the file" return render(request, 'webapp/upload.html', { 'file_error': file_error }) return render(request, 'webapp/upload.html') upload.html {% extends "./base.html" %} {% block content %} {% csrf_token %} Upload {% if uploaded_file_url %} File uploaded at: {{ uploaded_file_url }} {% endif %} {% if file_error %} There was an error in the file submission. {% endif %} {% endblock %} I know that checking if a file ends with .zip is not necessarily indicative of whether it's actually a zip file or not but it is sufficient for my purposes right now. myfile is a UploadedFile and I'm trying to find a way to unzip and process the contents but I'm not sure how to go about this. I could just store it in the FileSystem and then process it from there but I'd like to avoid storing it at all if possible. Any suggestions on how to do this would be greatly appreciated.

http://stackoverflow.com/q/49675972
accepted answer: http://stackoverflow.com/a/49676125
type: Question
has answer: http://stackoverflow.com/a/49676125
tagged with: python
has body: I am trying to add two new columns to my DataFrame that are copy of current columns, but despite seeing outputs of my assign method showing the columns as a part of my DataFrame, when I run the head() method they do not appear. Am I using the correct command to update my DataFrame with duplicates of two columns under new names? I am running all of these commands through jupyter notebooks Current Column -&gt; New Column (Duplicate of Current Column) 'date' -&gt; 'ts' 'y' -&gt; 'clicks' Code: import pandas as pd import numpy as np from fbprophet import Prophet df = pd.read_csv('car-sales-raw-data.csv') allDf = df allDf = allDf.fillna(0) allDf['date'] = pd.to_datetime(allDf['date']) allDf.head() """ OUTPUT """ date day_of_week leads clicks cars 181 2017-07-01 Saturday 44 611 26 182 2017-07-02 Sunday 30 203 14 183 2017-07-05 Wednesday 55 994 25 184 2017-07-06 Thursday 50 2854 23 185 2017-07-07 Friday 78 850 52 # duplicate date and click columns allDf.assign(ds = allDf['date']) allDf.assign(y = allDf['clicks']) allDf.head() """ OUTPUT """ date day_of_week leads clicks cars 181 2017-07-01 Saturday 44 611 26 182 2017-07-02 Sunday 30 203 14 183 2017-07-05 Wednesday 55 994 25 184 2017-07-06 Thursday 50 2854 23 185 2017-07-07 Friday 78 850 52
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has title: Python Pandas Copied Columns not Appearing in Head

http://stackoverflow.com/comment/86544693
comment on: http://stackoverflow.com/q/49754679
type: Comment
type: QuestionComment
score: 0
has text: This question has a lot of solutions - did any work or help you at all?

http://stackoverflow.com/a/49738110
answers question: http://stackoverflow.com/q/49703484
downvote count: 0
has comment: http://stackoverflow.com/comment/86506857
has comment: http://stackoverflow.com/comment/86526500
has comment: http://stackoverflow.com/comment/86506825
upvote count: 2
has body: As the traceback shows, the error is at the line where you define outlook. Actually, there is no cap S in GetNamespace so replace this line by: outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") but other errors occur, at the line where body is defined, a cap is mandatory for the attribute, such as body = message2.Body, and another cap issue in x.SaveASFile, it should be x.SaveAsFile Finally, I'm not sure that your code will do what you describe as you try to download the attachments of message2, being your last message, while you iterate through messages, I don't see the point then. Let me know if you need more help or if I misunderstood your problem.
has comment: http://stackoverflow.com/comment/86528608
type: Answer
has comment: http://stackoverflow.com/comment/86528452
has comment: http://stackoverflow.com/comment/86528308
has comment: http://stackoverflow.com/comment/86526393
has comment: http://stackoverflow.com/comment/86525818
score: 2
has comment: http://stackoverflow.com/comment/86528568

http://stackoverflow.com/a/49679736
upvote count: 2
downvote count: 0
has body: As per the language specification, imported bindings are immutable bindings, so they cannot be changed. The identifiers are reserved as the module gets parsed because of how ES6 modules work: Unlike in Python, imports are not statements that are included as they are executed; instead, all a module’s imports are basically collected during the early compilation and then resolved before the module starts executing. This makes ES6 modules kind of unsuitable as an implementation for Python’s import system. As a general way, to avoid losing those names, you can simply give the imported bindings different names. For example an from foo import bar, baz may be compiled to the following: import { bar as _foo__bar, baz as _foo__baz } from 'foo'; let bar = _foo__bar; let baz = _foo__baz; That will only reserve some special names while keeping the bar and baz identifiers mutable. Another way, which would probably also help you to solve possible import semantics differences would be to simply create a closure: import { bar, baz } from 'foo'; (function (bar, baz) { // … })(bar, baz); Or even add some other lookup mechanism in between. Btw. Python’s import is very similar to Node’s require, so it might be worth looking into all those solutions that made Node’s module system work in the browser.
score: 2
has comment: http://stackoverflow.com/comment/86371351
answers question: http://stackoverflow.com/q/49679340
type: Answer

http://stackoverflow.com/q/49601166
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49601369
tagged with: pandas
score: 1
has body: I have a Series object that has: df = index value 2014-05-23 07:00:00 0.67 2014-05-23 07:30:00 0.47 2014-05-23 08:00:00 0.42 2014-05-23 08:30:00 0.80 .... 2017-07-10 22:00:00 0.42 2017-07-10 22:30:00 0.79 2017-07-10 23:00:00 0.84 2017-07-10 23:30:00 Nan I would like to calculate the average in a year, and then group by month, so the dataframe would look like this, df_new = index value Jan {0.11, 0.5, 0.3, 0.99, ... ,0.13} &lt;- time step of each value is Feb {...............................} still 30 min, and each Mar {...............................} value is average of same Apr {...............................} time in the other year. .... Dec {...............................} I have some dataframe like this but with different time interval (15min, 60min ...), is there any better to calculate it automatically ? For example like function, and it would automatically know the time step from the index. Thanks in advance !
downvote count: 0
answer count: 1
has title: Pandas series sort by month index (time series different) in python
has comment: http://stackoverflow.com/comment/86209739
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49601369
tagged with: datetime

http://stackoverflow.com/comment/86366769
type: QuestionComment
score: 1
has text: Which language?
type: Comment
comment on: http://stackoverflow.com/q/49677732

http://stackoverflow.com/q/49709652
downvote count: 0
upvote count: 1
has title: How do I sort my topics by category in Django?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49709739
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49709739
type: AnsweredQuestion
has body: Alright so I want to order my topics by the category in Django. What's the best way of doing this? views.py: from django.shortcuts import render from .models import Category from .models import Topic # Create your views here. def forums(request): categorys = Category.objects.all() topics = Topic.objects.all() return render(request, 'forums.html', {'categorys': categorys, 'topics': topics}) models.py: from django.db import models # Create your models here. class Attachment(models.Model): file = models.FileField() def __str__(self): return self.file class Category(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Topic(models.Model): title = models.CharField(max_length=150) description = models.TextField() category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=150) body = models.TextField() forum = models.ForeignKey('Topic', on_delete=models.CASCADE) def __str__(self): return self.title Also, yes I know that categories is spelled wrong, I still need to add the Meta.
score: 1
answer count: 1

http://stackoverflow.com/a/49620927
has body: The traditional POSIX answer to this is to use a pidfile: a file stored in a consistent location that just holds the PID of the process. The reason you want to store the PID is so that if the script is killed, a new copy of your program will be able to see that and take over, instead of falsely reporting that another copy is already running. (You can send a 0 signal with os.kill; if it succeeds, the process exists.) There are libraries to do this for you and get all the details right, but a simple version is: import os import sys PIDFILE = '/var/run/myscript.pid' def is_running(): try: with open(PIDFILE) as f: pid = int(next(f)) return os.kill(pid, 0) except Exception: return False if __name__ == '__main__': if is_running(): print('Another copy is already running') sys.exit(0) with open(PIDFILE, 'w') as f: f.write(f'{os.getpid()}\n') You probably want cleaner error handling in real code, and you need to think about races, but I've kept it simple to make the idea clear. (If you want to do this for real, you're probably better off using a library, or thinking through all the issues yourself, than copying code off SO.) The traditional Windows answer is a little different. On Windows, it's very easy to get a mandatory exclusive lock on a file or other resource that's automatically released on exit. In fact, that's what happens by default when you open a file—but, unfortunately, it’s not what happens with Python’s open, which goes out of its way to allow sharing. You can use a library like win32api from PyWin32, or just ctypes, to call CreateFile requesting exclusive access. If you fail because the file is locked, there's another process running. It’s also important to decide where to create the file. Normally you use a per-user temp directory rather than a global one, which means each user can have one copy of the program running, rather than one copy for the entire system.
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/86249576
answers question: http://stackoverflow.com/q/49620862
downvote count: 0
has comment: http://stackoverflow.com/comment/86249630
has comment: http://stackoverflow.com/comment/86249615
score: 3

http://stackoverflow.com/q/49712889
has title: How to create a package of models in Django
answer count: 3
has answer: http://stackoverflow.com/a/50262767
score: 6
has body: Having a quite large models.py file (which contains several models), I'm trying to refactor, with one model per file. I'm therefore trying to create a models package, with the following structure: app/models/__init__.py app/models/first_model.py app/models/second_model.py Unfortunately, I cannot get Django lazy reference mechanism to work well, i.e.: first_model = models.ForeignKey('app.FirstModel') returns the error that Django cannot find the model. Any idea? Thanks!
downvote count: 0
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50262554
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/49714803
upvote count: 6
has answer: http://stackoverflow.com/a/49714803
possible better answer: http://stackoverflow.com/a/50262767

http://stackoverflow.com/comment/88259433
comment on: http://stackoverflow.com/a/50138915
has text: the issue I have with Tkinter and it’s kin, is they run in a blocking event loop which needs to run in the main thread. IB also has to run in the main thread.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/49720343
has answer: http://stackoverflow.com/a/49720444
score: -2
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49720564
type: AnsweredQuestion
tagged with: list
tagged with: random
has comment: http://stackoverflow.com/comment/86453966
has comment: http://stackoverflow.com/comment/86453769
has comment: http://stackoverflow.com/comment/86454369
has comment: http://stackoverflow.com/comment/86453759
has body: So, the assignment is to ask the user for how many randomly generated numbers they want in a list, and then from that list find the: total(sum), the average, the smallest and the largest number. SOFAR, I am getting an error on line 14 "object of type 'int' has no len()". I get the same responce when using &lt; too. import random def main(): randomList = 0 smallest = 0 largest = 0 average = int(input("How may numbers (between 1-100) would you like to generate?: ")) total = 0 if average &gt;= 101 or average &lt;= 0: print("Invalid input:How may numbers (between 1-100) would you like to generate?: ") else: while randomList != len(int(average)): randomList.append(random.randint(1,101)) randomList=sorted(randomList) print(randomList) total = sum(randomList) average = float(sum(randomList)) / max(len(randomList)) largest = randomList.pop(average) smallest = randomList.pop(0) print('The total of all the numbers are ',str(total)) print('The average of all the numbers are ',str(average)) print('The largest of all the numbers are ',str(largest)) print('The smallest of all the numbers are ',str(smallest)) main()
downvote count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/49720564
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49720444
has title: Generate a list of random numbers
answer count: 2

http://stackoverflow.com/comment/86292498
type: Comment
has text: Wow... nicely done. I'll take a look at YAML as well. Is there preferred library?
type: AnswerComment
comment on: http://stackoverflow.com/a/49617165
score: 0

http://stackoverflow.com/a/49756948
has body: You have mapping in your YAML with a key Object1 and a value that is a tagged mapping with tag !MyObject. For YAML that key is not the name of the instance, it is just a key in mapping, whose value happens to be a tagged mapping. When constructing that tagged mapping that key is not available as it is not part of your object. The parser of course already has that key Object1 constructed somewhere as a node, when it starts parsing your object, but you cannot access that without heavily changing the parser. And if you do that, things would likely break if your YAML looked like: MyList: - !MyObject value1: Test value2: 1.0 where there is no such key. IMO you should change your YAML to look like: MyList: !MyObject Object1: value1: Test value2: 1.0 Or to the following, that is easier to load: MyList: - !MyObject name: Object1 value1: Test value2: 1.0 If you cannot change your YAML, your best option is to write a (recursive) tree-walker that updates your objects after your call to safe_load(). You should also consider writing from_yaml as a generator. As it is now it will break as soon as your !MyObject gets more complicated values that might include self-references at some point in the future.
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49756482
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/49613851
has answer: http://stackoverflow.com/a/49614041
accepted answer: http://stackoverflow.com/a/49614041
has body: I have problem with my urls. Path of my site in localhost is: http://127.0.0.1:8000/detska-kniznica When I want to login I will click on the button and path looks like this: http://127.0.0.1:8000/detska-kniznica/login And when I will submit the form path looks like this: http://127.0.0.1:8000/detska-kniznica/login/logUser Problem is when I type incorrect password or username django returns forms to the same url so: http://127.0.0.1:8000/detska-kniznica/login/logUser And when I will again type correct username and password url looks like this: http://127.0.0.1:8000/detska-kniznica/login/login/logUser and this url does not exist. I will show you my urls: urlpatterns = [ path('detska-kniznica', include('homepage.urls')), path('detska-kniznica/admin', admin.site.urls), path('detska-kniznica/games', include('games.urls')), path('detska-kniznica/register', include('register.urls')), path('detska-kniznica/login', include('login.urls')), ] and urlpatterns = [ path('', views.index), path('/logUser', views.log_user), path('/logOut', views.log_out_user), ] my HTML submit button do this: &lt;form action="login/logUser" method="post" novalidate&gt; and my views.py looks like this: elif request.method == 'POST' and 'btn_login' in request.POST: form = inputForms.LogUser(request.POST) if form.is_valid(): print(form.errors) user_name = form.cleaned_data['username'] user_password = form.cleaned_data['password'] user = authenticate(username=user_name, password=user_password) if user is not None: print("som tu") request.session.set_expiry(86400) # sets the exp. value of the session login(request, user) # the user is now logged in else: print("help") print(form.errors) return render(request, "login.html", {'LogUser': form}) return HttpResponseRedirect('/detska-kniznica') else: print(form.errors) return render(request, "login.html", {'LogUser': form}) line above shoul return /login but it returns /login/logUser and this is wrong else: print("Error: bad request in login.") return HttpResp…
answer count: 1
tagged with: python
favorite count: 0
type: Question
has title: Django path missmatch
upvote count: 2
tagged with: path
downvote count: 0
tagged with: django
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/49626310
answer count: 4
tagged with: extract
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49626422
has body: Simple question: How to only extract integers (no floats) from a list of strings? Like this: list_1 = [['50', 'ALA', 'A', '53', '5', '4'], ['55', 'GLY', 'A', '60', '1', '6'], ['67', 'ILE', 'A', '71', '5', '5']] To this: list_1 = [['50', '53', '5', '4'], ['55', '60', '1', '6'], ['67', '71', '5', '5']] Thank you.
upvote count: 1
has answer: http://stackoverflow.com/a/49626425
has comment: http://stackoverflow.com/comment/86259916
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49626353
type: Question
has answer: http://stackoverflow.com/a/49626353
has comment: http://stackoverflow.com/comment/86260072
tagged with: python
possible better answer: http://stackoverflow.com/a/49626632
has answer: http://stackoverflow.com/a/49626632
has title: Is there a way to output the numbers, that are in string format, only from a python list?
tagged with: list

http://stackoverflow.com/q/49640981
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86290194
answer count: 1
has answer: http://stackoverflow.com/a/49641057
tagged with: google-bigquery
has title: Python, pandas.read_csv on large csv file with 10 Million rows from Google Drive file
type: Question
tagged with: google-drive-api
has comment: http://stackoverflow.com/comment/86289822
has comment: http://stackoverflow.com/comment/86290569
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86289930
has body: I extracted a .csv file from Google Bigquery of 2 columns and 10 Million rows. I have downloaded the file locally as a .csv with the size of 170Mb, then I uploaded the file to Google Drive, and I want to use pandas.read_csv() function to read it into pandas DataFrame in my Jupyter Notebook. Here is the code I used, with specific fileID that I wanna read. # read into pandasDF from .csv stored on Google Drive. follow_network_df = pd.read_csv("https://drive.google.com/uc?export=download&amp;id=1WqHWdgMVLPKVbFzIIprBBhe3I9faq4HA") Then here is what I got: It seems the 170Mb csv file is read as an html link? While when I tried the same code with another csv file of 40Mb, it worked perfectly # another csv file of 40Mb. user_behavior_df = pd.read_csv("https://drive.google.com/uc?export=download&amp;id=1NT3HZmrrbgUVBz5o6z_JwW5A5vRXOgJo") Can anyone give me some hint on the root cause of the difference? Any ideas on how to read a csv file of 10 Million rows and 170Mb from online storage? I know it's possible to just read the 10 Million rows into pandasDF by just using the BigQuery interface or from local machine, but I have to include this as part of my submission, so it's only possible for me to read from online source.

http://stackoverflow.com/q/49749706
type: Question
upvote count: 12
linked to: http://stackoverflow.com/q/57278214
has comment: http://stackoverflow.com/comment/86516089
has title: Randomly sample from multiple tf.data.Datasets in Tensorflow
tagged with: python
has answer: http://stackoverflow.com/a/49749970
has answer: http://stackoverflow.com/a/54337427
accepted answer: http://stackoverflow.com/a/54337427
has comment: http://stackoverflow.com/comment/86513882
score: 12
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52011299
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52011299
has body: suppose I have N tf.data.Datasets and a list of N probabilities (summing to 1), now I would like to create dataset such that the examples are sampled from the N datasets with the given probabilities. I would like this to work for arbitrary probabilities -> simple zip/concat/flatmap with fixed number of examples from each dataset is probably not what I am looking for. Is it possible to do this in TF? Thanks!
tagged with: tensorflow
favorite count: 0
tagged with: tensorflow-datasets

http://stackoverflow.com/comment/86460032
type: QuestionComment
comment on: http://stackoverflow.com/q/49712543
has text: (1) no response, just a quick return and exit, exit code=0 (2) I do not have that file.
score: 0
type: Comment

http://stackoverflow.com/comment/86317277
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49651595
has text: Yes I did, but its not even similar. In the dupe they need to change one column, that is also the reference. In my case my reference is ID, while I need to change column OLD_VALUES. so I have 2 columns in both files, while the other question has 1 column in file 1 and 2 columns in file 2. I need to change column OLD_VALUE with VALUE when ID matches SNPS.
type: Comment

http://stackoverflow.com/comment/86545810
comment on: http://stackoverflow.com/q/49750173
score: 0
type: Comment
type: QuestionComment
has text: payload is like this. `payload = {'username': url_encode(id), 'password': password}`

http://stackoverflow.com/q/49672902
score: 6
tagged with: django
tagged with: python
upvote count: 6
answer count: 0
downvote count: 0
has body: I'm trying to query a multi-column fulltext index in Django using a Lookup. I have the following lookup @CharField.register_lookup @TextField.register_lookup class Search(models.Lookup): lookup_name = "search" def as_mysql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return "MATCH (%s) AGAINST (%s IN BOOLEAN MODE)" % (lhs, rhs), params This is inspired from the lookup that I found here in the Django docs. However, this appears to only work for Fulltext indexes of a single column. I'm trying to do a query over two columns. Below is my MySQL table for reference: CREATE TABLE Entry ( entryID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(20) NOT NULL, time DATETIME NOT NULL, modified BOOLEAN NOT NULL, message TEXT NOT NULL, FULLTEXT (message, username), PRIMARY KEY (entryID) ); Of course when I try to do a query using the lookup above, I get an error: "django.db.utils.OperationalError: (1191, "Can't find FULLTEXT index matching the column list" I noticed there is Django code to accomplish this using a SearchVector, but only for PostgresSQL. Additionally, I realize there is a package that someone wrote to do this at https://blog.confirm.ch/django-1-8-mysql-mariadb-full-text-search/ However, I really wanted to know if there is a way I can accomplish easily without additional packages. Thank you!
linked to: http://stackoverflow.com/q/61486725
favorite count: 0
type: Question
has title: Django way to query multi column fulltext index in MySQL?
type: UnansweredQuestion

http://stackoverflow.com/comment/86479190
comment on: http://stackoverflow.com/q/49732726
score: 1
type: Comment
type: QuestionComment
has text: The question is quite vague, also because the equation is provided without explaining the notation. Do you want to know how to extract the gradient of a function in python? Take a look at numpy.gradient : https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html

dll
tags question: http://stackoverflow.com/q/49744870
tags question: http://stackoverflow.com/q/49690898
tags question: http://stackoverflow.com/q/49647689
tag name: dll
type: Tag
tags question: http://stackoverflow.com/q/49662522

http://stackoverflow.com/q/49638106
has answer: http://stackoverflow.com/a/49639573
answer count: 1
has body: In Python 3.6, is it possible to specify a set of types expected for a specific argument? For example, suppose I have two classes Point and Dot. I have a function, foo, which takes one argument. I want to use static type checking to make sure the argument passed is either a Point or a Dot. I am looking for something like this: def foo(x: [Point, Dot]) but this isn't valid syntax. I am trying not to create two separate functions for this, and I would like to use static type checking, new to Python 3.6
tagged with: polymorphism
type: Question
tagged with: static
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86284520
tagged with: python
score: 0
tagged with: types
has title: Python polymmorphic functions with static type checking
has comment: http://stackoverflow.com/comment/86284054

http://stackoverflow.com/a/77440661
score: 0
answers question: http://stackoverflow.com/q/49685498
has body: This works for me: installing conda in colab within conda installing sage Problems: at the start of each cell where you want to use sage you have to use this: %%bash source activate sage effectively, this "solution" only enables to use sage within colab, it is definitely not a proper full solution Installation: !pip install -q condacolab import condacolab condacolab.install() !conda create -n sage sage python=X # X is version of python, for instance 3.9 Now make your program %%bash source activate sage sage -c ' YOUR CODE HERE '
type: Answer
has comment: http://stackoverflow.com/comment/136524182
has comment: http://stackoverflow.com/comment/136528347
has comment: http://stackoverflow.com/comment/136528453

http://stackoverflow.com/a/49622313
has comment: http://stackoverflow.com/comment/86253268
has body: Usually this can be set by set_position, and specifying 'data': plt.subplot(10,1,x).spines['bottom'].set_position(('data', -1)) ‘data’ : place the spine at the specified data coordinate. ↳ matplotlib.spines | set_position
has comment: http://stackoverflow.com/comment/86253399
type: Answer
answers question: http://stackoverflow.com/q/49621994
score: 0

http://stackoverflow.com/a/49712371
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/86439167
has body: You're trying to use a feature that isn't in the latest released version yet. You can see on PyPI that the current version was released on 5 Jan 2017, but you can see on Github that the function you want to call was added on 13 May 2017. Issue #270 and Issue #211 are both asking when a new release will be pushed to PyPI, (Also, there's some weird issue with the version numbering.) Anyway, as #211 says: If you're running into issues still, you can install the package directly from the github repo. pip install git+https://github.com/plamere/spotipy.git --upgrade
accepted answer of: http://stackoverflow.com/q/49712100
score: 2
answers question: http://stackoverflow.com/q/49712100
type: AcceptedAnswer

http://stackoverflow.com/comment/86438391
comment on: http://stackoverflow.com/q/49712430
score: 0
type: Comment
type: QuestionComment
has text: And what is the content of `data`?

minidom
tags question: http://stackoverflow.com/q/49738661
type: Tag
tag name: minidom

http://stackoverflow.com/comment/86358821
score: 0
type: Comment
type: QuestionComment
has text: Since you're using `Table` instead of a mapped class this is not quite an exact duplicate, but you'll find the answer here: [Relations on composite keys using sqlalchemy](https://stackoverflow.com/questions/7504753/relations-on-composite-keys-using-sqlalchemy)
comment on: http://stackoverflow.com/q/49673471

http://stackoverflow.com/q/49661492
tagged with: copy-paste
has answer: http://stackoverflow.com/a/49679290
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pycharm
has title: pycharm ctrl+v copies the item in console instead paste when highlighted
answer count: 1
tagged with: ide
has body: This has been a very annoying problem for me and I couldn't find any keymaps or settings that could cause this behavior. Setup: Pycharm Professional 2018.1 installed on redhat linux I remote into the linux machine using mobaX and launch pycharm with window forwarding Scenario 1: I open a browser on windows, copy some text, go to editor or console, paste it somewhere without highlighting any text, hit ctrl+v, it pastes fine Scenario 2: I open a browser on windows, copy some text, go to editor or console, highlight some text there, hit ctrl+v in attempt to replace the highlighted text with what's in my clipboard. The text didn't change. I leave pycharm and paste somewhere else, the text in clipboard has now become the text I highlighted. Edit: ok I just realized this: as soon as I highlight the text, it gets copied...I've turned this feature off for terminal, but couldn't find a global settings for the editor etc. Anyone know how?
accepted answer: http://stackoverflow.com/a/49679290
type: Question

http://stackoverflow.com/q/49625820
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Django best practice to get object from id in POST request
has answer: http://stackoverflow.com/a/49626406
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86258898
has body: In my API, sometimes you make HTTP request with id of objects (like update preferred address you put the id of your new default address). I retrieve it like this: address = get_object_or_404( Address.objects.filter(...), pk=request.data['address_pk'] ) This is completely functional, however it doesn't feel as the best way. I tried to search for the best practice, however I was not able to find proper search term which would satisfy my curiosity. Is this way of getting a model instance from a request a good practice? Or should it be avoided?
tagged with: django
has comment: http://stackoverflow.com/comment/86259269
tagged with: python
has answer: http://stackoverflow.com/a/49627038
linked to: http://stackoverflow.com/q/11041405
answer count: 4
score: 0
has answer: http://stackoverflow.com/a/49626437
has answer: http://stackoverflow.com/a/49626379
has comment: http://stackoverflow.com/comment/86258688
linked to: http://stackoverflow.com/q/28545553

http://stackoverflow.com/comment/86349502
comment on: http://stackoverflow.com/a/49666871
type: Comment
score: 0
type: AnswerComment
has text: Works for me with all these values. Please append the problematic values.

http://stackoverflow.com/comment/86341130
type: Comment
has text: What about VMware?
type: QuestionComment
comment on: http://stackoverflow.com/q/49657966
score: 0

http://stackoverflow.com/comment/86408849
type: AnswerComment
comment on: http://stackoverflow.com/a/49683957
score: 0
type: Comment
has text: Thanks. Unfortunately for me, this still results in only the densist points being colored, rather than a smooth gradient from most to least dense. Also, just FYI, the 'darkblue' color was for the scatter plot only, the histogram was added as an image before that with the jet cmap.

http://stackoverflow.com/comment/86325326
type: QuestionComment
has text: Could you perform a 2D interpolation after creating a meshgrid from X and Y?
comment on: http://stackoverflow.com/q/49657956
score: 0
type: Comment

http://stackoverflow.com/comment/86508382
score: 0
has text: Did you by any chance use the Jupyter extension? I came across the same error couple days back, I think the #%% code lense syntax was not recognized if you try to run it in the normal terminal.
comment on: http://stackoverflow.com/q/49697090
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49604157
has body: Use scipy.special.xlogy. It treats zeros correctly: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from scipy import special &gt;&gt;&gt; &gt;&gt;&gt; p = np.array([0.5, 0.1, 0.0, 1.0, 0.0, 0.9]) &gt;&gt;&gt; y = np.array([0, 1, 0, 1, 1, 1 ]) &gt;&gt;&gt; &gt;&gt;&gt; -special.xlogy(y, p) - special.xlogy(1-y, 1-p) array([ 0.69314718, 2.30258509, -0. , -0. , inf, 0.10536052])
downvote count: 0
answers question: http://stackoverflow.com/q/49602205
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/86289766
type: QuestionComment
comment on: http://stackoverflow.com/q/49640823
type: Comment
score: 0
has text: @Brayden That's the way to import csv I believe. Let me know what you think?

http://stackoverflow.com/comment/86438454
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49712328
has text: The 1st part of the question was how did you do the install??.. You have something very non-standard in the way you have installed,, I'd suggest starting over with Anaconda

http://stackoverflow.com/comment/86483441
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49689595
has text: when i am trying to send structure with headers added giving following errorTypeError: cannot concatenate 'str' and 'ctype structure' objects my code: pkt = self.dstMacAddr + self.srcMacAddr + etherType + <ctype structure object>
score: 0

http://stackoverflow.com/comment/87054878
score: 0
type: Comment
has text: @Ghostintheshell I updated the answer. There is indeed something going on with the "n_jobs" parameter, but seems to be due to "lightgbm" package. Nothing to do with Datalab/VMs
type: AnswerComment
comment on: http://stackoverflow.com/a/49980435

http://stackoverflow.com/q/49683075
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86387419
tagged with: python
accepted answer: http://stackoverflow.com/a/49683217
has title: openpyxl possible lambda usage
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49683217
upvote count: 0
has body: I was trying to assign value of a cell equal to sum of few other cell. I could achieve this using two line like dailycell=45 while sheet['E' + str(dailycell)].value is not None: mysum+=sheet['E'+str(dailycell)].value sheet['B13']=mysum dailycell+=1 With my limited knowledge, I tried lambda. Then I get all sort of error. I tried few more iteration but none got me the same result. sheet['B13']=lambda weeklybudget,sheet['E'+str(dailycell)].value:weeklybudget+=sheet['E'+str(dailycell)] Is there an alternative to this?
tagged with: openpyxl
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/86261045
score: 0
comment on: http://stackoverflow.com/q/49626880
type: Comment
type: QuestionComment
has text: @Faibbus agreed. `self.listOfObject.append(self.tempObject)` is needed.

http://stackoverflow.com/q/49713058
has comment: http://stackoverflow.com/comment/86439528
favorite count: 0
has title: Python "\\" and "\" interchangable?
type: Question
type: UnansweredQuestion
downvote count: 2
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49713166
duplicate of: http://stackoverflow.com/q/3380484
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/129388053
duplicate of: http://stackoverflow.com/q/29245234
tagged with: subprocess
linked to: http://stackoverflow.com/q/59460305
linked to: http://stackoverflow.com/q/2953834
has comment: http://stackoverflow.com/comment/129388048
has body: I'm not sure why this is happening so i don't know how to resolve it, if my question is unclear please ask and i will clarify. I am on a 32bit windows and running python2.7. I have a list "commands" commands = ['open', 'C:\\Users\\Me\\Videos\\manimmedia\\animations\\example_scenes\\1080p60\\SquareToCircle.mp4'] When i print commands[-1] i get 'C:\Users\Me\Videos\manimmedia\animations\example_scenes\1080p60\SquareToCircle.mp4' The "\\" becomes single slash "\", but when i put it back in it becomes "\" again. So when i run windows doesn't see that path when i run the code so it gives a "WindowsError: [Error 2] The system cannot find the file specified" How do i replace double slash as single slash? edit When i include command as an argument, does it send the one with the single backslash or the one with the double slashes ? Basically is the string treated differently or are they both identical?
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86509513
comment on: http://stackoverflow.com/a/49734505
has text: ok did u not get any tables while rendering the content what u have got as tags
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49629466
answers question: http://stackoverflow.com/q/49629333
has body: I'm sorry for that post. Changed console width and found that my strings are read from file with \n at the end, so URL is broken. So the solution is: str(RRPTR).replace("-", "%2D").replace('\n', "") as the part of my URL.
type: Answer
score: 0

http://stackoverflow.com/a/49748695
has body: One efficient method is to use pd.Series.map: df['num2'] += df['cls'].map({'a': 10, 'b': -10}) This uses a dictionary to map values of cls to either 10 or -10. There are many other methods (see @Guybrush's answer), but the dictionary-based method is extendable and efficient for larger dataframes. In my opinion, it is also readable. Relevant: Replace values in a pandas series via dictionary efficiently
answers question: http://stackoverflow.com/q/49748498
type: Answer
has comment: http://stackoverflow.com/comment/86512293
accepted answer of: http://stackoverflow.com/q/49748498
downvote count: 0
has comment: http://stackoverflow.com/comment/86512801
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86512977
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86512405

http://stackoverflow.com/a/49660922
score: 1
type: Answer
has body: I think I know your problem: In these lines: num=fresp.at[i,'pregnum'] if num == 0 and case in pregmap: You try to fetch a row using at which is similar to loc and returns a pd.Series object. When you do the comparison, Python is comparing the pd.Series which has an ambiguous truth value. To avoid this, you can use iloc to fetch the row, and then access the pregnum value: num = fresp.iloc[i].pregnum if num ...
answers question: http://stackoverflow.com/q/49659820
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49621342
type: UnansweredQuestion
tagged with: python
has body: I have to encode that json file by utf-8 and use a generator to get content. when I tried to run it, there is an AttributeError: Traceback (most recent call last): File "F:\Files\python\yiyouhome\WordSeg\json_load.py", line 25, in &lt;module&gt; tags = jieba.analyse.extract_tags(content_seg,topK = top_K, withWeight = False, allowPOS = allow_pos) File "C:\Users\ThinkPad\AppData\Local\Programs\Python\Python36\lib\site-packages\jieba\analyse\tfidf.py", line 94, in extract_tags for w in words: File "C:\Users\ThinkPad\AppData\Local\Programs\Python\Python36\lib\site-packages\jieba\posseg\__init__.py", line 249, in cut for w in self.__cut_internal(sentence, HMM=HMM): File "C:\Users\ThinkPad\AppData\Local\Programs\Python\Python36\lib\site-packages\jieba\posseg\__init__.py", line 217, in __cut_internal sentence = strdecode(sentence) File "C:\Users\ThinkPad\AppData\Local\Programs\Python\Python36\lib\site-packages\jieba\_compat.py", line 37, in strdecode sentence = sentence.decode('utf-8') AttributeError: 'generator' object has no attribute 'decode' Why does this happen? At first: Traceback (most recent call last): File "F:\Files\python\yiyouhome\WordSeg\json_load.py", line 10, in &lt;module&gt; json_data = open('spider_raw.json',encoding = 'gbk').read() #,encoding = 'utf-8' UnicodeDecodeError: 'gbk' codec can't decode byte 0xa3 in position 74: illegal multibyte sequence So i add encoding = 'utf-8' to fix it. Here is my code: import json import jieba.analyse import jieba.posseg as pseg json_data = open('spider_raw.json',encoding = 'utf-8').read() data = json.loads(json_data) top_K = 20 allow_pos = ('nr',) def getcontent(spiderlist): for k,v in spiderlist.items(): for item in v['talk_mutidetails']: yield(item['cotent']) #def getcontenttopic(spiderlist): item = getcontent(data) content_seg = pseg.cut(item) tags = jieba.analyse.extract_tags(content_seg,topK = top_K, withWeight = False, allowPOS = allow_pos) for t in tags: print(t)
has title: jieba.analyse: 'generator' object has no attribute 'decode'
score: 0
has comment: http://stackoverflow.com/comment/86251765
answer count: 0
has comment: http://stackoverflow.com/comment/86249949
has comment: http://stackoverflow.com/comment/86250332
has comment: http://stackoverflow.com/comment/86250289
has comment: http://stackoverflow.com/comment/86250105
type: Question
has comment: http://stackoverflow.com/comment/86250346

http://stackoverflow.com/q/49652683
tagged with: args
has answer: http://stackoverflow.com/a/49652904
answer count: 5
has comment: http://stackoverflow.com/comment/86314009
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49652864
has title: Python 3, *args, print the output in a list
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49652850
has answer: http://stackoverflow.com/a/49652847
has comment: http://stackoverflow.com/comment/86313846
has comment: http://stackoverflow.com/comment/86313894
upvote count: 2
downvote count: 3
has body: def even_number(*args): for even in args: if even%2==0: even print(list(str(even)),end='') I want to print the output in a list as [8,6,4], but rather it prints it out as [8],[6],[4]. If I put out the last print statement and just print(even), it obviously doesn't list out the output.
has comment: http://stackoverflow.com/comment/86313892
has answer: http://stackoverflow.com/a/49652866
favorite count: 0
type: Question

http://stackoverflow.com/q/49647437
has title: Simpy time event not properly sorted
has comment: http://stackoverflow.com/comment/86303383
tagged with: simpy
tagged with: simulation
type: Question
tagged with: network-programming
type: UnansweredQuestion
tagged with: python
tagged with: sorting
score: 0
has comment: http://stackoverflow.com/comment/86304138
answer count: 0
has body: I'm trying to simulate a network queue using simpy library it works fine when I set the arrival rate and service are at 1sec (randomly generated exponetial dist with mean 1). However, when i set the arrival rate at 9x faster than the service rate(ie. arrival = 9pkts per sec, service rate = 1 pkt per sec), the simpy process are not printing it properly (in timely order) example: packet0 1219 arriving at 0.000000 packet1 3568 arriving at 0.150441 packet2 3194 arriving at 0.300072 packet3 783 arriving at 0.303343 packet4 1308 arriving at 0.622341 packet5 150 arriving at 0.879188 packet6 353 arriving at 0.949535 packet7 1066 arriving at 1.036728 packet8 305 arriving at 1.038195 **packet0 1219 depart at 1.585690** **packet1 3568 depart at 3.644606** **packet9 3101 arriving at 1.074615** packet10 217 arriving at 1.235867 packet11 186 arriving at 1.413119 packet12 169 arriving at 1.519886 packet2 3194 depart at 4.864265 packet13 2563 arriving at 1.520083 Notice that in between the ** **, the process are not printed within the timeline. Any workaround for this? Thanks. edited to include code: NEW_CUSTOMERS = 100 # Total number of customers INTERVAL_CUSTOMERS = 0.111111 # Generate new customers roughly every x seconds SIZE = 1250 def source(env, number, interval, port): """Source generates customers randomly""" for i in range(number): size = int(random.expovariate(0.0008)) packet = Packet(env, '%d' % i, size, port, time_in_port=1) env.process(packet) t = random.expovariate(1 / interval) yield env.timeout(t) def Packet(env, id, size, port, time_in_port): arrive = env.now yield Queue.buffer.put(size) print('packet%s %s arriving at %lf' % (id, size, arrive)) with port.request() as req: yield req tip = random.expovariate(1/time_in_port) yield env.timeout(tip) amount = size yield Queue.buffer.get(amount) print('packet%s %s depart at %lf' % (id, size, env.now)) class queue: def __init__(self, env): self.buffer = simpy.Container(env, init = 0, capacity=12500) random.seed(RANDOM_SEE…

http://stackoverflow.com/comment/86358307
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49673723
has text: I am missing the use case for this. The module doing the importing is going to get access to numpy if they want it. What problem are you fixing?
score: 2

http://stackoverflow.com/comment/86389824
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49687263
type: AnswerComment
has text: @YogeshSathe HDF-EOS tile datafiles do not carry geolocation arrays. Since the data is located on a regular grid (in MODIS sinusoidal projection), you can restore geolocation of each pixel from the coordinates of the tile's corners that can be read from `CoreMetadata.0` and `StructMetadata.0` attributes. Checkout the output from `print(getattr(hdf,'CoreMetadata.0'))` and `print(getattr(hdf,'StructMetadata.0'))`.

http://stackoverflow.com/comment/86441428
type: Comment
score: 2
type: AnswerComment
has text: Would be simpler to use `str.lstrip()` no?
comment on: http://stackoverflow.com/a/49714038

http://stackoverflow.com/comment/86371687
comment on: http://stackoverflow.com/a/49679585
has text: Yes, true. Let me fix that.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49637309
answer count: 2
has answer: http://stackoverflow.com/a/49637516
has answer: http://stackoverflow.com/a/49637818
has body: I am trying to extract a value from a line after a specific string of characters. The text files line is as follows: directory, batch: xxx Date: xxxxxx xx:xx Pulp: type AAAAAAAA bbbbbbbb cccccccc dddddddd eeeeeeee I need to add 'Pulp: type' to my list output[f] and append the line. The amount of characters that makes up the pulp type varies from 3-25 characters. This is what I currently have: for f in file_list: txtfile = open(f, 'r') output[f] = [] for line in txtfile: if 'batch' in line: #only identifier for line is 'batch' # What Goes Here?? for i,line in enumerate(txtfile): if i == 4: output[f].append(line) elif i == 5: output[f].append(line) I don't know how to extract what I need from the line. Any ideas?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86283045
has title: Retrieve value after a specfic string of characters
accepted answer: http://stackoverflow.com/a/49637516
tagged with: python
possible better answer: http://stackoverflow.com/a/49637818
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86282551

http://stackoverflow.com/q/49682006
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/59940622
tagged with: tkinter
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49682181
has title: Event for window show or mainloop started in TKinter?
has body: Is there an event in Tkinter I can bind to which indicates that the creation of the main window was finished and the window is show or if the mainloop() started? from tkinter import * root = Tk() def task(): print('foobar') root.after(5000, task) root.mainloop()
has answer: http://stackoverflow.com/a/49682181
score: 1
possible better answer: http://stackoverflow.com/a/59940622
favorite count: 0
type: Question

http://stackoverflow.com/a/49638366
accepted answer of: http://stackoverflow.com/q/49611608
type: AcceptedAnswer
has body: I solved this by follow the answer of How to serialize a CountVectorizer with a custom tokenize function with joblib
answers question: http://stackoverflow.com/q/49611608
score: 0
type: Answer

http://stackoverflow.com/a/49747850
answers question: http://stackoverflow.com/q/49710371
score: 2
has body: Change below font = ImageFont.load_default().font to font = ImageFont.load_default() And it should work
has comment: http://stackoverflow.com/comment/86529773
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49710371
type: Answer

http://stackoverflow.com/q/49708302
type: Question
tagged with: pymysql
tagged with: python
type: UnansweredQuestion
has title: Can't execute query with pymysql?
has body: Tried what it said in these questions but didn't help: Python MySQL Parameterized Queries Python MySQLdb TypeError: not all arguments converted during string formatting It keeps given me this error: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s AND e.MeetId = m.MeetId ORDER by e.eventId' at line 4") When I use a number, for example, put in 1 for the "meetId" in the query, it works. I'm trying to get it to work with inputs but nothing seems to work. Every different file is separated with asterisks, Here is the code: ********mainFile.py******** from dbconfig import* import pymysql from datetime import datetime, date, time import sys db = get_mysql_param(); cnx = pymysql.connect(user=db['user'], password=db['password'], host=db['host'], database=db['database']) cursor = cnx.cursor() meetId = input("MeetId: ") query = """ SELECT DISTINCT e.eventId as eventId, e.Title as title, concat(s.fname, " ", s.lname) as sName, if (Isnull(p.Comment), '', comment) as comment FROM Event e, Swimmer s, Participation p, Meet m WHERE s.SwimmerId = p.SwimmerId AND p.EventId = e.EventId AND m.MeetId = %s AND e.MeetId = m.MeetId ORDER by e.eventId """ cursor.execute(query,(meetId, )) ******dbconfig.py file******* import configparser # simplistic and no error handling. def get_mysql_param(filename='dbconfig.ini', section='mysql'): config = configparser.ConfigParser() config.read(filename) return config['mysql'] ******dbconfig.ini file***** [mysql] host = localhost database = clystms user = ********** password = ********* The problem is "m.MeetId = %s", it doesn't want to replace the "%s" in the query with whatever I input.
has comment: http://stackoverflow.com/comment/86440322
has comment: http://stackoverflow.com/comment/86441631
linked to: http://stackoverflow.com/q/775296
linked to: http://stackoverflow.com/q/21740359
score: 2
upvote count: 2
answer count: 0
downvote count: 0
tagged with: mysql
favorite count: 0
has comment: http://stackoverflow.com/comment/86435027

http://stackoverflow.com/q/49632933
has title: Django Python and pyad
answer count: 1
has body: I am trying to create a simple search form in Django to query Active Directory but I keep getting com_error at /console/users/ (-2147221008, 'CoInitialize has not been called.', None, None) views.py: from pyad import pyad, aduser, adquery @login_required def users(request): if request.method == 'POST': form = UserSearchForm(request.POST) if form.is_valid(): user = pyad.from_cn(form.cleaned_data['cn']) return render(request, 'console/users/details.html', {'user': user}) else: form = UserSearchForm() return render(request, 'console/users/index.html', {'form': form}) forms.py from django import forms class UserSearchForm(forms.Form): cn = forms.CharField(label='Common Name', max_length=100) Python 3.6. Django 2.0.3 pyad 0.5.20
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53603083
tagged with: django
tagged with: python
tagged with: pyad
score: 0

http://stackoverflow.com/a/49635865
has body: Try setting these headers: Host: login.microsoftonline.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
answers question: http://stackoverflow.com/q/49635758
type: Answer
has comment: http://stackoverflow.com/comment/86279229
score: 0

http://stackoverflow.com/comment/86260028
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49625694
has text: No, you need to add indents to the **current** line, never the next.
score: 0

http://stackoverflow.com/comment/123875727
comment on: http://stackoverflow.com/a/54337427
score: 0
type: Comment
has text: Is there a way to sample a single element form a dataset? If `a` is a dataset I can access the first sample with `a.take(1)`. Can I make something like `a.takerandom(1)`?
type: AnswerComment

http://stackoverflow.com/a/49640878
upvote count: 1
has comment: http://stackoverflow.com/comment/86313271
has body: c_1 is NoneType, therefore it cannot do the calculation. The problem is with this line (can't see the line number): _, c_1 = sess.run([loss_op_1, optimizer_1], feed_dict = {X: batch_x, Y: batch_y}) because in order to get the loss value back into c_1, you shouldn't ask for the return value from the optimizer but the loss itself loss_op_1. Therefore the line should be: c_1, _ = sess.run([loss_op_1, optimizer_1], feed_dict = {X: batch_x, Y: batch_y}) This will be the same for c_2 and c_3 analogously. This is only to fix the listed TypeError, I haven't reviewed your code for any other issues.
accepted answer of: http://stackoverflow.com/q/49640586
has comment: http://stackoverflow.com/comment/86320315
answers question: http://stackoverflow.com/q/49640586
type: Answer
has comment: http://stackoverflow.com/comment/86360508
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49741513
has comment: http://stackoverflow.com/comment/86497725
has title: Emacs Python Interpreter Is Not Set Correctly
tagged with: elpy
tagged with: emacs
tagged with: python
has comment: http://stackoverflow.com/comment/86497989
has comment: http://stackoverflow.com/comment/86498027
possible better answer: http://stackoverflow.com/a/49742179
has comment: http://stackoverflow.com/comment/86497792
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86498019
answer count: 2
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49741852
has body: Fresh install of Linux Mint 18.3 Cinnamon. Also a fresh install of Gnu Emacs 24.5.1 Also a fresh install of Anaconda3: ~ $ conda -version usage: conda [-h] [-V] command ... conda: error: the following arguments are required: command ~ $ conda -V conda 4.4.10 ~ $ python -V Python 3.6.4 :: Anaconda, Inc. ~ $ anaconda -V anaconda Command line client (version 1.6.9 Emacs has python-mode, python, and elpy installed, python code executed via ctrl+Enter is run with the executable in /usr/bin/python which is hopelessly out of date...2.7.2 Executing python on the command line ~ $ which python /home/user/anaconda3/bin/python ~ $ python Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19) Also, M-x elpy-config yields an error: neither easy install nor pip can be found very strange, given pip was installed with anaconda3 I don't know how to find what command elpy is using to run python or why elpy-config won't work, I assume that somewhere, it is hardcoded to the /usr/bin directory to look for all of the above executables, but no place I look indicates this.
has comment: http://stackoverflow.com/comment/86497654
has comment: http://stackoverflow.com/comment/86497826
downvote count: 0
has answer: http://stackoverflow.com/a/49741852
has comment: http://stackoverflow.com/comment/86497772
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49742179
has comment: http://stackoverflow.com/comment/86497836

http://stackoverflow.com/comment/86376991
comment on: http://stackoverflow.com/a/49681509
type: Comment
has text: Nice (+1)! FYI, I believe I have a way to exclude all but 2 candidates out of every 625 (roughly 99.7%). Please see my answer at https://stackoverflow.com/a/49682351/2554867 , if interested.
type: AnswerComment
score: 1

http://stackoverflow.com/q/49734961
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86483890
score: 0
tagged with: pandas
answer count: 0
tagged with: pandasql
has comment: http://stackoverflow.com/comment/86483911
has title: How do I use today's date in the where clause when using Pandasql in Python?
type: Question
has body: I am struggling to use some SQL functions in Pandasql as it seems that the same names aren't used for the functions. For example, using Pandasql in Python I type: q = """ select e.Date, e.SITA, e.Events from df_event e where e.Date &gt;= getdate() """ This gives me the error that "(sqlite3.OperationalError) no such function: getdate" So how do I use today's date in the where clause so that only entries for today and onward are selected? I further tried this: q = """ select e.Date, e.SITA, e.Events from df_event e where e.Date &gt;= datetime.date.today() """ and it gave me the error " sqlite3.OperationalError) near "(" " Any help will be appreciated.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86484066

http://stackoverflow.com/q/49670913
tagged with: doc2vec
has comment: http://stackoverflow.com/comment/86370197
answer count: 0
has body: I am a little new to python and the unsupervised learning methods, but I have a quick question. where as doc2vec model has docvecs property holding all trained vectors for the 'document tags' seen during training; Are there similar properties that holds trained vectors for models like glove, word2vec, fastext, tfidf and some related text vectorsiation models in python, what do could they be? For example doc2vec model could look like this when extracting vectors for classification doc2vecModel.docvecs['Text_'+str(i)]
tagged with: word2vec
tagged with: python
type: UnansweredQuestion
tagged with: vectorization
tagged with: fasttext
has comment: http://stackoverflow.com/comment/86368085
score: 0
has title: Document tags in vectorization models
type: Question

http://stackoverflow.com/comment/86406550
comment on: http://stackoverflow.com/q/49696850
has text: what is your question??
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/93695676
type: AnswerComment
has text: @user8190410, Another question, how do you use the same algorithm for vertical lines?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49740052

http://stackoverflow.com/q/49629062
answer count: 2
upvote count: 0
has body: Another file's modules cannot be used.I have 2 filed of test1.py and test2.py .I want to use test2's class in test1. test2.py is class Test2(object): def data(self, Test): self.user =user test1.py is class Test1(test2.Test2): def __init__(self): Test.__init__(self) But when I run these codes,NameError: name 'test2' is not defined happens.In this time,I have no import statement.So I wrote codes import test2 as tein test1.py and I rewrote class Test1(te.Test2): but te is not defined error happens.What is wrong in my code?How should I fix this?
has title: Another file's modules cannot be used
has answer: http://stackoverflow.com/a/49629503
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86264897
has comment: http://stackoverflow.com/comment/86264881
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86265344
tagged with: django
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49629218

http://stackoverflow.com/comment/86256582
comment on: http://stackoverflow.com/q/49624767
score: 1
type: Comment
type: QuestionComment
has text: The words you don't want are called *stopwords*. Look at this link: https://pythonspot.com/nltk-stop-words/

http://stackoverflow.com/q/49680181
upvote count: 3
has comment: http://stackoverflow.com/comment/86378500
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86373874
favorite count: 0
type: Question
tagged with: tesseract
linked to: http://stackoverflow.com/q/273946
score: 3
has answer: http://stackoverflow.com/a/76960615
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86384296
has answer: http://stackoverflow.com/a/64483196
tagged with: python
has body: I am trying to pass configuration arguments to pytesseract's image_to_string function. The code I am running is the following. filename = 'address1_203.png' img = Image.open(cam_img+filename) ocr_out = ocr.image_to_string(img, lang='por', config='-psm 7') print(ocr_out) and the error message is TypeError: image_to_string() got an unexpected keyword argument 'config' There is another similar question in stackoverflow, but I don't think it solves the problem I am having. I installed pytesseract through conda with conda install -c auto pytesseract The code works if I remove the config parameter P.S.: this is the first question I am posting, please give me feedback if I've done it properly or not. thanks =)
tagged with: image
tagged with: conda
has title: pytesseract: unexpected keyword "config"

http://stackoverflow.com/comment/86346978
comment on: http://stackoverflow.com/a/49668372
type: AnswerComment
has text: I don't speak Python, but can you alter to `distance.cdist(coords1,coords2,'sqeuclidean')` to avoid the square root which is potentially expensive - since if `a^2` < `b^2`, it follows that `a` < `b` (when `a` and `b` are both already squares and therefore positive).
score: 3
type: Comment

http://stackoverflow.com/q/49621169
has answer: http://stackoverflow.com/a/49638608
answer count: 3
accepted answer: http://stackoverflow.com/a/49638608
has answer: http://stackoverflow.com/a/79257060
has body: I'm starting to dive into deploying a predictive model to a web app using Flask, and unfortunately getting stuck at the starting gate. What I did: I pickled my model in my model.py program: import numpy as np from sklearn.externals import joblib class NeuralNetwork(): """ Two (hidden) layer neural network model. First and second layer contain the same number of hidden units """ def __init__(self, input_dim, units, std=0.0001): self.params = {} self.input_dim = input_dim self.params['W1'] = np.random.rand(self.input_dim, units) self.params['W1'] *= std self.params['b1'] = np.zeros((units)) self.params['W2'] = np.random.rand(units, units) self.params['W2'] *= std * 10 # Compensate for vanishing gradients self.params['b2'] = np.zeros((units)) self.params['W3'] = np.random.rand(units, 1) self.params['b3'] = np.zeros((1,)) model = NeuralNetwork(input_dim=12, units=64) #####THIS RIGHT HERE ############## joblib.dump(model, 'demo_model.pkl') then I created an api.py file in the same directory as my demo_model.pkl, per this tutorial (https://blog.hyperiondev.com/index.php/2018/02/01/deploy-machine-learning-models-flask-api/): import flask from flask import Flask, render_template, request from sklearn.externals import joblib app = Flask(__name__) @app.route("/") @app.route("/index") def index(): return flask.render_template('index.html') # create endpoint for the predictions (HTTP POST requests) @app.route('/predict', methods=['POST']) def make_prediction(): if request.method == 'POST': return render_template('index.html', label='3') if __name__ == '__main__': # LOAD MODEL WHEN APP RUNS #### model = joblib.load('demo_model.pkl') app.run(host='0.0.0.0', port=8000, debug=True) I also made a templates/index.html file in the same directory with this info: NN Model as Flask API Boston Housing Price Predictor {% if label %} {{ label }} {% endif %} running: >> python api.py gives me an error with the pickler: Traceback (most recent call last): File "api.py", line 22, in <module> mo…
has title: joblib.load __main__ AttributeError
has comment: http://stackoverflow.com/comment/86250101
has comment: http://stackoverflow.com/comment/86274301
downvote count: 0
score: 16
favorite count: 0
type: Question
tagged with: machine-learning
tagged with: pickle
tagged with: python
has answer: http://stackoverflow.com/a/50093533
tagged with: flask
possible better answer: http://stackoverflow.com/a/50093533
upvote count: 16
type: AnsweredQuestion

enter
tags question: http://stackoverflow.com/q/49689748
tag name: enter
type: Tag

http://stackoverflow.com/comment/86224523
type: AnswerComment
comment on: http://stackoverflow.com/a/49608760
has text: Got this one now. `ValueError: could not convert string to float: 'Disable this function'`
type: Comment
score: 0

http://stackoverflow.com/comment/86377166
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49682725
has text: @RyanHaining String deconcatenation?
type: Comment

http://stackoverflow.com/q/49738811
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49744956
has title: Python Scrapy is not getting all html elements from a webpage
accepted answer: http://stackoverflow.com/a/49740303
has comment: http://stackoverflow.com/comment/86492797
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49744956
has answer: http://stackoverflow.com/a/49740303
tagged with: scrapy
linked to: http://stackoverflow.com/q/8550114
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86494894
tagged with: python
has body: I am trying to use Scrapy to get the names of all current WWE superstars from the following url: http://www.wwe.com/superstars However, when I run my scraper, it does not return any names. I believe (through attempting the problem with other modules) that the problem is that Scrapy is not finding all of the html elements from the page. I attempted the problem with requests and Beautiful Soup, and when I looked at the html that requests got, it was missing important aspects of the html that I was seeing in my browsers inspector. The html containing the names looks like this: == $0 name here My code is posted below. Is there something that I am doing wrong that is causing this not to work? import scrapy class SuperstarSpider(scrapy.Spider): name = "star_spider" start_urls = ["http://www.wwe.com/superstars"] def parse(self, response): star_selector = '.superstars--info' for star in response.css(star_selector): NAME_SELECTOR = 'span ::text' yield { 'name' : star.css(NAME_SELECTOR).extract_first(), }
has comment: http://stackoverflow.com/comment/86492324

http://stackoverflow.com/q/49638445
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86284592
has comment: http://stackoverflow.com/comment/86284868
answer count: 1
has title: No module named 'redis' with python code
has comment: http://stackoverflow.com/comment/86284575
type: Question
tagged with: redis
has comment: http://stackoverflow.com/comment/86285038
accepted answer: http://stackoverflow.com/a/54207648
tagged with: python
has answer: http://stackoverflow.com/a/54207648
has comment: http://stackoverflow.com/comment/86311403
has body: I have checked redis-server --version Redis server v=4.0.8 sha=00000000:0 malloc=jemalloc-4.0.3 bits=64 build=4d30adc486b198e5 If I try to run my code File "app.py", line 5, in &lt;module&gt; import redis ModuleNotFoundError: No module named 'redis' Why?
has comment: http://stackoverflow.com/comment/86284709

http://stackoverflow.com/a/54457237
type: Answer
has body: I haven't found a way to set validators at runtime, but there is a way to define a validation function for a field on a form class, and that function can be based on data passed to form at construction time. Here's an example class MyForm(flask_wtf.FlaskForm): user_id_field = wtforms.StringField("User ID") def __init__(self, valid_user_id, **kwargs): super().__init__(**kwargs) self.valid_user_id = valid_user_id def validate_user_id_field(self, field): """ Function name must be 'validate_' + name of field you want to validate """ if field.data != self.valid_user_id raise wtforms.validators.ValidationError("Wrong user id!") # In endpoint definition: my_form = MyForm(formdata=flask.request.form, valid_user_id=flask_login.current_user.id) my_form.validate() Edit Ha, turns out setting validators at runtime is incredibly easy, it's just that documentation doesn't mention it anywhere. If you have a form with field some_field, you can simply set self.some_field.validators = [...] in form's constructor, e.g. class MyForm(flask_wtf.FlaskForm): some_field = wtforms.HiddenField() def __init__(self, some_data, **kwargs): super().__init__(**kwargs) self.some_field.validators = [MyValidator(some_data)] # In endpoint form = MyForm(formdata=flask.request.form, some_data=some_data) Or you can set validators directly in endpoint handler: form = MyForm(formdata=flask.request.form) form.some_field.validators = [MyValidator(some_data)]
answers question: http://stackoverflow.com/q/49615983
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49668464
score: 0
has body: courtesy : Compare 2 excel files using Python from itertools import zip_longest import xlrd import os first_files = os.listdir('folder1') second_files = os.listdir('folder2') matches = [x for x in second_files if x in first_files] #print(matches) for (matches[0]) in matches: print (matches[0]) rb1 = xlrd.open_workbook(os.path.join('folder1',matches[0])) rb2 = xlrd.open_workbook(os.path.join('folder2',matches[0])) sheet1 = rb1.sheet_by_index(0) sheet2 = rb2.sheet_by_index(0) for rownum in range(max(sheet1.nrows, sheet2.nrows)): if rownum < sheet1.nrows: row_rb1 = sheet1.row_values(rownum) row_rb2 = sheet2.row_values(rownum) for colnum, (c1, c2) in enumerate(zip_longest(row_rb1, row_rb2)): if c1 != c2: print ("Row {} Col {} - {} != {}".format(rownum+1, colnum+1, c1, c2)) else: print ("Row {} missing".format(rownum+1))
answers question: http://stackoverflow.com/q/49666426
has comment: http://stackoverflow.com/comment/86347288
type: Answer

http://stackoverflow.com/q/49742503
tagged with: python
has title: serializing django models (for use in js files)?
score: 0
has answer: http://stackoverflow.com/a/49742582
answer count: 1
has body: -- DJANGO/PYTHON-- class Sounds(models.Model): sound = models.TextField(max_length=500, blank=True) syl = models.TextField(max_length=500, blank=True) tone = models.IntegerField(blank=True, default=0) def as_json(self): return dict( input_id=self.id, sound=self.sound, syl=self.syl, tone=self.tone) --JS-- function init() { -- create a list of all instances with tone = 1 -- } This is what my model looks like. In my js file, I want to be able to pull all created instances with a certain tone (or syllable, etc..) into a list so I can use them. I created the as_json function (above), but I'm not sure where to call this function. If I call in in the python file, then..how can I use it in the js file, and vice versa?
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: javascript

http://stackoverflow.com/a/49752330
has comment: http://stackoverflow.com/comment/86519506
type: Answer
answers question: http://stackoverflow.com/q/49751963
has comment: http://stackoverflow.com/comment/86519318
downvote count: 0
score: 1
upvote count: 1
has body: First of all, you should check whether range(9) is really what you want to do as it will index from 0 to 8, while range(10) will index from 0 to 9. Now comes the definition of variance, you have the variance n that you use when you have a full set, and the variance n-1 that you use when you have a sample. The difference between the 2 is whether the value m = sum(xi) / n is the real average or whether it is just an approximation of what the average should be. Variance n gives the real variance and is used for cases like variance of a height of class (data set is full). In this case we use, sum([(xi - m) ** 2 for xi in dataset]) / len(dataset) Variance n-1 is just an approximation, and used in cases like price of a stock, the value gets better as more data set is added. In this case we use, sum([(xi - m) ** 2 for xi in dataset]) / (len(dataset) - 1) To get the same result, In numby you can use ddof parameter, by default it is ddof=0. So for variance n-1 you will simply do ddof=1: np.var(dataset, ddof=1) and, sum([(xi - m) ** 2 for xi in dataset]) / (len(dataset) - 1)

nested
tags question: http://stackoverflow.com/q/49739102
tags question: http://stackoverflow.com/q/49689424
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/49724113
tags question: http://stackoverflow.com/q/49697844
tags question: http://stackoverflow.com/q/49704700
tags question: http://stackoverflow.com/q/49662970
tags question: http://stackoverflow.com/q/49686764
tags question: http://stackoverflow.com/q/49676240
tags question: http://stackoverflow.com/q/49619662
tags question: http://stackoverflow.com/q/49699779
tags question: http://stackoverflow.com/q/49728723
tags question: http://stackoverflow.com/q/49645763
tags question: http://stackoverflow.com/q/49671660

debugging
tags question: http://stackoverflow.com/q/49607174
tag name: debugging
tags question: http://stackoverflow.com/q/49715854
type: Tag
tags question: http://stackoverflow.com/q/49689817
tags question: http://stackoverflow.com/q/49602872

http://stackoverflow.com/q/49698809
answer count: 3
has comment: http://stackoverflow.com/comment/86410931
score: 1
accepted answer: http://stackoverflow.com/a/49699056
downvote count: 0
has answer: http://stackoverflow.com/a/49699056
upvote count: 1
favorite count: 0
has title: How do i format a value as a list from a dictionary
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49698919
has comment: http://stackoverflow.com/comment/86411157
tagged with: python
has body: I'm trying to do some simple projects on my own to learn python a little better, what I am trying to do is format the the values into fields. I've managed to sort the keys in ascending order and match the keys with their respective lists. I know why only the first word in the list gets formatted and that is because it is being treated as one string with spaces in-between, I am at a complete loss as how to proceed It should look like this: Id name species age spayed/neutered 1020 b cat 9 yes 1022 brn dog 10 no 1023 bren cat 2 yes This is the relevant function that will be displaying the information from the dictionary, and my progress so far. cust_rec = {'1020': ['b','cat','9','yes'], '1023': ['brn','dog','10','no'], '1022': ['bren','cat','2','yes']} def cust_disp (cust_rec): for key in sorted(cust_rec.keys()): print("{0:12s} {1:10s} {2:10s} {3:4s} {4:s}".format("ID","Name","Species","Age","Spayed/Neutered")) print ("{0:12s} {1:10s}".format(key, " ".join(cust_rec[key]) ) ) If i need to clarify anything let me know.
type: Question
possible better answer: http://stackoverflow.com/a/49698919
has answer: http://stackoverflow.com/a/49699249

http://stackoverflow.com/comment/90674808
has text: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
type: AnswerComment
comment on: http://stackoverflow.com/a/51860964
type: Comment
score: 4

http://stackoverflow.com/comment/86478182
score: 0
comment on: http://stackoverflow.com/q/49732069
type: Comment
type: QuestionComment
has text: The third line quote was a type @Rachitkapadia. Apologies.

http://stackoverflow.com/q/49611520
answer count: 1
has answer: http://stackoverflow.com/a/49611546
has title: strptime() does not convert string to datetime object in Python 3.6
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
score: 1
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has body: I am getting an exception when I run the following code which I can not explain: import datetime datetime.datetime.strptime("2018-04-02", format = "%Y-%m-%d") TypeError: strptime() takes no keyword arguments
upvote count: 2
tagged with: strptime
accepted answer: http://stackoverflow.com/a/49611546

http://stackoverflow.com/q/49671660
has body: [["hello", "bye", "start"], ["bye", "start", "hello"], ["john", "riya", "tom"], ["riya","john", "tom"].....] I have got a list like this. I want to remove duplicate elements from nested list in Python where elements should be in any order. Output should be:- [["hello", "bye", "start"], ["john", "riya", "tom"]] 3 strings should be present only once in any list. How to achieve this?
tagged with: list
tagged with: nested-lists
has answer: http://stackoverflow.com/a/49671874
has comment: http://stackoverflow.com/comment/86353584
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49672225
has answer: http://stackoverflow.com/a/49671782
downvote count: 0
tagged with: nested
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49671886
accepted answer: http://stackoverflow.com/a/49675822
has answer: http://stackoverflow.com/a/49675822
possible better answer: http://stackoverflow.com/a/49672225
type: Question
has title: Removing duplicate strings from python nested list present in any order
answer count: 5
tagged with: duplicates
tagged with: python
has comment: http://stackoverflow.com/comment/86353757

http://stackoverflow.com/a/49605906
type: Answer
answers question: http://stackoverflow.com/q/49605684
score: 0
has body: import numpy as np import pandas as pd df = pd.DataFrame({"gender":np.random.choice(["male","female"],[20]), "admitted":np.random.choice([True,False],[20]), "major":np.random.choice(["Chemistry","Physics"],[20])}) phy_female_admited = df.loc[(df["major"]=="Physics") &amp; (df["admitted"]==True) &amp; ((df["gender"]=="female"))] phy_female_applied = df.loc[(df["major"]=="Physics") &amp; ((df["gender"]=="female"))] acceptance_rate = phy_female_admited.shape[0]/phy_female_applied.shape[0] A little more expanded answer but basically works in the same way as DZurico's ignore the line where i am creating a dataframe and use your own data instead

http://stackoverflow.com/a/49625647
downvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49620140
has comment: http://stackoverflow.com/comment/86279152
has body: Not a python solution, but I think this is how you could do it using CDO in a bash script loop: # loop over months: for i in {1..12}; do # This gives the hourly mean for each month separately cdo yhourmean -selmon,${i} datafile.nc mon${i}.nc done # merge the files cdo mergetime mon*.nc hourlyfile.nc rm -f mon*.nc # clean up the files Note that if you data doesn't start in January then you will get a "jump" in the final file time... I think that can be sorted by setting the year after the yhourmean command if that is an issue for you.
score: 0
upvote count: 2

http://stackoverflow.com/a/49624108
type: Answer
answers question: http://stackoverflow.com/q/49614238
score: 0
has body: Files.list has a 'q' property where you can filter search results. Following the Search for Files and Team Drives guide, you can use the 'visibility' filter: visibility (string) =, '!=' The visibility level of the file. Valid values are anyoneCanFind, anyoneWithLink, domainCanFind, domainWithLink, and limited.

http://stackoverflow.com/comment/86463865
has text: Well, in Python the main case is if its possible the list is empty
comment on: http://stackoverflow.com/q/49724663
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86479191
type: Comment
type: QuestionComment
score: 0
has text: Yes I am, does it anything to do with this one here?
comment on: http://stackoverflow.com/q/49731961

http://stackoverflow.com/comment/86399761
has text: Please provide a **[mcve]**. For example, give a dataframe with example data and *show us* what you want as output.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49693649

http://stackoverflow.com/a/49721136
has body: var + 1 ^ | In your recursion_function you are not assigning var ! Also and your recursion_function does not know what this var is Good way to write code var = 6 def recursion_function(n): if(n &gt; 0): print(str((var + 1)-n)) recursion_function(n-1) recursion_function(var) Your Desired Output: 1 2 3 4 5 6
type: Answer
answers question: http://stackoverflow.com/q/49720930
score: 0

http://stackoverflow.com/q/49732573
has answer: http://stackoverflow.com/a/54248099
has answer: http://stackoverflow.com/a/66215673
type: UnansweredQuestion
tagged with: mnist
linked to: http://stackoverflow.com/q/12201928
has body: I'm trying to load the mnist data set for this neural networks and deep learning example (http://neuralnetworksanddeeplearning.com/chap1.html) but I keep getting this error. &gt;&gt;&gt; import mnist_loader &gt;&gt;&gt; training_data, validation_data, test_data = mnist_loader.load_data_wrapper() Traceback (most recent call last): File "&lt;pyshell#34&gt;", line 1, in &lt;module&gt; training_data, validation_data, test_data = mnist_loader.load_data_wrapper() File "C:/Users/Joseph Gannon/AppData/Local/Programs/Python/Python36-32\mnist_loader.py", line 68, in load_data_wrapper tr_d, va_d, te_d = load_data() File "C:/Users/Joseph Gannon/AppData/Local/Programs/Python/Python36-32\mnist_loader.py", line 42, in load_data f = open('mnist.pkl', 'rb') File "C:\Users\Joseph Gannon\AppData\Local\Programs\Python\Python36-32\lib\gzip.py", line 53, in open binary_file = GzipFile(filename, gz_mode, compresslevel) File "C:\Users\Joseph Gannon\AppData\Local\Programs\Python\Python36-32\lib\gzip.py", line 163, in __init__ fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') FileNotFoundError: [Errno 2] No such file or directory: '../data/mnist.pkl' This is the code I am using: """ mnist_loader ~~~~~~~~~~~~ A library to load the MNIST image data. For details of the data structures that are returned, see the doc strings for ``load_data`` and ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the function usually called by our neural network code. """ #### Libraries # Standard library import _pickle as cPickle import gzip # Third-party libraries import numpy as np def load_data(): """Return the MNIST data as a tuple containing the training data, the validation data, and the test data. The ``training_data`` is returned as a tuple with two entries. The first entry contains the actual training images. This is a numpy ndarray with 50,000 entries. Each entry is, in turn, a numpy ndarray with 784 values, representing the 28 * 28 = 784 pixels in a single MNIST image. The sec…
tagged with: python
has comment: http://stackoverflow.com/comment/86479323
has answer: http://stackoverflow.com/a/49733285
has comment: http://stackoverflow.com/comment/86479332
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has title: Python 3 - FileNotFoundError: [Errno 2] No such file or directory: '../data/mnist.pkl'
duplicate of: http://stackoverflow.com/q/12201928
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49667337
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: machine-learning
has body: I'm trying to create this simple RNN architecture in Keras: Input layer of 24 input neurons Recurrent hidden layer of 4 hidden neurons Output layer of 4 output neurons Here is my code: import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import Activation from keras.layers import SimpleRNN #fix random seed np.random.seed(7) trainX = np.loadtxt('trainX.csv', delimiter=',', dtype=np.float32) trainT = np.loadtxt('trainT.csv', delimiter=',', dtype=np.float32) print(trainX) print(trainT) print(trainX.shape[1]) HIDDEN_LAYERS = 4 model = Sequential() model.add(Dense(output_dim=HIDDEN_LAYERS, input_dim=trainX.shape[1])) model.add(Activation("relu")) model.add(SimpleRNN(4, input_dim=trainX.shape[1], input_length=128)) model.add(Activation("relu")) model.add(Dense(output_dim=4)) model.add(Activation("softmax")) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(trainX, trainT, nb_epoch=20, batch_size=128) When I run this code, I get the following error on the line where I add a SimpleRNN layer: ValueError: Input 0 is incompatible with layer simple_rnn_1: expected ndim=3, found ndim=2 Does anyone know what's going on? The value of trainX.shape[1] is 24
tagged with: keras
favorite count: 0
type: Question
score: 3
tagged with: python
has title: ValueError: Input 0 is incompatible with layer simple_rnn_1: expected ndim=3, found ndim=2 in Keras
has answer: http://stackoverflow.com/a/49667974
upvote count: 3

http://stackoverflow.com/a/49624164
answers question: http://stackoverflow.com/q/49623765
accepted answer of: http://stackoverflow.com/q/49623765
type: Answer
has body: Try to push reading from file and inserting into db in another method. Also add gc.collect() for garbage collection. import gc; def read_xml_insert(xmlfile): soup = BeautifulSoup(z.read(xmlfile), 'lxml') json_study = json.loads(re.sub('\s', ' ', json.dumps(xmltodict.parse(str(soup.find('clinical_study'))))).strip()) coll.insert_one(json_study) for xmlfile in z.namelist(): print(i, 'parsing:', xmlfile) if xmlfile == 'Contents.txt': print(xmlfile, '==&gt; entering "continue"') continue; else: read_xml_insert(xmlfile); i+=1 gc.collect() ` Please see.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49641682
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/86291095
linked to: http://stackoverflow.com/q/626759
upvote count: 1
has comment: http://stackoverflow.com/comment/86290970
answer count: 1
has comment: http://stackoverflow.com/comment/86291018
has comment: http://stackoverflow.com/comment/86291001
accepted answer: http://stackoverflow.com/a/49641771
has title: How to mathematically change value pairs in a dictionary?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86290983
tagged with: python
score: -1
has body: I'm storing 2D coordinate pairs as the value in a dictionary. It seems to be treating them as integers (when I print them there are no quotation marks). Adding 10 to the value simply appends 10, however... so it's a tuple? import random d={} num_points=8 def find_rand_points(num_points): for i in range(num_points): d[i]=(random.randrange(-250,251),random.randrange(-250,251)) d[0][0]=d[0][0]+[10] I'm confused why they're tuples in the first place, because I thought randrange would return integers. I can see why it's not working though, since tuples are immutable. I'm trying to get them to add like an array, but am pretty new to Python.
has answer: http://stackoverflow.com/a/49641771

http://stackoverflow.com/comment/86520656
has text: Thank you very much Umair. I was unaware that process_item already has reference to spider object. Just new to scrapy. Thanks for your help.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49752802
score: 0

http://stackoverflow.com/comment/86426027
has text: No, the error traceback you are seeing.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49706284

http://stackoverflow.com/comment/86284541
comment on: http://stackoverflow.com/q/49638305
score: 0
has text: I'm sorry, but as it stands this post makes absolutely no sense. Please, rewrite it to include a clear problem statement, a well formatted [mcve], and anything else necessary to unambiguously convey what you want to solve.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86304128
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49647855
type: QuestionComment
has text: @cdarke that part does not make sense yes, what OP meant to do was probably `a.lower() in {"yes", "y"}`

http://stackoverflow.com/comment/95100487
has text: You can use space as a separator
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49659019
type: Comment

http://stackoverflow.com/a/49635780
has body: You could try something crude like return part.get_payload().split('\nCONFIDENTIALITY NOTICE\n')[0] to truncate every body part which contains this string (and conveniently pass through all others without modification). In the general case, there is no convention for identifying this type of section -- it's just a fragment of the body text with no specific machine-readable markup -- and you can't easily predict what laws or local customs shape its wording (except in very broad terms; organizations and jurisdictions which require this are idiotic). As long as you are dealing with a small set of templates for which you have representative samples, ideally in languages you understand, it's doable in practice, though.
score: 0
answers question: http://stackoverflow.com/q/49634463
type: Answer

http://stackoverflow.com/q/49614946
type: AnsweredQuestion
tagged with: list
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49615040
has body: I'm trying to create a list of arrays consisting of random values according to a normal distribution with different standard deviations of the normal distribution for each array. What I should have is in the first array all normal distribution values should have a standard deviation of 0.01, in the second array all should have a standard deviation of 0.02, and so on all the way up to 1. My code looks like this: noise_stdv = np.linspace(0.01, 1, 100) for i in noise_stdv: noise1 = [np.random.normal(0, noise_stdv, 100) for i in range(100)] But this creates a list in such a way that the first element in each array has a standard deviation of 0.01, the second element has 0.02 and so on, instead of the whole first array having a standard deviation of 0.01 etc. How do I make it so that the for loop runs and creates an array for each element in noise_stdv instead of running for every element in it for each array? Thanks for any help!
tagged with: standard-deviation
has answer: http://stackoverflow.com/a/49615040
type: Question
tagged with: python-3.x
tagged with: arrays
tagged with: python
has title: Creating a normal distribution in Python over many standard deviations with a for loop

http://stackoverflow.com/q/49628393
score: 1
accepted answer: http://stackoverflow.com/a/49629547
tagged with: python
has answer: http://stackoverflow.com/a/49629547
type: Question
has comment: http://stackoverflow.com/comment/86265019
has body: I have an HTML page and I want to find some items of it. I am finding it hard to apply beautifulsoup or lxml HTML page: Title to scrape Title2 to scrape Title3 to scrape How to get all these 3 Ids and titles in a different dictionary within a list [{'id':'t1', 'title': 'Title to scrape'}, {'id':'t2', 'title': 'Title2 to scrape'}, {'id':'t3', 'title': 'Title3 to scrape'}]
has comment: http://stackoverflow.com/comment/86264548
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
has title: Unable to parse HTML by BeautifulSoup / LXML
type: AnsweredQuestion
tagged with: python-2.7
tagged with: lxml

http://stackoverflow.com/comment/86398311
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49692817
score: 0
has text: @lsma no proxy. And the main site (on Django) work perfectly.

http://stackoverflow.com/q/49713516
favorite count: 0
type: Question
has title: Flask session.logged_in not working
tagged with: if-statement
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49779184
tagged with: python
score: -1
tagged with: flask
has body: Using Flask session I am testing whether the user is logged in using {%if session.logged_in%} display a logout button, and {%else%} to display login and register buttons. I am following this tutorial Python Flask From Scratch and using the Flask documentation on templates as a guide . The author of the tutorial is using Bootstrap and I am using Semantic-UI but up until now I have not run in to any issues, I am receiving the error and success messages as described in the tutorial. The only issue I'm having is my logout button is not displaying when the user is logged in; which is explained at approx. 20:45 in the tutorial. My code for _navbar.html: Home About Articles {% if session.logged_in %} Logout {% else %} Login Sign Up {% endif %}
upvote count: 0
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/86220560
type: AnswerComment
has text: It didn't seem to work. It provided me with no output.
comment on: http://stackoverflow.com/a/49606931
score: 0
type: Comment

http://stackoverflow.com/comment/86487227
comment on: http://stackoverflow.com/q/49736428
score: 0
type: QuestionComment
has text: https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html
type: Comment

join
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/49663835
tags question: http://stackoverflow.com/q/49711665
tags question: http://stackoverflow.com/q/49657860

http://stackoverflow.com/comment/86467531
has text: @asimo - try omit it and no change. :) Problem is need same columns names for both dataframes in `fillna`
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49726671
type: AnswerComment

http://stackoverflow.com/comment/86307175
score: 0
type: Comment
type: QuestionComment
has text: how e.txt looks? Can you give some example data. **Note** : close file outside the loop.
comment on: http://stackoverflow.com/q/49649489

http://stackoverflow.com/comment/86301183
score: 1
has text: ``time.sleep()`` **stops** the execution of your program for a given period of time. It does not call anything periodically.
type: Comment
comment on: http://stackoverflow.com/q/49646270
type: QuestionComment

http://stackoverflow.com/q/49630178
favorite count: 0
has title: how to know which node is dropped after using keras dropout layer
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: keras-2
has answer: http://stackoverflow.com/a/49815548
tagged with: keras-layer
has comment: http://stackoverflow.com/comment/86386637
has comment: http://stackoverflow.com/comment/86645276
downvote count: 0
has body: From nick blog it is clear that in dropout layer of CNN model we drop some nodes on the basis of bernoulli. But how to verify it, i.e. how to check which node is not selected. In DropConnect we leave some weights so I think with the help of model.get_weights() we can verify, but how in the case of dropout layer. model = Sequential() model.add(Conv2D(2, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(4, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(8, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) Another question is that it is mention in keras that dropout rate should float b/w 0 to 1. But for above model when I take dropout rate = 1.25, then also my model is working, how this happens?
score: 1
upvote count: 1
tagged with: keras
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/a/49741581
type: AcceptedAnswer
downvote count: 0
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49741509
accepted answer of: http://stackoverflow.com/q/49741509
has body: First, round df1 and df2: i, j = map(np.round, [df1, df2]) Next, merge on B and C: v = pd.merge(i, j, on=['B', 'C'], how='inner', left_index=True) Add dummy count columns to i and the merged result: v['Count'] = v.groupby(['B', 'C']).cumcount() i['Count'] = i.groupby(['B', 'C']).cumcount() Perform a second merge on i with the new count column. v.merge(i'B','C','Count', on=['B','C','Count']).drop('Count', 1) A B C D E x y z w 0 1 2.0 5 0 a 3 0 1 2 1 1 2.0 5 0 a 3 1 9 9 2 9 4.0 4 1 d 1 3 8 0

http://stackoverflow.com/q/49732069
has comment: http://stackoverflow.com/comment/86477813
downvote count: 1
has comment: http://stackoverflow.com/comment/86478182
favorite count: 0
has answer: http://stackoverflow.com/a/49732303
has title: maximum recursion depth exceeded requests
has comment: http://stackoverflow.com/comment/86477952
answer count: 1
score: -1
has body: Currently new to python/django so forgive me if this is a simple question. I am using requests to download a json file and am trying to parse/display the values in a template. I receive the following error: `maximum recursion depth exceeded while calling a Python object Code is below: from django import template from django.template.loader import render_to_string from wagtail.wagtailcore.blocks.base import Block from django.http import HttpResponse from django.shortcuts import render from django.template import loader import datetime import urllib import json import requests import requests_cache requests_cache.install_cache('demo_cache') register = template.Library() # Advert snippets @register.inclusion_tag('swd/templates/adverts.html', takes_context=True) def adverts(context): return { 'adverts': Advert.objects.all(), 'request': context['request'], } #Socialboard #Pinterest @register.inclusion_tag('blocks/socialboard.html') def get_pinterest_pins(): req = requests.get(URL) req_json = json.loads(req.content) for key, value in req_json.items(): print (key, value) # Related within article @register.filter def inject_related_after_paragraph(value, arg): related_list = render_to_string("related.list.html") paragraphs = value.split('&lt;/p&gt;') if arg &lt; len(paragraphs): paragraphs[arg] = related_list + paragraphs[arg] value = '&lt;/p&gt;'.join(paragraphs) return value @register.filter def inject_advert_after_paragraph(value, arg): advert = render_to_string("adverts.html") paragraphs = value.split('&lt;/p&gt;') if arg &lt; len(paragraphs): paragraphs[arg] = advert + paragraphs[arg] value = '&lt;/p&gt;'.join(paragraphs) return value This loops through the URL ok but continously until a point that it times out.
has comment: http://stackoverflow.com/comment/86477768
type: Question
has comment: http://stackoverflow.com/comment/86478142
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86477818
has comment: http://stackoverflow.com/comment/86477811
tagged with: wagtail
upvote count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86477861

http://stackoverflow.com/comment/86438298
comment on: http://stackoverflow.com/a/49712361
type: AnswerComment
has text: I just tried `tf.reduce_mean(1 - tf.abs(labels-prediction_op))`, might that work? My thought was that it would yield a float between `0==terribly bad` to `1==perfect match`.
score: 0
type: Comment

http://stackoverflow.com/q/49635436
tagged with: shapely
has answer: http://stackoverflow.com/a/49635530
has answer: http://stackoverflow.com/a/56249512
has answer: http://stackoverflow.com/a/62977112
tagged with: python
answer count: 3
upvote count: 31
tagged with: geopandas
downvote count: 0
has body: I have a geopandas df with a column of shapely point objects. I want to extract the coordinate (lat/lon) from the shapely point objects to generate latitude and longitude columns. There must be an easy way to do this, but I cannot figure it out. I know you can extract the individual coordinates like this: lon = df.point_object[0].x lat = df.point_object[0].y And I could create a function that does this for the entire df, but I figured there was a more efficient/elegant way.
tagged with: gis
tagged with: latitude-longitude
favorite count: 0
type: Question
has title: Shapely point geometry in geopandas df to lat/lon columns
score: 31
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56249512
accepted answer: http://stackoverflow.com/a/49635530

http://stackoverflow.com/q/49702512
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50101450
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49702595
tagged with: django
has answer: http://stackoverflow.com/a/50101450
has answer: http://stackoverflow.com/a/49702595
favorite count: 0
has title: Does Django have an equivalent of Rails's “rails db:seed”?
type: Question
tagged with: python
has body: One thing I like about Rails projects is that you can create test content and place them in seeds.rb and seed them into the database by running rake db:seed instead of having to feed them one by one directly. Is there something similar for Python/Django?
score: 4
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/q/49640823
tagged with: gradient-descent
has comment: http://stackoverflow.com/comment/86289490
tagged with: machine-learning
tagged with: python
has title: Python gradient-descent multi-regression - cost increases to infinity
has comment: http://stackoverflow.com/comment/86290207
type: AnsweredQuestion
score: 0
has body: Writing this algorithm for my final year project. Used gradient descent to find the minimum, but instead getting the cost as high as infinity. I have checked the gradientDescent function. I believe that's correct. The csv I am importing and its formatting is causing some error. The data in the CSV is of below format. Each quad before '|' is a row. First 3 columns are independent variables x. 4th column is dependent y. 600 20 0.5 0.63 | 600 20 1 1.5 | 800 20 0.5 0.9 import numpy as np import random import pandas as pd def gradientDescent(x, y, theta, alpha, m, numIterations): xTrans = x.transpose() for i in range(0, numIterations): hypothesis = np.dot(x, theta) loss = hypothesis - y # avg cost per example (the 2 in 2*m doesn't really matter here. # But to be consistent with the gradient, I include it) cost = np.sum(loss ** 2) / (2 * m) print("Iteration %d | Cost: %f" % (i, cost)) # avg gradient per example gradient = np.dot(xTrans, loss) / m # update theta = theta - alpha * gradient return theta df = pd.read_csv(r'C:\Users\WELCOME\Desktop\FinalYearPaper\ConferencePaper\NewTrain.csv', 'rU', delimiter=",",header=None) x = df.loc[:,'0':'2'].as_matrix() y = df[3].as_matrix() print(x) print(y) m, n = np.shape(x) numIterations= 100 alpha = 0.001 theta = np.ones(n) theta = gradientDescent(x, y, theta, alpha, m, numIterations) print(theta)
tagged with: pandas
has comment: http://stackoverflow.com/comment/86289526
answer count: 1
accepted answer: http://stackoverflow.com/a/49647874
has comment: http://stackoverflow.com/comment/86289776
has answer: http://stackoverflow.com/a/49647874
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/49658448
has comment: http://stackoverflow.com/comment/86289766

http://stackoverflow.com/comment/86357202
type: QuestionComment
comment on: http://stackoverflow.com/q/49673317
has text: I wrote some shell to perform search and replace of strings in my Dockerfile so each environment has a synthesized custom Dockerfile
score: 0
type: Comment

http://stackoverflow.com/comment/86249933
score: 0
has text: I'm not. The function expects an iterable. I have a list of dicts that I need to be able to iterate through, in some way that's compatible with the input the flask_table function is expecting. I've copied the template from the function and an example of what I think it should look like. There's not a lot of documentation and I don't have a working example, so I don't know for sure.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49621478

http://stackoverflow.com/q/49664057
score: 4
has comment: http://stackoverflow.com/comment/86338005
linked to: http://stackoverflow.com/q/16424484
upvote count: 4
has comment: http://stackoverflow.com/comment/86338036
duplicate of: http://stackoverflow.com/q/6074018
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86337975
has answer: http://stackoverflow.com/a/49664257
accepted answer: http://stackoverflow.com/a/49664257
downvote count: 0
answer count: 1
has title: Result of the chaining of comparison operators
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am confused on how does the != operator works in python. I am new to python programming. I know simple != simply checks whether the LHS expression and RHS expression are not equal. for eg: True != False returns True. My question is how it works in series of != operators. e.g.: when I type -5 != False != True != True in my python interactive session it returns False, but if I solve it step by step I get the answer True. Solving it step by step: -5 != False returns True True != True returns False False != True returns True So it should return True but it returns False. I don't know why.
has comment: http://stackoverflow.com/comment/86338108
tagged with: python

http://stackoverflow.com/a/49737097
has comment: http://stackoverflow.com/comment/86505285
has comment: http://stackoverflow.com/comment/86491133
has body: If your nothing means null or nan, you can try the below code (reference: https://stackoverflow.com/a/20606278/9584980) import numpy as np size = 20 somearray = np.full([size,],np.nan) somearray[10] = True # but this would make the element to 1. as nans are considered as float. you can change np.nan to False if you literally want a True here EDITED: If you need to use numpy methods only at the end, you can just store all the required indices and later create a numpy array of the desired size and populate the Trues accordingly. One more way is to first declare a numpy array of the size as the index that you need (10 in your example). And later resize it if the next index you need to populate is bigger than the array. index = 10 somearray = np.full([index+1,], False) somearray[index] = True #if the next index you need to make true is 20 then index = 20 somearray.resize([index+1,], refcheck=False) somearray[index] = True
type: Answer
answers question: http://stackoverflow.com/q/49734812
score: 0

http://stackoverflow.com/a/49732314
answers question: http://stackoverflow.com/q/49690613
type: Answer
score: 0
has body: This would be minimal: for i in range(20): print(i) #print(i) This includes a condition: for i in range(20): if True: test = i print(test) #print(test) Your problem is just to get the last computed value from a loop - you already achieved this, but you are printing every computed value inside the loop, i.e. on every iteration where the conditions are met. The quick solution is to just print it after the loop (swap the comments on print() above). You would generally stop the loop once you found what your are looking for. Otherwise, you'd use another variable to store the result: keepitthatway = None for i in range(42): if i==7: keepitthatway = i # keep on iterating if necessary or #break print(i) print(keepitthatway) There are lots of Python programming tutorials out there, e.g. https://wiki.python.org/moin/ForLoop. Have a look ;-) Regarding Minimal, Complete, and Verifiable example, this would have worked too. While not exactly minimal, it resembles your code structure: for current_date in range(2): print('calculating something...') for index, row in enumerate(range(20)): if index == current_date: for index2, row2 in enumerate(range(20)): if True: if True: if True: test = index print(test) #print(test) Just limiting your dataset would have been an improvement already: import pandas as pd # pretend to be the csv file import io csv = io.StringIO("""date\ttype\tyear\tvalue 2015-02-09\ta\t2D\t1.1275 2015-02-09\tb\t10M\t58.125 2015-02-09\tc\t2Y\t-28.5 2015-02-10\ta\t2D\t1.1297 2015-02-10\tb\t10M\t60.5 2015-02-10\tc\t2Y\t-29.5 2015-02-10\tc\t10Y\t-26.25 """) def CalcValue(year, a, b): normalization = 0.0 value_0D = 0.0 value_1D = 0.0 Calc = 0.0 normalization = 10000.0 if year == "0D": value_0D = b elif year == "1D": value_1D = b Calc = a-(value_0D+value_1D)/normalization return Calc data = pd.read_csv(csv, sep="\t").fillna('') #print(data) #import sys;sys.exit() pd_date = pd.DatetimeIndex(data['date'].values) data['date'] = pd_date index_data = data.set_index('date') for …

http://stackoverflow.com/comment/86436661
has text: That is very weird why it hasn't crashed or "restarted". I tried 10/10 times to run the same code inside the console and it didn't crash. I guess it doesn't work in the IDLE shell? thank you for the recommendation.
comment on: http://stackoverflow.com/a/49710747
type: Comment
type: AnswerComment
score: 0

maya
tags question: http://stackoverflow.com/q/49599888
tags question: http://stackoverflow.com/q/49618722
type: Tag
tag name: maya
tags question: http://stackoverflow.com/q/49608252

http://stackoverflow.com/q/49695681
possible better answer: http://stackoverflow.com/a/49696016
tagged with: datetime
has title: Pandas order rows by datetime month given external order
has answer: http://stackoverflow.com/a/49695971
linked to: http://stackoverflow.com/q/23482668
has body: So I'm having a little trouble ordering my Dataframe, I've tried using this question, but haven't managed to get it to work. What I have is a Dataframe nudf like so: date level_1 0 0 2016-10-01 00:00:00 0.0 74.00 1 2016-10-01 00:30:00 0.5 72 2 2016-10-01 01:00:00 1.0 70 3 2016-10-01 01:30:00 1.5 64 4 2016-10-01 02:00:00 2.0 63 5 2016-10-01 02:30:00 2.5 60 ... ... ... ... 19003 2017-09-31 21:30:00 21.5 129 19004 2017-09-31 22:00:00 22.0 118 19005 2017-09-31 22:30:00 22.5 106 19006 2017-09-31 23:00:00 23.0 84 19007 2017-09-31 23:30:00 23.5 76 And what I would like to do is order the rows by an external month order: [4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3] This is the last 12 months, from last month. I'd like to ignore the year and order each month block of rows in accordance with the order above. For example, given the following rows: 0 2016-02-01 00:00:00 0.0 74.00 1 2016-02-01 00:30:00 0.5 72 2 2016-03-01 01:00:00 1.0 70 3 2016-03-01 01:30:00 1.5 64 4 2017-04-01 02:00:00 2.0 63 5 2017-04-01 02:30:00 2.5 60 The result should be: 4 2017-04-01 02:00:00 2.0 63 5 2017-04-01 02:30:00 2.5 60 0 2016-02-01 00:00:00 0.0 74.00 1 2016-02-01 00:30:00 0.5 72 2 2016-03-01 01:00:00 1.0 70 3 2016-03-01 01:30:00 1.5 64 I've tried: nudf['month'] = nudf.apply(lambda row: row.date.month, axis=1) nudf.month = nudf.month.astype("category") nudf.month.cat.set_categories([x.month for x in reversed(_get_last_x_months(12))], inplace=True) nudf.sort_values(["month"], inplace=True) But the day and hour order is not maintained.
tagged with: python
has answer: http://stackoverflow.com/a/49696016
score: 4
type: AnsweredQuestion
upvote count: 4
answer count: 3
accepted answer: http://stackoverflow.com/a/49695971
tagged with: pandas
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49696061

http://stackoverflow.com/a/55797881
score: 0
answers question: http://stackoverflow.com/q/49649606
has body: This might be of use to you ^(\"([^\"\n\\]|\\[abfnrtv?\"'\\0-7]|\\x[0-9a-fA-F])*\"|'([^'\n\\]|\\[abfnrtv?\"'\\0-7]|\\x[0-9a-fA-F])*'|\"\"\"((?!\"\"\")[^\\]|\\[abfnrtv?\"'\\0-7]|\\x[0-9a-fA-F])*\"\"\")$ It's something that I cut-n-pasted from a project. See it in action at regex101.com.
type: Answer

http://stackoverflow.com/q/49703774
type: Question
tagged with: http://stackoverflow.com/tag/docx
has answer: http://stackoverflow.com/a/49703826
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: k-means
tagged with: cluster-analysis
tagged with: python
score: -1
has title: How do I extract words in documents (.docx) and transform it into csv for clustering?
has answer: http://stackoverflow.com/a/49703960
upvote count: 0
answer count: 2
downvote count: 1
has body: I'm new in python but i would like to try to do clustering using k-means. but first i need to extract my documents so i can execute preprocessing process. after that i'd like to transform it into csv. Can anyone suggest what step do I need to take?
favorite count: 0

http://stackoverflow.com/comment/86472232
type: QuestionComment
comment on: http://stackoverflow.com/q/49692436
type: Comment
has text: Well then, as I said above, you need to store that process somewhere. Because if you dont, then the results which you get on the new data will be useless.
score: 0

http://stackoverflow.com/q/49672411
answer count: 1
has comment: http://stackoverflow.com/comment/86355717
has comment: http://stackoverflow.com/comment/86355420
tagged with: shutil
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86355526
tagged with: python
has title: shutil.copytree --> [WinError 183]
has body: I am trying to copy an entire directory to a newly created directory. When running this, it does everything correctly and to what I can see actually does copy everything from the source folder. However, it will still return [WinError 183] - Cannot create a file that already exists despite the fact that the file does not exist. Not sure what I'm doing wrong. EDIT: After checking it is copying everything over before the error hits -- every file, every folder, so not sure what is going wrong import os import shutil #Directory Definitions root_dir = "C:\\Users\\Gabe Weiner\\Desktop\\GMImport" #os.getcwd() source_dir = root_dir + "\source" target_dir = root_dir + "\\target" #Target Duplicate for root, dirs, files in os.walk(str(target_dir)): shutil.copytree(root, root_dir + "\\Backup")
downvote count: 0
has answer: http://stackoverflow.com/a/49673318
tagged with: operating-system
has comment: http://stackoverflow.com/comment/86355306
score: 1
upvote count: 1

http://stackoverflow.com/q/49616151
score: 3
linked to: http://stackoverflow.com/q/13348766
has answer: http://stackoverflow.com/a/49618527
tagged with: python
has title: Which attributes should be changed to allow for image upload via Selenium
tagged with: image
has comment: http://stackoverflow.com/comment/86265628
type: Question
answer count: 2
downvote count: 0
has body: Set-Up I'm using Python + Selenium to upload an image to the back-end of a system. The upload button to which I send_keys() has the following HTML, &lt;div id="uploadifive-FileNameUpload" class="uploadifive-button" style="height: 18px; line-height: 18px; overflow: hidden; position: relative; text-align: center; width: 50px;"&gt; Upload &lt;input id="FileNameUpload" name="FileNameUpload" data-editor="#FileName" data-url="http://also-inc.com/upload/uploadfile" data-path="~/UserFiles/Products/Images/" data-maxsize="10240" data-extensions="*.jpg;*.jpeg;*.png;*.gif;*.bmp;" data-thumbnailwidth="128" data-thumbnailheight="128" data-thumbnailpath="/UserFiles/Products/Images/Preview/" data-uniquename="True" data-preview="/Content/uploadify/noimage.jpg" data-isnew="true" data-auth="D2C14774E29BBB87D2F34719884CFC5C6370502B067D5FC55D0C40A5EE6B1646ED4C77C9C0180D607052FF52653BA981732417A24C3F7547903649C4D64491C184E1C60D7756608784B4B3E806417E77750D87BABD9CDDCB6294EA62DE884EC7B3A4416558405874ED1C0259CD4430990BA83FC0" data-session="f1txsiyxglqb3ma1dr45awrf" class="file-uploader hide-input" style="display: none;" type="file"&gt; &lt;input style="font-size: 18px; opacity: 0; position: absolute; right: -3px; top: -3px; z-index: 999;" type="file"&gt; &lt;/div&gt; Note that the button has two input with type="file". Code Used upload_button = el_id('uploadifive-FileNameUpload').find_element_by_xpath('input[2]') upload_button.send_keys(path_to_my_image) where el_id() = browser.find_element_by_id() and path_to_my_image ends with .jpeg. Problem The code used successfully uploads the image via the second input. The image, however, is saved without the .jpeg extension. Thus the image appears broken in the back-end; i.e. image_name instead of image_name.jpeg. I think the image is saved without the extension because the second input does not allow for it. Tries adding an attribute to second input The first input has the following attribute data-extensions="*.jpg;*.jpeg;*.png;*.gif;*.bmp;". I add…
type: UnansweredQuestion
tagged with: upload
tagged with: selenium
favorite count: 0
has answer: http://stackoverflow.com/a/49616469
has comment: http://stackoverflow.com/comment/86328226
upvote count: 3

http://stackoverflow.com/q/49694128
has answer: http://stackoverflow.com/a/49694411
accepted answer: http://stackoverflow.com/a/49694411
has comment: http://stackoverflow.com/comment/86406996
type: Question
has answer: http://stackoverflow.com/a/49694632
answer count: 3
downvote count: 1
has body: If I have a function that returns multiple outputs, from which some aren't needed at times, I found that it is a convention to "ignore" these outputs with underscore, e.g. a, _ = fn_with_two_outputs() Until now I assumed that the value is just dropped and naively hoped that the compiler is clever enough not to execute any code associated with the value. But in a recent debugging session I noticed that this method actually creates a variable _ with the output - which is a waste of memory and should discourage from using the underscore-convention, shouldn't it? I'm now leaning to this variant: a = fn_with_two_outputs()[0] that I found among other ways of "ignoring output", since as far as I tested it, at least it doesn't store the output fn_with_two_outputs()[1] as a variable in the environment calling the function (it IS stored in the function environment itself). To avoid discussion: To get several return values without calling twice one can use slicing, e.g. fn_with_two_outputs()[0:4]. But: The return value - if "ignored" or not - always seems to be evaluated. I tested this for three variants of "ignoring" it with below code. def fn_with_two_outputs(): a = [1, 2, 3] b = [0, 0, 0] return a, needless_fn(b) def needless_fn(b): print("\"Be so good they can't ignore you.\" - Steve Martin") return b # I want to ignore output b (wrapped by needless_fn) a, _ = fn_with_two_outputs() # stores _ = b, needless_fn was executed a, *b = fn_with_two_outputs() # suggested for Python3, stores a list b = [b], needless_fn was executed a = fn_with_two_outputs()[0] # b nowhere to be found, but needless_fn was executed Is there a convenient way to actually ignore the output IN the function itself, causing the optional output not to consume any memory and cause code execution? My first idea is, give fn() a parameter to branch between two return statements, one "lazy", the other not - but that seems more like a workaround than an elegant solution.
linked to: http://stackoverflow.com/q/47150638
has answer: http://stackoverflow.com/a/49694285
favorite count: 0
has title: Lazy store and code execution in Python functions with optional return values
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/86400954
possible better answer: http://stackoverflow.com/a/49694285
tagged with: python
linked to: http://stackoverflow.com/q/431866

http://stackoverflow.com/comment/86267159
comment on: http://stackoverflow.com/q/49630042
score: 0
type: Comment
has text: How do you "observe" that? Did you use [sys.getsizeof](https://docs.python.org/3/library/sys.html#sys.getsizeof)?
type: QuestionComment

http://stackoverflow.com/a/49639690
answers question: http://stackoverflow.com/q/49639619
score: 1
downvote count: 0
has body: One option could be to create an ordered Categorical column, apply argsort on it which returns the correct indices to reorder your data frame: df.iloc[pd.Categorical(df.ticker, categories=["CAT","AI", "BOC"], ordered=True).argsort()] # date price ticker volume #6 2018-01-01 5.199 CAT 2000 #7 2018-01-02 4.980 CAT 450 #8 2018-01-03 4.990 CAT 3000 #0 2018-01-01 1.323 AI 2000 #1 2018-01-02 1.525 AI 1500 #2 2018-01-03 1.045 AI 500 #3 2018-01-01 2.110 BOC 3201 #4 2018-01-02 2.150 BOC 5200 #5 2018-01-03 2.810 BOC 1980
upvote count: 1
type: Answer

http://stackoverflow.com/q/49617180
has answer: http://stackoverflow.com/a/49617442
score: 1
tagged with: python
tagged with: average
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/49617442
has body: I've written a simple rolling average function, which works well. I also don't want to use external libraries like numpy or pandas, just so you know. def get_rolling_average(data, period): rolling = [] for i in range (0, len(data)): end = i + period nums = data[i:end] # if i &lt; (period-1): # nums = data[0:i+1] # rolling.append(mean(nums)) if len(nums) == period: rolling.append(mean(nums)) return rolling def round_nicely(num, places): return round(num, places) def mean(lst): summ = sum(lst[0:len(lst)]) summ = float(summ) return round_nicely(summ/len(lst),1) print("Rolling average!") xl = [45, 51, 73, 82, 76, 56, 57, 78, 89, 59] print get_rolling_average(xl, 3) With the results being Rolling average! [56.3, 68.7, 77.0, 71.3, 63.0, 63.7, 74.7, 75.3] However, I want to include the first few values if they are smaller than the period. In this exmple, it'll be just 45 &amp; 48. Rolling average! [45.0, 48.0, 56.3, 68.7, 77.0, 71.3, 63.0, 63.7, 74.7, 75.3] where (45)/1 = 45.0 (45 + 51)/2 = 48.0 I'm not sure the most Pythonic method to do this. I've got a bit of a brain-freeze and my most cohesive attempt is the three lines commented out, but it skips a value.
linked to: http://stackoverflow.com/q/13728392
has comment: http://stackoverflow.com/comment/86241852
accepted answer: http://stackoverflow.com/a/49617732
tagged with: arrays
downvote count: 0
has title: Simple rolling average - first few values
upvote count: 1
has answer: http://stackoverflow.com/a/49617732
favorite count: 0
type: Question

http://stackoverflow.com/q/49690100
has comment: http://stackoverflow.com/comment/86392126
has answer: http://stackoverflow.com/a/61037073
has comment: http://stackoverflow.com/comment/86391802
tagged with: web-scraping
tagged with: python
tagged with: scrapy
has title: Scrapy code error - inconsistent use of tabs
has comment: http://stackoverflow.com/comment/86400346
score: 0
answer count: 1
has body: when I try to run this code, I get this error help me with this File "E:\pycode\testscrap1\testscrap1\spiders\quotes.py", line 11 h1_tag = response.xpath('//h1/a/text()').extract_first() ^ TabError: inconsistent use of tabs and spaces in indentation import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' allowed_domains = ['quotes.toscrape.com'] start_urls = ['http://quotes.toscrape.com/'] def parse(self, response): h1_tag = response.xpath('//h1/a/text()').extract_first() tags = response.xpath('//*[@class="tag-item"]/a/text()').extract() yield {'H1 TAG' : h1_tag, 'Tags' : tags}
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49687583
favorite count: 0
score: -1
type: Question
has title: How to print publisher attributes in subscription code mqtt?
possible better answer: http://stackoverflow.com/a/49693330
answer count: 2
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/49693330
upvote count: 0
has body: I have my subscription code running on raspberry pi. Since it is connected to multiple publishers, I want to print out the publisher attributes like its name ID. How can i do that?
tagged with: raspberry-pi3
downvote count: 1
accepted answer: http://stackoverflow.com/a/49687621
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49687621
tagged with: mqtt
tagged with: python

http://stackoverflow.com/a/49619729
has body: Figured that using application hotkeys vs find on the screen is a much less brittle approach. Below how I finally build Spotify bot. import time import pyautogui # use pyauutogui key shortcut to open OSX spotlight search pyautogui.hotkey('command', 'space') # type spotify and press enter to open application pyautogui.typewrite('Spotify') pyautogui.hotkey('enter') # use Spotify keyboard shortcuts to select search. # key docs here: https://support.spotify.com/ie/article/Keyboard-shortcuts/ time.sleep(5) pyautogui.hotkey('command', 'l') # typewrite allows passing string arguments using keyboard pyautogui.typewrite('concentration music') # move to select the song with tab and press enter to play pyautogui.hotkey('tab', 'tab', 'tab', 'tab') time.sleep(2) pyautogui.hotkey('enter') pyautogui.hotkey('space') # sleeps 30 seconds while music is playing time.sleep(30) pyautogui.hotkey('command', 'q')
answers question: http://stackoverflow.com/q/49615588
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86399542
has text: @chepner I don't think it's a bug, it's considered an error to overload the method signature of a subclass (even the types) since it breaks covariance. That being said, I'm not sure I agree with that conclusion.
comment on: http://stackoverflow.com/q/49693410
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/49719527
upvote count: 2
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49719504
has body: As mentioned, you can use numpy.pad. You can use pad_width=1 and mode='constant'. You can add constant_values=0, but since 0 is the default value this is not necessary. import numpy as np a = np.array([(1, 2, 3),(4, 5, 6)]) res = np.pad(a, pad_width=1, mode='constant') print(res) # [[0 0 0 0 0] # [0 1 2 3 0] # [0 4 5 6 0] # [0 0 0 0 0]]
downvote count: 1

http://stackoverflow.com/q/49735419
has title: Trouble rendering graph as dictionary with lists in sets in Python 2 vs 3
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49735580
type: AnsweredQuestion
score: 2
has body: This is a 2 parter. The following code is in Python 2. It renders a graph as a dict with values as sets containing lists. import urllib2 CITATION_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_phys-cite.txt" def load_graph(graph_url): graph_file = urllib2.urlopen(graph_url) graph_text = graph_file.read() graph_lines = graph_text.split('\n') graph_lines = graph_lines[ : -1] print "Loaded graph with", len(graph_lines), "nodes" answer_graph = {} for line in graph_lines: neighbors = line.split(' ') node = int(neighbors[0]) answer_graph[node] = set([]) for neighbor in neighbors[1 : -1]: answer_graph[node].add(int(neighbor)) return answer_graph Sample output: {1001: set([9304045, 9308122]), 1002: set([9201007, 9204031, 9210123, 9912187]), ... } The above code was updated for Python 3. The part responsible for rendering the graph remained unchanged: answer_graph = {} for line in graph_lines: neighbors = line.split(' ') node = int(neighbors[0]) answer_graph[node] = set([]) for neighbor in neighbors[1 : -1]: answer_graph[node].add(int(neighbor)) return answer_graph Sample output: {9306112: {9210128, 1, 9202065}, 9306114: {1, 9204065, 9301122} ...} 1) Why did the node: set([1, 2, 3]) notation disappear even though it was embedded in the code? 2) I tried changing answer_graph[node].add(int(neighbor)) to answer_graph[node].add([int(neighbor)]) to get the list to appear within the set. I got the error TypeError: unhashable type: 'list'. This is a point of extreme confusion for me at the moment. I've seen posts on here that suggest sets can't contain lists. This is manifestly false, as I've represented graphs this way. That said, it just threw an error at me when I tried to add a list to a set. What am I missing with respect to these two questions?
accepted answer: http://stackoverflow.com/a/49735580
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/86287467
type: QuestionComment
score: 0
has text: @martineau I edited the post a little, could you please check that out and let me know what you think
comment on: http://stackoverflow.com/q/49638148
type: Comment

http://stackoverflow.com/q/49673876
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49674078
tagged with: row
tagged with: pandas
has answer: http://stackoverflow.com/a/49674334
has body: I am trying to change the value in one row in pandas dataframe for certain columns with other values: sub_data.loc[[0],20:71] = sub_data.loc[1,20:71] or sub_data.loc[0,20:71] = sub_data.loc[1,20:71] both did not work. any suggestion? Update It was solved when I used series sub_data.iloc[0,20:71].update(sub_data.iloc[1,20:71])
accepted answer: http://stackoverflow.com/a/49674334
type: Question
has answer: http://stackoverflow.com/a/49674078
answer count: 2
has title: Assign new values in pandas
tagged with: python
has comment: http://stackoverflow.com/comment/86359030

http://stackoverflow.com/q/49607346
answer count: 0
tagged with: gpio
downvote count: 0
has comment: http://stackoverflow.com/comment/86221599
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86222074
type: Question
has body: UPDATE: Problem solved. Sigh. It was as simple as adding a bit of a delay when turning the pins on and off. Not a permissions issue at all. I guess the IDLE3 ide ran just the littlest bit slower that the signal was detected by the arduino. When running it from the console, it happened too quickly. Adding a time.sleep(.5) between switching the pins from Low to High gave the ard enough time to read. Everything works now. I've got a python script that functions as a MQTT client as well as controls some GPIO pins based on signals it gets from the MQTT feeds. This script works without issue when run from IDLE3. However, when I try to run it at startup using both /etc/rc.local and crontab (I've used both, separately, to no avail) or from the console, the script runs (and I know because I see it publishing to a MQTT feed) but the GPIO pins do not function. The script is: import sys import RPI.GPIO as GPIO import serial import time from Adafruit_IO import MQTTClient ADAFRUIT_IO_KEY = 'mykeyhere' ADAFRUIT_IO_USERNAME = 'myusernamehere' GPIO.setmode(GPIO.BCM) FEED_ID = 'DoorFeed' reset_feed_id = 'GameReset' door_override = 18 reset_pin = 17 GPIO.setup(door_override, GPIO.OUT) GPIO.setup(reset_pin, GPIO.OUT) GPIO.output(door_override, True) GPIO.output(reset_pin, True) def connected(client): print('connected to adafruit io') client.subscribe(FEED_ID) client.subscribe(reset_feed_id) def disconnected(client): print('disconnected from adafruit io') client.connect() def handle_msg(payload): if(payload == '1'): GPIO.output(door_override, False) print('manual override sent') GPIO.output(door_override, True) def handle_reset(payload): if(payload == '1'): GPIO.output(reset_pin, False) print('reset signal sent') GPIO.output(reset_pin, True) client.publish('GameReset', 'F') def message(client, feed_id, payload): print('feed {0} received new value {1}'.format(feed_id, payload)) if(feed_id == 'GameReset'): handle_reset(payload) if(feed_id == 'DoorFeed'): handle_msg(payload) client = MQTTC…
has comment: http://stackoverflow.com/comment/86221527
tagged with: python
type: UnansweredQuestion
favorite count: 0
tagged with: python-3.x
tagged with: adafruit
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/86221563
has comment: http://stackoverflow.com/comment/86221928
has title: GPIO pins in Python Script work in IDLE3 but not when run from console (using Adafruit IO MQTT)
has comment: http://stackoverflow.com/comment/86221679

http://stackoverflow.com/a/49611813
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49611579
has body: You can use map to apply a function to every item in an iterable. The result, in Python 3.x, is an iterable. There are several different ways you can then extract results. Below is an example. I have also corrected some errors in your logic. Your function f should take a parameter, presumably i, as this is used in your function. Similarly, it seems you want the function count to take a parameter n to determine your range of inputs. def count(n): def f(i): return i*i return map(f, range(1, n)) ## iterate using next res = count(5) print(next(res)) # 1 print(next(res)) # 4 print(next(res)) # 9 ## iterate using for loop for k in count(4): print(k) # 1 # 4 # 9 ## build list and exhaust all results print(list(count(4))) # [1, 4, 9]

http://stackoverflow.com/comment/86357381
type: Comment
type: QuestionComment
has text: I'm using python 3.6 too and here works. Check if your python file is encoded as UTF-8 Unicode text or try use `# -*- coding: utf-8 -*-` on the top
score: 0
comment on: http://stackoverflow.com/q/49673257

http://stackoverflow.com/q/49623765
has body: I downloaded a zip file from https://clinicaltrials.gov/AllPublicXML.zip, which contains over 200k xml files (most are &lt; 10 kb in size), to a directory (see 'dirpath_zip' in the CODE) I created in ubuntu 16.04 (using DigitalOcean). What I'm trying to accomplish is loading all of these into MongoDB (also installed in the same location as the zip file). I ran the CODE below twice and consistently failed when processing the 15988th file. I've googled around and tried reading other posts regarding this particular error, but couldn't find a way to solve this particular issue. Actually, I'm not really sure what problem really is... any help is much appreciated!! CODE: import re import json import zipfile import pymongo import datetime import xmltodict from bs4 import BeautifulSoup from pprint import pprint as ppt def timestamper(stamp_type="regular"): if stamp_type == "regular": timestamp = str(datetime.datetime.now()) elif stamp_type == "filename": timestamp = str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "_")[:15] else: sys.exit("ERROR [timestamper()]: unexpected 'stamp_type' (parameter) encountered") return timestamp client = pymongo.MongoClient() db = client['ctgov'] coll_name = "ts_"+timestamper(stamp_type="filename") coll = db[coll_name] dirpath_zip = '/glbdat/ctgov/all/alltrials_20180402.zip' z = zipfile.ZipFile(dirpath_zip, 'r') i = 0 for xmlfile in z.namelist(): print(i, 'parsing:', xmlfile) if xmlfile == 'Contents.txt': print(xmlfile, '==&gt; entering "continue"') continue else: soup = BeautifulSoup(z.read(xmlfile), 'lxml') json_study = json.loads(re.sub('\s', ' ', json.dumps(xmltodict.parse(str(soup.find('clinical_study'))))).strip()) coll.insert_one(json_study) i+=1 ERROR MESSAGE: Traceback (most recent call last): File "zip_to_mongo_alltrials.py", line 38, in &lt;module&gt; soup = BeautifulSoup(z.read(xmlfile), 'lxml') File "/usr/local/lib/python3.5/dist-packages/bs4/__init__.py", line 225, in __init__ markup, from_encoding, e…
accepted answer: http://stackoverflow.com/a/49624164
has title: python memoryerror - large loop xml to mongodb
tagged with: python
has answer: http://stackoverflow.com/a/49624164
tagged with: ubuntu
tagged with: digital-ocean
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 0
tagged with: mongodb
linked to: http://stackoverflow.com/q/29904161
answer count: 1
has comment: http://stackoverflow.com/comment/86254990
type: Question

function
tags question: http://stackoverflow.com/q/49711323
tags question: http://stackoverflow.com/q/49610817
tags question: http://stackoverflow.com/q/49700368
type: Tag
tags question: http://stackoverflow.com/q/49681606
tags question: http://stackoverflow.com/q/49719138
tags question: http://stackoverflow.com/q/49680080
tag name: function
tags question: http://stackoverflow.com/q/49713333
tags question: http://stackoverflow.com/q/49601496
tags question: http://stackoverflow.com/q/49696658
tags question: http://stackoverflow.com/q/49617543
tags question: http://stackoverflow.com/q/49658210
tags question: http://stackoverflow.com/q/49710187
tags question: http://stackoverflow.com/q/49682296
tags question: http://stackoverflow.com/q/49696850
tags question: http://stackoverflow.com/q/49667924
tags question: http://stackoverflow.com/q/49689424
tags question: http://stackoverflow.com/q/49746071
tags question: http://stackoverflow.com/q/49602691
tags question: http://stackoverflow.com/q/49701446
tags question: http://stackoverflow.com/q/49628193
tags question: http://stackoverflow.com/q/49611116
tags question: http://stackoverflow.com/q/49670906
tags question: http://stackoverflow.com/q/49641710
tags question: http://stackoverflow.com/q/49641454
tags question: http://stackoverflow.com/q/49639986
tags question: http://stackoverflow.com/q/49751425
tags question: http://stackoverflow.com/q/49665752
tags question: http://stackoverflow.com/q/49611579
tags question: http://stackoverflow.com/q/49723432
tags question: http://stackoverflow.com/q/49681114
tags question: http://stackoverflow.com/q/49663292
tags question: http://stackoverflow.com/q/49639578
tags question: http://stackoverflow.com/q/49687566
tags question: http://stackoverflow.com/q/49717224

http://stackoverflow.com/comment/91775513
type: AnswerComment
comment on: http://stackoverflow.com/a/50874554
type: Comment
has text: Oh, sorry for late response. I gave up this issue long ago and bypassed with using [pydbind](https://github.com/pybind/pybind11). Anyway, I will try this out. Thanks for your answer! :-)
score: 0

http://stackoverflow.com/comment/86261166
has text: Found a solution.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49626353
type: AnswerComment

http://stackoverflow.com/a/49722131
type: AcceptedAnswer
downvote count: 0
has body: You can use a dict() to speed up this process to just going through 10 million entries. So the first thing you want to do is to change all the sublists in A to hashable objects do you can use them as keys in a dict. Converting all the sublists to tuples: A = [tuple(i) for i in A] Then create a dict() with every value in A as the key and the value being 0. d = {i:0 for i in A} Now for each subarray in your numpy array, you just want to convert it to a tuple and increment d[that array] by 1 for subarray in B: d[tuple(subarray)] += 1 D is now a dictionary where for each key the value is how many times that key occured in B.
type: Answer
accepted answer of: http://stackoverflow.com/q/49722046
answers question: http://stackoverflow.com/q/49722046
upvote count: 1
score: 1

http://stackoverflow.com/comment/86464456
comment on: http://stackoverflow.com/q/49725203
type: Comment
has text: You can try `foo['col5'] = [myList]*len(foo) `
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86330442
has text: Also, note that `soup.find_all('a')` is gathering *every* link on the site, which will probably include absolute paths for routing, which will not work with `requests.get` as no sitename is provided.
comment on: http://stackoverflow.com/q/49660379
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86416916
comment on: http://stackoverflow.com/a/49701538
score: 0
type: Comment
has text: Thank you. I will play around with this and see how it works.
type: AnswerComment

http://stackoverflow.com/a/49636992
has body: I guess it's because you are using the function drawContours(), it draws the contours literally. If you want to see the difference i.e. just the points, I think you should just try to plot the points returned and not use the drawContours() function.
has comment: http://stackoverflow.com/comment/86282156
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49636870
has comment: http://stackoverflow.com/comment/86282077
score: 2

http://stackoverflow.com/comment/87143447
has text: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/setuptools-1.3.1-py2.7.egg' Consider using the `--user` option or check the permissions. .... Should I add the --user option?
comment on: http://stackoverflow.com/a/49748494
type: AnswerComment
score: 6
type: Comment

http://stackoverflow.com/comment/86485305
comment on: http://stackoverflow.com/q/49735693
score: 1
type: Comment
type: QuestionComment
has text: did you try `export CUDA_VISIBLE_DEVICES=2,3` ?

http://stackoverflow.com/a/49626876
answers question: http://stackoverflow.com/q/49626788
type: AcceptedAnswer
downvote count: 0
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49626788
has body: decode JSON strings into dicts and put them in a list, last, convert the list to JSON json_list = [] json_list.append(json.loads(JSON_STRING)) json.dumps(json_list) or more pythonic syntax output_list = json.dumps([json.loads(JSON_STRING) for JSON_STRING in JSON_STRING_LIST])

http://stackoverflow.com/a/49696245
answers question: http://stackoverflow.com/q/49695859
downvote count: 0
upvote count: 1
type: Answer
has body: for file in files: with open(file) as fin: if fin.read(): print file print file.read()
score: 1

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/49625915

http://stackoverflow.com/a/49682329
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49662333
has body: Here is the more succinct way of doing things (for my example of standardizing the columns). I post the apply way and then the transform way (which is the more succinct way). #verbose df1.groupby("someindex").apply(lambda x: x.apply(lambda y: (y - y.mean())/y.std())) #clear df1.groupby("someindex").transform(lambda x: (x - x.mean())/x.std())
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49662333

http://stackoverflow.com/comment/86373463
has text: one simple way would be adding a symlink
comment on: http://stackoverflow.com/q/49680829
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87201176
score: 0
type: AnswerComment
type: Comment
has text: @fumi_fwh please accept the answer if it addressed your issue.
comment on: http://stackoverflow.com/a/49803118

http://stackoverflow.com/comment/86483760
comment on: http://stackoverflow.com/q/49734434
has text: @VPfB: I am using MacOS Sierra
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49658301
has answer: http://stackoverflow.com/a/49658596
tagged with: user-interface
downvote count: 1
has answer: http://stackoverflow.com/a/49658628
favorite count: 0
has comment: http://stackoverflow.com/comment/86326281
type: Question
tagged with: python-3.x
tagged with: tkinter
upvote count: 1
possible better answer: http://stackoverflow.com/a/49658628
tagged with: python
has body: I have been wanting to know how to make a GUI without using a module on Python, I have looked into GUI's in Python but everything leads to Tkinter or other Python GUI modules. The reason I do not want to use Tkinter is because I want to understand how to do it myself. I have looked at the Tkinter modules files but it imports like 4 other Modules. I don't mind the modules like system, os or math just not modules which I will use and not understand. If you do decide to answer my question please include as much detail and information on the matter. Thanks -- Darrian Penman
type: AnsweredQuestion
has title: Python - How do I make a window along with widgets without using modules like Tkinter?
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49658596
has comment: http://stackoverflow.com/comment/86326411

http://stackoverflow.com/comment/86378325
has text: What have you tried so far (presumably your `waveform.py` script) and where did you get stuck?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49683215

http://stackoverflow.com/a/49682913
has body: I can't really grasp what you're doing aside from plotting your memory usage (might want to scrap the code that isn't really related to the problem), but I can give you some general pointers how to handle lots of data and why it eats up all your memory. The reasons. Python isn't really a high-performance language in terms of efficiency and speed. In Python, everything is an object and every object has their own properties. When you create a nested list of properties, then the parent list, all the nested lists and every little integer has their own stuff attached to them - their own metadata and description. You can visualize that when you call dir() on different objects - for example an integer in Python has 69 different methods and attributes attached to it. And all of those have to fit in the memory, this is why your memory is gobbled up much faster than the actual size of the JSON format which doesn't hold any metadata about the data. How to combat that? There are languages out there that are much better with handling big amounts of data simply because they are not so developer friendly and look out for you every step of the way. You could switch to C and accomplish the task with 8 GB of RAM. But I'm not recommending to switch languages, just use some better practices. Right now you're holding all your data in lists and dicts (?) which really isn't efficient. Look up what numpy and pandas can do for you - they are exactly meant for such use cases. They are implemented in C which provides much better performance while having a Python API that makes usage rather convenient. If that isn't enough, just do what you're doing in chunks. If all you want is a huge list of lists with some integers in it, you can do it in iterations while saving all of it in intervals and you don't need it all in the memory at the same time. If Python native garbage collection isn't enough, you can try to force Python to release memory by deling the huge variables and calling garbage collec…
type: Answer
has comment: http://stackoverflow.com/comment/86378265
upvote count: 1
has comment: http://stackoverflow.com/comment/86392426
answers question: http://stackoverflow.com/q/49682701
downvote count: 0
score: 1

http://stackoverflow.com/comment/86485121
comment on: http://stackoverflow.com/q/49735569
score: 1
has text: Can you give an example of which packages are being ignored?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86348032
has text: Did you try anything? Doesn't seem too complex to achieve, even with a simple iteration.
score: 2
comment on: http://stackoverflow.com/q/49668991
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49708209
tagged with: c++
tagged with: runtime-error
score: 2
upvote count: 2
tagged with: ioerror
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86429990
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86429846
has body: I have a short snippet of python code which calls a C++ DLL. The DLL function takes in a pointer to a table of 6 doubles (for output), and a table of strings for input. myDll.get_results.argtypes = [ ctypes.POINTER(ctypes.c_double * 6), ctypes.POINTER(ctypes.c_char*100) ] results = (ctypes.c_double * 6)() myDLL.get_results(ctypes.byref(results), input_string) I then print out the results: for r in results: print r And this works fine most of the time. Once in a while though, I get the following error, which happens when printing the values. It happens randomly, i.e. it can happen after printing the first value or the last. 0.0 0.1 Traceback (most recent call last): File "d:\Documents\test.py", line 109, in &lt;module&gt; execute() File "d:\Documents\test.py", line 45, in execute print(f)IOError: [Errno 0] Error PS D:\Documents&gt; It also (seems to) never happens if I set a breakpoint before printing. I tried putting a sleep of 1 second before printing and that doesn't help, the error still happens. On the C++ side of things, my function looks like this: RESULT_API void get_results(double res[6], char c[][100]) { for (int i = 0; i &lt; 6; i++) res[i] = (double)i*0.1; } Thanks!
type: UnansweredQuestion
tagged with: io
tagged with: python
has title: Python - Printing values from a c++ DLL error
has answer: http://stackoverflow.com/a/49708409

http://stackoverflow.com/comment/89698321
type: AnswerComment
type: Comment
has text: Going back to your proposed solution, I tried it without after() or after_idle() and I could check that the progressbar does not update properly. But I do not understand 100% the reason why. Thanks
comment on: http://stackoverflow.com/a/49755445
score: 0

http://stackoverflow.com/q/49701446
upvote count: 7
has comment: http://stackoverflow.com/comment/86416777
has title: How can we define a function without using the `def` keyword?
score: 4
has comment: http://stackoverflow.com/comment/86942620
has comment: http://stackoverflow.com/comment/86416517
type: Question
tagged with: python-3.x
tagged with: function
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/13184281
has body: It's possible to define a class without using the class keyword. The following ... get_i = lambda self: self.i get_i.__name__ = 'get_i' get_i.__qualname__ = 'Klass2.get_i' dct = dict(a=1, i=4, get_i=get_i) Klass2 = type('Klass2', (SuperK,), dct) ... produces the same end result as: class Klass1(SuperK): a = 1 i = 4 def get_i(self): return self.i How can we do something similar for functions? That is, how can we define a function without using the def or lambda keywords? What might a pure-python implementation of dehf look like if the following two pieces of code created identical foos? def foo(bar): bar += 934 return bar foo = dehf(blah, blah, blah, blah, [...])
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86418651
favorite count: 0
has answer: http://stackoverflow.com/a/49701495
has comment: http://stackoverflow.com/comment/86939940

http://stackoverflow.com/q/49608496
score: 0
has comment: http://stackoverflow.com/comment/86223682
tagged with: python
tagged with: formatting
has comment: http://stackoverflow.com/comment/86261322
has comment: http://stackoverflow.com/comment/86243245
has comment: http://stackoverflow.com/comment/86235658
has title: TypeError: Mismatch between array dtype ('float32') and format specifier ('%5.2f , %5.2f , %5.2f')
answer count: 0
has comment: http://stackoverflow.com/comment/86243290
has body: I am stuck with a format issue during reading/storing files. Any comment/remark is welcome how to solve this. I am defining some arrays pos_pb_now = np.array(pos_pb_now, dtype='f') # 6x3 pos_pw_now = np.array(pos_pw_now, dtype='f') #6x3 pos_ball_now = np.array(pos_ball_now, dtype='f') # 1x3 save the data later in a file np.savetxt(f_store_handler, pos_pb_now, fmt='%5.2f', delimiter=' , ') np.savetxt(f_store_handler, pos_pw_now, fmt='%5.2f', delimiter=' , ') np.savetxt(f_store_handler, pos_ball_now, fmt='%5.2f', delimiter=' , ') recover the data later for further use; only in 1 array of size (n*13) x 3 and this line below is initializing it. array_coord_sequence = np.loadtxt(filename_coord_retrieve, delimiter=',', skiprows=0, dtype='f') Then I modify the array_coord_sequence and want to store it again in one time np.savetxt(f_store_handler_local, array_coord_sequence, fmt='%5.2f', delimiter=' , ') but errors comes up Traceback (most recent call last): store coord into file new/overwriting pos_uwr_player.csv File "/home/family/glade/game_uwr/game_uwr.py", line 1844, in store_file_coord np.savetxt(f_store_handler_local, array_coord_sequence, fmt='%5.2f', delimiter=' , ') File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 1219, in savetxt % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('float32') and format specifier ('%5.2f , %5.2f , %5.2f') Update 1: example of a code how array_coord_sequence is modified (lfd_seq is an integer) for k in range(6): array_coord_sequence[k + (lfd_seq - 1) * 13, 0] = pos_pb_now[k, 0] array_coord_sequence[k + (lfd_seq - 1) * 13, 1] = pos_pb_now[k, 1] array_coord_sequence[k + (lfd_seq - 1) * 13, 2] = pos_pb_now[k, 2] array_coord_sequence[k + (lfd_seq - 1) * 13 + 6, 0] = pos_pw_now[k, 0] array_coord_sequence[k + (lfd_seq - 1) * 13 + 6, 1] = pos_pw_now[k, 1] array_coord_sequence[k + (lfd_seq - 1) * 13 + 6, 2] = pos_pw_now[k, 2] array_coord_sequence[12 + (lfd_seq - 1) * 13, 0] = pos_ball_now[0, 0] array_coord_sequ…
type: UnansweredQuestion
tagged with: file
tagged with: floating-point
type: Question

http://stackoverflow.com/comment/86247961
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49601031
has text: Possible duplicate of [Why this z3 equation is failing?](https://stackoverflow.com/questions/49281487/why-this-z3-equation-is-failing)

http://stackoverflow.com/q/49701359
tagged with: tensorflow
type: Question
score: 0
has body: This question is related to this SO post and this github discussion I'm using a TFRecord to store my data, the code works if I hardcode the shape. However, I need to obtain the shape from the TFRecord. def _parse_function(example_proto): keys_to_features = {'image_size': tf.FixedLenFeature((), tf.int64), 'seq_steps': tf.FixedLenFeature((), tf.int64), 'K': tf.FixedLenFeature((), tf.int64), 'T': tf.FixedLenFeature((), tf.int64), 'input_seq': tf.FixedLenFeature((), tf.string)} parsed_features = tf.parse_single_example(example_proto, keys_to_features) image_size = tf.cast(parsed_features['image_size'],tf.int32) seq_steps = tf.cast(parsed_features['seq_steps'],tf.int32) K = tf.cast(parsed_features['K'],tf.int32) T = tf.cast(parsed_features['T'],tf.int32) input_shape = [image_size, image_size, seq_steps*(K+T), 2] input_seq = tf.reshape(tf.decode_raw(parsed_features['input_seq'], tf.float32), tf.stack(input_shape), name='reshape_input_seq') return input_seq The returned tensor has dynamic shape and when going through the model tf.reshape is called at some point which then returns an error since the tensor shape is only partially known. I'm not sure how to proceed. I tried fixing this by setting input_seq.set_shape(tf.stack(input_shape)) before returning it. This however gives me another error TypeError: Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn. To fix this I tried dataset = dataset.map(lambda elems: tf.map_fn(_parse_function, elems)) instead of just dataset = dataset.map(_parse_function) This then returns ValueError: slice index 0 of dimension 0 out of bounds. Any help would be appreciated!
linked to: http://stackoverflow.com/q/35620157
has comment: http://stackoverflow.com/comment/86586865
has comment: http://stackoverflow.com/comment/86492165
tagged with: python
has title: Using values read from TFRecords as arguments to tf.reshape
has comment: http://stackoverflow.com/comment/86536741
has comment: http://stackoverflow.com/comment/86516687
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86305487
score: 0
type: AnswerComment
has text: My intention is to do it purely with `gdal`, not with using wrappers like `rasterio`
type: Comment
comment on: http://stackoverflow.com/a/49648734

http://stackoverflow.com/q/49636078
score: 1
has comment: http://stackoverflow.com/comment/86279915
has title: Multiprocessing a member function
has comment: http://stackoverflow.com/comment/86280714
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86279812
type: Question
has answer: http://stackoverflow.com/a/49636565
accepted answer: http://stackoverflow.com/a/49636565
has comment: http://stackoverflow.com/comment/86280305
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86279870
has comment: http://stackoverflow.com/comment/86279795
tagged with: multiprocessing
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49637965
has body: I have a list of objects and need to call a member function of every object. Is it possible to use multiprocessing for that? I wrote a short example of what i want to do. import multiprocessing as mp class Example: data1 = 0 data2 = 3 def compute(): self.val3 = 6 listofobjects = [] for i in range(5): listofobjects.append(Example()) pool = mp.Pool() pool.map(listofobjects[range(5)].compute())
has comment: http://stackoverflow.com/comment/86280216

http://stackoverflow.com/comment/86391655
comment on: http://stackoverflow.com/q/49688731
type: QuestionComment
has text: terminating the execution of script
score: 0
type: Comment

http://stackoverflow.com/comment/86329427
comment on: http://stackoverflow.com/q/49659873
score: 3
has text: It is a mistake to assume that just because you are modifying an existing list, your new storage must go into the same space in memory.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57841836
upvote count: 1
has body: The frequency array f is limited by half of nperseg plus the zero frequency, so f.size = int(1 + nperseg / 2) while the time array is limited by the amount of segments you can extract from the data array based on nperseg and noverlap, like so t.size = int(len(data[:, 1]) - noverlap) / (nperseg - noverlap)) It's easier to understand this if you imagine that to have two segments with nperseg=8 and noverlap=1 you need a signal with 15 samples at least.
has comment: http://stackoverflow.com/comment/102111178
type: Answer
answers question: http://stackoverflow.com/q/49709861
has comment: http://stackoverflow.com/comment/122499321
score: 1
downvote count: 0

http://stackoverflow.com/comment/86442026
score: 0
comment on: http://stackoverflow.com/q/49714426
type: QuestionComment
type: Comment
has text: Under what conditions should you increment count? Under what conditions should you reset the count?

http://stackoverflow.com/comment/86469764
score: 0
has text: `obj='...'` # here lies the problem
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49724882

http://stackoverflow.com/comment/110670574
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49604694
has text: Pro-tip, .join() takes an iterable. Generator expressions are iterable hence no need to wrap with list conversion.

http://stackoverflow.com/comment/86282917
has text: Thanks for accepting my answer. Please note that I marked your question as a duplicate of a question asked a while ago, but that method originally was incorrect as it didn't display the actual points that you wanted. That has changed using the information from my answer and it is now correct. The duplicate is used as a beacon for other people to see that this problem has been solved in the past.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49636870

http://stackoverflow.com/a/49686172
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49683175
answers question: http://stackoverflow.com/q/49683175
type: Answer
has body: One way to do it is to first left join the two table on test and name, and then drop rows where the sequence in index is not found in config: ind2 = index.set_index(['test', 'name']) out = config.join(ind2, ['test', 'name'], 'left', lsuffix='_config', rsuffix='_index') out['sequence_config'] = out.apply(lambda x: x['sequence_index'] in x['sequence_config'] if x['sequence_config'] is not None else False, axis=1) out = out[out['sequence_config']].set_index('index').drop_duplicates().drop( 'sequence_config', axis=1).rename(columns={'sequence_index': 'sequence'}) This gives: name test sequence index 901922.0 john A 111.0 930293.0 sam B 444.0 238394.0 ashley C 555.0
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/49618628
has comment: http://stackoverflow.com/comment/86244520
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49618250
has comment: http://stackoverflow.com/comment/86244695
answers question: http://stackoverflow.com/q/49618250
type: Answer
has body: I see. I believe your logic is fine until the inner for loop (for elem in ...). The solution is simpler: you don't need to have nested for loop, just use the zip function to pair every element in a (which I call keys) with corresponding elements in b (which I call values): from collections import defaultdict inputfile = open("file.txt","r") my_dict = defaultdict(list) for line in inputfile: line = line.split() keys = line[4].split("-") values = [v.strip("'") for v in line[7].split("-")] for k, v in zip(keys, values): my_dict[k].append(v) for k, v in sorted(my_dict.items()): print('{} = {}'.format(k, v)) Output: word1 = ['word7', 'word11', 'word11'] word2 = ['word8', 'word7'] word3 = ['word9'] word4 = ['word10']

http://stackoverflow.com/q/49688880
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86389531
favorite count: 0
type: Question
tagged with: opencv
possible better answer: http://stackoverflow.com/a/53817846
tagged with: mnist
has comment: http://stackoverflow.com/comment/86389239
has answer: http://stackoverflow.com/a/49691328
accepted answer: http://stackoverflow.com/a/49691328
tagged with: python
has answer: http://stackoverflow.com/a/53817846
has title: MNIST: Trying to obtain high accuracy
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86389442
has body: I'm currently working on the handwritten digits recognition problem. To start with, I have tested sample handwritten digits against MNIST dataset. I'm getting an accuracy of 53% and I need above 90% accuracy. Following are the things that I have tried so far to increase the accuracy. Created my own dataset I have created 41,000 examples. To get started I made a small dataset, which has 10000 examples( 1000 for each digits ). The dataset was created on the lines of mnist format( probably thought of clubbing my dataset and mnist dataset in the later stage ). The accuracy of the model built on this was close to 65%. Approach I have been testing my input data using softmax, but it didn't help much on the accuracy part. So I have started trying the cnn way. So my question is: Is there another approach/algorithm, which would be able to detect the digits more accurately. Do I need to train the model more ? Do I need to clean the images ? I am working on clubbing the mnist dataset and my dataset(41,000 digits data) to see, if it increases the accuracy. Code To test my images against mnist(Run the mnist before this code) You can find the Ipyhton notebooks for: Testing my sample digits against MNIST ( Script - 1 ) Testing my sample digits against my dataset( Script - 2 ) The scripts and the images are available at this link
has comment: http://stackoverflow.com/comment/86389215

http://stackoverflow.com/comment/86233203
score: 0
has text: are you sure the table name can be given with `%s` ?
comment on: http://stackoverflow.com/q/49613228
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86525226
type: QuestionComment
has text: Hi @codemuch, please put the error in the text. That way your question will be useful to others even when the image is no longer there, and the error will also be searchable. Welcome to SO.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49755099

iterable-unpacking
type: Tag
tags question: http://stackoverflow.com/q/49711931
tags question: http://stackoverflow.com/q/49626782
tag name: iterable-unpacking

http://stackoverflow.com/comment/86313588
has text: You might want to try the rolling_mean (http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_mean.html) in that case. It would take the average of window consecutive points for plotting
type: QuestionComment
comment on: http://stackoverflow.com/q/49652259
score: 0
type: Comment

http://stackoverflow.com/q/49687748
has answer: http://stackoverflow.com/a/49704950
has comment: http://stackoverflow.com/comment/86386671
has comment: http://stackoverflow.com/comment/86386630
score: -5
has comment: http://stackoverflow.com/comment/86386619
has body: enter image description here between the codes there are the following codes: def regTreeEval(model, inDat): if model is not None: return float(model) def modelTreeEval(model, inDat): n = shape(inDat)[1] X = mat(ones((1, n+1))) X[:, 1: n+1] = inDat # print X, model xmodel = X*model if xmodel is not None: return float(X * model)
answer count: 1
has comment: http://stackoverflow.com/comment/86423156
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86388586
has title: float() argument must be a string or a number, not 'map'
upvote count: 0
type: UnansweredQuestion
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86422727

http://stackoverflow.com/q/49747835
tagged with: list
linked to: http://stackoverflow.com/q/4664850
has answer: http://stackoverflow.com/a/49748016
has body: Given a pattern [1,1,0,1,1], and a binary list of length 100, [0,1,1,0,0,...,0,1]. I want to count the number of occurences of this pattern in this list. Is there a simple way to do this without the need to track the each item at every index with a variable? Note something like this, [...,1, 1, 0, 1, 1, 1, 1, 0, 1, 1,...,0] can occur but this should be counted as 2 occurrences.
has comment: http://stackoverflow.com/comment/86510351
downvote count: 0
has answer: http://stackoverflow.com/a/49749907
has comment: http://stackoverflow.com/comment/86510252
linked to: http://stackoverflow.com/q/2970520
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49748138
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/49748328
has comment: http://stackoverflow.com/comment/86511106
tagged with: count
type: UnansweredQuestion
tagged with: python
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/49748180
has answer: http://stackoverflow.com/a/49749827
has title: Count the number of occurences of a pattern in a list in Python
linked to: http://stackoverflow.com/q/3873361
has answer: http://stackoverflow.com/a/49748656
has answer: http://stackoverflow.com/a/49748070
tagged with: python-2.7

http://stackoverflow.com/comment/112639659
has text: I appreciate you suggestion, will keep in mind next time. Thanks
type: Comment
comment on: http://stackoverflow.com/a/63676273
score: 0
type: AnswerComment

http://stackoverflow.com/a/49736916
has comment: http://stackoverflow.com/comment/126429095
type: Answer
has comment: http://stackoverflow.com/comment/129243592
score: 80
has comment: http://stackoverflow.com/comment/128514824
has body: Whenever I'm not 100% sure what types a function accepts, I like to consult typeshed, which is the canonical repository of type hints for Python. Mypy directly bundles and uses typeshed to help it perform its typechecking, for example. We can find the stubs for contextlib here: https://github.com/python/typeshed/blob/master/stdlib/contextlib.pyi if sys.version_info &gt;= (3, 2): class GeneratorContextManager(ContextManager[_T], Generic[_T]): def __call__(self, func: Callable[..., _T]) -&gt; Callable[..., _T]: ... def contextmanager(func: Callable[..., Iterator[_T]]) -&gt; Callable[..., GeneratorContextManager[_T]]: ... else: def contextmanager(func: Callable[..., Iterator[_T]]) -&gt; Callable[..., ContextManager[_T]]: ... It's a little overwhelming, but the line we care about is this one: def contextmanager(func: Callable[..., Iterator[_T]]) -&gt; Callable[..., ContextManager[_T]]: ... It states that the decorator takes in a Callable[..., Iterator[_T]] -- a function with arbitrary arguments returning some iterator. So in conclusion, it would be fine to do: @contextlib.contextmanager def foo() -&gt; Iterator[None]: yield So, why does using Generator[None, None, None] also work, as suggested by the comments? It's because Generator is a subtype of Iterator -- we can again check this for ourselves by consulting typeshed. So, if our function returns a generator, it's still compatible with what contextmanager expects so mypy accepts it without an issue.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49733699
downvote count: 1
has comment: http://stackoverflow.com/comment/100507691
answers question: http://stackoverflow.com/q/49733699
upvote count: 81
has comment: http://stackoverflow.com/comment/135708816
has comment: http://stackoverflow.com/comment/133862768

http://stackoverflow.com/comment/86395374
type: QuestionComment
has text: @Aran-Fey I see your point, but that won't be the right answer given the expected output.
score: 0
comment on: http://stackoverflow.com/q/49691154
type: Comment

http://stackoverflow.com/q/49656864
tagged with: attributes
type: Question
accepted answer: http://stackoverflow.com/a/49656894
has body: I am trying to write a function that takes a Pandas DataFrame (df) and a column name (col) as inputs and returns a list of all unique values in the column in sorted order. I am trying to do this without any module methods. I am using the following code: import pandas as pd def list_col(df, col): """puts unique items of given column in a list""" f = pd.df() l = [] r = f.loc[:,col] for i in r: if i not in l: l.append(i) return l.sort() However, i get the error message: AttributeError: module 'pandas' has no attribute 'df' How can I fix this? Thanks!
downvote count: 0
has comment: http://stackoverflow.com/comment/86322889
has title: Python function with pandas dataframe and column name as inputs
tagged with: python
has answer: http://stackoverflow.com/a/49656894
type: AnsweredQuestion
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
tagged with: dataframe
favorite count: 0

http://stackoverflow.com/q/49647572
has answer: http://stackoverflow.com/a/49648392
score: 0
tagged with: python
type: Question
tagged with: numpy
has title: Wanna built a new 2d array with n-numbers right and left form the maximum value x in a numpy array BUT the left site might be n<x?
has body: I have this: pI= np.array([[0,0]]) pI=np.append(pI,float(q),float(I),axis=0) and read in several .csv Eingabe_Höhe = int(input("Höhe?")) Eingabe_Breite = int(input("Breite?")) for i in range(Eingabe_Breite): for k in range(Eingabe_Höhe): phI = read_pI(arguments[k+i*Eingabe_Höhe]) print(arguments[k+i*Eingabe_Höhe], i ,k) print(phI) I_max = np.max(phI[:,1]) print(I_max) I_max_index = np.argmax(phI[:,1]) print(I_max_index) phI_max = phI[(I_max_index-50 ):(I_max_index+50)] print(phI_max) And here is my prob: phI_max = phI[(I_max_index-50 ):(I_max_index+50)] In some cases, I_max_index -50 is out of range. Only "10" e.g is possible, but I never know in advance, how much "left" i can go. How can I tell the program only to go to Index "0" and not try to go "more left"?
type: UnansweredQuestion
answer count: 1
tagged with: arrays

http://stackoverflow.com/comment/86364852
type: Comment
has text: It seems like you are missing the step that involves creating the *.rst files that contain `automodule` directives. You can do this "by hand" or use the sphinx-apidoc script.
type: QuestionComment
comment on: http://stackoverflow.com/q/49673177
score: 0

http://stackoverflow.com/comment/86309288
type: Comment
comment on: http://stackoverflow.com/a/49648845
type: AnswerComment
has text: Did you notice this in my answer: `rdd.map(lambda l: l[1])\ .reduceByKey(lambda a,b: a+b)\ .collect()`? This `rdd` is the same one created by the preceding statement. Your updated question does a `reduceByKey` done incorrectly. If you just use all the lines of code in this answer, it will give you the expected results.
score: 0

http://stackoverflow.com/comment/86453776
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49720219
has text: @njx You probably need to keep track of the hand as well, so pop() the cards into a list (`myHand`) and print that afterwards.
type: Comment

arrays
tags question: http://stackoverflow.com/q/49729075
tags question: http://stackoverflow.com/q/49673248
tag name: arrays
tags question: http://stackoverflow.com/q/49618983
tags question: http://stackoverflow.com/q/49647182
tags question: http://stackoverflow.com/q/49695402
tags question: http://stackoverflow.com/q/49644385
tags question: http://stackoverflow.com/q/49632200
tags question: http://stackoverflow.com/q/49720118
tags question: http://stackoverflow.com/q/49749709
tags question: http://stackoverflow.com/q/49643676
tags question: http://stackoverflow.com/q/49617180
tags question: http://stackoverflow.com/q/49735187
tags question: http://stackoverflow.com/q/49722389
tags question: http://stackoverflow.com/q/49709801
type: Tag
tags question: http://stackoverflow.com/q/49722046
tags question: http://stackoverflow.com/q/49687823
tags question: http://stackoverflow.com/q/49626515
tags question: http://stackoverflow.com/q/49697577
tags question: http://stackoverflow.com/q/49737345
tags question: http://stackoverflow.com/q/49740518
tags question: http://stackoverflow.com/q/49734441
tags question: http://stackoverflow.com/q/49626724
tags question: http://stackoverflow.com/q/49706228
tags question: http://stackoverflow.com/q/49614946
tags question: http://stackoverflow.com/q/49631660
tags question: http://stackoverflow.com/q/49729810
tags question: http://stackoverflow.com/q/49661587
tags question: http://stackoverflow.com/q/49734603
tags question: http://stackoverflow.com/q/49706760
tags question: http://stackoverflow.com/q/49725025
tags question: http://stackoverflow.com/q/49704522
tags question: http://stackoverflow.com/q/49607273
tags question: http://stackoverflow.com/q/49737734
tags question: http://stackoverflow.com/q/49718603
tags question: http://stackoverflow.com/q/49613477
tags question: http://stackoverflow.com/q/49751455
tags question: http://stackoverflow.com/q/49620677
tags question: http://stackoverflow.com/q/49683357
tags question: http://stackoverflow.com/q/49727037
tags question: http://stackoverflow.com/q/49635509
tags question: http://stackoverflow.com/q/49698020
tags question: http://stackoverflow.com/q/49640234
tags question: http://stackoverflow.com/q/49711922
tags question: http://stackoverflow.com/q/49709892
tags question: http://stackoverflow.com/q/49656317
tags question: http://stackoverflow.com/q/49644482
tags question: http://stackoverflow.com/q/49611116
tags question: http://stackoverflow.com/q/49603221
tags question: http://stackoverflow.com/q/49753980
tags question: http://stackoverflow.com/q/49684213
tags question: http://stackoverflow.com/q/49666036
tags question: http://stackoverflow.com/q/49722955
tags question: http://stackoverflow.com/q/49702766
tags question: http://stackoverflow.com/q/49675737
tags question: http://stackoverflow.com/q/49716552
tags question: http://stackoverflow.com/q/49651046
tags question: http://stackoverflow.com/q/49719504
tags question: http://stackoverflow.com/q/49734812
tags question: http://stackoverflow.com/q/49755715
tags question: http://stackoverflow.com/q/49729127
tags question: http://stackoverflow.com/q/49733841
tags question: http://stackoverflow.com/q/49698418
tags question: http://stackoverflow.com/q/49628329
tags question: http://stackoverflow.com/q/49702861
tags question: http://stackoverflow.com/q/49681524
tags question: http://stackoverflow.com/q/49716504
tags question: http://stackoverflow.com/q/49697876
tags question: http://stackoverflow.com/q/49691845
tags question: http://stackoverflow.com/q/49647572
tags question: http://stackoverflow.com/q/49737192
tags question: http://stackoverflow.com/q/49624029
tags question: http://stackoverflow.com/q/49731425
tags question: http://stackoverflow.com/q/49635573
tags question: http://stackoverflow.com/q/49757871
tags question: http://stackoverflow.com/q/49717999
tags question: http://stackoverflow.com/q/49603215
tags question: http://stackoverflow.com/q/49657317
tags question: http://stackoverflow.com/q/49717224

http://stackoverflow.com/a/49690913
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49690720
answers question: http://stackoverflow.com/q/49690720
has body: Putting aside the fact that these are not constants, you are probably changing the wrong thing when you're trying to change the values accross files. Use import constants and always refer to constants.A and changes to constants.A will be reflected everywhere. Do not do from constants import A and do not do A = constants.A; A = 10 and expect that to change A to 10 everywhere. Rather do constants.A = 10.
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86393546
type: AcceptedAnswer

http://stackoverflow.com/comment/86333328
comment on: http://stackoverflow.com/a/49661411
score: 0
type: AnswerComment
has text: @Sushant Use `[a-z\d]` to match lowercase letters and digits. Does that help?
type: Comment

http://stackoverflow.com/comment/100133953
type: AnswerComment
comment on: http://stackoverflow.com/a/49639741
type: Comment
score: 0
has text: How do I do this if I'm using a dask distributed client?

http://stackoverflow.com/comment/86328061
comment on: http://stackoverflow.com/a/49658864
score: 0
has text: `str.replace` is still hot :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86395863
comment on: http://stackoverflow.com/q/49691897
type: Comment
type: QuestionComment
score: 0
has text: using the docs linked above you can look at making the `init()`, `add()` and `commit()` as subparsers that way you can have certain flags for each function.

http://stackoverflow.com/comment/86423872
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49705263
score: 0
has text: Should I define X before defining this fuction?

http://stackoverflow.com/comment/86493931
has text: What do you mean 'score of word in a document'?
type: Comment
comment on: http://stackoverflow.com/a/49725388
score: 0
type: AnswerComment

http://stackoverflow.com/q/49736782
tagged with: tkinter
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86488335
has comment: http://stackoverflow.com/comment/86487898
has comment: http://stackoverflow.com/comment/86488264
has title: read widget values in python Tkinter
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
has body: i want to recover the real value entered by users to a variable using Tkinter. Here is my code from Tkinter import * master = Tk() Label(master, text="real value 1").grid(row=0) Label(master, text="real value 2").grid(row=1) e1 = Entry(master) e2 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) print e1.get() x=e1.get() mainloop( ) However my code can neither print the real value i have entred in the table nor assign this number to my variable x (a variable i would like to use outside tkinter). How can i get the value e1, e2 entered by users?
tagged with: python
has comment: http://stackoverflow.com/comment/86559161
has answer: http://stackoverflow.com/a/49737007
has comment: http://stackoverflow.com/comment/86487923
linked to: http://stackoverflow.com/q/9815063
upvote count: 0

http://stackoverflow.com/comment/86423461
comment on: http://stackoverflow.com/q/49704687
has text: Or more specific `C = C if isinstance(C, pd.Series) else pd.Series([C])`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86460123
score: 0
comment on: http://stackoverflow.com/q/49722187
type: QuestionComment
has text: Like a start and stop bit?
type: Comment

http://stackoverflow.com/a/55016424
answers question: http://stackoverflow.com/q/49616399
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: Even i faced the same problem because of python path was not added in environment variable ,follow below steps : Go to Anaconda prompt type : where python say it is C:\ProgramFiles\Anaconda3\python.exe Open "Advanced system setting" from main menu. In environment variable,edit path and add path : C:\ProgramFiles\Anaconda3 Now in command prompt you see by typing : python --version &amp; the error "python' is not recognized as an internal or external command on CMD" will also go off.

http://stackoverflow.com/comment/86371086
type: AnswerComment
comment on: http://stackoverflow.com/a/49679585
score: 1
type: Comment
has text: @Azsgy actually, the upvote was cancelled. Noone is currently downvoting your answer. And this "why (not) the downvote ?" running gag is fun.

http://stackoverflow.com/q/49727152
has comment: http://stackoverflow.com/comment/86468376
has comment: http://stackoverflow.com/comment/86473612
linked to: http://stackoverflow.com/q/42234039
has comment: http://stackoverflow.com/comment/86468320
has comment: http://stackoverflow.com/comment/86468554
has comment: http://stackoverflow.com/comment/86468828
has comment: http://stackoverflow.com/comment/86468542
answer count: 0
has comment: http://stackoverflow.com/comment/86468042
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/86468791
has comment: http://stackoverflow.com/comment/86468673
duplicate of: http://stackoverflow.com/q/42234039
downvote count: 0
upvote count: 1
has title: Return only rows with latest date from a pandas dataframe
favorite count: 0
duplicate of: http://stackoverflow.com/q/9850954
type: Question
has comment: http://stackoverflow.com/comment/86468059
has comment: http://stackoverflow.com/comment/86468114
has comment: http://stackoverflow.com/comment/86468086
linked to: http://stackoverflow.com/q/9850954
tagged with: pandas
has body: I have a large dataframe (100 dates for 943 stocks) with date as index. My aim is to create a smaller dataframe with each stock on the latest date adj_close ticker short_name date 2018-04-06 0.290 0001 SCOMNET 2018-04-05 0.300 0001 SCOMNET 2018-04-04 0.305 0001 SCOMNET 2018-04-03 0.340 0001 SCOMNET 2018-04-02 0.345 0001 SCOMNET I tried filtering by using the max date but it only gave me the date and not the other columns... klse_df'adj_close','ticker','short_name'.index.max() Timestamp('2018-04-06 00:00:00')
has comment: http://stackoverflow.com/comment/86468087
has comment: http://stackoverflow.com/comment/86468049
has comment: http://stackoverflow.com/comment/86468362
has comment: http://stackoverflow.com/comment/86468985
has comment: http://stackoverflow.com/comment/86468120
has comment: http://stackoverflow.com/comment/86468489
tagged with: python
has comment: http://stackoverflow.com/comment/86468624

http://stackoverflow.com/q/49751339
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/86518238
accepted answer: http://stackoverflow.com/a/49752155
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49752155
has body: I'm trying to search in a webpage the "spanish" content but can't get it at all. This is the code I have so far: from bs4 import BeautifulSoup import requests import re url = 'http://www.autotaskstatus.net/' r = requests.get(url) estado = r.status_code r = r.content soup = BeautifulSoup(r, "html.parser") data = soup.find_all('span', attrs={'class':'name'})[1] pais = 'Spanish' data.get_text() print(data.text) I have there the "pais" var so it will be replaced by an input so the user can search the country they want. The only data I get with a 1 there is "Limited Release" but if I go with a 0 I can't filter the results at all I have been searching all over Internet and couldn't find anyone with this same problem so I can't find a solution. I am using Python 3.6 Edit: since people seemed to find this unclear I'll explain it now What I have on the page is: - just a part &lt;div data-component-id="fp5s6cp13l47" class="component-inner-container status-green " data-component-status="operational" data-js-hook=""&gt; &lt;span class="name"&gt; Concord &amp;nbsp; &lt;/span&gt; &lt;span class="tooltip-base tool" title="https://concord.centrastage.net"&gt;?&lt;/span&gt; &lt;span class="component-status"&gt; Operational &lt;/span&gt; So spanish is like "Concord" and what I want to take out is the "Spanish" (and later on the "operational") which will be in a var so it can later be changed for any country there
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Can't find and process text taken out of an HTML
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86517608
score: 1

http://stackoverflow.com/q/49618066
linked to: http://stackoverflow.com/q/3730019
has body: I am trying to make a program related to money and the user needs to input a decimal. But it always gives me an error. Here is the code: price = input("What is the price of your vegetable?") pounds = input("How many pounds did you buy?") price = int(price) pounds = int(pounds) if pounds < 5: price = price * 1 print("Your price is " + str(price)) elif pounds < 10: price = price * 0.90 print("Your price is " + str(price)) elif pounds < 20: price = price * 0.80 print("Your price is " + str(price)) elif pounds > 30: price = price * 0.75 print("Your price is " + str(price)) And here is the error: What is the price of your vegetable?6.72 How many pounds did you buy?4 Traceback (most recent call last): File "C:/Users/Jerry Cui/Documents/pricediscount.py", line 4, in <module> price = int(price) ValueError: invalid literal for int() with base 10: '6.72' Where is the problem?
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68257124
tagged with: python
has answer: http://stackoverflow.com/a/49618086
has title: How do you let a user input a decimal number?
has answer: http://stackoverflow.com/a/49618077
tagged with: decimal
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86243099
upvote count: 1

http://stackoverflow.com/q/49737588
has comment: http://stackoverflow.com/comment/86489905
tagged with: pandas
upvote count: 5
accepted answer: http://stackoverflow.com/a/49737737
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49737737
has title: Python Pandas - Add values from one dataframe to another by matching labels to columns
has comment: http://stackoverflow.com/comment/86489534
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86489806
has answer: http://stackoverflow.com/a/49737814
has comment: http://stackoverflow.com/comment/86497282
has answer: http://stackoverflow.com/a/49738095
score: 5
has body: I know there is an easy, elegant solution to this problem but I am struggling to find it. All I'm trying to do is add a third column to df2 with the corresponding values from df2, based on Date and PN. There may be values in df2 that don't match to df1, and vice versa (fill NaN where there is no match). df1: 2017-11-01 2017-11-02 2017-11-03 PN 90020 105.0 105.0 105.0 90022 100.0 100.0 100.0 90061 -3.0 -3.0 -3.0 90065 30.0 30.0 30.0 90099 2.0 2.0 2.0 df2: PN Date 4 90020 2017-11-01 9 90020 2017-11-02 12 90061 2017-11-01 13 90065 2017-11-02 17 94008 2017-11-03 Desired result: PN Date Value 4 90020 2017-11-01 105.0 9 90020 2017-11-02 105.0 12 90061 2017-11-01 -3.0 13 90065 2017-11-02 30.0 17 94008 2017-11-03 NaN
has answer: http://stackoverflow.com/a/49738560
has comment: http://stackoverflow.com/comment/86489644
answer count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/49738646
possible better answer: http://stackoverflow.com/a/49737814
type: AnsweredQuestion

http://stackoverflow.com/comment/86382352
type: Comment
type: QuestionComment
has text: Looks like some objects in the column are lists.
comment on: http://stackoverflow.com/q/49685419
score: 0

http://stackoverflow.com/a/49661010
upvote count: 2
has comment: http://stackoverflow.com/comment/86331939
downvote count: 0
has comment: http://stackoverflow.com/comment/86331858
has comment: http://stackoverflow.com/comment/86331896
has body: Your x value does not contain a list of tuples, but a list of lists. If it did contain a list of tuples: x = [('aaron','jeng'),('sdf','wqd'),('aaron','jeng')] out = set([i for i in x]) print(list(out)) [('aaron', 'jeng'), ('sdf', 'wqd')]
answers question: http://stackoverflow.com/q/49660966
has comment: http://stackoverflow.com/comment/86331960
has comment: http://stackoverflow.com/comment/86331842
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86331881

http://stackoverflow.com/q/49702372
type: Question
has body: I'm using spacy to recognize street addresses on web pages. My model is initialized basically using spacy's new entity type sample code found here: https://github.com/explosion/spaCy/blob/master/examples/training/train_new_entity_type.py My training data consists of plain text webpages with their corresponding Street Address entities and character positions. I was able to quickly build a model in spacy to start making predictions, but I found its prediction speed to be very slow. My code works by iterating through serveral raw HTML pages and then feeding each page's plain text version into spacy as it's iterating. For reasons I can't get into, I need to make predictions with Spacy page by page, inside of the iteration loop. After the model is loaded, I'm using the standard way of making predictions, which I'm referring to as the prediction/evaluation phase: doc = nlp(plain_text_webpage) if len(doc.ents) &gt; 0: print ("found entity") Questions: How can I speed up the entity prediction / recognition phase? I'm using a c4.8xlarge instance on AWS and all 36 cores are constantly maxed out when spacy is evaluating the data. Spacy is turning processing a few million webpages from a 1 minute job to a 1 hour+ job. Will the speed of entity recognition improve as my model becomes more accurate? Is there a way to remove pipelines like tagger during this phase, can ER be decoupled like that and still be accurate? Will removing other pipelines affect the model itself or is it just a temporary thing? I saw that you can use GPU during the ER training phase, can it also be used in this evaluating phase in my code for faster predictions? Update: I managed to significantly cut down the processing time by: Using a custom tokenizer (used the one in the docs) Disabling other pipelines that aren't for Named Entity Recognition Instead of feeding the whole body of text from each webpage into spacy, I'm only sending over a maximum of 5,000 characters My updated code to load the model: nlp =…
has title: Speed up Spacy Named Entity Recognition
type: UnansweredQuestion
score: 18
upvote count: 18
tagged with: python
tagged with: nlp
tagged with: spacy
has answer: http://stackoverflow.com/a/49711536
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49714258
has answer: http://stackoverflow.com/a/49848740
has comment: http://stackoverflow.com/comment/86443534
has body: I am trying to determine if there are pills in different cells of a pillbox. I have a raspberry pi camera that takes pictures of a pillbox at regular intervals. I would like to use computer vision using opencv and python to determine which of the 14 cells have pills in them. I have gotten as far as isolating the borders of the cells. How do I create opencv masks for the interiors of the cells? I tried running hough transform on the processed image, but it does not accurately find lines corresponding to each wall Original image: After Processing with cell walls isolated:
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49711650
has title: Given a image of white lines forming a grid, how to get masks of the interior shapes using opencv?
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/86445364
has comment: http://stackoverflow.com/comment/86443429
tagged with: opencv
downvote count: 0
score: 1
upvote count: 1
tagged with: hough-transform
has comment: http://stackoverflow.com/comment/86456706

http://stackoverflow.com/comment/86266288
comment on: http://stackoverflow.com/q/49629508
score: 0
has text: @chris85 yes this is mysql problem i think .. there is a reason why < 3 character is slow because i used full text with match against and its only support >3 character <3 character will be used as default %like% statement. but i mentioned as parent language so that i can found any alternative like machine learning etc which help me to build fastest way for search
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86496760
comment on: http://stackoverflow.com/q/49740628
type: QuestionComment
type: Comment
score: 0
has text: still getting the same error

http://stackoverflow.com/comment/86247736
score: 1
has text: Yuki.kuroshita, thinking about it I think there may be a way, I'll try and make an answer. Btw. I think @Blckknght has a point: `-1 0 2` doesn't seem to be a valid representation, since by the position equals child id convention it would have to be read as 0: no parent, 1: parent is 0, 2: parent is 2.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49618983

http://stackoverflow.com/comment/86290304
comment on: http://stackoverflow.com/q/49641241
score: 0
type: Comment
type: QuestionComment
has text: This problem is more than just the usual "floats aren't exact" problem, because the OP is writing `__hash__` methods, which means that he can't just use `isclose` or an equivalent.

http://stackoverflow.com/q/49714768
tagged with: flask
has body: I am very new to Python flask and webserver concept in general but have managed to create a simple webapp. It basically consists of a home page with a form to fill in and a submit button which returns a flashed messages when : 1) all fields are filled correctly and 2) not all fields are filled. My code looks like this: @app.route('/', methods = ['GET', 'POST']) def home(): form = preference_form(request.form) print(form.errors) if request.method == 'POST': name = request.form['name'] age = request.form['age'] address = request.form['distance'] date = request.form['date'] if form.validate(): flash('All good!') else: flash('Oops! All details are required to provide accurate results!') return render_template('home.html', form = form) @app.route('/results', methods = ['POST']) def return_results(): name = request.form.get('name') age = request.form.get('age') address = request.form.get('address') result = function_a(name=name, age=age, address=address) return result The flash messages worked as desired but after I added the return_results() route, after the form is filled (whether complete or incomplete) it brings me straight to /results. Could you please tell me what am I missing here? Thank you!
downvote count: 1
accepted answer: http://stackoverflow.com/a/49714902
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49714902
has title: Python - flask - flashed messages are skipped (not appearing) and webserver returns responses straight away
tagged with: python
score: -1
upvote count: 0
answer count: 1

http://stackoverflow.com/q/49710259
has body: When I run my code, it prints out the values I tell it to but it does it rarely. and majority of the time it restarts the shell after a few seconds. it just says: ============= RESTART: Shell ============= I try to run the code a few time but it rarely executes it fully.
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86434119
upvote count: 1
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/86434147
has title: Python IDLE shell restarting
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86434025
answer count: 1
has answer: http://stackoverflow.com/a/49710747
accepted answer: http://stackoverflow.com/a/49710747

http://stackoverflow.com/comment/86490490
score: 0
has text: @BlackVegetable Why not? What's wrong with the dupe?
type: QuestionComment
comment on: http://stackoverflow.com/q/49738007
type: Comment

matlab
tags question: http://stackoverflow.com/q/49742625
tags question: http://stackoverflow.com/q/49600169
tags question: http://stackoverflow.com/q/49657956
type: Tag
tags question: http://stackoverflow.com/q/49713637
tag name: matlab
tags question: http://stackoverflow.com/q/49623766
tags question: http://stackoverflow.com/q/49714309
tags question: http://stackoverflow.com/q/49630115
tags question: http://stackoverflow.com/q/49728878
tags question: http://stackoverflow.com/q/49656244
tags question: http://stackoverflow.com/q/49663401
tags question: http://stackoverflow.com/q/49725744
tags question: http://stackoverflow.com/q/49604385
tags question: http://stackoverflow.com/q/49752134

http://stackoverflow.com/comment/86329939
type: Comment
has text: `for child in stat.children: handle your usecase here ` That means that you are able to get the stat object. i would inspect the object for its child objects and work from there. If my answer helped you solve your problem please mark it as the answer for me.
type: AnswerComment
comment on: http://stackoverflow.com/a/49659999
score: 0

http://stackoverflow.com/a/49687836
score: 1
answers question: http://stackoverflow.com/q/49687078
type: Answer
has body: By default, the index is unnamed in a DataFrame. When you export it to Excel, it stores it in a separate column, but since the index does not have a name, the column is untitled. My solution would be to reset the index to its own column, and then to export it to Excel: ab = pd.DataFrame(dicti) writer = pd.ExcelWriter("ExcelFile.xlsx", engine='xlsxwriter') ab.reset_index(drop=False, inplace=True) #Store the index in a column named "Index" ab.to_excel(writer, sheet_name='Sheet1', index=False) #Omit the now-irrelevant index.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86256820
comment on: http://stackoverflow.com/q/49622575
type: QuestionComment
type: Comment
has text: You say "I cannot run this script directly as a Lambda function because the script does some parallel processing which requires more RAM", but Lambda functions can be allocated a lot of RAM (which also increases the assigned Compute resources).
score: 0

http://stackoverflow.com/q/49678649
tagged with: interactive
has answer: http://stackoverflow.com/a/49696586
type: Question
tagged with: graph
has body: I'm trying to get my HoverTool to show the values for bars on the y-axis. It is showing ??? instead which is weird. Further, if anyone knows how, is there a way to have the y-axis not be in scientific notation with the e? This is the code: #RQ Do people who are scared about a loss of privacy own less devices than those who are not? output_notebook() categories = ['The Loss of Privacy', "We'll all lose touch with one another", "We'll all be less safe", "I have no fears about a more connected future", "Other"] #Interactivity hover = HoverTool(tooltips=[ ("Biggest Fear", "@x"), ("Number of Devices Owned", "@y"), ]) p = figure(x_range = categories, plot_height = 250, plot_width = 1000, title = "Total Devices Owned", tools = [hover]) p.vbar(x = categories, top = [268252,133344,86014,44688,47270], width = 0.5) p.xgrid.grid_line_color = None p.y_range.start = 0 p.y_range.end = 300000 p.xaxis.axis_label = "What is your biggest fear as we move towards a more connected future?" p.yaxis.axis_label = "Amount of Devices Owned" show(p) And the Graph:
tagged with: python
tagged with: bokeh
has title: How to get y-axis to interact with Bokeh and Hovertool?
score: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/86324133
has text: But from my point of view it's not the question of python as language - it's concerning only numpy, isn't it?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49657195

http://stackoverflow.com/a/49745085
answers question: http://stackoverflow.com/q/49744989
accepted answer of: http://stackoverflow.com/q/49744989
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Just do total = total + i and check the indentation in the line num = input('Enter an integer: ') it should be one level indside
has comment: http://stackoverflow.com/comment/86504711

http://stackoverflow.com/a/65799952
upvote count: 1
answers question: http://stackoverflow.com/q/49691410
score: 1
type: Answer
downvote count: 0
has body: I guess you are looking to print only two. So you need to check if the next value is also not one. my_list=['one', 'two', 'one', 'one', 'two'] for i, ml in enumerate(my_list): if ml =='one' and my_list[i+1] != 'one': print (my_list[i+1]) The output of this will be: two two

http://stackoverflow.com/comment/86369727
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49677935
has text: (I forgot to keep `bytes` and `str` objects distinct, and `bytes.format` isn't defined in Python 3.)
score: 0

http://stackoverflow.com/a/49706271
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49706231
type: Answer
has body: list1 = ['john','amal','joel','george'] list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']] res = [] for i, m in enumerate(list2): #Iterate list2 for j, n in enumerate(m): #Iterate nested list if n in list1: #Check if element in list1 res.append((i, j)) #Append index. print res Output: [(0, 0), (1, 1), (2, 1)]

http://stackoverflow.com/a/49616396
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49613600
score: 3
answers question: http://stackoverflow.com/q/49613600
has comment: http://stackoverflow.com/comment/86239879
type: Answer
has body: Maybe try using rstrip() to trip any trailing whitespace/newlines and json.dumps() so the data isn't passed as form-encoded... import requests import json with open("output.txt", "rb") as infile: for line in infile: headers = {"Content-Type": "application/json"} data = {"fields": { "project": {"key": "TECH"}, "parent": {"key": line.rstrip()}, "summary": "Create AD List ", "description": "", "issuetype": {"name": "Sub-task"}, "customfield_10107": {"id": "10400"} }} response = requests.post("https://jira.company.com/rest/api/latest/issue/", headers=headers, data=json.dumps(data), auth=("user", "pass")) Like another answer said, if you use json param instead of the data param, the dict will automatically be encoded for you and the Content-Type set to application/json. See here for more information.

http://stackoverflow.com/comment/86502408
score: 0
has text: I'm sorry I'm not trying to be rude but the working code is right there. You just have to copy and paste it.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49724759

http://stackoverflow.com/comment/86259384
type: QuestionComment
comment on: http://stackoverflow.com/q/49625415
has text: So I have to perform SELECT for IDs and update my dictionary to have hash_val, hash_plain and id from Hashes table first?
score: 0
type: Comment

http://stackoverflow.com/a/49744655
has comment: http://stackoverflow.com/comment/86542239
has comment: http://stackoverflow.com/comment/86542514
has comment: http://stackoverflow.com/comment/86579409
has comment: http://stackoverflow.com/comment/86547818
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86547457
downvote count: 0
answers question: http://stackoverflow.com/q/49723946
has body: Looks like a bit of source-diving is needed; fortunately, it does not require copying a lot of source code. This is how basic fit works: from scipy.stats import cauchy data = [0, 3, 4, 4, 5, 9] res = cauchy.fit(data) # (3.9798237305661255, 0.9205374643383732) and this is how it is modified to return OptimizeResult: from scipy.optimize import minimize args = cauchy._fitstart(data) x0, func, restore, args = cauchy._reduce_func(args, {}) res = minimize(func, x0, args=(data,), method='BFGS') Now res is fun: 14.337039523098689 hess_inv: array([[ 0.23321703, -0.0117229 ], [-0.0117229 , 0.36807373]]) jac: array([ 0.0000000e+00, -1.1920929e-07]) message: 'Optimization terminated successfully.' nfev: 32 nit: 5 njev: 8 status: 0 success: True x: array([3.9798262 , 0.92055376]) where you may recognize the parameters as being res.x. The function being minimized is "penalized NNLF" (nonnegative likelihood function). By the way, For all its optimizations, SciPy returns an object called OptimizeResult is an over-generalization. This is true for minimize method. The scipy.stats.fit uses fmin by default, which returns no such thing. So, if want identical output to fmin, that can be arranged, but there'll be no extra information there. from scipy.optimize import fmin args = cauchy._fitstart(data) x0, func, restore, args = cauchy._reduce_func(args, {}) res = fmin(func, x0, args=(data,)) print(tuple(res)) #(3.9798237305661255, 0.9205374643383732) Using minimize with method='Nelder-Mead' has essentially the same effect. You do get a bit of extra information, but given that the method is simplex-based (no derivatives being computed), this information is of limited use. res = minimize(func, x0, args=(data,), method='Nelder-Mead') print(res) print(tuple(res.x)) prints final_simplex: (array([[3.97982373, 0.92053746], [3.97983057, 0.92060317], [3.97977536, 0.92059568]]), array([14.33703952, 14.33703953, 14.33703953])) fun: 14.337039523477827 message: 'Optimization terminated successfully.' n…
score: 3
has comment: http://stackoverflow.com/comment/86577667
has comment: http://stackoverflow.com/comment/86537096
has comment: http://stackoverflow.com/comment/86535207
type: Answer
accepted answer of: http://stackoverflow.com/q/49723946

http://stackoverflow.com/a/49679415
type: Answer
answers question: http://stackoverflow.com/q/49679380
has body: Split the string by comma and then use you can use in to check if string is list. Ex: payments = 'cash:no,square_cash:yes,venmo:no'.split(",") if "cash:yes" in payments: print('Cash') elif "square_cash:yes" in payments: print("square_cash") elif "venmo:yes" in payments: print("Venmo") else: print("not found")
score: 0
has comment: http://stackoverflow.com/comment/86370867
upvote count: 1
has comment: http://stackoverflow.com/comment/86370845
has comment: http://stackoverflow.com/comment/86371104
has comment: http://stackoverflow.com/comment/86371433
downvote count: 1
has comment: http://stackoverflow.com/comment/86371322
has comment: http://stackoverflow.com/comment/86370600
has comment: http://stackoverflow.com/comment/86370625

http://stackoverflow.com/q/49676246
has answer: http://stackoverflow.com/a/49676843
has body: I have gone through all similar questions on stackoverflow, but the solutions still don't work for me. I have two dfs: df1: User_ID | Code_1 123 htrh 345 NaN 567 cewr ... df2: User_ID | Code_2 123 ert 345 nad I want to replace df1.Code_1 with df2.Code_2 based on User_ID. Please note that df2 is a subset of df1's user_ids. I tried this df1['Code_1'] = df1['User_ID'].replace(df2.set_index('User_ID')['Code_2']) and I tried this df1.loc[df1.User_ID.isin(df2.User_ID), ['Code_1']] = df2'Code_2' and both didn't work.Nothing changed. Expected Output: df1: User_ID | Code_1 123 ert 345 nad 567 cewr ... Thank You
tagged with: python
possible better answer: http://stackoverflow.com/a/49676349
accepted answer: http://stackoverflow.com/a/49676944
tagged with: replace
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49676349
has comment: http://stackoverflow.com/comment/86363888
answer count: 3
tagged with: syntax
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: Replace values in python pandas column based on second df
has answer: http://stackoverflow.com/a/49676944

memory
tags question: http://stackoverflow.com/q/49682701
tags question: http://stackoverflow.com/q/49681084
tag name: memory
tags question: http://stackoverflow.com/q/49671985
tags question: http://stackoverflow.com/q/49661377
type: Tag
tags question: http://stackoverflow.com/q/49721621

http://stackoverflow.com/comment/86467215
comment on: http://stackoverflow.com/q/49719265
type: Comment
has text: It doesn't really matter in this case, I'm not that interested in writing to the file as I am with getting the file in tact.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86473352
type: AnswerComment
has text: But I don't see the name `AxesSubplot` anywhere inside the `_subplots.py` file
type: Comment
comment on: http://stackoverflow.com/a/49729756
score: 0

http://stackoverflow.com/q/49708337
has body: Create a simple python program(factorial), then load/add it in git-hub, then i need to run it through Jenkins when I make change in that python program and add it again in git-hub.Then send the reports to mail. I.I am new to git hub and Jenkins. Please help me out.
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to effectively use jenkins, github and send jenkins report to email?
tagged with: python
score: 2
upvote count: 2
downvote count: 0
tagged with: jenkins
answer count: 1
has answer: http://stackoverflow.com/a/49709947
tagged with: github

http://stackoverflow.com/a/49688938
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/86400113
accepted answer of: http://stackoverflow.com/q/49684766
type: Answer
has comment: http://stackoverflow.com/comment/86400537
score: -1
answers question: http://stackoverflow.com/q/49684766
has body: To make each day a button, you're going to want to stop using a Text widget. The calendar module has a useful function called calendar.monthcalendar, which returns a calendar of a specific month in a matrix (nested lists). If you generate a matrix of buttons, you can then use the output of monthcalendar to fill the numbers in the right locations: from tkinter import * from tkinter import ttk import calendar class main: def __init__(self, master): self.master = master self.month = IntVar() self.year = IntVar() self.months = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) self.widgets() def getcal(self): # Day/Month/Year Computations m = self.month.get() y = self.year.get() # Fill current month label self.current['text'] = calendar.month_name[m] + ' ' + str(y) # Remove text from all buttons for ii in range(6): for jj in range(7): self.area[ii][jj]['text'] = '' # Loop over monthcalendar matrix and fill button text for ii, week in enumerate(calendar.monthcalendar(y, m)): for jj, day in enumerate(week): if day != 0: self.area[ii][jj]['text'] = day def click(self, event): print(event.widget.cget('text')) def widgets(self): # Main Heading Label(self.master, text='Calendar', font=('freesansbold', 30), bd=10).pack() f = Frame(self.master, pady = 10, padx=10) # Month Label: Label(f, text='Month: ', font=('freesansbold', 13)).grid() # Month Dropdown Selector mon = ttk.Combobox(f, width=7, font=('freesansbold', 15), values=self.months, textvariable = self.month) mon.grid(row=0, column=1) mon.current(0) # Year Label: Label(f, text='Year: ', font=('freesansbold', 13)).grid(row=0, column=2) # Year Entry Box: ttk.Entry(f, width=7, font = ('freesansbold', 13), textvariable=self.year).grid(row=0, column=3) self.year.set(2010) f.pack() # Label for currently displayed month self.current = Label(self.master, text='', font=('freesansbold', 13)) self.current.pack() # Calendar Display area: f2 = Frame(self.master, pady = 10, padx=10) # Add day indicators for i, day in enumerate(calendar.day_abbr):…
upvote count: 0

http://stackoverflow.com/a/49744106
upvote count: 1
answers question: http://stackoverflow.com/q/49743301
type: Answer
has body: If for some reason you do have a column of mixed dtypes, you could apply the build int type() function to the column and then use value_counts() df = pd.DataFrame([[1,2,3],[1.1,2.2,3.3],['foo','man','chu']],columns=['one','two','three'],dtype='object') one two three 0 1 2 3 1 1.1 2.2 3.3 2 foo man chu df.one.apply(type).value_counts() &lt;type 'str'&gt; 1 &lt;type 'float'&gt; 1 &lt;type 'int'&gt; 1
score: 1
has comment: http://stackoverflow.com/comment/86529231
downvote count: 0

http://stackoverflow.com/a/58138369
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49695990
score: 3
has body: I was trying to do the same thing and after reading the OPs answer I tested out pymssql and noticed that it worked with just the below: pymssql.connect(server='myserver', user='domain\username', password='password', database='mydb') After realizing that that was all pymssql needed I went back to pyodbc and was able to get it working with: pyodbc.connect("DRIVER={FreeTDS};SERVER=myserver;PORT=1433;DATABASE=mydb;UID=domain\username;PWD=password;TDS_Version=8.0") I just wanted to thank you for posting this as it helped me so greatly!!!! :)
upvote count: 3

http://stackoverflow.com/comment/86329929
type: QuestionComment
comment on: http://stackoverflow.com/q/49659649
has text: Okay but the output for head(10) looks like this: color director_name num_critic_for_reviews duration director_facebook_likes actor_3_facebook_likes actor_2_name actor_1_facebook_likes gross genres ... num_user_for_reviews language country content_rating budget title_year actor_2_facebook_likes imdb_score aspect_ratio movie_facebook_likes 0 Color James Cameron 723.0 178.0 0.0 855.0 Joel David Moore 1000.0 760505847.0 Action|Adventure|Fantasy|Sci-Fi ... 3054.0 English USA PG-13 237000000.0 2009.0 936.0 7.9 1.78 33000 1 Color Gore Verbinski 302.0 169.0 563.0 1000.0 Orlando Bloom 40000.0 3090
score: 0
type: Comment

http://stackoverflow.com/q/49683018
tagged with: django-templates
answer count: 2
accepted answer: http://stackoverflow.com/a/49690548
downvote count: 0
tagged with: authentication
has answer: http://stackoverflow.com/a/49690548
tagged with: django
has comment: http://stackoverflow.com/comment/86384209
score: 4
has body: I'm having this error message after trying to change my app's password. Do you have any idea of what's causing this route to fail? Actually, it is changing the password but it isn't rendering the success template "password_change_done.html". Thanks! app/urls.py from django.contrib.auth import views as auth_views from django.urls import path ​ from . import views ​ app_name = 'account' ​ urlpatterns = [ # path('login/', views.user_login, name='login'), path('', views.dashboard, name='dashboard'), ​ # login / logout urls path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), ​ # change password urls path('password-change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] ​ ​ ERROR MESSAGE # NoReverseMatch at /account/password-change/ # Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. # Request Method: POST # Request URL: http://localhost:8000/account/password-change/ # Django Version: 2.0.4 # Exception Type: NoReverseMatch # Exception Value: # Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. # Exception Location: C:\env\django_social_website\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 # Python Executable: C:\env\django_social_website\Scripts\python.exe # Python Version: 3.6.3 # Python Path: # ['C:\\Projects\\django_social_website', # 'C:\\env\\django_social_website\\Scripts\\python36.zip', # 'C:\\ProgramData\\Anaconda3\\DLLs', # 'C:\\ProgramData\\Anaconda3\\lib', # 'C:\\ProgramData\\Anaconda3', # 'C:\\env\\django_social_website', # 'C:\\env\\django_social_website\\lib\\site-packages', # 'C:\\…
has comment: http://stackoverflow.com/comment/86393736
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/74426542
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74426542
tagged with: python
has title: Django 2.0 - Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name
upvote count: 4

http://stackoverflow.com/comment/86525110
type: QuestionComment
comment on: http://stackoverflow.com/q/49754476
has text: @user9613318 I hoped for some way of paralleling the for loop, but couldn't find anything relevant. thanks for the ideas.
score: 0
type: Comment

http://stackoverflow.com/q/49691932
tagged with: tensorflow
type: Question
tagged with: reinforcement-learning
accepted answer: http://stackoverflow.com/a/49692864
tagged with: python
type: AnsweredQuestion
has title: Incompatible shapes when output * actions_one_hot
score: 0
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49692864
has body: I'm trying to implement a Deep Q Network that plays Doom (vizdoom) However I'm stuck (since yesterday) with the problem of one hot encoding and its consequences: in fact, I have 3 possible actions that are encoded like that [[True, False, False], [False, True, False], [False, False, True]] size = [Batch_size, 3] When I one_hot encode this action array I obtain an array of this size [BatchSize, 3, 3] As consequence when I want to calculate my Q-value estimation: Q = tf.reduce_sum(tf.multiply(self.output, self.actions_one_hot), axis=1) The tf.multiply(self.output, self.actions_one_hot) produces an error: InvalidArgumentError: Incompatible shapes: [10,3] vs. [10,3,3] [[Node: DQNetwork/Mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](DQNetwork/dense/BiasAdd, DQNetwork/one_hot)]] I understand that these 2 have incompatible shapes to be multiplied but I don't understand what I must do to make them compatible. To be more clear this is the notebook with each part explained: I'm sure that I made a really stupid mistake but I don't see it. Thanks for your help!
answer count: 1

http://stackoverflow.com/a/49724193
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49724109
upvote count: 1
has body: It looks like you want to set a variable dynamically. In this case, since there are only two possible values, an inline if will do: LED_BRIGHTNESS = 75 if GPIO.input(4) == 1 else 255 Or you could expand the if: if GPIO.input(4) == 1: LED_BRIGHTNESS = 75 else: LED_BRIGHTNESS = 255
type: Answer
answers question: http://stackoverflow.com/q/49724109

http://stackoverflow.com/comment/86364574
type: Comment
score: 0
type: QuestionComment
has text: Actually, I am debugging the task with *logging* module, and the traces stops at the very beginning of this pw3_parseDOM. I don't know how to redirect error stream to logging trace. It could be helpfull though.
comment on: http://stackoverflow.com/q/49659035

http://stackoverflow.com/comment/86331960
score: 1
has text: @PatrickArtner: Not a set comprehension. `{tuple(a) for a in x}` would be a set comprehension.
comment on: http://stackoverflow.com/a/49661010
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49623495
downvote count: 0
upvote count: 1
has body: You can try this approach: data=[[i]*initialList[i] for i,j in enumerate(initialList)] print([k for i in data for k in i]) Just for fun I tried with lambda : initialList=[1,2,3,5] print(list(map(lambda x:[x]*initialList[x],range(0,len(initialList))))) lambda result is in nested list.
answers question: http://stackoverflow.com/q/49613360
type: Answer
score: 1

http://stackoverflow.com/comment/86330607
score: 0
type: Comment
has text: More Song Results is in your a list and when I print href above the if statements is makes it to this before erroring
comment on: http://stackoverflow.com/a/49660485
type: AnswerComment

http://stackoverflow.com/comment/86399021
score: 0
comment on: http://stackoverflow.com/a/49691819
type: AnswerComment
has text: Glad to help :)
type: Comment

http://stackoverflow.com/comment/86275571
type: QuestionComment
comment on: http://stackoverflow.com/q/49629221
score: 0
has text: Yeah his book is solid---I like the tutorial because it doesn't go too deep and just covers the main points, so it's a good refresher. I haven't used any specific BA sw packages, so I'm not sure how that works. I'm not sure if this is what *needs* to be done, but what would work to label each feature across images is use connected components. If feature `xi1, yi1` in `img1` is matched to `xj2, yj2` in `img2`, and `xj2, yj2` is matched to `xk3, yk3` in `img3`, and you compute all pairwise matches and put it all into one graph, each connected component is a matched feature which you can id.
type: Comment

http://stackoverflow.com/a/49625982
answers question: http://stackoverflow.com/q/49625751
type: Answer
accepted answer of: http://stackoverflow.com/q/49625751
score: 1
type: AcceptedAnswer
downvote count: 0
has body: What i can see is when you call: right_table=soup.find_all('table',{'class':'wikitable sortable plainrowheaders'}) the output of this command i.e right_table contains an array. You would need to call find_all on it's members(even though it has one element), not on entire thing. So this line: for row in right_table.find_all("tr"): should be changed to: for row in right_table[0].find_all("tr"):
upvote count: 1
has comment: http://stackoverflow.com/comment/86259988

http://stackoverflow.com/q/49700380
tagged with: attributeerror
tagged with: com
answer count: 1
tagged with: vba
type: Question
has answer: http://stackoverflow.com/a/49701083
has body: I have a VBA script that i run from within a software called Visum. This script calculates some stuff and returns some results to the software. What I'm trying to do is to "convert" this script to Python, but I'm having problem with this part of the code: VBA (works, using Visum library): Dim PathList_0 As IPrTPathLinkList Set PathList_0 = Visum.Lists.CreatePrTPathLinkList Set DSeg = Visum.Net.DemandSegments.ItemByKey(Segmento_Demanda) PathList_0.SetObjects newDemandSegOrPathSet:=DSeg, PathTypeSelection:=routeFilter_filterFromZoneFilter, ListFormat:=listFormat_databaseWithoutHeadLine, zone:=All PathList_0.AddColumn ("OrigZoneNo") aPath_0 = PathList_0.SaveToArray() Python (doesn't work... according to the software manual, it's not necessary to import any 'Visum' module, since I'm running this script from within the software): PathList_0 = Visum.ListsCreatePrTPathLinkList #ERROR DSeg = Visum.NetDemandSegments.ItemByKey(Segmento_Demanda) PathList_0.SetObjects("All", DSeg, "routeFilter_filterFromZoneFilter", False, "listFormat_databaseWithoutHeadLine") PathList_0.AddColumn("OrigZoneNo") aPath_0 = PathList_0.SaveToArray() When I run the VBA script, it works. But when I run the Python script, it returns an AttributeError: I've read some similar questions about AttributeError, but I couldn't find useful information for this specific situation. I've also read dynamic.py and pyscript.py, but since I'm not an experienced programmer, I couldn't find out the problem. My Python version is compatible with the the Visum software (I've checked on it). I'm asking this question because I think it may be related with some mistake I made when "converting" to Python. Can anyone help me with this error?
tagged with: python
accepted answer: http://stackoverflow.com/a/49701083
has title: Python AttributeError when using a specific type of object
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49657838
has answer: http://stackoverflow.com/a/49659192
linked to: http://stackoverflow.com/q/42872142
has answer: http://stackoverflow.com/a/49659258
has comment: http://stackoverflow.com/comment/86327732
tagged with: matplotlib
tagged with: python
type: UnansweredQuestion
has title: How to overwrite a plot after pressing a button in pyplot?
has comment: http://stackoverflow.com/comment/86325476
has answer: http://stackoverflow.com/a/49660108
has comment: http://stackoverflow.com/comment/86324857
score: 0
has body: I have some csv files with data I want to plot. I want to use my arrow keys on my keyboard to overwrite the plot. My Code: import os, pandas, glob import matplotlib.pyplot as plt import tkinter as tk from tkinter import filedialog counter = 0 class Plotter: def __init__(self, filepath): self.plotter(filepath) def press(self, event): print('press', event.key) global counter if event.key == 'down': if (counter + 1) &lt; len(files): counter = counter + 1 self.plotter(files[counter]) if event.key == 'up': if not (counter - 1) &lt; 0: counter = counter - 1 self.plotter(files[counter]) def plotter(self, filepath): data = pandas.read_csv(filepath) fig = plt.figure() fig.canvas.mpl_connect('key_press_event', self.press) ax = fig.add_subplot(111) ax.plot(data.x, data.y1, 'r-') ax2 = ax.twinx() ax2.plot(data.x, data.y2, '--') plt.show() if __name__ == '__main__': root = tk.Tk() root.withdraw() dir_path = filedialog.askdirectory() files = list(glob.glob(os.path.join(dir_path, 'test*.csv'))) print(files[counter]) Plot = Plotter(files[counter]) My issue is: When I press the button a new window opens instead of overwriting the plot. Any suggestions? [EDIT](I want to keep the previous code, as the error is different with this approach) My Code after the comment from DavidG looks like: import os, pandas, glob import matplotlib.pyplot as plt import tkinter as tk from tkinter import filedialog counter = 0 class Plotter: def __init__(self, filepath): self.fig = plt.figure() self.fig.canvas.mpl_connect('key_press_event', self.press) self.plotter(filepath) def press(self, event): print('press', event.key) global counter if event.key == 'down': if (counter + 1) &lt; len(files): counter = counter + 1 self.plotter(files[counter]) if event.key == 'up': if not (counter - 1) &lt; 0: counter = counter - 1 self.plotter(files[counter]) def plotter(self, filepath): data = pandas.read_csv(filepath) ax = self.fig.add_subplot(111) ax.plot(data.x, data.y1, 'r-') ax2 = ax.twinx() ax2.plot(data.x, data…
answer count: 3
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/86207248
type: Comment
type: QuestionComment
has text: @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 Please do not vote to close with a custom reason that "it belongs on Code Review". Nothing in the Stack Overflow rules justifies such a custom reason, and sloppy reasoning perpetuates inappropriate referrals. Not all questions about analyzing code are off-topic on Stack Overflow, and not all code review requests are on-topic on Code Review. Instead, vote to close as too broad or primarily opinion-based. See also [the guide to CR for SO users](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users).
comment on: http://stackoverflow.com/q/49599961
score: 0

http://stackoverflow.com/a/49683568
upvote count: 1
answers question: http://stackoverflow.com/q/49683070
score: 1
has body: import pandas as pd df = pd.DataFrame(data=[ [1, 'John', 'Smith', 'a'], [1, 'John', 'Smith', 'b'], [2, 'Kate', 'Smith', 'c'], ], columns=['ID', 'First', 'Last', 'Avail'] ) output = (df .groupby(['ID', 'First', 'Last'], as_index=False) .agg({'Avail': lambda x: ';'.join(x)})) You can use groupby as @Sphinx suggested. An example with the style of output you requested is above.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86363014
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49675751
has text: In memory OLTP is designed to solve problems with locking & latching. Depending on what kind of operations you're doing with the data, it might help a lot -- or be totally useless. There's no locking, so you can't update the data on the same row at the same time.

http://stackoverflow.com/comment/86461925
has text: Thanks tangoal for the response however I think I have a different situation than the link you mentioned.Is it possible for you to add in the code ?
comment on: http://stackoverflow.com/q/49711332
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49653422
score: 1
downvote count: 0
has body: You can do this: l = ["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"] n = 13 # Chosen number (you can assign any integer you want) r = 25 # Index of Z element = l[(r + n) % len(l)] print("Element: ", element) Output: Element: M You can use the randint function from the random module to assign a random number for r, as well as n.
answers question: http://stackoverflow.com/q/49653107
type: Answer
upvote count: 1

http://stackoverflow.com/comment/86374883
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49681524
score: 1
has text: You could just try it out in the interactive interpreter

http://stackoverflow.com/comment/86278981
has text: OK, that's a structured array (actually `record` subclass, but effectively the same), with 2 of fields being object dtype. I'll have to construct something similar, and play around with various ways of flattening it. It isn't going to be easy.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49635509

http://stackoverflow.com/comment/86244180
score: 0
comment on: http://stackoverflow.com/q/49614682
type: Comment
type: QuestionComment
has text: @phil0s0pher You can use the ORM programatically in a script, to assign `Coin` objects to `CoinData` objects, as long as you have an appropriate algorithm for the assignment. The relationship between the objects is through the `ForeignKey`, so what I said before about `coin_name` being unnecessary still applies (in fact, it is undesirable, because it denormalizes the database with no gain). Also, for the user to "click on a coin and be presented with a number of ways to request data", you'll probably want to create your own views and not do that in the admin.

http://stackoverflow.com/comment/86332725
type: QuestionComment
comment on: http://stackoverflow.com/q/49661075
has text: Perfect. Thank you.
score: 0
type: Comment

http://stackoverflow.com/a/55529363
answers question: http://stackoverflow.com/q/49645415
has body: Working on google ads have been a bit tuff but this problem has a very simple solution.As we just need to switch the version. 1 - Update the googleads libs: pip install --upgrade googleads 2 - You need to change v201802 to v201809 everywhere this code has been used. WHY - v201809 is the latest version relased in september. campaign_service = client.GetService('CampaignService', version='v201809')
type: Answer
score: 0

http://stackoverflow.com/comment/86335840
score: 0
type: Comment
type: QuestionComment
has text: I don't like the idea but a simple way to do it is to use BLEU if you're considering ngram similarity.
comment on: http://stackoverflow.com/q/49658383

http://stackoverflow.com/comment/86404726
comment on: http://stackoverflow.com/a/49695988
score: 0
type: AnswerComment
has text: you don't have to convert to `list`, just iterate on the characters.
type: Comment

http://stackoverflow.com/a/49692421
type: Answer
answers question: http://stackoverflow.com/q/49663567
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86404378
has body: Here is an example with Manager. import multiprocessing as mp import time import requests # for example we will fetch data about countries def call_url(url: str, result: dict): response = requests.get(url) result['data'] = response.json() def test(): manager = mp.Manager() # result of process result = manager.dict() # send url and result to process single = mp.Process( target=call_url, args=( 'https://restcountries.eu/rest/v2/all', result, )) start_time = time.time() single.start() # wait when process is finish and print time + result single.join() print('\nSingle time: %s' % (time.time() - start_time)) print('\nSingle result: %s' % result.values()) processes = [] start_time = time.time() # create 4 processes and fetch data in each process for i in range(4): result = manager.dict() process = mp.Process( target=call_url, args=( 'https://restcountries.eu/rest/v2/all', result, )) processes.append((process, result, )) process.start() # wait until all processes are finished for process, _ in processes: process.join() # print results of each process and time print('\nresults: ') for _, result in processes: print('\n') print(result.values()) print('\n4 process time: %s' % (time.time() - start_time)) if __name__ == '__main__': test() Run our script(Python 3.6.1). Example of output: Single time: 0.9279030323028564 Single result: [[{'name': 'Afghanistan'... results: # long output (the same result as in single - [[{'name': 'Afghanistan'...) 4 process time: 1.0175669193267822 Process finished with exit code 0 So, as you can see 0.9 ~= 1.0. But in the second time was sent 4 requests. Also you can use Queue, Pool etc. There are many examples on SO(also in internet). Hope this helps.
accepted answer of: http://stackoverflow.com/q/49663567

http://stackoverflow.com/q/49729075
score: 0
has comment: http://stackoverflow.com/comment/86472807
tagged with: string
tagged with: slice
has body: I have a large string array which i store as an nparray named np_base: np.shape(np_base) Out[32]: (65000000, 1) what i intend to do is to vertically slice the array in order to decompose it into multiple columns that i'll store later in an independant way, so i tried to loop over the row indexes and to append: for i in range(65000000): INCDN.append(np.base[i, 0][0:5]) but this trhows out a memory error. Could anybody please help me out with this issue, i've been searching for days for an alternative way to slice the string array. Thanks,
type: Question
has comment: http://stackoverflow.com/comment/86481309
type: UnansweredQuestion
tagged with: arrays
answer count: 1
tagged with: python
has title: Specific string slicing
has answer: http://stackoverflow.com/a/49729689

http://stackoverflow.com/comment/86518681
type: QuestionComment
comment on: http://stackoverflow.com/q/49752007
type: Comment
has text: This question makes no sense. The dict won't change its order if you don't modify it, so what's the problem? You have to do _absolutely nothing_ to maintain its order. If you're planning to modify the dict though, then use an OrderedDict.
score: 4

http://stackoverflow.com/q/49690748
type: Question
tagged with: openstreetmap
tagged with: gdal
type: UnansweredQuestion
tagged with: python
tagged with: gis
has body: I've downloaded an openstreetmap shapefile and want to extract certain features (to make the file less heavy and have only the ones I'm interested in, for example bicycle paths from the roads). How would I do this, I can currently open the file and look at the features with this code: from osgeo import ogr file = ogr.Open('gis.osm_roads_free_1.shp') shape = file.GetLayer(0) # here I want to filter on an "fclass" value Any suggestions on how to do this?
has comment: http://stackoverflow.com/comment/86393586
score: 0
tagged with: ogr
has comment: http://stackoverflow.com/comment/86393433
has answer: http://stackoverflow.com/a/49691284
has title: python OGR Shapefile export features
answer count: 1
has comment: http://stackoverflow.com/comment/86393368

http://stackoverflow.com/comment/86258198
type: QuestionComment
has text: What is the structure of the JSON file ? Please add a sample structure of your alert message.
comment on: http://stackoverflow.com/q/49625548
score: 0
type: Comment

http://stackoverflow.com/comment/86430824
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49699973
score: 2
has text: @Topto, `driver.execute_script("window.iScrollElenco.scrollBy(0, -10000)")`. but you'll have to wait for the dynamic content to be updated. It would be much more easier and efficient to send the request directly to scrap the the data.

http://stackoverflow.com/comment/86310579
score: 0
type: Comment
has text: what you can do is call a function which after the hero dies, which blits the message on the whole screen
comment on: http://stackoverflow.com/a/49651007
type: AnswerComment

http://stackoverflow.com/q/49673126
type: Question
tagged with: google-app-engine
has body: I have a Google App Engine Python project that I haven't touched since 2014, when you worked with a desktop app to upload and deploy it. Google App engine changed a lot in the meantime. According to the information the deploying guide I copy the file(s) like this: gsutil cp main.py gs://myproject.appspot.com/ I converted my app.yaml file to a json file using their utility. When I initially deployed the app using this page it failed because there was no deployment information, so I added this: "deployment": { "files": { "main": { "sourceUrl": "https://storage.googleapis.com/myproject/main.py" }, } }, However when I deployed again I got an error because it couldn't find the file with that URL. The gsutil has to use a bucket with gs://something and the file has to exist at https:// something. How can I upload the file to the project and specify the location in the app.json file?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49674104
has comment: http://stackoverflow.com/comment/86359575
has title: Changing a file on Google App Engine
has answer: http://stackoverflow.com/a/49674104
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49668380
tagged with: numpy
has answer: http://stackoverflow.com/a/49668451
accepted answer: http://stackoverflow.com/a/49668451
has body: I have two arrays: A such that A.shape = (N, M, K) and index such that index.shape = (N, M). As a result I want to get such array B that B[i, j] = A[i, j, index[i, j]]. How to achieve that in the simplest way? One solution that comes to my mind is that we can do it like this: B = A.reshape(-1, K)[np.arange(N * M), index.reshape(-1)].reshape(N, M). I wonder if there are any other solutions?
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion
downvote count: 0
answer count: 1
has title: Advanced indexing in Numpy
favorite count: 0
type: Question

http://stackoverflow.com/q/49721089
favorite count: 0
has body: I am working with Django for a first time and I'm trying to build an API and I am following some tutorials and examples and it works right, but I am running the project now in a Raspberry Pi after install all the requirements and the project is failing with the following error: Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0xb547adb0&gt; Traceback (most recent call last): File "/home/pi/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/pi/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __…
type: Question
tagged with: python-3.x
answer count: 8
has answer: http://stackoverflow.com/a/59515969
accepted answer: http://stackoverflow.com/a/49721133
possible better answer: http://stackoverflow.com/a/51648513
has answer: http://stackoverflow.com/a/56924196
downvote count: 0
has answer: http://stackoverflow.com/a/49721133
tagged with: django
upvote count: 49
has answer: http://stackoverflow.com/a/76749735
tagged with: django-rest-framework
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73050390
score: 49
has answer: http://stackoverflow.com/a/51648513
has answer: http://stackoverflow.com/a/59926348
tagged with: python
has answer: http://stackoverflow.com/a/63369374
has title: Django viewset has not attribute 'get_extra_actions'

http://stackoverflow.com/q/49756909
type: UnansweredQuestion
has body: I trained a simple neural network with TensorFlow on the MNIST dataset. The training portion of the code works fine. However, when I feed a single image into the network, it gives me the following traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1021, in _do_call return fn(*args) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1003, in _run_fn status, run_metadata) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 88, in __exit__ next(self.gen) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 469, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "tfbasics.py", line 113, in &lt;module&gt; classification = sess.run(y, feed_dict) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 766, in run run_metadata_ptr) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 964, in _run feed_dict_string, options, run_metadata) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1014, in _do_run target_list, options, run_metadata) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 103…
downvote count: 0
tagged with: neural-network
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/49757134
answer count: 3
has answer: http://stackoverflow.com/a/72250857
upvote count: 3
tagged with: tensorflow
favorite count: 0
has title: InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1'
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49757831
tagged with: invalid-argument

http://stackoverflow.com/q/49710321
score: 1
tagged with: speech-to-text
tagged with: python
tagged with: cmusphinx
has body: I am rather perplexed over how to use grammar files with Python's speech_recognition package. I've tried hunting for solutions online, but information is sparse to say the least regarding grammars. Here's my setup: main.py: import speech_recognition as sr converter = sr.Recognizer() with sr.Microphone() as source: print('Please say "zero":') audio = converter.listen(source) print('Without: ' + str(converter.recognize_sphinx(audio, show_all=False))) print('With: ' + str(converter.recognize_sphinx(audio, show_all=False, grammar='Numbers.jsgf'))) Numbers.jsgf: #JSGF V1.0; grammar Numbers; &lt;Zero&gt; = ( zero ); Output: Please say "zero": Without: zero INFO: jsgf.c(706): Defined rule: &lt;Numbers.g00000&gt; INFO: jsgf.c(706): Defined rule: &lt;Numbers.Zero&gt; Process finished with exit code -1073741819 (0xC0000005) I'm working in PyCharm, using Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32. Any ideas what's going on? Thanks in advance for your help!
type: Question
has answer: http://stackoverflow.com/a/49711876
tagged with: grammar
upvote count: 1
answer count: 1
downvote count: 0
tagged with: speech-recognition
favorite count: 0
has title: Adding grammar causes speech recognition to fail
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49711876

http://stackoverflow.com/comment/86504474
comment on: http://stackoverflow.com/q/49744842
type: Comment
type: QuestionComment
score: 0
has text: If you're not joining the threads, how do you know the program is finished?

http://stackoverflow.com/q/49744581
upvote count: 1
has title: PyQt 5 QTableWidget.cellClicked Signal Not Working
favorite count: 0
type: Question
tagged with: qtablewidget
score: 1
tagged with: python
has body: I am trying to make a simple files app (or, file explorer app) and I am using the QTableWidget to Display the files and directories. When the user clicks an directory, I want the program to jump to that directory. I have used the QTableWidget.cellClicked signal, and it does not currently work. The signal part: self.filesTable.connect(print)#self.updateUiCellClick) Added print instead of self.updateUiCellClick for debugging purposes. Code (probably you do not need this): #!/usr/bin/python3 print('i Import Modules') print(' | Import sys') import sys print(' | Import PyQt5.QtCore') from PyQt5.QtCore import * print(' | Import PyQt5.QtGui') from PyQt5.QtGui import * print(' | Import PyQt5.QtWidgets') from PyQt5.QtWidgets import * # PyQt5 Support print(' | Import os') import os print(' | Import subprocess.Popen') # For backward-compatibility from subprocess import Popen, PIPE print(' | Done') print('i Define class Form') class root(QMainWindow): def __init__(self, parent=None): '''self.__init__ - Initializes QMainWindow''' print(' self.__init__ - Initializes QMainWindow') super(root, self).__init__(parent) # Create Variables self.currentPath = '/' os.chdir(self.currentPath) self.currentItems = os.listdir() self.currentItemsLsProcess = Popen(['ls','-l'], stdout=PIPE, stderr=PIPE) self.currentItemsLsProcessResult = self.currentItemsLsProcess.communicate() if self.currentItemsLsProcessResult[1].decode('utf-8'): QMessageBox.warning(self,'Files - ls -l Error','ls -l responded with non-blank stderr.Error is shown here: {} Error LsStderr (e-lsstderr) If you want to support the team, go to the GitHub Repository.'.format(self.currentItemsLsProcessResult[1].decode('utf-8'))) self.currentItemsLs = self.currentItemsLsProcessResult[0].decode('utf-8').split('\n')[1:-1] # Create Table Widget self.filesTable = QTableWidget() # Init Table Widget self.filesTable.clear() self.filesTable.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents) self.filesTable.setRowCount(len(self.currentIte…
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49744840
has answer: http://stackoverflow.com/a/49744840
tagged with: pyqt
downvote count: 0
answer count: 1
tagged with: pyqt5

http://stackoverflow.com/comment/86485195
comment on: http://stackoverflow.com/q/49735569
type: Comment
type: QuestionComment
score: 2
has text: @hisi, ah, those are not installed packages via conda or pip, those are part of the standard library and will not be listed.

http://stackoverflow.com/comment/86250097
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49621605
has text: This makes way more sense, and this is the part I wasn't seeing - defining the cols in addition to the objects is what I was missing in the documentation. Gonna try this now, thank you!

http://stackoverflow.com/a/49738629
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49738600
has body: You can use inner_function() anywhere in the scope where inner_function() is defined, that is anywhere in outer_function() after you defined inner_function().

http://stackoverflow.com/q/49677060
has answer: http://stackoverflow.com/a/77288170
answer count: 4
accepted answer: http://stackoverflow.com/a/49677854
possible better answer: http://stackoverflow.com/a/49677499
tagged with: pandas
has answer: http://stackoverflow.com/a/67736328
score: 12
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86366095
downvote count: 0
has answer: http://stackoverflow.com/a/49677499
has comment: http://stackoverflow.com/comment/86365364
tagged with: string
has comment: http://stackoverflow.com/comment/86366071
favorite count: 0
tagged with: series
has body: I tried to find the number of cells in a column that only contain empty string ''. The df looks like: currency USD EUR ILS HKD The code is: df['currency'].str.contains(r'\s*') but the code also recognizes cells with actual string values as containing empty strings. I am wondering how to fix this issue that it only detects cells that only contains empty strings.
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/49677854
tagged with: dataframe
tagged with: python
has title: Pandas: count empty strings in a column
has comment: http://stackoverflow.com/comment/86365746

http://stackoverflow.com/a/49677975
type: Answer
answers question: http://stackoverflow.com/q/49677099
has comment: http://stackoverflow.com/comment/86369247
downvote count: 0
score: 1
upvote count: 1
has body: df['Category_Final'] = ( df.apply(lambda _: "0", axis=1) .where(df['Category_A'] == df['Category_B'], "X") .where(~df['Category_A'].isin(["0", "Unknown", np.NaN]), "Unknown") )

http://stackoverflow.com/q/49677614
answer count: 1
downvote count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86366559
score: 3
has comment: http://stackoverflow.com/comment/86366656
upvote count: 3
tagged with: rsa
tagged with: python
has title: Overflow Exception when encrypting message with python-rsa
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49677761
has body: I'm using Python 3 and Python-rsa (https://stuvel.eu/rsa) and I keep getting the same error when encrypting a message: &gt; Traceback (most recent call last): ``File "client.py", line 65, in &lt;module&gt; msgg = encrypt_text(pubkey, msg) File "client.py", line 54, in encrypt_text return rsa.encrypt(msg.encode(), pubkey) File "C:\Users\N0t_an_admin\AppData\Local\Programs\Python\Python36-32\lib\s -packages\rsa\pkcs1.py", line 170, in encrypt padded = _pad_for_encryption(message, keylength) File "C:\Users\N0t_an_admin\AppData\Local\Programs\Python\Python36-32\lib\s -packages\rsa\pkcs1.py", line 87, in _pad_for_encryption ' space for %i' % (msglength, max_msglength)) OverflowError: 1 bytes needed for message, but there is only space for -10 Code: def get_server_pub(): pubkey = listener("serverpub").decode("utf-8") pubkey = pubkey.strip(";") xd = rsa.PublicKey(n= int(pubkey[0]), e= int(pubkey[1])) return xd def encrypt_text(pubkey, msg): return rsa.encrypt(msg.encode(), pubkey) if __name__ == '__main__': print("Hello") if os.path.isfile('ckeys.json') == False: keys = createkeys() write_to_json_file('ckeys.json', keys) pubkey = get_server_pub() while True: msg = input("Message: ") msgg = encrypt_text(pubkey, msg) recived = listener(msgg) if not recived: continue print(recived) The documentation says: OverflowError – when the message is too large to fit in the padded block.
has answer: http://stackoverflow.com/a/49677761

http://stackoverflow.com/comment/86395011
type: QuestionComment
comment on: http://stackoverflow.com/q/49691285
score: 0
has text: No logger output, as I said above, the code executes without any exception. What do you mean by "system call", pywin32?
type: Comment

eval
tag name: eval
type: Tag
tags question: http://stackoverflow.com/q/49726442

http://stackoverflow.com/comment/86269317
has text: @nicolallias `b'hello \0 world'` is a bytestring
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49630861
type: Comment

http://stackoverflow.com/a/78548247
answers question: http://stackoverflow.com/q/49755480
score: 0
has comment: http://stackoverflow.com/comment/138487566
type: Answer
has body: This is an update of the class CaseInsensitiveDict for python 3.12 class CaseInsensitiveDict(collections.abc.MutableMapping): &quot;&quot;&quot; Ordered case insensitive mutable mapping class. &quot;&quot;&quot; def __init__(self, *args, **kwargs): self._d = collections.OrderedDict(*args, **kwargs) self._convert_keys() def _convert_keys(self): for k in list(self._d.keys()): v = self._d.pop(k) self._d.__setitem__(k, v) def __len__(self): return len(self._d) def __iter__(self): return iter(self._d) def __setitem__(self, k, v): self._d[k.lower()] = v def __getitem__(self, k): return self._d[k.lower()] def __delitem__(self, k): del self._d[k.lower()] def copy(self): result = CaseInsensitiveDict() for k, v in self.items(): result[k] = v return result
has comment: http://stackoverflow.com/comment/138480702

http://stackoverflow.com/comment/86458147
type: QuestionComment
score: 0
has text: also on gpstate 20180408:23:21:48:017711 gpstate:datanode3:root-[INFO]:-Starting gpstate with args: 20180408:23:21:48:017711 gpstate:datanode3:root-[INFO]:-local Greenplum Version: 'postgres (Greenplum Database) 5.7.0 build f7c6eb5-oss' 20180408:23:21:48:017711 gpstate:datanode3:root-[CRITICAL]:-gpstate failed. (Reason='could not connect to server: Connection refused
comment on: http://stackoverflow.com/q/49716375
type: Comment

http://stackoverflow.com/comment/86432450
score: 0
has text: Thanks, but what does "index" mean in this context?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49709495

http://stackoverflow.com/comment/86312540
has text: @TommasoBendinelli Can you update the question with this new information and what your current output is?
type: AnswerComment
comment on: http://stackoverflow.com/a/49651276
score: 0
type: Comment

http://stackoverflow.com/comment/86448608
type: Comment
type: QuestionComment
has text: Can you ping it from your shell? I believe that's not reachable, maybe you need to open ports
score: 0
comment on: http://stackoverflow.com/q/49716237

http://stackoverflow.com/comment/86465922
score: 0
comment on: http://stackoverflow.com/q/49726125
has text: Can you post your csv?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86434588
type: Comment
type: QuestionComment
has text: I don't see how the answer you accepted fixed your problem. You keep overwriting the file on each iteration of `for element in data['RoleDetailList']:` . Using csv.writer doesn't fix that.
score: 0
comment on: http://stackoverflow.com/q/49710351

http://stackoverflow.com/a/49626168
score: 3
upvote count: 3
downvote count: 0
has body: I was able to reproduce the problem and after some testing I've narrowed it down to using a DatetimeIndex as the input of the calendar parameter in CustomBusinessDay. You can skip that and use the calendar instance directly: import datetime as dt import pandas as pd from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, \ USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, \ USLaborDay, USThanksgivingDay from pandas.tseries.offsets import CustomBusinessDay, BDay class USTradingCalendar(AbstractHolidayCalendar): rules = [ Holiday('NewYearsDay', month=1, day=1, observance=nearest_workday), USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, Holiday('USIndependenceDay', month=7, day=4, observance=nearest_workday), USLaborDay, USThanksgivingDay, Holiday('Christmas', month=12, day=25, observance=nearest_workday) ] bday_us = CustomBusinessDay(calendar=USTradingCalendar()) d = dt.datetime(2018, 3, 31) c = d - bday_us print(c) The output: 2018-03-29 00:00:00
type: Answer
answers question: http://stackoverflow.com/q/49624124

http://stackoverflow.com/q/49674860
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50216257
downvote count: 0
tagged with: python
has body: I' m trying to use the deeplab3+ tensorflow implementation to finetune with a new dataset (with a different number of classes). I converted the dataset to tfrecords and started to train the model without problems. Now I want to evaluate the new checkpoint, running the evaluation script, and I obtain a shape mismatch error. tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape mismatch The model implementation uses tensorflow.slim and I think my problem is related to the function slim.evaluation.evaluation_loop( master=FLAGS.master, checkpoint_dir=FLAGS.checkpoint_dir, logdir=FLAGS.eval_logdir, num_evals=num_batches, eval_op=list(metrics_to_updates.values()), max_number_of_evaluations=num_eval_iters, eval_interval_secs=FLAGS.eval_interval_secs, hooks=[tf_debug.LocalCLIDebugHook()])) The log of my error `tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape mismatch in tuple component 1. Expected [513,513,3], got [2448,2448,3] [[Node: batch/padding_fifo_queue_enqueue = QueueEnqueueV2[Tcomponents=[DT_INT64, DT_FLOAT, DT_STRING, DT_INT32, DT_UINT8, DT_INT64], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](batch/padding_fifo_queue, Reshape_3/_4659, add_2/_4661, Reshape_1, add_3/_4663, case/cond/Merge/_4665, Reshape_6/_4667)]]` I don't understand this error because the implementation uses the same preprocessing routine during training and validation. I also tried to debug using tf_debug.LocalCLIDebugHook() but it didn't work.
has title: Tensorflow DeepLab: Shape mismatch in tuple component 1. Expected [x,x,3], got [y,y,3]
has answer: http://stackoverflow.com/a/54373965
score: 2
answer count: 2
tagged with: deep-learning
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2

codeception
type: Tag
tags question: http://stackoverflow.com/q/49652911
tag name: codeception

http://stackoverflow.com/q/49701323
has title: Merging PDF files using Python and PyPDF2 throws a TypeError
has comment: http://stackoverflow.com/comment/86418299
has comment: http://stackoverflow.com/comment/86416717
favorite count: 0
has body: I am using Python 3.6.5 to merge PDFs together but am running into a problem. The code below throws a 'TypeError: 'NumberObject' object is not subscriptable' error. What am I doing wrong? When I comment out the line with the merger.append, it prints out the file paths correctly. import webbrowser import os from PyPDF2 import PdfFileMerger, PdfFileReader path = 'C:/test/pdfs' merger = PdfFileMerger() for pdf in os.listdir(path): merger.append(PdfFileReader(open(os.path.join(path,pdf), 'rb'))) print(os.path.join(path,pdf)) merger.write(path+'/merged.pdf') merger.close() webbrowser.open_new(path+'/merged.pdf') File "C:\test\pdftest.py", line 9, in merger.append(PdfFileReader(open(os.path.join(path,pdf), 'rb'))) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1084, in init self.read(stream) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1805, in read assert xrefstream["/Type"] == "/XRef" TypeError: 'NumberObject' object is not subscriptable When I change the merger.append to take a file path, I get: File "C:\test\pdftest.py", line 9, in merger.append(os.path.join(path,pdf)) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\merger.py", line 203, in append self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\merger.py", line 133, in merge pdfr = PdfFileReader(fileobj, strict=self.strict) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1084, in init self.read(stream) File "C:\python\lib\site-packages\pypdf2-1.26.0-py3.6.egg\PyPDF2\pdf.py", line 1805, in read assert xrefstream["/Type"] == "/XRef" TypeError: 'NumberObject' object is not subscriptable UPDATE: It looks like one of the PDFs in the folder was causing this. The only thing different with that PDF is that it uses Type 1 font whereas the other PDFs use TrueType font. Does anyone know a workaround or fix for this?
upvote count: 4
has comment: http://stackoverflow.com/comment/86417060
has comment: http://stackoverflow.com/comment/86416984
type: Question
has comment: http://stackoverflow.com/comment/86416735
downvote count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86416383
answer count: 1
has comment: http://stackoverflow.com/comment/86491111
has answer: http://stackoverflow.com/a/65523730
has comment: http://stackoverflow.com/comment/86416883
score: 4
tagged with: pypdf
has comment: http://stackoverflow.com/comment/99509180
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/q/49732469
has comment: http://stackoverflow.com/comment/86478784
tagged with: tensorflow
type: Question
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/49732736
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86478923
score: 0
has body: I am trying to crop and save images from tensorflow object detection API output with following code I created using previous stack overflow questions. But after saving the image seemed to have high density of blue color. The original image has normal color. Since both cropping and encoding refer image channel for format I am not sure about the source of the issue.
answer count: 1
has title: Image becomes blue masked after applying tf.image.crop_to_bounding_box and tf.image.encode_jpeg
accepted answer: http://stackoverflow.com/a/49732736

http://stackoverflow.com/comment/86533851
type: AnswerComment
has text: The mongo docs I linked to in my answer states that operations are ordered by default. I tried this out with a cap of 6 records and got the right results. Are you able to provide a sample I can work with?
comment on: http://stackoverflow.com/a/49698422
type: Comment
score: 0

http://stackoverflow.com/a/49651437
has comment: http://stackoverflow.com/comment/86319742
upvote count: 3
downvote count: 0
has body: You need to register the model Choice as well. # admin.py admin.site.register(Choice)
score: 3
answers question: http://stackoverflow.com/q/49651085
type: Answer

http://stackoverflow.com/a/49757398
has comment: http://stackoverflow.com/comment/86529852
answers question: http://stackoverflow.com/q/49756717
score: 0
has comment: http://stackoverflow.com/comment/86529985
type: AcceptedAnswer
has body: For the simplest case, you might solve this with a regular expression: &gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(r"('?null'?)", "'Null'", "{'abcd': null}") "{'abcd': 'Null'}" &gt;&gt;&gt; re.sub(r"('?null'?)", "'Null'", "{'abcd': 'null'}") "{'abcd': 'Null'}" &gt;&gt;&gt; but from the look of you example and the comment (which should really be part of your question) mentionning you might have a lot more in the string, I suspect you are dealing with json here. If that's the case, the proper solution (the only robust solution actually) is to deserialize your string to Python (using json.loads(...)), update the resulting Python object (usually a dict, but might be a list of dicts or might contains lists containing dicts etc), then serialize it back with json.dumps().
accepted answer of: http://stackoverflow.com/q/49756717
type: Answer

http://stackoverflow.com/a/49739930
type: Answer
has body: Use os.stat() to get the last modified time and datetime to convert that into the string timestamp that you want. import os from datetime import datetime filename = 'rs' st = os.stat(filename) modified_time = datetime.fromtimestamp(st.st_mtime) tar_filename = modified_time.strftime('{}_%b_%m_%Y.tar'.format(filename))
score: 0
answers question: http://stackoverflow.com/q/49739465

http://stackoverflow.com/q/49600142
score: 1
has comment: http://stackoverflow.com/comment/86207367
tagged with: python
tagged with: regex
has title: Why does this regex expression give two different results in Python and Javascript?
tagged with: substring
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: javascript
upvote count: 1
has body: I have the following string: [?]The Taliban Have Gone High-Tech. That Poses a Dilemma for the U.S. The frequency and ferocity of the nighttime Taliban attacks are linked to attempts by Afghan forces, based in small checkpoints across the country, to hold territory that has been wrested away from the militants. Afghan troops said the missing devices were reported as "Battle losses," but could not support that claim with any proof or records to explain where or when they were left behind, according to the documents. Over the summer and fall, the Afghan National Army suffered 15 percent fewer casualties around Kandahar than it had during the same period in 2016.The documents credited the night-vision equipment for the marked reduction, concluding that the devices are "Becoming an integral part of base defense plans." The American military is now planning to equip the unit with roughly 2,500 night-vision goggles as part of what the documents described as a concept for a "Permanent program." Capt. Tom Gresback, a spokesman for United States forces in Afghanistan, declined to comment on the plans to distribute the devices to the Afghan National Army, as outlined in the military documents. With the night-vision devices, Taliban fighters have been able to approach Afghan bases nearly undetected before attacking. Zabihullah Mujahid, a spokesman for the Taliban, said fighters obtained night-vision devices after attacking Afghan bases or capturing members of the Afghan security forces. In Helmand Province, Marine Corps advisers are helping a request by the 505th Zone of the Afghan National Police to receive night-vision devices, Col.Reduced And, I want to get the following output (Removing "[?]" and "Reduced"): The Taliban Have Gone High-Tech. That Poses a Dilemma for the U.S. The frequency and ferocity of the nighttime Taliban attacks are linked to attempts by Afghan forces, based in small checkpoints across the country, to hold territory that has been wrested away from the m…
has comment: http://stackoverflow.com/comment/86289329
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86207366
accepted answer: http://stackoverflow.com/a/49600268
has answer: http://stackoverflow.com/a/49600268

http://stackoverflow.com/comment/86237324
has text: it prints because i put `print line` i just updated question-it's bash conmmand converted to work under python
type: Comment
comment on: http://stackoverflow.com/a/49613690
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86369579
type: Comment
has text: @Prateek, I want 24 values for each of 12 month i.e. `24 * 12`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49620140

http://stackoverflow.com/comment/86430217
type: QuestionComment
comment on: http://stackoverflow.com/q/49703810
has text: @JiewMeng It is not possible to say without seeing the data, but nce you know the schema, which has been inferred, you can use it right away by passing it to `DataFrameReader.schema` method. By wildcard I mean `*`. It might not make much of a difference, but it is usually behaves less than optimally (details vary on store basis).
score: 0
type: Comment

http://stackoverflow.com/comment/86216688
has text: I have constraint about using python2. It is not possible ?
type: Comment
comment on: http://stackoverflow.com/a/49604804
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86470642
has text: @ArturMüllerRomanov Great. If there's some mistake, though, please feel free to LMK and I'll correct it.
type: Comment
comment on: http://stackoverflow.com/a/49721510
type: AnswerComment
score: 1

http://stackoverflow.com/a/60601644
type: Answer
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/112036130
has body: With TF 2.1, You can create an iterator like so: iterator = iter(dataset) And get the next batch of values: batch = iterator.get_next()
upvote count: 5
answers question: http://stackoverflow.com/q/49658802

http://stackoverflow.com/q/49663720
type: Question
has comment: http://stackoverflow.com/comment/86337286
tagged with: javascript
type: UnansweredQuestion
tagged with: python
has title: Equivalent to python's uuid.uuid4().hex in javascript?
upvote count: 6
score: 6
tagged with: security
has answer: http://stackoverflow.com/a/66605338
has comment: http://stackoverflow.com/comment/86337311
tagged with: uuid
has comment: http://stackoverflow.com/comment/86337316
has body: Python has functionality to create hex UUID's like so: &gt;&gt;&gt; import uuid &gt;&gt;&gt; uuid.uuid4().hex '47be94c37e484e13ab04ed3c54a5b681' Is it possible to do the same in client javascript, with the same hex formatting? Is there a way to "validate" the UUID the client sends back? I.e. prevent or notice if a malicious user sends back "1234abcdsh*t..." A solution idea is to just generate each of the 32 characters randomly on the frontend, but I don't know if there's anything special about the hex UUID's, and I'm also not sure if there's a good way to validate the client sent back a valid value (and not a series of 32 a's) Edit: just realized there's nothing special about the "hex" formatting, it's just missing the dashes. Will leave that bullet up in case it confuses anyone else.
downvote count: 0
has comment: http://stackoverflow.com/comment/86337780
tagged with: cryptography
has comment: http://stackoverflow.com/comment/86337538
linked to: http://stackoverflow.com/q/105034
has comment: http://stackoverflow.com/comment/86337626
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86337474
has comment: http://stackoverflow.com/comment/86337587
has comment: http://stackoverflow.com/comment/86337744

python-unittest
tags question: http://stackoverflow.com/q/49640451
tags question: http://stackoverflow.com/q/49638700
tags question: http://stackoverflow.com/q/49599665
tags question: http://stackoverflow.com/q/49718428
tags question: http://stackoverflow.com/q/49698009
tags question: http://stackoverflow.com/q/49616239
tags question: http://stackoverflow.com/q/49633193
tags question: http://stackoverflow.com/q/49723266
tag name: python-unittest
type: Tag
tags question: http://stackoverflow.com/q/49633359

http://stackoverflow.com/a/49617732
accepted answer of: http://stackoverflow.com/q/49617180
has body: You were close. Try modifying your existing function as below. def get_rolling_average(data, period): rolling = [] for i in range (0, len(data)): nums = data[i-period+1:i+1] if i &lt; period-1: rolling.append(mean(data[:i+1])) if (i &gt;= period-1) and (len(nums) == period): rolling.append(mean(nums)) return rolling Returns: [45.0, 48.0, 56.3, 68.7, 77.0, 71.3, 63.0, 63.7, 74.7, 75.3] Explanation You want specific logic for i &lt; period-1 versus i &gt;= period-1. Structure your logic in this way. Define nums = data[i-period:i] to enable you to capture all the groupings of 3 values. Once you are happy with this solution, you may wish to understand alternative implementations, e.g. itertools, numpy, pandas.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49617180
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49681377
type: Question
accepted answer: http://stackoverflow.com/a/49681644
tagged with: dask
score: 3
has answer: http://stackoverflow.com/a/49681644
tagged with: python
has body: I have two data frames and I need to compare the full combinations of rows and return those combinations that meet a criteria. This turns out to be too intensive for our small cluster with Spark (using a cross join) so I am experimenting with this approach and would eventually see if Dask can improve on it. If table A and B are a=pd.DataFrame(np.array([[1,2,3],[4,5,6]]), columns=['a','b','c']) b=pd.DataFrame(np.array([[4,7,4],[6,5,1],[8,6,0]]), columns=['d','e','f']) Then all combinations looks like this, where A-D is calculated. Say I want to keep only the rows where A-D >=-3 A B C D E F A-D 1 2 3 4 7 4 -3 1 2 3 6 5 1 -5 1 2 3 8 6 0 -7 4 5 6 4 7 4 0 4 5 6 6 5 1 -2 4 5 6 8 6 0 -4 I attempted to do this with an apply but it appears I can not return a multi row dataframe out of the function (the function creates all the combinations of the single row of 'A' and the entire table of 'B' and returns the rows that meet the criteria. Here is the function I was testing: def return_prox_branches(a, B, cutthresh): aa=a['a']-B['d'] keep_B = B.copy().loc[(aa.values &gt;= cutthresh),:] keep_B['A']=a['a'] keep_B['B']=a['b'] keep_B['C']=a['c'] keep_B['A-D']=a['a']-keep_B['d'] print(keep_B) return(keep_B) a.apply(return_prox_branches, axis=1, args=(b,-3)) ValueError: cannot copy sequence with size 7 to array axis with dimension 1 In actuality, these two tables are in the millions of rows. Is there a way to make this work in pandas efficiently?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/120199675
has title: Pandas Apply - Return Multiple Rows
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/13050003
favorite count: 0

http://stackoverflow.com/q/49624932
has comment: http://stackoverflow.com/comment/86256831
has title: Unicode display in Python
has comment: http://stackoverflow.com/comment/86258317
has comment: http://stackoverflow.com/comment/86256847
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86258056
duplicate of: http://stackoverflow.com/q/27256006
has comment: http://stackoverflow.com/comment/86260165
linked to: http://stackoverflow.com/q/17560620
has comment: http://stackoverflow.com/comment/86260224
has comment: http://stackoverflow.com/comment/86256853
linked to: http://stackoverflow.com/q/5127855
type: Question
has comment: http://stackoverflow.com/comment/86256774
has comment: http://stackoverflow.com/comment/86256875
duplicate of: http://stackoverflow.com/q/17560620
type: UnansweredQuestion
has body: The Unicode standard describes how characters are represented by code points and contains a lot of tables listing characters and their corresponding code points: 0061 'a'; LATIN SMALL LETTER A 0062 'b'; LATIN SMALL LETTER B From https://docs.python.org/2/howto/unicode.html#definitions In Python, a character has two different display forms, and the two forms are equal: u'中文' == u'\u4e2d\u6587' Apparently, human want to read u'中文' instead of u'\u4e2d\u6587'. But in some situations in Python2, unicode only display as unicode points: &gt;&gt;&gt; print(u'\u4e2d\u6587') 中文 &gt;&gt;&gt; print({u'\u4e2d\u6587': 1}) {u'\u4e2d\u6587': 1} &gt;&gt;&gt; print([u'\u4e2d\u6587', 1]) [u'\u4e2d\u6587', 1] But there is no problem in Python3 &gt;&gt;&gt; print({u'\u4e2d\u6587': 1}) {'中文': 1} &gt;&gt;&gt; print([u'\u4e2d\u6587', 1]) ['中文', 1] Here are my questions: Can I tell Python which display form of unicode that I want? Why there's no problem with Python3? Is there a simple solution for Python2? I haven't found a good solution in the following links: Print a list that contains Chinese characters in Python Python: Certain unicode characters do not display correctly python display unicode in html
has comment: http://stackoverflow.com/comment/86262609
linked to: http://stackoverflow.com/q/38330713
tagged with: python
tagged with: unicode
has comment: http://stackoverflow.com/comment/86257387

http://stackoverflow.com/comment/86436698
has text: sample code is added as requested. Extracting this templates is another process but it is not a question. The question is that why template matching returns zero when two inputs have same resolution and almost same intensity levels.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49711408
type: Comment

http://stackoverflow.com/comment/86221294
comment on: http://stackoverflow.com/q/49604812
has text: @MarkRansom hi, the error is coming from this line graph_def = tf.GraphDef.FromString(open(MODEL_LOC).read()) ..... I tried putting encoding='utf-8' in the open call .... and I still get error
score: 0
type: Comment
type: QuestionComment

sorting
tags question: http://stackoverflow.com/q/49671990
tags question: http://stackoverflow.com/q/49681081
tags question: http://stackoverflow.com/q/49660139
tags question: http://stackoverflow.com/q/49599735
tags question: http://stackoverflow.com/q/49647437
tags question: http://stackoverflow.com/q/49752739
tags question: http://stackoverflow.com/q/49711793
tags question: http://stackoverflow.com/q/49676276
tags question: http://stackoverflow.com/q/49659348
tag name: sorting
tags question: http://stackoverflow.com/q/49639619
tags question: http://stackoverflow.com/q/49749940
tags question: http://stackoverflow.com/q/49720033
tags question: http://stackoverflow.com/q/49639242
tags question: http://stackoverflow.com/q/49628097
tags question: http://stackoverflow.com/q/49612027
tags question: http://stackoverflow.com/q/49637805
tags question: http://stackoverflow.com/q/49625891
tags question: http://stackoverflow.com/q/49605457
type: Tag

http://stackoverflow.com/q/49614682
has comment: http://stackoverflow.com/comment/86239238
has comment: http://stackoverflow.com/comment/86239737
has comment: http://stackoverflow.com/comment/86244180
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86239442
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86236059
downvote count: 0
has comment: http://stackoverflow.com/comment/86235934
upvote count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86236133
has body: I'm perhaps a little confused as to how ForiegnKey and database relationships work. I have two classes, Coin contains a list of items coin names. CoinData rows of data, containing daily price data for each coin. I want each CoinData to be ForiegnKey tied to their matching item in Coin, and to do this I gave CoinData a 'coin' ForeignKey attribute to my Coin model but all this does is produce a field of 'Coin' options on each CoinData item. I want to programmatically assign the value in coin_name, to the Coin object it matches with on each row of data. Am I going about this the right way, or am I doing things wrong? class Coin(models.Model): """ A class defining all the coins we'll have on the website """ # Fields name = models.CharField(max_length=30, unique=True, help_text="Enter coin name") class CoinData(models.Model): """ A class defining the daily coin data """ # Fields coin_name = models.CharField(max_length=30, null=True, default='empty') coin = models.ForeignKey(Coin, on_delete=models.SET_NULL, null=True) date = models.DateField(null=True, blank=True) open_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Opening Price") high_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="High Price") low_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Low Price") close_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Low Price") volume = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Volume") market_cap = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Market Cap")
has title: Set the ForeignKey to value in field of self in Django 2.0 and Python
has answer: http://stackoverflow.com/a/49614861
score: 1
has answer: http://stackoverflow.com/a/49630041

http://stackoverflow.com/comment/86353070
score: 0
comment on: http://stackoverflow.com/q/49671282
type: Comment
has text: Thanks @Aran-Fey. I'm new to coding and it still amazes me the simplicity to some problems and solutions.
type: QuestionComment

http://stackoverflow.com/a/49620241
has comment: http://stackoverflow.com/comment/86247743
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49620178
has body: First let's clean up the string: &gt;&gt;&gt; clean_hex = re.sub(r'\\x?([a-f0-9]{2})', lambda x: chr(int(x.group(1), 16)), r"\E8\x03", flags=re.I) &gt;&gt;&gt; clean_hex '\xe8\x03' And then we can use the struct module: &gt;&gt;&gt; struct.unpack('&lt;H', clean_hex)[0] 1000
answers question: http://stackoverflow.com/q/49620178
type: Answer
has comment: http://stackoverflow.com/comment/86247595

http://stackoverflow.com/comment/86300810
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49631724
has text: Oh and yes : "I could configure the default root logger, but it's definitely bad practice." => well, no it isn't. That's even why there's a root logger and propagation from children to their parents.
score: 0

http://stackoverflow.com/a/49781639
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49709425
has body: Sorted it out, just had to add the path to report file function.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49709425

http://stackoverflow.com/q/49728464
has title: Python Max method giving wrong result
possible better answer: http://stackoverflow.com/a/49728515
type: AnsweredQuestion
downvote count: 2
answer count: 3
upvote count: 1
has body: I am trying to check for the longest word in a Python list using the max method, but the result seems strange to me. max(['hello', 'there', 'people']) returns 'there' instead of 'people'. How is that possible?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49728521
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49728505
has answer: http://stackoverflow.com/a/49728515
accepted answer: http://stackoverflow.com/a/49728505

http://stackoverflow.com/comment/86282897
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49635179
has text: Does your family know you're doing this? ️

http://stackoverflow.com/comment/86382248
has text: Possible duplicate of [Split string into strings by length?](https://stackoverflow.com/questions/13673060/split-string-into-strings-by-length)
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49685426

http://stackoverflow.com/q/49615349
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86237616
tagged with: javascript
upvote count: 1
tagged with: flask
has answer: http://stackoverflow.com/a/49615537
has comment: http://stackoverflow.com/comment/86238680
favorite count: 0
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: Problems passing json to javascript in flask application
tagged with: python
has body: I have the following route code: @app.route('/getUser', methods=['GET']) def getUser(): main = Main() value = request.args.get('user_name') user = main.getValues(value) print(json.dumps(user)) return json.dumps(user) which passes json to the template: Nome usuario: Pesquisar but when I ask for the javascript to put the json values ​​in the label, it puts undefined, however when I print the json before the return in the route function it returns the following json: {"id": 17, "nome": "teste", "idade": 22, "senha": "1234"} Can anyone help me put the values in the template?

http://stackoverflow.com/comment/86500733
has text: Do not always trust your feelings. Unless the old word and the replacement have exactly the same length, the only way to modify the file content is to read the file, modify the content, and write it back.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49742962
score: 5

http://stackoverflow.com/comment/86322245
comment on: http://stackoverflow.com/q/49656004
type: Comment
type: QuestionComment
has text: Do not import tkinter and ttk with both `*` and `tk/ttk`. The recommended method of importing is to use `import tkinter as ttk` and `import tkinter.ttk as ttk`. You should remove the other imports that use `*`.
score: 0

http://stackoverflow.com/comment/86266729
score: 0
has text: no it's not possible because of python GIL.
comment on: http://stackoverflow.com/q/49629722
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86494784
score: 3
type: Comment
type: QuestionComment
has text: Could you include what the original dataframe looked like?
comment on: http://stackoverflow.com/q/49740139

header
tags question: http://stackoverflow.com/q/49712419
type: Tag
tag name: header
tags question: http://stackoverflow.com/q/49739977

http://stackoverflow.com/comment/86288149
has text: The use of an uppercase variable name is typical of Linux shell (e.g `bash`) functions. Try, for example `ls --help`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49637830

http://stackoverflow.com/q/49653146
score: 0
tagged with: image-segmentation
has comment: http://stackoverflow.com/comment/86315798
answer count: 1
accepted answer: http://stackoverflow.com/a/49674427
has comment: http://stackoverflow.com/comment/86316684
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86319040
has title: Counting objects in binary images
type: Question
has answer: http://stackoverflow.com/a/49674427
has comment: http://stackoverflow.com/comment/86315765
tagged with: python
has comment: http://stackoverflow.com/comment/86315677
has body: I am working with binary images in which there are a lot of small blobs. I would like to count the number of blobs and have found out that contours are commonly used to do that. However, the information I get does not allow me to measure certain parameters such as the area and the perimeter of these blobs. Does anybody have any recommendations how to do this with Python? import cv2 from skimage.measure import regionprops img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) image, contours, hierarchy = cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)`
type: AnsweredQuestion

http://stackoverflow.com/a/49714750
type: AcceptedAnswer
has body: I just found out that running pip install pygame without the sudo would actually install everything from scratch and could now be imported if you run import pygame from the python console. I don't know the reason for that funny behavior but it works for me now.
score: 0
accepted answer of: http://stackoverflow.com/q/49713943
type: Answer
answers question: http://stackoverflow.com/q/49713943

http://stackoverflow.com/comment/86390212
comment on: http://stackoverflow.com/a/49680289
has text: No, you're still mixing up the odb and mdb objects. So, actually according to my answer the odb object returns a symbolic constant, which doesn't have the pointOn member, and that's why you get an attribute error.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86439394
type: AnswerComment
has text: I don't remember all the details, as it was more than 15 years ago. Maybe we tried an a.out but found the ELF could be made smaller by cheating on the specification (leaving out certain header values or letting them be nonsense)? I do recall the end result was smaller than a normal ELF header should be (we just truncated it and it still worked). We didn't know much assembly or machine code at the start of that effort, we started with a Hello World program compiled from C and gradually made the binary smaller and smaller, reading the ELF spec and an x86 instruction set manual as we went.
comment on: http://stackoverflow.com/a/49712680
score: 0
type: Comment

http://stackoverflow.com/a/49650170
type: Answer
downvote count: 0
has body: @app.task(base=whatever) creates a new task class, so you end up with two distinct task instances. I'd stronly suggest you don't use task instances to persist state - this is ok for either read-only values or local caching (cf the db connection cache in the fine manual) but not for this use case. If you want to maintain shared state between tasks executions, persist your state in some database, read it at the start of the task function and update it when done (and don't forget to setup some lock so only one single task can access this resource at a time).
upvote count: 1
answers question: http://stackoverflow.com/q/49649735
has comment: http://stackoverflow.com/comment/86308653
score: 1

http://stackoverflow.com/a/49669356
has comment: http://stackoverflow.com/comment/86348971
has comment: http://stackoverflow.com/comment/86353056
has body: IIUC I think you need something like this data = pd.DataFrame({'col_A' : [1,2,3,4], 'col_B' : [1,2,np.NaN,4]}) #finding null values in columns and if atleat one null value is present printing it. print(data.columns.values[data.isnull().any()]) ['col_B'] Try this print(data.isnull().sum()[data.isnull().any()]) col_B 1 dtype: int64 For OP if data.apply(num_missing, axis=0)&gt;0: print('Yay') Since the line data.apply(num_missing, axis=0)&gt;0 produces a series not a single boolean value. If you use if statement for a series bool column, it will throw the traceback as: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-282-12bc35218d0e&gt; in &lt;module&gt;() ----&gt; 1 if data.apply(num_missing, axis=0)&gt;0: 2 print('Yay') ~\AppData\Local\conda\conda\envs\py3\lib\site-packages\pandas\core\generic.py in __nonzero__(self) 1119 raise ValueError("The truth value of a {0} is ambiguous. " 1120 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." -&gt; 1121 .format(self.__class__.__name__)) 1122 1123 __bool__ = __nonzero__ ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). The above if statement should be used along with either of a.empty, a.bool(), a.item(), a.any() or a.all(). So, at the end you get a boolean series with length of number of columns. Which is redundant. So better use the above mentioned ways instead of sticking to if statement. If you still want to execute inside a if statement. Try this: if (data.apply(num_missing, axis=0)&gt;0).any(): print(data.apply(num_missing, axis=0)[data.apply(num_missing, axis=0)&gt;0]) If there is no NaN values in any column then it would be helpful, otherwise the if statement will be redundant. Thank you.
answers question: http://stackoverflow.com/q/49668982
has comment: http://stackoverflow.com/comment/86348677
accepted answer of: http://stackoverflow.com/q/49668982
type: Answer
has comment: http://stackoverflow.com/comment/86348851
has comment: http://stackoverflow.com/comment/86353024
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49693406
has title: Write application for analysis of satellite imagery of dates from cvs file
has answer: http://stackoverflow.com/a/49694218
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: image
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49693477
possible better answer: http://stackoverflow.com/a/49693477
upvote count: 0
answer count: 2
downvote count: 4
tagged with: satellite
accepted answer: http://stackoverflow.com/a/49694218
score: -4
has body: I want to write an application/ software, preferrably using python, which will allow me to read in a csv file which contains dates and will then save satellite imagery from these dates. Before I attempt this I want to know if this actually possible using an existing web-based api from sources such as NASA? Sorry for a vague question but I have not been able to find any answers thus far and do not want to begin an impossible task as I am quite new to programming, so any advice on this question is much appreciated.
favorite count: 0
type: Question

http://stackoverflow.com/a/49693247
has comment: http://stackoverflow.com/comment/96388846
score: 12
has comment: http://stackoverflow.com/comment/86401473
upvote count: 12
has comment: http://stackoverflow.com/comment/86408112
type: AcceptedAnswer
has body: docker run only one CMD, so only the first CMD get executed, the work around is to create a bash script that execute both worker and beat and use the docker CMD to execute this script
downvote count: 0
has comment: http://stackoverflow.com/comment/86401333
has comment: http://stackoverflow.com/comment/86405545
has comment: http://stackoverflow.com/comment/86409016
has comment: http://stackoverflow.com/comment/86402153
has comment: http://stackoverflow.com/comment/101086902
has comment: http://stackoverflow.com/comment/86409244
answers question: http://stackoverflow.com/q/49693148
has comment: http://stackoverflow.com/comment/86402375
type: Answer
accepted answer of: http://stackoverflow.com/q/49693148
has comment: http://stackoverflow.com/comment/86409148

http://stackoverflow.com/comment/86383000
has text: Possible duplicate of [scipy.misc module has no attribute imread?](https://stackoverflow.com/questions/15345790/scipy-misc-module-has-no-attribute-imread)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49685160

http://stackoverflow.com/a/49616643
has comment: http://stackoverflow.com/comment/86240401
score: 9
upvote count: 9
accepted answer of: http://stackoverflow.com/q/49616600
type: Answer
answers question: http://stackoverflow.com/q/49616600
has body: Your __repr__s don't explicitly return anything. You build up a string, then throw it away, causing None to be implicitly returned instead. Just add a return: def __repr__(self): return super().__repr__() + "Grade: " + str(self._grade)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49654856
has comment: http://stackoverflow.com/comment/86319695
answer count: 3
has title: How to open a "root" file without typing your password every time?
has comment: http://stackoverflow.com/comment/86320476
downvote count: 0
has comment: http://stackoverflow.com/comment/86319774
tagged with: permissions
tagged with: sudo
favorite count: 0
has comment: http://stackoverflow.com/comment/86319967
type: Question
has comment: http://stackoverflow.com/comment/86320439
has comment: http://stackoverflow.com/comment/86319641
upvote count: 2
has comment: http://stackoverflow.com/comment/86319932
accepted answer: http://stackoverflow.com/a/49656188
has answer: http://stackoverflow.com/a/49657719
has comment: http://stackoverflow.com/comment/86320086
has answer: http://stackoverflow.com/a/49656188
tagged with: python
possible better answer: http://stackoverflow.com/a/49664706
has comment: http://stackoverflow.com/comment/86319878
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49664706
tagged with: linux
has body: I read this very interesting post, which is very close to what I need but not completely, they use it for shell scripting while I need the same solution mainly for a built-in Python function. Long story short: open("/dev/input/event3", "rb") This doesn't work out of the box because in order to open event3 I need to type my password every single time I execute my Python script, due to elevated privileges. What can I do so I don't have to type my password every time nor write my password in plane text in my script? I like the solution offered in the post I linked above, but this doesn't work because that would mean the -sort of speak- handle I get on this open file will be in another scope/python script. Any solutions? Thanks EDIT I tried modifying the privileges of my entire Python script, so that I don't need to type a password, but that didn't work neither. What I tried: 1) modify access rights sudo chown root:root /home/username/myscript.py sudo chmod 700 /home/username/myscript.py 2) modify visudo myusername ALL=(ALL) NOPASSWD: /home/username/myscript.py 3) trying to execute my python script now fails, altough it is clearly there myusername$ ./myscript bash: ./myscript: No such file or directory

http://stackoverflow.com/comment/86439478
score: 0
has text: Did you have a look at [How to obscure a line behind a surface plot in matplotlib?](https://stackoverflow.com/questions/41699494/how-to-obscure-a-line-behind-a-surface-plot-in-matplotlib)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49712546

http://stackoverflow.com/comment/86387721
has text: The `bytes` type is trying (and yet failing) to be 'helpful' when it produces a representation of its contents. If all your original `int` values align with printable ascii, then the representation will look like a string. Otherwise it looks like escaped hex and control codes.
comment on: http://stackoverflow.com/q/49687823
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49621092
type: Answer
answers question: http://stackoverflow.com/q/49620982
has comment: http://stackoverflow.com/comment/86252012
has comment: http://stackoverflow.com/comment/86252114
has comment: http://stackoverflow.com/comment/86249686
score: 0
has body: If you decide on Pandas, after loading the csv into a pandas dataframe, you can extract the last 1 or 2 characters from column 3 this way and prepend it to column 2 this way: df_city_names['col3'].map(lambda x: "".join(str(x)[-(2 if len(str(x)) &gt; 1 else 1 if len(str(x)) &gt; 0 else ''):])) + df_city_names['col2']
has comment: http://stackoverflow.com/comment/86250481
has comment: http://stackoverflow.com/comment/86251711

http://stackoverflow.com/comment/86220822
score: 0
has text: Yes, its working in Python2.7 & 3.5
type: Comment
comment on: http://stackoverflow.com/a/49606998
type: AnswerComment

http://stackoverflow.com/comment/86416740
has text: It worked really well, thanks. I have tried also an alpha shape (concave hull) around the `coordinates` but it was too on larger images slow compared with your proposed solution.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49618930
type: AnswerComment

http://stackoverflow.com/comment/86334748
type: Comment
has text: I do not have `jq` currently installed, and got an error installing jq: `error: [WinError 2] The system cannot find the file specified`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49662098

http://stackoverflow.com/comment/138091476
type: AnswerComment
comment on: http://stackoverflow.com/a/57860277
score: 1
type: Comment
has text: `int(es.cat.count(index_name, params={"format": "json"})[0]["count"])`

http://stackoverflow.com/q/49723373
has body: I tried to run a script which is a bot that google questions based on a screenshot. A little hard to explain but yeah. I tried to run the script by doing python answer_bot.py and I get this error Traceback (most recent call last): File "answer_bot.py", line 284, in &lt;module&gt; load_json() File "answer_bot.py", line 64, in load_json sample_questions = json.loads(open("Data/questions.json").read()) File "C:\Users\Phili\AppData\Local\Programs\Python\Python36-32\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 0x9d in position 94: character maps to &lt;undefined&gt; The script I'm trying to run is: https://github.com/sushant10/HQ_Bot/blob/12f774c9f4b231aa8a0326f133ac968febf5241b/answer_bot.py
has comment: http://stackoverflow.com/comment/86461942
downvote count: 1
has comment: http://stackoverflow.com/comment/86460785
favorite count: 0
has comment: http://stackoverflow.com/comment/86460411
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86461022
has comment: http://stackoverflow.com/comment/86460802
has comment: http://stackoverflow.com/comment/86460815
tagged with: python
linked to: http://stackoverflow.com/q/49640513
has comment: http://stackoverflow.com/comment/86462424
has comment: http://stackoverflow.com/comment/86462973
has comment: http://stackoverflow.com/comment/86461033
has comment: http://stackoverflow.com/comment/86461291
has comment: http://stackoverflow.com/comment/86460737
has comment: http://stackoverflow.com/comment/86460464
has comment: http://stackoverflow.com/comment/86460502
score: 0
linked to: http://stackoverflow.com/q/9233027
has title: I get strange error when running a python script
answer count: 0
has comment: http://stackoverflow.com/comment/86460988
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86460845
upvote count: 1

http://stackoverflow.com/comment/86305981
type: AnswerComment
has text: I have the result [(26970, 0]) does this mean the amount of occurances is 26970 or is that userID?
comment on: http://stackoverflow.com/a/49648845
type: Comment
score: 0

http://stackoverflow.com/q/49699833
has title: load file in package class, no package in import
has answer: http://stackoverflow.com/a/49699945
has body: Here is my problem, I created a package that contains a class, this one is a word parser, in this package I created a json containing a list of words. This file is called fr.json. The problem is that when I import the class with the command from bin.Parser.parser import Parser and I create the parser object it loads the file into the folder where I imported the class and not into the packages where the class is located. I could specify the direction with "os.path", but, if I want to move my package and reuse it for another project I am obliged to specify again the link from where "fr.json" is located. class Parser: def __init__(self, language): self.language = language + ".json" words_and_caracters = json.load(open('self.language')) self.LIST_WORD = words_and_caracters["LIST_WORD"] self.LIST_CARACTER = words_and_caracters["LIST_CARACTER"] .... The tree structure: ├── Parser │ ├── fr.json │ ├── __init__.py │ ├── parser.py ├── test.py Import in test: from Parser.parser import Parser parser = Parser('fr')
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49699945
type: Question
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/86510397
comment on: http://stackoverflow.com/a/49734010
score: 0
has text: Ah! This makes it easier to understand now! I think this should work without having to change my code a lot. Thanks a lot again @jezrael. You're helpful as always :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86513701
has text: C# is statically typed, so for that reason alone python syntax is not possible, because type of `subtuple` in your example cannot be determined at compile time (it can be ValueTuple<T>, or ValueTuple<T1, T2> etc).
type: QuestionComment
comment on: http://stackoverflow.com/q/49748514
score: 4
type: Comment

http://stackoverflow.com/comment/86328033
type: Comment
type: AnswerComment
has text: Oh, now I see that `x` contains *rows* of numbers in string format. You might have to specify the data types of each column in your call to `read_csv` to ensure they're imported as numeric, instead of string.
comment on: http://stackoverflow.com/a/49658648
score: 1

http://stackoverflow.com/comment/86413222
has text: What versions are you using? (redis, python) Although closed [this](https://github.com/celery/celery/issues/3436) seems related
comment on: http://stackoverflow.com/q/49699926
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49643676
type: Question
upvote count: 2
score: 2
has body: I have an array in python created from numpy as: a = [[1. 0.5 0.3 ... 0.71 0.72 0.73] [0. 0.4 0.6 ... 0.74 0.75 0.76] [0. 0.3 0. ... 0.72 0.73 0.74] ... [0. 0.2 0.3 ... 0.56 0.57 0.58] [0. 0.1 0.3 ... 0.67 0.68 0.69]] and another array b = [[1. 0.5 0.6 ... 0.74 0.75 0.76]] which i got from np.max(a, axis=0). Now I need the index of the array where the value in array 'a' is equal to the corresponding value in 'b' for which i used: locn = [] for i in range(0, len(b[0])): for j in range(0, len(a)): fav = np.where(a[j][i] == b[0][j]) locn.append(fav) print(locn) I get the output as [(array([0]),), (array([0]),), (array([0]),), (array([0]),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([], dtype=int64),), (array([0]),), (array([0]),), (array([0]),), (array([0]),), (array([], dtype=int64),), ............ I could have used np.where(a == np.max(a)) to get the location on maximum, but that is not my problem. I need the exact location (like 1st element of 1st array.. or something like that) append the index of array in loc[]. For example: for the first round 1 is the highest, i just need to append the index value 0 to a new list locn[] as 0 is the index for first round where the element of inner array is equal to the maximum value. How can I do this? Thanks in advance.
answer count: 2
tagged with: arrays
downvote count: 0
has title: Getting the location of value from numpy.where() as single value and append it to another array
tagged with: python
has answer: http://stackoverflow.com/a/49643735
tagged with: indexing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49643735
possible better answer: http://stackoverflow.com/a/49643916
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/49643916

http://stackoverflow.com/comment/86442103
type: AnswerComment
comment on: http://stackoverflow.com/a/49714471
type: Comment
has text: Awesome. Worked great. Thank you so much.
score: 0

http://stackoverflow.com/comment/86443199
score: 0
type: AnswerComment
has text: And you didn't render a template file in it.
comment on: http://stackoverflow.com/a/49714902
type: Comment

http://stackoverflow.com/comment/86396881
comment on: http://stackoverflow.com/q/49691443
score: 0
type: Comment
has text: @PauloAlmeida my images are saving with this method in models.py def get_image_filename(instance, filename): title = instance.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename)
type: QuestionComment

http://stackoverflow.com/comment/86410008
type: QuestionComment
comment on: http://stackoverflow.com/q/49698418
type: Comment
score: 2
has text: You haven't listed the error, stack trace, or line numbers, nor have you included the code for 'get_heuristics()'

http://stackoverflow.com/comment/86562206
type: QuestionComment
comment on: http://stackoverflow.com/q/49737339
score: 0
has text: I thought I tied widgets and python code already. Or did I misunderstood your comment?
type: Comment

http://stackoverflow.com/a/49647776
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49647444
has body: One way would be to install signal handlers: https://docs.python.org/3/library/signal.html, for example, for SIGHUP (the hang up signal)
type: Answer

http://stackoverflow.com/a/49638050
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49637805
has body: data = '''asdf:15.3 eazzz:31.12 qw:1.65 adasf:7.3''' # convert string to list lst = data.split('\n') #sort list of data by two things. first the string part second number part print '\n'.join(sorted(lst, key=lambda item:(item.split(':')[0],float(item.split(':')[1])), reverse = True)) output: qw:1.65 eazzz:31.12 asdf:15.3 adasf:7.3
type: Answer

http://stackoverflow.com/comment/86515550
has text: I had even tried returning simple String but still the issue is the same. I don't find any error in the Python Script hindering the issue and not any in the browser console as well. In fact I just included `alert('Completed!')` inside the javascript after the ajax call. What i believed is that the `alert('Completed')` should be called once the ajax call is completed with corresponding success or failure message that has been acted upon. But instead what i get is upon button click the flask gets triggered and soon after it is triggered it shows the alert message. (1/2)
type: Comment
comment on: http://stackoverflow.com/q/49746131
type: QuestionComment
score: 0

http://stackoverflow.com/q/49618983
has title: Delete a node and all of its children from a binary tree, without using a tree data structure
has comment: http://stackoverflow.com/comment/86245938
has comment: http://stackoverflow.com/comment/86246948
tagged with: arrays
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49620793
has comment: http://stackoverflow.com/comment/86258672
tagged with: binary-tree
tagged with: tree
has answer: http://stackoverflow.com/a/49620793
has comment: http://stackoverflow.com/comment/86247736
type: AnsweredQuestion
tagged with: python-2.7
has body: Suppose I have an array as an input, say array = -1 0 0 1 2 1 3 5 5 6 6 (This is actually a parent array representation of a binary tree) The tree looks like this in this case: 0 / \ 1 2 / \ / 3 5 4 / / \ 6 7 8 / \ 9 10 And I have another input, say input = 1 (this is a node to be deleted from the tree) What I want to achieve is basically: Delete array[input] Search for the input variable in the remaining array Delete all the elements with value = input Store the indices of the deleted values Search the remaining array for value = indices Delete those elements and store their indices Repeat from step 5 until nothing more can be deleted This is the algorithm I have thought of to delete a node and all of its children. So basically for the sample input given above, the output should be: -1 0 2 I have opted not to use a tree data structure because I feel that constructing the tree from the parent array, then searching for the node and deleting it might be slower (although I may be wrong). I haven't been able to achieve this in code though, I just have the logic. Whenever I am trying to write the pseudo code, one or more problems in my logic become visible. Which is why I have no concrete code to post here yet. So I have no idea how long this will take. This is a question for a class assignment and just using a tree data structure will work, but I want to implement a better solution in this case if possible. Any help is appreciated. No need to give me complete code. Just some pointers would be enough.
has comment: http://stackoverflow.com/comment/86246916
score: 1
has comment: http://stackoverflow.com/comment/86246610
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86432720
score: 1
has text: This is almost identical to my answer.
comment on: http://stackoverflow.com/a/49709607
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86343307
type: Comment
type: QuestionComment
has text: @PeterDolan the function in the question is all the code I have in my file. I am currently using python 3.6.5.
score: 0
comment on: http://stackoverflow.com/q/49639986

http://stackoverflow.com/comment/86524059
score: 0
type: Comment
type: QuestionComment
has text: I expect to grab text from file `zen.md` @jonrsharpe using regex
comment on: http://stackoverflow.com/q/49751151

http://stackoverflow.com/q/49695382
upvote count: 2
has comment: http://stackoverflow.com/comment/86406176
has body: I have data that is in 3 columns (name, question, response) that resulted from judging a student research symposium. There are 2 possible choices for level (graduate/undergraduate), and 5 for college (science, education, etc.) What I need to do is take the average of the numerical responses for a given name, and sort by average numerical score for that person to output a table containing: College Level Rank science graduate 1st science graduate 2nd science graduate 3rd science undergrad 1st ... education graduate 1st ... education undergrad 3rd Here's a sample data table: name question response Smith, John Q1 10 Smith, John Q2 7 Smith, John Q3 10 Smith, John Q4 8 Smith, John Q5 10 Smith, John Q8 8 Smith, John level graduate Smith, John colleg science Smith, John Q9 4 Jones, Mary Q3 10 Jones, Mary Q2 10 Jones, Mary Q1 10 Jones, Mary Q4 10 Jones, Mary level undergraduate Jones, Mary college education Jones, Mary Q6 10 Jones, Mary Q7 10 Jones, Mary Q9 10 A talented student did this for us in excel using pivot tables, but I'm sure this can be done using pandas, and I'm very curious how to do it (I'm quite new to pandas). The tricky part is all the 'useful' information is in that 3rd column.
has answer: http://stackoverflow.com/a/49695944
has comment: http://stackoverflow.com/comment/86403736
type: UnansweredQuestion
tagged with: python
has title: pandas sort/average numerical/text data in single column
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/49697247
score: 0
answer count: 2
downvote count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/86403567
type: Question

http://stackoverflow.com/q/49720605
type: Question
tagged with: numpy
score: 5
answer count: 1
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49738373
has answer: http://stackoverflow.com/a/49738373
has title: Pixel coordinates vs Drawing Coordinates
type: AnsweredQuestion
tagged with: python-imaging-library
upvote count: 5
has comment: http://stackoverflow.com/comment/86455565
has body: In the code snippet below, passing x and y values puts the dot in (y,x) coordinates while the drawing is done in (x,y). What is the correct way to set up the drawing buffer so it's placing pixels and drawing in the same coordinate system? from PIL import Image, ImageDraw def visual_test(x, y): grid = np.zeros((100, 100, 3), dtype=np.uint8) grid[:] = [0, 0, 0] grid[x, y] = [255, 0, 0] img = Image.fromarray(grid, 'RGB') draw = ImageDraw.Draw(img) draw.line((x, y, x, y-5), fill=(255,255,255), width=1) img.show()
favorite count: 0

http://stackoverflow.com/q/49606662
tagged with: webhooks
has comment: http://stackoverflow.com/comment/86253244
has answer: http://stackoverflow.com/a/70557884
has answer: http://stackoverflow.com/a/52198687
favorite count: 0
tagged with: python-2.7
answer count: 3
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86253315
has comment: http://stackoverflow.com/comment/86257667
tagged with: python
has body: Without using the requests module, how can I send messages to a Discord webhook? I have tried following code: import urllib2 import json url = 'webhook url' values = {"username": "Bot", "text": "This is a test message."} data = json.dumps(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() This returns following error: urllib2.HTTPError: HTTP Error 403: Forbidden
has title: Send data to a Discord webhook
tagged with: discord
has answer: http://stackoverflow.com/a/70562877
type: Question
upvote count: 2
tagged with: urllib2
has comment: http://stackoverflow.com/comment/86220947
type: UnansweredQuestion

http://stackoverflow.com/q/49627457
type: AnsweredQuestion
tagged with: python-2.7
has body: What is correct way to filter out data from functions? Should I try to compress everything as much as possible (search_query) or should I filter through list everytime there is new argument that needs to be included (search_query2). More arguments I have, quicker I become more confused how to deal with this problem. Example: import os query = "" my_path = os.getcwd() def search_query(query, path, extensions_only=False, case_sensitive=False): results = [] if extensions_only is True: for f in os.listdir(path): if case_sensitive: if f.endswith(query): results.append(os.path.join(path, f)) else: if f.endswith(query): results.append(os.path.join(path, f).lower()) elif case_sensitive is not True: for f in os.listdir(path): if query.lower() in f.lower(): results.append(os.path.join(path, f)) return results results = search_query("_c", my_path) print(results) # Alternative way to deal with this def search_query2(query, path, extensions_only=False, case_sensitive=False): results = [] for f in os.listdir(path): results.append(os.path.join(path, f)) if extensions_only: filtered_lst = [] for part in results: if part.endswith(query): filtered_lst.append(part) results = filtered_lst if case_sensitive: filtered_lst = [] for part in results: if query in part: filtered_lst.append(part) results = filtered_lst elif not case_sensitive: filtered_lst = [] for part in results: if query.lower() in part.lower(): filtered_lst.append(part) results = filtered_lst print(results) return results search_query2("pyc", my_path, case_sensitive=True)
score: 0
has answer: http://stackoverflow.com/a/49627785
possible better answer: http://stackoverflow.com/a/49627785
has title: How to deal with multiple arguments in function?
has answer: http://stackoverflow.com/a/49627758
accepted answer: http://stackoverflow.com/a/49627758
linked to: http://stackoverflow.com/q/364802
linked to: http://stackoverflow.com/q/3207219
has answer: http://stackoverflow.com/a/49628066
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49627903
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/86262144
tagged with: search

http://stackoverflow.com/comment/128566436
comment on: http://stackoverflow.com/a/59462478
type: AnswerComment
has text: For case with concurrent invocations of the lambda - won't it create collisions using same '/tmp/yourfilename.txt' ?
score: 1
type: Comment

http://stackoverflow.com/comment/86437372
type: QuestionComment
has text: Why don't you render `template` with `render()` method with `context` , so you can easily loop through it ?
comment on: http://stackoverflow.com/q/49711851
score: 0
type: Comment

http://stackoverflow.com/comment/86483929
comment on: http://stackoverflow.com/q/49734856
type: QuestionComment
has text: Have you tried to benchmark the list comprehension against a call to apply (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html). You may also have a look at https://pandas.pydata.org/pandas-docs/stable/enhancingperf.html.
type: Comment
score: 0

http://stackoverflow.com/q/49738396
has answer: http://stackoverflow.com/a/49738546
accepted answer: http://stackoverflow.com/a/49738546
has title: REGEX for blocks
score: -4
tagged with: python
tagged with: regex
has body: I have a lot of START/STOP text blocks in a text file. start value1 as5q value3 dd9w type b value6 dp1p stop start value1 as value2 er type a stop start value1 as5 value2 er2 type c value4 dd1 stop I need to extract the value1's value when the type is "a". Please, could you help me? I tried a lot of ways but I'm still newbie with regex. Thanks in advance.
has comment: http://stackoverflow.com/comment/86491406
type: AnsweredQuestion
upvote count: 0
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/49739480
possible better answer: http://stackoverflow.com/a/49739480
has comment: http://stackoverflow.com/comment/86491432
has comment: http://stackoverflow.com/comment/86491249
favorite count: 0
type: Question

http://stackoverflow.com/q/49646236
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/86301459
has comment: http://stackoverflow.com/comment/86301982
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49647270
score: 1
has comment: http://stackoverflow.com/comment/86301078
answer count: 1
upvote count: 1
favorite count: 0
tagged with: aws-lambda
type: Question
has comment: http://stackoverflow.com/comment/86301317
has body: I'm trying to use a Python 3.6 AWS Lambda function to parse Windows logs sent from Cloudwatch. These arrive in Lambda as JSON, so I extract the field I want using: for i in data['logEvents'] message = json.dumps((i['message'])) which gives me this in my message string: " 2 4 0 0x80000000000000 <TimeCreated SystemTime='2018-04-03T15:33:57.186213000Z'/> 25371 System EC2AMAZ-1KJC0H1 <Security/> Geolocation positioning has been disabled by the user. Information Info Classic \u0000" I am then trying to turn this string into XML to use with either xmltodict or xml.etree.ElementTree, but both of those return a malformed XML error because of the \u0000 at the end. So I then run this to remove the unicode: xml = re.sub(u'(\u0000)', "", message) which works fine on my computer in my local python console, and bothxmltodict & xml.etree.ElementTree can then work with the newly created xmlstring. But when I run the re.sub command in the Lambda function, the \u0000 remains at the end of the string. Am I missing something obvious?? Adding the full output of print(i['message']) 7036 0 4 0 0 0x8080000000000000 <TimeCreated SystemTime='2018-04-03T15:31:31.854941100Z'/> 25365 <Correlation/><Execution ProcessID='712' ThreadID='4768'/> System EC2AMAZ-1KJC0H1 <Security/> Volume Shadow Copy running 5600530053002F0034000000 The Volume Shadow Copy service entered the running state. Information Microsoft-Windows-Service Control Manager Classic \u0000 Many thanks, Dave
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49647270
has title: AWS Lambda Python function remove trailing unicode
downvote count: 0

http://stackoverflow.com/a/49682351
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/86381649
upvote count: 3
has comment: http://stackoverflow.com/comment/86378582
has comment: http://stackoverflow.com/comment/86379001
has comment: http://stackoverflow.com/comment/86378741
downvote count: 0
has comment: http://stackoverflow.com/comment/86378590
answers question: http://stackoverflow.com/q/49673030
has body: We only need to test 1 in 625 candidate numbers. Either solution A: upper_limit = 10**4 lower_limit = int(10**3.5) + 1 rem = lower_limit % 625 if rem &gt; 0: lower_limit = lower_limit - rem + 625 for n in xrange(lower_limit, upper_limit, 625): if n % 16 in [1, 15]: print {1: n, 15: n+1}[n%16] break or Solution B: print (1 * (-39) * 16 + 0 * 1 * 625) % 10000 Read on for explanation. Starting from the brute-force list-comprehension that tests all candidates: from math import ceil [n for n in xrange(ceil(10**3.5), 10000) if (n*n) % 10000 == n] (The ceil rounds the square root of 10**7 up to nearest integer). (Notice that 10000 is the first number whose square has 9 digits, and the loop will not test that number.) ... or if you'd like to early-terminate as soon as you find a solution: for n in xrange(ceil(10**3.5), 10000): if (n*n) % 10000 == n: print n break But consider: we are looking for numbers n**2 - n = n*(n-1) which are divisible by 10**4 = 2**4 * 5**4. either n or n-1 is odd; so the other one would have to be divisible by the full 2**4 = 16. Similarly, you can't have both n and (n-1) be divisible by 5; so we need either n or (n-1) to be divisible by 5**4 = 625. if either one (n or (n-1)) is divisible by both 625 and 16, then that number is divisible by 10000. No such number has four digits, so it must be that either n or (n-1) is divisible by 625, and the other one is divisible by 16. We can thus restrict our search space to looking only at multiples of 625 which have four digits; we just have to be careful to remember that the multiple of 625 might be either n or (n-1); the other one has to be divisible by 16. So: upper_limit = 10**4 lower_limit = ceil(10**3.5) rem = lower_limit % 625 if rem &gt; 0: lower_limit = lower_limit - rem + 625 for n in xrange(lower_limit, upper_limit, 625): if (n-1) % 16 == 0: print n break if (n+1) % 16 == 0: print n+1 break Or if you test n instead of (n-1), and combine both condition branches into n % 16 in [1, 15], and for compac…

http://stackoverflow.com/comment/86364383
has text: yeah, it's running. But the coefficient values are far away from what excel gives. @Eolmar I defined y = df[3]
comment on: http://stackoverflow.com/q/49674212
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49683500
upvote count: 3
has answer: http://stackoverflow.com/a/49683542
accepted answer: http://stackoverflow.com/a/49683588
has title: numpy.ones results in red, green, blue, and black bars on image
has body: I have the following code: from PIL import Image import numpy as np a = np.ones((512, 256, 3)).astype(int)*255 image = Image.fromarray(a, "RGB") image.save("test.png", "PNG") I would expect this to result in a white image of size 512x256. Instead, I get this: For some reason, this image is a series of bars rather than a solid color. What am I doing wrong? Is it the format of the numpy array?
has answer: http://stackoverflow.com/a/49683588
tagged with: image
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/49683542
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: python-imaging-library

http://stackoverflow.com/comment/86263644
score: 0
has text: No, there is no solution what you are searching... You need to change your collection structure, so single document could not expand (during time) to that 16MB. One document should be one measure of one sensor or if sensor is sending information f.ex. every second, then one document have data of one sensor minute (60 measures)..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49627975

http://stackoverflow.com/a/49767916
has comment: http://stackoverflow.com/comment/86567978
has body: As pointed out in comments, regex is your best friend here, here is the sample approach import re count=0 fl=open('C:\\Users\\Zee\\Downloads\\testLog.txt','r') fillines=fl.readlines() fl.close() for i in fillines: if re.search(r'status=404',i): count+=1 to make a list of all the paths in logs having status as 404 we can again use regex import re count=0 lst=[] fl=open('C:\\Users\\Zee\\Downloads\\testLog.txt','r') fillines=fl.readlines() fl.close() for i in fillines: if re.search(r'status=404',i): count+=1 path=re.search(r'path="[/\w+/]+"',fillines[0]).group(0)#get path using regex path=path.split("path=")[1] #since we only want the url path=path.replace('"','') #we dont want the quotes in log lst.append(path)#since we only want the url
has comment: http://stackoverflow.com/comment/86568038
has comment: http://stackoverflow.com/comment/86600274
type: Answer
accepted answer of: http://stackoverflow.com/q/49742047
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86613735
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49742047
has comment: http://stackoverflow.com/comment/86571967

http://stackoverflow.com/q/49671889
has title: Not being able to print a value corresponding to a particular "div" element using Beautiful Soup
accepted answer: http://stackoverflow.com/a/49720904
type: AnsweredQuestion
answer count: 2
has body: I want to print both the CVE-IDs "CVE-2013-2566" and "CVE-2015-2808" under References and "tcp 23" which corresponds to Unencrypted telnet server using beautiful soup. Couldn't think of a logic for that. 42263 - Unencrypted Telnet Server Risk Factor Medium Plugin Information: Published: 2009/10/27, Modified: 2015/10/21 **References** CVE CVE-2013-2566 CVE CVE-2015-2808 Plugin Output tcp/23 This is what I have written and I am stuck where I have put the comments. I am very much a beginner in bs4 so just bear with me please and I have to submit a report tomorrow so, please help. from bs4 import BeautifulSoup import csv import urllib.request as urllib2 with open(r"C:\Users\sourabhk076\Documents\CHIDRMUM_DR8016CHI1_CTSINWDB01_9xtqpj.html") as fp: soup = BeautifulSoup(fp.read(), 'html.parser') f = csv.writer(open("Report.csv", "w")) f.writerow(["Observation", "Port", "CVE-ID"]) medium = soup.find_all('div', attrs={'style':'box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;'}) ####this will search for text "Unencrypted telnet server"#### for x in medium: port = x.find('h2') cve = x.find('div', class_='table-wrapper see-also').findAll('tr') ######## don't know what to do next ############# obsv = x.text portd = port.text print([obsv,portd,cve])
has answer: http://stackoverflow.com/a/49720904
possible better answer: http://stackoverflow.com/a/49672131
score: 0
has answer: http://stackoverflow.com/a/49672131
tagged with: beautifulsoup
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/comment/86452299
comment on: http://stackoverflow.com/a/49719662
has text: He said he knows how to replace using for loop,but he did not know how to create substitute function.At no point he said he did not want to use replace function
type: Comment
score: 0
type: AnswerComment

raspbian
tags question: http://stackoverflow.com/q/49749648
type: Tag
tags question: http://stackoverflow.com/q/49612117
tags question: http://stackoverflow.com/q/49684656
tag name: raspbian
tags question: http://stackoverflow.com/q/49723350

http://stackoverflow.com/comment/86504332
score: 0
comment on: http://stackoverflow.com/a/49716089
type: Comment
type: AnswerComment
has text: James when. I am trying your function the output is "name maxlen is not defined". Why?

http://stackoverflow.com/a/49650697
downvote count: 0
has body: From the documentation, you can use the method query_radius: Query for neighbors within a given radius: import numpy as np np.random.seed(0) X = np.random.random((10, 3)) # 10 points in 3 dimensions tree = KDTree(X, leaf_size=2) print(tree.query_radius(X[0], r=0.3, count_only=True)) ind = tree.query_radius(X[0], r=0.3) # indices of neighbors within distance 0.3 This work with sklearn version 19.1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49650149
score: 1
accepted answer of: http://stackoverflow.com/q/49650149
type: AcceptedAnswer

http://stackoverflow.com/a/50138915
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49725455
has body: The simplest and quickest way will probably be to add GUI directly to your Python App. If you don't need it to be pretty or to run on mobile, I'd say go with TKinter for simplicity. Then, connect to wherever the App is located and control it remotely. Adding another component that will communicate with your Python App introduces a higher level of complexity which I think is redundant in this case. You didn't specify in details what kind of data you will require the app to display. If this includes any form of charting, I'd use an existing charting software such as Ninjatrader / Multicharts / Sierracharts to run my indicators and see the positions status, and restrict the GUI of the python app to adjusting the trading parameters and reporting numerical stats.
type: Answer
has comment: http://stackoverflow.com/comment/88259433

http://stackoverflow.com/q/49668991
has comment: http://stackoverflow.com/comment/86348032
tagged with: python
has title: Python : find difference between two arrays in python
has answer: http://stackoverflow.com/a/49669529
has comment: http://stackoverflow.com/comment/86348281
has answer: http://stackoverflow.com/a/49669263
tagged with: python-2.7
has answer: http://stackoverflow.com/a/64992516
has comment: http://stackoverflow.com/comment/86348065
downvote count: 0
has body: I have two arrays in python. arr1 = [(7, 0.78, 7920), (8, 0.9, 9000)] arr2 = [(7, 1.68, 8460)] In this array first value is ID (7,8,7).I want result basis on ID. If ID same then get difference between others two value. Between arr1 and arr2 ID 7 is same then will be subtraction (1.68-0.78 = 0.9) And (8460-7920 = 540) otherwise it will be same. How to get Result like that ? diffArray = [(7, 0.9, 540), (8, 0.9, 9000)]
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49669302
has answer: http://stackoverflow.com/a/49669474
favorite count: 0
has comment: http://stackoverflow.com/comment/86348168
type: Question
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/comment/86482820
type: QuestionComment
has text: You should give at least one valid and one invalid example of a document as well as the schema you got so far. i have the impression that you're overcomplicating your task.
type: Comment
comment on: http://stackoverflow.com/q/49658391
score: 0

http://stackoverflow.com/comment/86529656
comment on: http://stackoverflow.com/q/49630662
type: QuestionComment
has text: In my experience, I've not found many code generators that produce anything useful. Have you considered moving the python code into something like jython and just natively calling into the existing classes?
score: 0
type: Comment

http://stackoverflow.com/q/49613309
score: 0
has body: i am trying to define c a class for node that will look like : 3, [5,8,2] What i am doing wrong? -------------- # Node Class class Node(): def __init__(self,name, neighbors): self.name = name self.neighbors = [] self.n_records = 0 def __str__(self): s = "{} (#{}): name: {:3}, neighbors: {}" return s.format(self.name,self.neighbors) def add_record(self, rec): self.records.append(rec) self.n_records += 1 IndexError Traceback (most recent call last) &lt;ipython-input-18-6d6c9b659eeb&gt; in &lt;module&gt;() 4 nodes = Node(1,[5,6]) 5 ----&gt; 6 print(nodes) &lt;ipython-input-17-f3f5914a055f&gt; in __str__(self) 11 def __str__(self): 12 s = "{} (#{}): name: {:3}, neighbors: {}" ---&gt; 13 return s.format(self.name,self.neighbors) 14 15 def add_record(self, rec): IndexError: tuple index out of range
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49613926
tagged with: python-3.x
type: UnansweredQuestion
has title: error - tuple index out of range
tagged with: python
has comment: http://stackoverflow.com/comment/86233172
has comment: http://stackoverflow.com/comment/86233244

http://stackoverflow.com/comment/86531039
score: 1
type: Comment
type: AnswerComment
has text: @Kassandstorm with `askopenfilename` you can only select 1 file, so you don't need the loop and can write `E2.insert(0, file)`
comment on: http://stackoverflow.com/a/49757531

http://stackoverflow.com/comment/86354866
comment on: http://stackoverflow.com/a/49671172
type: AnswerComment
score: 0
has text: I want dic={'a':1,'a':5}...I know that a dictionary can't hold multiple values for same key but is there any other way in which this can be done. By creating a list or a dataframe.
type: Comment

http://stackoverflow.com/comment/86245729
type: AnswerComment
comment on: http://stackoverflow.com/a/49616358
score: 1
type: Comment
has text: Which pattern you use depends on how you want the results represented. Multiple asserts in a single test still roll up as 1 test that passed or failed, and anything after the first assertion failure will not be executed. If you want more granular results indicating the result of each, then you'll want to model them as separate tests.

http://stackoverflow.com/comment/86341929
type: Comment
comment on: http://stackoverflow.com/a/49666057
has text: @piRSquared - `lazers` ? not `list` ?
type: AnswerComment
score: 0

http://stackoverflow.com/a/49681509
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49673030
downvote count: 0
has body: Here's the one-line implementation, and it excludes 97.24% of candidates: import itertools step = itertools.cycle((24, 1, 24, 51)) [x for x in range(3176, 10000, next(step)) if str(x*x)[-4:] == str(x) ] Call the number abcd. You can optimize by restricting the last two digits cd, there are only 4 legal possibilities, excluding 96% of candidates for cd. Similarly we only need to test 31 <= ab < 100, excluding 31% of candidates for ab. Thus we excluded 97.24% cd_cands = set((n**2) % 100 for n in range(0,99+1) if ((n**2 % 100) == n)) cd_cands = sorted(cd_cands) [0, 1, 25, 76] for ab in range(31,99+1): for cd in cd_cands: n = ab*100 + cd if n**2 % 10**4 == n : print("Solution: {}".format(n)) #break if you only want the lowest/unique solution ... Solution: 9376 (Sure you could squeeze that into a one-line list comprehension, but it would be ugly) Now we can separate the multiple for-loops with the following observations: strictly we only need to start testing at the first legal candidate above 3162, i.e. 3176. Then, we increment by successively adding the steps (100-76, 1-0, 25-1, 76-25) = (24, 1, 24, 51) import itertools step = itertools.cycle((24, 1, 24, 51)) abcd = 3176 while abcd < 10**4: if abcd**2 % 10000 == abcd: print("Solution: {}".format(abcd)) abcd += next(step) and again that can be reduced to the one-liner(/two-liner) shown at top. UPDATE: As @mathmandan shows, we can improve further to step = itertools.cycle((1, 624)), eliminating 99.68% of candidates. And start searching at 625 * 6 = 3750
has comment: http://stackoverflow.com/comment/86378996
has comment: http://stackoverflow.com/comment/86376991
score: 5

http://stackoverflow.com/a/49803118
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87201176
answers question: http://stackoverflow.com/q/49728797
has body: Please see documentation for Mac that says Note: As of version 1.2, TensorFlow no longer provides GPU support on macOS. That means you are not supposed to install the GPU version if you intend to use version 1.2 and higher. Simply because its not officially supported. In your case you are supposed to stick with version &lt; 1.2. This is the question with many accepted answers on Stackoverflow per official site
type: Answer

subprocess
tags question: http://stackoverflow.com/q/49709993
tag name: subprocess
tags question: http://stackoverflow.com/q/49756273
tags question: http://stackoverflow.com/q/49706015
tags question: http://stackoverflow.com/q/49621612
type: Tag
tags question: http://stackoverflow.com/q/49687815
tags question: http://stackoverflow.com/q/49702758
tags question: http://stackoverflow.com/q/49742624
tags question: http://stackoverflow.com/q/49704105
tags question: http://stackoverflow.com/q/49696238
tags question: http://stackoverflow.com/q/49748702
tags question: http://stackoverflow.com/q/49675767
tags question: http://stackoverflow.com/q/49746712
tags question: http://stackoverflow.com/q/49728472
tags question: http://stackoverflow.com/q/49713058
tags question: http://stackoverflow.com/q/49728090
tags question: http://stackoverflow.com/q/49746499
tags question: http://stackoverflow.com/q/49738508
tags question: http://stackoverflow.com/q/49709826
tags question: http://stackoverflow.com/q/49615928
tags question: http://stackoverflow.com/q/49691515
tags question: http://stackoverflow.com/q/49719673
tags question: http://stackoverflow.com/q/49675778
tags question: http://stackoverflow.com/q/49722235
tags question: http://stackoverflow.com/q/49641453

http://stackoverflow.com/q/49619443
has body: I am very new to pandas and have a data frame similar to the below import pandas as pd df = pd.DataFrame({'id': ["1", "2", "3","4","5"], 'mill': ["Company A Palm Oil Mill – Special Company A of CC Ltd", "Company X POM – Company X Ltd","DDDD Mill – Company New and Old Ltd", "Company Not Special – R Mill","Greatest Company – Great World POM"]}) id mill 0 1 Company A Palm Oil Mill – Special Company A of... 1 2 Company X POM – Company X Ltd 2 3 DDDD Mill – Company New and Old Ltd 3 4 Company Not Special – R Mill 4 5 Greatest Company – Great World POM What I would like to get from the above data frame is something like the below: Is there an easy way to extract those substrings into the same column. The mill name can sometimes be before and other times after the '-' but will almost always end with Palm Oil Mill, POM or Mill.
has comment: http://stackoverflow.com/comment/86246088
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49619521
has comment: http://stackoverflow.com/comment/86246405
has answer: http://stackoverflow.com/a/49619521
has comment: http://stackoverflow.com/comment/86246459
tagged with: python
tagged with: text-processing
accepted answer: http://stackoverflow.com/a/49619612
tagged with: substring
type: AnsweredQuestion
has title: pandas: extract specific text before or after hyphen, that ends in given substrings
has comment: http://stackoverflow.com/comment/86246061
has answer: http://stackoverflow.com/a/49619612
score: 0
has answer: http://stackoverflow.com/a/49619793
answer count: 3
tagged with: pandas

bdd
tag name: bdd
type: Tag
tags question: http://stackoverflow.com/q/49648506

http://stackoverflow.com/comment/89812082
type: AnswerComment
has text: Hi R.S., thanks for this workaround - I was having a similar issue and it's good to know that it's possible to manually download Keras models. By any chance have you found a permanent solution to your problem?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49733570

http://stackoverflow.com/comment/86396464
type: QuestionComment
comment on: http://stackoverflow.com/q/49692151
score: 1
type: Comment
has text: In the python script, instead of running all that you can just do `' '.join(users)` for creating the string out of the list

http://stackoverflow.com/q/49649393
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49649521
has body: I have a data set of dates: (u'x', datetime.datetime(2018, 1, 5, 4, 49, 30)) (u'y', datetime.datetime(2018, 1, 5, 9, 59, 10)) (u'x', datetime.datetime(2018, 1, 13, 10, 23, 17)) (u'y', datetime.datetime(2018, 1, 15, 17, 16, 34)) (u'x', datetime.datetime(2018, 1, 22, 11, 9, 55)) (u'y', datetime.datetime(2018, 1, 22, 14, 24, 59)) Here is my code to subtract the date: for x in range(len(y)): if y[x][0] == 'x' and y[x+1][0] != 'y': #subtract the date print y[x+1][1] - y[x][1] The code above prints below: 5:09:40 2 days, 6:53:17 3:15:04 My question is how do I add them all up and convert them as total in hours? Appreciate the help on this.
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3
tagged with: datetime
has title: How to add the subtracted date value in Python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49649521
answer count: 1

http://stackoverflow.com/a/49638656
upvote count: 2
type: Answer
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/49638617
has body: If you unroll seen[x] += 1 into seen[x] = seen[x] + 1, the problem with your code is obvious: you're trying to access seen[x] before you've assigned to it. Instead, you need to check if the key exists first: seen = {} for x in ['one', 'two', 'three', 'one']: if x in seen: seen[x] += 1 # we've seen it before, so increment else: seen[x] = 1 # first time seeing x

http://stackoverflow.com/q/49660129
favorite count: 0
has body: I have been struggling for a few days now with a python application where I am expecting to look for a file or files in a folder and iterate through the each file and each record in it and create objects to be persisted on a Janusgraph database. The particular OGM that I am using, requires that the transactions with the database are done in an asynchronously using asyncio. I have read a lot of blogs, posts about asyncio and I think I understand the concept of async, await, tasks, etc... In my application I have defined several functions that handle different parts of the processing: Retrieves the list of all files available Select one file for processing Iterates through the selected file and reads a line/record for processing Receives the record, determines parses the from in and calls several other functions that are responsible for creating the Model objects before they are persisted to the database. For instance, I different functions that creates: User, Session, Browser, DeviceUsed, Server, etc... I understand (and I may be wrong) that the big advantage of using asyncio is for situations where the call to a function will block usually for I/O, database transaction, network latency, etc... So my question is if I need to convert all my functions into coroutines and schedule to run through the event loop, or just the ones that would block, like committing transaction to the database. I tried this approach to begin with and had all sorts of problems.
type: Question
has comment: http://stackoverflow.com/comment/86329984
accepted answer: http://stackoverflow.com/a/49665627
tagged with: python-asyncio
score: 6
tagged with: goblin
tagged with: janusgraph
tagged with: python
has title: asyncio - how many coroutines?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49665627
answer count: 1
upvote count: 7
downvote count: 1

http://stackoverflow.com/comment/106790920
type: AnswerComment
has text: Upvoted and thanks for doing it on OpenCV. I was looking for an OpenCV implementation.
type: Comment
comment on: http://stackoverflow.com/a/49733099
score: 0

http://stackoverflow.com/comment/86406996
comment on: http://stackoverflow.com/q/49694128
score: 1
has text: How much memory is your unneeded second return value occupying? Is it actually a concern?
type: Comment
type: QuestionComment

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/49635758

http://stackoverflow.com/comment/86289644
has text: Thanks for this thorough explanation. My guess is also that someone just renamed it to be a little clearer. Not even to micro-optimize. I'll have to look into which ones actually matter though.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49640908

http://stackoverflow.com/comment/86339416
has text: Can you actually mix `turtle` and `PySide` in a single program like this?
comment on: http://stackoverflow.com/q/49664780
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86381437
comment on: http://stackoverflow.com/a/49684466
has text: So given a list [1,2,3,'a'], and given 'a', you want a function to return what? A list of lists? If so, list the list of lists exactly as they should appear. I understand loops just fine, but you need to phrase the question better so people understand what result you want. Just literally write out the result.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49706760
score: 3
has answer: http://stackoverflow.com/a/49707340
has title: How to extract columns from an indexed matrix?
accepted answer: http://stackoverflow.com/a/49707340
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has body: I have the following matrix: M = np.matrix([[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]]) And I receive a vector indexing the columns of the matrix: index = np.array([1,1,2,2,2,2,3,4,4,4]) This vector has 4 different values, so my objective is to create a list containing four new matrices so that the first matrix is made by the first two columns of M, the second matrix is made by columns 3 to 6 and so on: M1 = np.matrix([[1,2],[11,12],[21,22]]) M2 = np.matrix([[3,4,5,6],[13,14,15,16],[23,24,25,26]]) M3 = np.matrix([[7],[17],[27]]) M4 = np.matrix([[8,9,10],[18,19,20],[28,29,30]]) l = list(M1,M2,M3,M4) I need to do this in a automated way, since the number of rows and columns of M as well as the indexing scheme are not fixed. How can I do this?
tagged with: python-2.7
upvote count: 3
linked to: http://stackoverflow.com/q/4151128
answer count: 2
has answer: http://stackoverflow.com/a/49706906
downvote count: 0
possible better answer: http://stackoverflow.com/a/49706906
linked to: http://stackoverflow.com/q/1373164
tagged with: arrays
favorite count: 0
type: Question

relationship
tag name: relationship
type: Tag
tags question: http://stackoverflow.com/q/49730133

http://stackoverflow.com/a/49701675
has comment: http://stackoverflow.com/comment/86416958
downvote count: 0
has comment: http://stackoverflow.com/comment/86416953
type: Answer
accepted answer of: http://stackoverflow.com/q/49701441
score: 2
answers question: http://stackoverflow.com/q/49701441
has body: First off: str.format is the wrong tool for the job, because it doesn't allow you to generate a different value for each replacement. The correct solution is therefore to implement your own replacement function. We'll replace the {one_digit} and {two_digit} format specifiers with something more suitable: {1} and {2}, respectively. format_string = "{1}:{2}:{1}" Now we can use regex to substitute all of these markers with random numbers. Regex is handy because re.sub accepts a replacement function, which we can use to generate a new random number every time: import re def repl(match): num_digits = int(match.group(1)) lower_bound = 10 ** (num_digits - 1) upper_bound = 10 * lower_bound - 1 random_number = random.randint(lower_bound, upper_bound) return str(random_number) result = re.sub(r'{(\d+)}', repl, format_string) print(result) # result: 5:56:1
upvote count: 2
type: AcceptedAnswer

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/49702179
tags question: http://stackoverflow.com/q/49735175
tags question: http://stackoverflow.com/q/49619152
tags question: http://stackoverflow.com/q/49640823
tags question: http://stackoverflow.com/q/49627823
tags question: http://stackoverflow.com/q/49680331
tags question: http://stackoverflow.com/q/49612091
tags question: http://stackoverflow.com/q/49730288
tags question: http://stackoverflow.com/q/49601077
tags question: http://stackoverflow.com/q/49654041
tags question: http://stackoverflow.com/q/49739356
tags question: http://stackoverflow.com/q/49690256
tags question: http://stackoverflow.com/q/49685591
tags question: http://stackoverflow.com/q/49707881
tags question: http://stackoverflow.com/q/49738295
tags question: http://stackoverflow.com/q/49691170
tags question: http://stackoverflow.com/q/49653088
tags question: http://stackoverflow.com/q/49702795
tags question: http://stackoverflow.com/q/49743337
tags question: http://stackoverflow.com/q/49699488
tags question: http://stackoverflow.com/q/49684069
tags question: http://stackoverflow.com/q/49744601
tags question: http://stackoverflow.com/q/49700936
tags question: http://stackoverflow.com/q/49644124
tags question: http://stackoverflow.com/q/49711343
tags question: http://stackoverflow.com/q/49734374
tags question: http://stackoverflow.com/q/49719616
tags question: http://stackoverflow.com/q/49604812
tags question: http://stackoverflow.com/q/49647606
tags question: http://stackoverflow.com/q/49637814
tags question: http://stackoverflow.com/q/49703296
tags question: http://stackoverflow.com/q/49709242
tags question: http://stackoverflow.com/q/49712859
tags question: http://stackoverflow.com/q/49701918
tags question: http://stackoverflow.com/q/49690154
tags question: http://stackoverflow.com/q/49604269
tags question: http://stackoverflow.com/q/49661591
tags question: http://stackoverflow.com/q/49640148
tags question: http://stackoverflow.com/q/49658462
tags question: http://stackoverflow.com/q/49745029
tags question: http://stackoverflow.com/q/49691870
tags question: http://stackoverflow.com/q/49713164
tags question: http://stackoverflow.com/q/49714309
tags question: http://stackoverflow.com/q/49600319
tags question: http://stackoverflow.com/q/49716991
tags question: http://stackoverflow.com/q/49606686
tags question: http://stackoverflow.com/q/49612619
tags question: http://stackoverflow.com/q/49708926
tags question: http://stackoverflow.com/q/49679707
tags question: http://stackoverflow.com/q/49741328
tags question: http://stackoverflow.com/q/49709352
tags question: http://stackoverflow.com/q/49632828
tags question: http://stackoverflow.com/q/49659310
tags question: http://stackoverflow.com/q/49739101
tags question: http://stackoverflow.com/q/49684468
tags question: http://stackoverflow.com/q/49750513
tags question: http://stackoverflow.com/q/49611510
tags question: http://stackoverflow.com/q/49620100
tags question: http://stackoverflow.com/q/49603346
tags question: http://stackoverflow.com/q/49663506
tags question: http://stackoverflow.com/q/49754939
tags question: http://stackoverflow.com/q/49745744
tags question: http://stackoverflow.com/q/49638782
tags question: http://stackoverflow.com/q/49732911
tags question: http://stackoverflow.com/q/49745192
tags question: http://stackoverflow.com/q/49663796
tags question: http://stackoverflow.com/q/49643622
tags question: http://stackoverflow.com/q/49755450
tags question: http://stackoverflow.com/q/49687009
tags question: http://stackoverflow.com/q/49692842
tags question: http://stackoverflow.com/q/49720109
tags question: http://stackoverflow.com/q/49714328
tags question: http://stackoverflow.com/q/49621169
tags question: http://stackoverflow.com/q/49729510
tags question: http://stackoverflow.com/q/49606805
tags question: http://stackoverflow.com/q/49692436
tags question: http://stackoverflow.com/q/49681910
tags question: http://stackoverflow.com/q/49651354
tags question: http://stackoverflow.com/q/49743838

bytecode-manipulation
tag name: bytecode-manipulation
type: Tag
tags question: http://stackoverflow.com/q/49632327

http://stackoverflow.com/comment/86449714
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49713293
type: Comment
has text: @AntonvBR, Really? I'm not sure `Counter` works *exactly* the same way as `value_counts()` [or does it? I haven't checked the pandas source code]. The `map(frozenset,(...))` of course is the same because both methods require hashable objects.

http://stackoverflow.com/a/49653287
has comment: http://stackoverflow.com/comment/86344609
type: Answer
accepted answer of: http://stackoverflow.com/q/49652893
score: 4
has comment: http://stackoverflow.com/comment/104870726
upvote count: 4
has comment: http://stackoverflow.com/comment/104870803
answers question: http://stackoverflow.com/q/49652893
has body: The upgrade can be difficult, depends on your situation. First, check the changelog for every version. The goal here is to understand if there is a major change that can affect your code. For example, the on_delete parameter in the foreign field models was optional, now is mandatory. If you spot something, just update your code. What can really make the differences are the presence of tests. When we move from python2 to python3 and django 1.7 to 1.11 the tests were our insurance. We just start to upgrade our code to a different branch using the virtualenv with the new python and new django and just fixing, testing and then merging in develop. If you don't have tests maybe is the right time to write some of them. I would not suggest you jump directly to django 2.0. Again, if you have tests you can update gradually and then check the deprecation warnings. Those are very helpful to prepare your code for the next version. Update During the process, we check our requirements and revise every package we had in our system to verify the compatibility. We clean up a little bit removing some packages and update some others. Again, if you have tests you have your insurance :-) Conclusion Check the changelogs Use a separate branch Then: Update gradually ( e.g. from 1.7 to 1.8) (write and) Run tests Update your code/packages Run tests If all it's ok then merge back in develop branch again and go back to 1
type: AcceptedAnswer
downvote count: 0

valueerror
tags question: http://stackoverflow.com/q/49690066
tags question: http://stackoverflow.com/q/49702529
tag name: valueerror
type: Tag
tags question: http://stackoverflow.com/q/49681081
tags question: http://stackoverflow.com/q/49739183
tags question: http://stackoverflow.com/q/49650449

http://stackoverflow.com/q/49690511
type: Question
tagged with: python-multiprocessing
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 6
tagged with: pathos
has title: Can't pickle local object
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/86479401
answer count: 0
has comment: http://stackoverflow.com/comment/86513349
tagged with: multithreading
downvote count: 0
has comment: http://stackoverflow.com/comment/86518407
has body: I would like to use multiprocess package for example in this code. I've tried to call the function create_new_population and distribute the data to 8 processors, but when I do I get pickle error. Normally the function would run like this: self.create_new_population(self.pop_size) I try to distribute the work like this: f= self.create_new_population pop = self.pop_size/8 self.current_generation = [pool.apply_async(f, pop) for _ in range(8)] I get Can't pickle local object 'exhaust.__init__.&lt;locals&gt;.tour_select' or PermissionError: [WinError 5] Access is denied I've read this thread carefully and also tried to bypass the error using an approach from Steven Bethard to allow method pickling/unpickling via copyreg: def _pickle_method(method) def _unpickle_method(func_name, obj, cls) I also tried to use pathos package without any luck. I've know that the code should be called under if __name__ == '__main__': block, but I would like to know if this can be done with minimum possible changes in the code.
has comment: http://stackoverflow.com/comment/86479659
linked to: http://stackoverflow.com/q/1816958
favorite count: 0

http://stackoverflow.com/comment/86293412
type: Comment
comment on: http://stackoverflow.com/q/49629443
score: 0
type: QuestionComment
has text: @PeterE If I knew I wouldn't be asking the question would I ? If anything about the question is unclear let me know. The processing does not require copy, the question is can I avoid (some of) the copies in pure Python with speedup in mind. If you could answer that as a categorical yes or a no, please do.

http://stackoverflow.com/q/49677732
has comment: http://stackoverflow.com/comment/86367053
has title: Regex And Stop At Whitespace
has comment: http://stackoverflow.com/comment/86366844
tagged with: python
has comment: http://stackoverflow.com/comment/86366867
has body: I have strings looking like: -(void) isItem:(bool)//arg//arg//arg//arg//arg rowIndex:(bool)//arg//arg//arg//arg//arg textLayout:(bool)//arg//arg//arg//arg//arg numberOfLines:(bool)//arg//arg//arg//arg//arg isPad:(bool)//arg//arg//arg//arg//arg { I want to select only //arg//arg//arg//arg//arg in each of these strings (number of args will depend) So I can replace it later and end up with: -(void) configureForItem:(bool)ARG rowIndex:(bool)ARG textLayout:(bool)ARG numberOfLines:(bool)ARG isPad:(bool)ARG { I tried: \)\/\/[^/]*.*[^/]*{ But it doesnt really work... I think I need a similar regex, but to make it stop at first whitespace. Thoughts?
accepted answer: http://stackoverflow.com/a/49677918
tagged with: regex
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86366769
has comment: http://stackoverflow.com/comment/86366813
has answer: http://stackoverflow.com/a/49677918
type: Question
has comment: http://stackoverflow.com/comment/86366924

http://stackoverflow.com/comment/86256085
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49624396
type: AnswerComment
has text: 1.6 has VectorUDT in mllib. Just import as , from pyspark.mllib.linalg import Vectors, VectorUDT, http://spark.apache.org/docs/1.6.0/api/python/_modules/pyspark/mllib/linalg.html

http://stackoverflow.com/comment/86220396
score: 0
comment on: http://stackoverflow.com/q/49606792
type: Comment
has text: `for items in text: for item in items: new_list.append(item)`, then the new_list should be like zai4 tui1 jin4 shi2 pin3 an1 quan2 xin4 xi1. Is this correct? @Atiq
type: QuestionComment

http://stackoverflow.com/comment/86481309
score: 0
type: Comment
type: QuestionComment
has text: Hi, basically each line of my array is stored as a single array, whereas i want to slice the whole array in order to get the column composed of the 5 first character which is an index, then the column composed of the 5 other following characters which is a first feature, then the other following 5 characters and so on .. i guess factorizing is the best solution
comment on: http://stackoverflow.com/q/49729075

http://stackoverflow.com/a/49749702
answers question: http://stackoverflow.com/q/49744216
type: Answer
has comment: http://stackoverflow.com/comment/86542926
has comment: http://stackoverflow.com/comment/86541003
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86540520
score: 1
has body: You can either put your script inside the page loop and construct the HTML between the requests or first get all the auctions, store them in some data structure, e.g. a list and then loop over it appending the rows to the HTML. I followed the second approach, because it was closer to what you already had. I refactored the code a bit and added: if not soup.find_all('a', string='Next'): break It breaks the loop after it fails to find an a tag with the Next text inside, which means that's the last page. What I dislike is creating headers for the table and inserting styles programmatically. If I were you, I'd just create a "template" HTML that has all the styles, page title, table included and read it from the file. You could then just append the rows to the tbody of the table. You can also include links to the auctions instead of bare text. The following code works and produces an html with 1300+ auctions last time I checked: import itertools from collections import namedtuple import requests from bs4 import BeautifulSoup url = 'https://www.johnpyeauctions.co.uk/lot_list.asp?saleid=4808&amp;siteid=1&amp;h=0&amp;pageno={}' auctions = [] Auction = namedtuple('auction', ['index', 'picture_link', 'description', 'current_bid', 'time_left']) for page in itertools.count(start=1): response = requests.get(url.format(page)) soup = BeautifulSoup(response.content, 'html.parser') table = soup.find('table', width='97%') for tr in table.find_all('tr')[1:]: # skip the table header tds = tr.contents index = tds[0].find('h5').text pic_elem = tds[1].find('img') # html of this img tag is broken, so I create a new one below picture = soup.new_tag('img', src=pic_elem['src'], width=pic_elem['width']) description = tds[2].find('h5').text current_bid = tds[3].find('h5').text time_left = tds[4].find('h5').text auction = Auction(index, picture, description, current_bid, time_left) auctions.append(auction) if not soup.find_all('a', string='Next'): break headers = ['Index Number', 'Picture', 'Info…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86539134
has comment: http://stackoverflow.com/comment/86544192
accepted answer of: http://stackoverflow.com/q/49744216
has comment: http://stackoverflow.com/comment/86542783

http://stackoverflow.com/a/49610341
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49610295
score: 3
has body: Full example: import pandas as pd data = '''\ No type 123 C01 123 C02 123 T01 345 C01 345 H12 345 H22''' df = pd.read_csv(pd.compat.StringIO(data),sep='\s+') arr = ['Car', 'Tree', 'House'] d = {x[0]:x for x in arr} # Create a map df['category'] = df['type'].str[0].map(d) # Apply map to str[0] Results in: No type category 0 123 C01 Car 1 123 C02 Car 2 123 T01 Tree 3 345 C01 Car 4 345 H12 House 5 345 H22 House Explanation: Create dictionary by first values of arr Select first value of type column by str[0] and map by dict
answers question: http://stackoverflow.com/q/49610295
has comment: http://stackoverflow.com/comment/86227239
type: Answer
has comment: http://stackoverflow.com/comment/86227182
upvote count: 3

http://stackoverflow.com/q/49744497
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/86503718
upvote count: 1
has body: I want to censor words by using Python regex. My word is defined as Alphanumeric[a-zA-Z0-9] and separated by Non-Alphanumeric[^a-zA-Z0-9]. And the words should be censored by inner characters are replaced by * and others remain the same. Ex: test=y tes't test' test-y tes-ty test Test test abcdefg Test ... test are the best... some thing words @@$: HAHA TEST ONE REAL PLAYER!!! EXCELLENT! It's testy night Result should be t**t=y tes't t**t' t**t-y tes-ty t**t T**t t**t abcdefg T**t ... test are the best... some thing words @@$: HAHA T**T ONE REAL PLAYER!!! EXCELLENT! It's testy night I have tried to use the regex to do it. I use re module in python3. 1.I try to match the pattern. 2.Capture the group in matched pattern without the censored word. 3.Try to concat the groups with the word. For example: I tried to censor the word 'test'. Since I don't how to replace it with *, I try to replace with 'SUB' to see my pattern is right or not first. inputStr = re.sub(r'([^a-zA-z0-9]+)test([^a-zA-z0-9]+)', r'\1SUB\2', inputStr, flags=re.IGNORECASE) inputStr = re.sub(r'^test([^a-zA-z0-9]+)', r'SUB\1', inputStr, flags=re.IGNORECASE) replacedStr = re.sub(r'([^a-zA-z0-9]+)test$', r'\1SUB', inputStr, flags=re.IGNORECASE) print(replacedStr) Also, is it possible to use one line to do above thing, I don't know how to use the group in one-line pattern. replacedStr = re.sub('[^a-zA-z0-9]+test[^a-zA-z0-9]+|^test[^a-zA-z0-9]+|[^a-zA-z0-9]+test$', 'SUB', inputStr, flags=re.IGNORECASE) But it doesn't work well. re.sub('[^a-zA-z0-9]+test[^a-zA-z0-9]+|^test[^a-zA-z0-9]+|[^a-zA-z0-9]+test$', 'SUB', inputStr, flags=re.IGNORECASE) My Result SUB=y tes't SUB' test-y tes-ty SUB Test SUB abcdefg SUB ... test are the best... some thing words @@$: HAHA SUB ONE REAL PLAYER!!! EXCELLENT! It's testy night I see my pattern somewhat doesn't match some 'test' and I don't know why. https://regexr.com/3nk9l So, my questions are 1.What is wrong with my pattern? 2.How to let the matched word be replaced with * in…
accepted answer: http://stackoverflow.com/a/49745344
downvote count: 1
has answer: http://stackoverflow.com/a/49745344
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49745334
has comment: http://stackoverflow.com/comment/86503673
has answer: http://stackoverflow.com/a/49745334
tagged with: python
tagged with: regex
has title: Regex replace middle content of match words

http://stackoverflow.com/comment/86397190
has text: @Aran-Fey why? 0x51ba did this in his answer. And I tested OK.Oh, and mine is Python 2.7.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49692051
type: Comment

http://stackoverflow.com/q/49714845
score: 0
has comment: http://stackoverflow.com/comment/86443702
answer count: 1
linked to: http://stackoverflow.com/q/47373762
accepted answer: http://stackoverflow.com/a/49714943
has title: Matplotlib pyplot horizontal bar chart - prevent auto ordering of axes
type: Question
has comment: http://stackoverflow.com/comment/86710424
has comment: http://stackoverflow.com/comment/86671222
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/47373762
has comment: http://stackoverflow.com/comment/86695318
tagged with: python
has body: I want to force a bar chart to have the x-axis in a certain order. But for some reason it always orders it alphabetically, I don't know why. Is there a setting I can use to keep it from doing that. In the example below, I want the x-axis ordered as ['d', 'a', 'c', 'b']. But it always orders it to ['a', 'b', 'c', 'd']. Code: import pandas as pd import matplotlib.pyplot as plt ser = pd.Series([1,2,3,4], index=['d', 'a', 'c', 'b']) fig = plt.bar(ser.index, ser.values, tick_label=ser.index) Screenshot:
has comment: http://stackoverflow.com/comment/86443024
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49714943
has comment: http://stackoverflow.com/comment/86459549

http://stackoverflow.com/q/49624730
has comment: http://stackoverflow.com/comment/86256491
answer count: 0
tagged with: windows
has comment: http://stackoverflow.com/comment/86256642
has comment: http://stackoverflow.com/comment/86257295
has title: PIP for Python3 installs Python2 script that cannot be ran
type: Question
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86257333
has body: I've installed a small script ever2simple via pip as follows: pip install -U ever2simple (following the installation instructions) It has installed an EXE file to ...\Miniconda3\Scripts\ever2simple.exe (I use Miniconda3 64bit for Python 3.6 on Windows 10 x64). When I try to run this, it gives me SyntaxError: Missing parentheses in call to 'print'. Did you mean print(print 'File does not exist: %s' % filepath)? Looks like this is because script is for Python2. How do I make the script working on my machine? Isn't this bug in pip, as it allows to install Python2 script that cannot be properly ran? Thanks!
tagged with: miniconda
score: 0

http://stackoverflow.com/comment/86289558
comment on: http://stackoverflow.com/a/49629851
has text: @water77 Glad that helped. Please see https://stackoverflow.com/help/accepted-answer Your second comment seems like a separate topic, and probably needs a new question with more detail. That is, I do not understand what you are asking. Please see https://stackoverflow.com/help/asking
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49697757
answers question: http://stackoverflow.com/q/49697056
downvote count: 0
upvote count: 2
type: Answer
has body: A dictionary comprehension is the cleanest way to structure your data: d = {k: df[df['Particulars'] == k] for k in df['Particulars'].unique()} Related: How do I create a variable number of variables?
score: 2

http://stackoverflow.com/q/49728460
tagged with: database
has comment: http://stackoverflow.com/comment/86500101
tagged with: python
has comment: http://stackoverflow.com/comment/86471429
has comment: http://stackoverflow.com/comment/86499964
has comment: http://stackoverflow.com/comment/86471679
has body: I have a network bottleneck in my system so I want to shave off the bytes. My current data format is 2 ID bytes, 8 DateTime bytes and 2 Variable A bytes and 2 Variable B bytes. I suspect the range of A is A: 0 ≤ A &lt; 100 and B: 0 ≤ B &lt; 100 How to I shave off the ID, A, and B data bits. All have a low range of possible values so some system that has base a couple of thousand. I imagine using a character system and then mapping each character to a unique value and then not even needing to do arithmetic. Then use the excessive processing power on decoding each input to a normal encoding (utf-8, base 10... all that) My question then becomes how to find a good number-character data format / encoding so i can ease that network and storage bottleneck. I dont know if postgreSQL or mySQL has a good answer but ill likely use one of those databases paired with a Django backend.
tagged with: encoding
answer count: 0
tagged with: sql
has title: High base number systems for compression?
type: UnansweredQuestion
tagged with: compression
has comment: http://stackoverflow.com/comment/86471280
type: Question
has comment: http://stackoverflow.com/comment/86500333
has comment: http://stackoverflow.com/comment/86641312
score: 0

http://stackoverflow.com/comment/86483310
has text: Thank you! Super helpful. Was unfamiliar with both the dataclass in v3.7+ and unfamiliar with attrs. The latter did the trick via the _attrs_post_init_ method. Also...thanks for turning me onto the X, Y Problem. Glad to have the vocab to know identify a widespread problem...of which, occasionally, I myself manifest.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49687931

http://stackoverflow.com/a/49690812
has body: Just a quick illustration of the problem with reduced numbers for contrast: from scipy.interpolate import interp1d import numpy as np import matplotlib.pyplot as plt M_centre = 2e30 G = 1.67e-11 m_test = 6e24 radius1 = np.linspace(5,1e3,10) radius2 = np.linspace(5,1e2,10) V_circ1 = np.sqrt(G*M_centre/radius1) V_circ2 = np.sqrt(G*M_centre/radius2) velocities_circ1 = interp1d(radius1,V_circ1) test_r1 = velocities_circ1(50) print(test_r1) velocities_circ2 = interp1d(radius2,V_circ2) test_r2 = velocities_circ2(50) print(test_r2) plt.plot(radius1, V_circ1, "ro", label = "radius1") plt.plot(radius2, V_circ2, "bx", label = "radius2") plt.plot(radius1, velocities_circ1(radius1), "r") plt.plot(radius2, velocities_circ2(radius2), "b") plt.legend() plt.xlim(0, 400) plt.show() I think the reason for the different output is obvious. And the equivalent diagram for same range (5, 1e2), but different number of points (3 vs 10):
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49689741
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49689741

http://stackoverflow.com/comment/86303925
score: 0
has text: unfortunately not
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49647703

http://stackoverflow.com/q/49628739
has comment: http://stackoverflow.com/comment/86264630
has comment: http://stackoverflow.com/comment/86264476
has answer: http://stackoverflow.com/a/49632132
has comment: http://stackoverflow.com/comment/86264951
tagged with: python
tagged with: artificial-intelligence
has comment: http://stackoverflow.com/comment/86265105
has comment: http://stackoverflow.com/comment/86264417
has body: I have an input image 416x416. How can I create an output of 4 x 10, where 4 is number of columns and 10 the number of rows? My label data is 2D array with 4 columns and 10 rows. I know about the reshape() method but it requires that the resulted shape has same number of elements as the input. With 416 x 416 input size and max pools layers I can get max 13 x 13 output. Is there a way to achieve 4x10 output without loss of data? My input label data looks like for example like [[ 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 0 0] [116 16 128 51] [132 16 149 52] [ 68 31 77 88] [ 79 34 96 92] [126 37 147 112] [100 41 126 116]] Which indicates there are 6 objects on my images that i want to detect, first value is xmin, second ymin , third xmax, fourth ymax. The last layer of my networks looks like (None, 13, 13, 1024)
score: 12
has answer: http://stackoverflow.com/a/55670429
has comment: http://stackoverflow.com/comment/86264567
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/86265586
answer count: 2
upvote count: 12
has title: Reshaping Keras layers
type: UnansweredQuestion
tagged with: neural-network
downvote count: 0
tagged with: keras
favorite count: 0
type: Question

http://stackoverflow.com/q/49652698
score: 4
favorite count: 0
accepted answer: http://stackoverflow.com/a/49654699
type: AnsweredQuestion
has body: I am trying to add custom methods to an ORM class member to get it to process things relevant to this member. Trying to follow the documentation. class EnhDateTime(types.TypeDecorator): impl = types.DateTime def foo(self): return "foo" class MyDoc(Base): id = Column(Integer, primary_key=True, autoincrement=False) created = Column(EnhDateTime) doc = session.query(MyDoc).filter_by(id=123).one() Unfortunately nothing happened and the member is still of DateTime type: type(doc.created) datetime.datetime doc.created.foo() AttributeError
has answer: http://stackoverflow.com/a/49654699
tagged with: python
tagged with: sqlalchemy
has title: How to add methods to a column using SQLAlchemy TypeDecorator
type: Question
upvote count: 4
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49629343
has comment: http://stackoverflow.com/comment/86267667
has body: I am collecting data from the web using Python and appending the data to a pandas dataframe. I wanted to view the updated dataframe on the dos command prompt each time it is appended. This is what I am currently doing: for i in range(0,len(Record_files)): os.system('cls') with pd.option_context('display.max_rows', None, 'display.max_columns', None,'expand_frame_repr', False): print(Database) Since, the Database is too big, it scrolls most of the time continuously than just viewing the last updated entry. For Example: Let the initial data frame output be Time Temperature 12:34 PM 45 C 12:37 PM 42 C Now when new data gets appended, I want it to print it as: Time Temperature 12:34 PM 45 C [old] 12:37 PM 42 C [old] 12:42 PM 39 C [new] I want only the [new] entry to printed as it is queued while the other [old] entries should remain on the screen. The issues with my current method of clearing the screen using os.system('cls') for every update is that, when the list gets more than the length of the terminal window it keeps on scrolling and its seems useless.
has comment: http://stackoverflow.com/comment/86269383
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/49631684
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86265546
answer count: 1
has comment: http://stackoverflow.com/comment/86265814
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/86266910
has title: Printing Pandas DataFrame with only the last appended values

http://stackoverflow.com/comment/86280729
has text: You should open the file for writing with mode 'a'. See: https://docs.python.org/3/library/functions.html#open. Or make a list of words and then use `writelines`
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49636557

http://stackoverflow.com/comment/86327072
type: Comment
type: QuestionComment
has text: @abarnert I tried to but it yielded the same result.
comment on: http://stackoverflow.com/q/49658623
score: 0

http://stackoverflow.com/comment/86327947
type: AnswerComment
comment on: http://stackoverflow.com/a/49659294
type: Comment
has text: _". . .if it's the same as the elem in b. . ."_.
score: 0

http://stackoverflow.com/q/49687051
tagged with: azure
score: 1
has title: Azure AD Authentication through Python Web API
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49687604
type: Question
has body: I am building a Python web API where I want to use Azure AD as authentication backend. On certain scenarios the clients needs to authenticate through the API to authorize to certain endpoints. The client itself is not able to authenticate to AD directly, so it needs to do it through the API using raw credentials (username, password). The API will then authenticate the user and receive the AD token and give it to the user. So in short I am looking for a way to programmatically authenticate a user using username/password and receive the token using Python.
answer count: 2
tagged with: azure-authentication
type: UnansweredQuestion
downvote count: 0
tagged with: azure-active-directory
upvote count: 1
tagged with: active-directory
has answer: http://stackoverflow.com/a/49700981

http://stackoverflow.com/q/49722785
has comment: http://stackoverflow.com/comment/86459051
score: 2
has comment: http://stackoverflow.com/comment/86463472
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/62850538
upvote count: 3
has answer: http://stackoverflow.com/a/79542461
answer count: 3
has comment: http://stackoverflow.com/comment/86459108
downvote count: 1
has comment: http://stackoverflow.com/comment/86459121
favorite count: 0
has comment: http://stackoverflow.com/comment/86459132
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86461420
accepted answer: http://stackoverflow.com/a/49724037
possible better answer: http://stackoverflow.com/a/79542461
type: Question
has answer: http://stackoverflow.com/a/49724037
has comment: http://stackoverflow.com/comment/86460514
tagged with: python
has comment: http://stackoverflow.com/comment/86462945
has title: How can I delete an instance of a class within that class?
has comment: http://stackoverflow.com/comment/86459156
has body: I want to know how you can delete a instance within the class. I am trying del self, but it doesn't seem to work. Here's my code: class Thing: def __init__(self): self.alive = True self.age = 0 def update(self): self.age += 1 def kill(self): if self.age &gt;= 10: del self def all(self): self.update() self.kill() things = [] for i in range(0, 10): thing.append(Thing()) while True: for thing in things: thing.all() I specifically want to delete the instance inside the class. I have also replaced del self with self = None, but this statement doesn't seem to have any effect. How can I do this?
has comment: http://stackoverflow.com/comment/86460569

http://stackoverflow.com/comment/86286471
type: QuestionComment
has text: Research first, then post. There are many questions and tutorials that will show you how to take the mean of a sequence of numbers.
comment on: http://stackoverflow.com/q/49639352
score: 0
type: Comment

http://stackoverflow.com/comment/86456213
comment on: http://stackoverflow.com/a/49721524
has text: No, it didn't in the original. I thought he was looking at adjacent pairs of weights. Modified my answer now.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86485955
comment on: http://stackoverflow.com/q/49735906
type: Comment
has text: Unfortunately this is not possible in my case
type: QuestionComment
score: 0

http://stackoverflow.com/a/49616132
answers question: http://stackoverflow.com/q/49599665
type: Answer
score: 0
has body: IMO the best way is dependency injection. # MyClass def __init__(self, collaborator=None) self.collaborator = collaborator or Coll() from unittest.mock import create_autospec, Mock def setUp mock_c = create_autospec( Coll, get_val=Mock(return_value=12), get_val2=Mock(...), ) self.sut = myclass(collaborator=Coll)

http://stackoverflow.com/a/49721867
has body: You're getting an error because using the x[key] = val syntax only works one level deep. Trying to assign x[y][key] = val results in an error because y doesn't exist within the dictionary. If you execute myitem['Item']['ItemSpecifics']={}, before trying to create a dictionary within it will work. Alternatively, you could specify it right away when you create you dict: myitem = { "Item": { ... "ItemSpecifics": {} } }
type: Answer
accepted answer of: http://stackoverflow.com/q/49721369
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49721369
type: AcceptedAnswer

http://stackoverflow.com/q/49610140
has comment: http://stackoverflow.com/comment/86235383
has title: How to detect lane from an image using opencv and python3
type: Question
score: 0
answer count: 0
tagged with: python
tagged with: computer-vision
type: UnansweredQuestion
tagged with: opencv
has body: I am new to Image Processing and am trying to detect side lanes in a given image. This is the Expected output: I need an output something similar to this So i thought of using houghTransform to detect the straight lane lines but its providing me a large number of lines as output. Finally i was able to filter out it to few lines as image below This is the output obtained : AM sort of stuck now and have no idea how to proceed. I have searched online in many sites but none gave me the result i needed. import numpy as np import cv2 img = cv2.imread('frame3.jpg') print(img.shape) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,100,250,apertureSize = 3) print(img.shape[1]) print(img.shape) minLineLength=img.shape[1]-300 lines = cv2.HoughLinesP(image=edges,rho=0.02,theta=np.pi/500, threshold=1,lines=np.array([]), minLineLength=minLineLength,maxLineGap=100) a,b,c = lines.shape for i in range(a): cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA) cv2.imshow('edges', edges) cv2.imshow('result', img) cv2.waitKey(0) cv2.destroyAllWindows()
tagged with: hough-transform
has comment: http://stackoverflow.com/comment/86233400
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86234763
has comment: http://stackoverflow.com/comment/86240249

http://stackoverflow.com/comment/86263999
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49627823
has text: This is way too abstract and depends on your desired functionality. One approach might be to find the number of values common between all of your m vectors, if you want a strict measure of similarity.

http://stackoverflow.com/comment/86329481
comment on: http://stackoverflow.com/q/49659873
type: QuestionComment
type: Comment
score: 0
has text: In (pure) Python you don't need to worry about memory _at all_. At least to a point where you run out of said memory, but that's another problem.

http://stackoverflow.com/comment/86356452
has text: Thx for your answer! I tried and got this error: pymongo.errors.OperationFailure: $project specification must be an object
type: Comment
comment on: http://stackoverflow.com/a/49672490
score: 0
type: AnswerComment

http://stackoverflow.com/q/49622575
has body: I am trying to schedule my python script in AWS, however I don't want the instances to be running all the time. So, trying to automate the process of: Start the EC2 instance on a specific time Run the python script within it Stop the EC2 instance once the job is completed. I cannot run this script directly as a Lambda function because the script does some parallel processing which requires more RAM, so choosing a bigger AWS instance rather than writing it as a lambda function. Also, don't want this instance to be running all the time as it is expensive. So far, I followed Automatic starting and stopping of AWS EC2 instances with Lambda and CloudWatch · matoski.com and created a Lambda function to start and stop the instance at specific time, however I couldn't find a way to run the python script once the instance is started. Can anyone point me in the right direction?
tagged with: amazon-ec2
linked to: http://stackoverflow.com/q/23013274
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/86263973
has comment: http://stackoverflow.com/comment/86252193
has comment: http://stackoverflow.com/comment/86252177
has answer: http://stackoverflow.com/a/56790690
possible better answer: http://stackoverflow.com/a/56790690
type: AnsweredQuestion
has title: Schedule to start an EC2 instance and run a python script within it
has comment: http://stackoverflow.com/comment/86256820
answer count: 3
has comment: http://stackoverflow.com/comment/86252158
has comment: http://stackoverflow.com/comment/86252109
has comment: http://stackoverflow.com/comment/86332365
has answer: http://stackoverflow.com/a/57812894
score: 17
upvote count: 17
has comment: http://stackoverflow.com/comment/86252303
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86294771
downvote count: 0
has answer: http://stackoverflow.com/a/49962590
accepted answer: http://stackoverflow.com/a/49962590

http://stackoverflow.com/q/49619536
tagged with: python
has answer: http://stackoverflow.com/a/49619838
answer count: 1
has title: New to coding python , need help on why my code isnt working?
downvote count: 1
favorite count: 0
score: -1
type: Question
has comment: http://stackoverflow.com/comment/86246132
type: UnansweredQuestion
upvote count: 0
has body: def Factorial(n): num = 1 while n &gt;= 1: num = num * n n = n - 1 return num def Fibonacci(num): i=0 present=1 previous=0 while i&lt;=num: nextterm=present+previous present=previous previous=nextterm i=i+1 print("The fibonacci number for", i, 'is', nextterm) def CallFibOrFac(x): num = 10 if x == 'Fib': Fibonacci(num) if x == 'Fac': print (Factorial(n)) x = input('enter fibonacci or factorial') num = input('enter value for fibonacci') Fibonacci(num) n = input('enter value for factorial' print(Factorial(n)) I defined all my functions and wrote an if statement, but when I enter Factorial, when it asks for x=input(‘enter fibonacci or factorial’), it gives me the input to ‘enter value for fibonacci’ when I need the n=input(‘enter value for factorial’) to display when I put in "factorial".

http://stackoverflow.com/comment/86255181
type: QuestionComment
has text: Also, you might want to specify which version of PDFTables you're using. There are 2 main ones that I know of on GitHub, for example: [this](https://github.com/chrisdev/pdftables) and [this](https://github.com/drj11/pdftables). (And you can try switching between them to see if one of them works better for you.)
comment on: http://stackoverflow.com/q/49623051
score: 0
type: Comment

http://stackoverflow.com/comment/86611503
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49752388
has text: One last question if you change the Country in the VW Gold row, therefore also change the Country in VW Polo, is that what you expect?
score: 0

http://stackoverflow.com/comment/124580011
type: Comment
comment on: http://stackoverflow.com/a/51961882
has text: I couldn't get the chunked type requests to work - was getting 400 Bad request error. What worked for me was saving every chunk of data into a temporary file, and then making the request.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86497772
comment on: http://stackoverflow.com/q/49741513
type: Comment
type: QuestionComment
has text: @Prateek: You might be thinking of Windows.
score: 0

http://stackoverflow.com/q/49668079
answer count: 0
linked to: http://stackoverflow.com/q/5419888
linked to: http://stackoverflow.com/q/136168
tagged with: file
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86346192
has body: When trying to monitor a logfile for new lines with python I stumbled upon an issue. What I try to do: while True: file = open("log.txt", "r") file.seek(0,2) where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: *do stuff with line* The line returned is always empty. I see why this is: file.seek(0,2) will always move the cursor to the end of the file and therefore there is no line after the cursor. But to watch the logfile for only new lines I will need to do this. Can someone point me in the right direction on how to approach something like this.
has comment: http://stackoverflow.com/comment/86346172
tagged with: python
duplicate of: http://stackoverflow.com/q/5419888
has title: reading last line in logfile with python
tagged with: tail
score: 0

http://stackoverflow.com/a/49626437
score: 0
answers question: http://stackoverflow.com/q/49625820
has body: pk=request.data['address_pk'] This will raise a KeyError if address_pk is not present in the request data. Later on, you'll find yourself writing a try...except block to handle it. A shorter way would be to use the dict.get method. request.data.get('address_pk') # this will default to None if key is absent And the KeyError won't raise. This helps reduce 3-4 lines of code. But this may not always be the best solution, because you might want to maybe send a 400 Bd Request response when a particular key is absent from POST data. In that case, you'll have to write the try...except block for that.
type: Answer

http://stackoverflow.com/q/49711512
has title: "Python Programming for the Absolute Beginner, Third Edition" book has error in Chapter 5, can someone debug the code?
duplicate of: http://stackoverflow.com/q/37739765
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86436573
has comment: http://stackoverflow.com/comment/86437259
answer count: 0
has comment: http://stackoverflow.com/comment/86436638
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20449427
has body: After typing out a code from chapter 5 of "Python Programming for the Absolute Beginner, Third Edition", a beginner programming book of mine. The program seems pretty self explanatory... scores = [] choice = None while choice != "0": print( """ High Scores 2.0 0 - Quit 1 - List Scores 2 - Add a Score """ ) choice = input("choice: ") print() # exit if choice == 0: print("Goodbye") # display high-score table elif choice == 1: print("High Scores\n") print("NAME\tSCORE") for entry in scores: score, name = entry print(name, "\t", score) # add a score elif choice == 2: name = input("Player's name:") score = int(input("What was the score:")) entry = (name, score) scores.append(entry) scores.sort(reverse=true) scores = scores[:5] else: print("Sorry, but", choice, "isn't a valid choice.") input("") ...the "while" loop at the beginning appears to run infinitely. Python Shell: High Scores 2.0 0 - Quit 1 - List Scores 2 - Add a Score choice: 1 Sorry, but 1 isn't a valid choice. High Scores 2.0 0 - Quit 1 - List Scores 2 - Add a Score choice: 2 Sorry, but 2 isn't a valid choice. High Scores 2.0 0 - Quit 1 - List Scores 2 - Add a Score choice: 0 Sorry, but 0 isn't a valid choice. It even seems to list my input as invalid, despite me defining it in the program. Can someone help find the error, and point out why it's causing the program to misbehave? EDIT: I now know what was wrong with the original code. I forgot to add an "int" function on this line, before I added "input" (stupid me). The "duplicate" python2 threads helped. choice = int(input("choice: "))
upvote count: 1
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/37739765
score: 0
has comment: http://stackoverflow.com/comment/86436547

http://stackoverflow.com/comment/86513106
score: 0
comment on: http://stackoverflow.com/q/49748482
type: Comment
has text: with this function`def _build_tree(self)` what do you get after refreshing
type: QuestionComment

http://stackoverflow.com/a/49846052
downvote count: 0
type: Answer
has body: Blur the image, then find the contours. If the edges are that close together, a simple blurring with something like def blur_image(image, amount=3): '''Blurs the image Does not affect the original image''' kernel = np.ones((amount, amount), np.float32) / (amount**2) return cv2.filter2D(image, -1, kernel) should connect all the little gaps, and you can do contour detection with that. If you then want to convert those contours into polygons, you can look to approximate those contours as polygons. A great tutorial with code for that is here. The basic idea behind detecting polygons is running cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) Which tells OpenCV to approximate the contours with straight lines, creating polygons. (I'm not sure what the cv2.RETR_EXTERNAL parameter does at this time.)
accepted answer of: http://stackoverflow.com/q/49603106
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/49603106

http://stackoverflow.com/q/49621331
has comment: http://stackoverflow.com/comment/86249697
has answer: http://stackoverflow.com/a/49621415
answer count: 4
accepted answer: http://stackoverflow.com/a/49621407
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49621407
has body: I am trying to add all the digits of a positive integer. When I test out the number 434, the result was 4, instead of 11. Here is what I have, I don't understand why is my code not going through all the digits of the number. How to correct it? def digit_sum(x): n=0 if x&gt;0: #get the end digit of the number,add to n n+=x%10 #remove the end digit of the number x=x//10 return n
type: Question
has answer: http://stackoverflow.com/a/58282014
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49621381
has title: Adding all digits for a positive integer
has answer: http://stackoverflow.com/a/49621381
tagged with: python

http://stackoverflow.com/comment/86510450
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49707807
has text: My java version is: java-8-openjdk-amd64. buildozer.spec at https://github.com/sergeLabo/androidserver2/blob/master/buildozer.spec, and yes, twisted programs are from examples and works fine on my PC.
score: 0

http://stackoverflow.com/comment/86524873
score: 0
has text: @flyx I updated the question: "I want to export the classes to yaml. There will always be classes only, never instances. At least that's what I think today."
type: Comment
comment on: http://stackoverflow.com/q/49747632
type: QuestionComment

http://stackoverflow.com/comment/92427929
type: Comment
type: QuestionComment
score: 0
has text: FYI, another approach here (with the advantage of converting pandas dtype=object to numpy dtype=string: https://stackoverflow.com/questions/52579601/convert-dataframe-with-strings-to-a-record-array/52749127#52749127
comment on: http://stackoverflow.com/q/49734441

http://stackoverflow.com/comment/86232304
type: Comment
has text: no need to use BeautifulSoup here when selenium can locate any element and parse the text
type: QuestionComment
comment on: http://stackoverflow.com/q/49612510
score: 0

http://stackoverflow.com/q/49687734
duplicate of: http://stackoverflow.com/q/993358
downvote count: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49687881
tagged with: time
upvote count: 0
has title: Create series of dates and times in python
has answer: http://stackoverflow.com/a/49687918
possible better answer: http://stackoverflow.com/a/49687918
has body: I want to release particles every hour for a month and need an array with a date in this format '2013/05/23;00:00:00:000' (YYYY/MM/DD;hh:mm:SS:sss) that has the following hour in every step. So something like this for a whole month: x=['2013/05/23;01:00:00:000' '2013/05/23;02:00:00:000' '2013/05/23;03:00:00:000' ...'2013/06/23;01:00:00:000'] Any idea how to loop this? Thanks!
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86386655
accepted answer: http://stackoverflow.com/a/49687881
linked to: http://stackoverflow.com/q/993358
tagged with: date

http://stackoverflow.com/comment/126549072
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49610498
has text: I updated pytest version if I remember it right
type: Comment

http://stackoverflow.com/q/49612346
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49613177
upvote count: 2
has answer: http://stackoverflow.com/a/49613177
downvote count: 0
tagged with: python
score: 2
has body: So I want to make a scraper for steam games with Scrapy. I didn't know why exactly some games weren't showing in the result csv/json. I figured that it was because of the age verification form. I really tried to see what was the problem... but everything seems like it should work. Can anyone help on this? I noticed that the callback would return the same agecheck link and the dupefilter would remove that link. So the game would never be scraped. Example games: Rise of the Tomb Raider, Doom. This is the code: def parse_product(self, response): # Circumvent age selection form. if '/agecheck/app' in response.url: logger.debug(f"Form-type age check triggered for {response.url}.") form = response.css('#agegate_box form') action = form.xpath('@action').extract_first() name = form.xpath('input/@name').extract_first() value = form.xpath('input/@value').extract_first() formdata = { name: value, 'ageDay': '21', 'ageMonth': '5', 'ageYear': '1975' } yield FormRequest( url=action, method='POST', formdata=formdata, callback=self.parse_product ) else: yield load_product(response)
type: AnsweredQuestion
answer count: 1
has title: Steam age check circumvent by using Scrapy
tagged with: scrapy

http://stackoverflow.com/q/49733845
linked to: http://stackoverflow.com/q/45330737
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49734010
type: Question
type: AnsweredQuestion
has body: I am scraping multiple tables from multiple pages of a website. The issue is there is a row missing from the initial table. Basically, this is how the dataframe looks. mar2018 feb2018 jan2018 dec2017 nov2017 oct2017 sep2017 aug2017 balls faced 345 561 295 0 645 balls faced 200 58 0 runs scored 156 281 183 0 389 runs scored 50 20 0 strike rate 52.3 42.6 61.1 0 52.2 strike rate 25 34 0 dot balls 223 387 173 0 476 dot balls 125 34 0 fours 8 12 19 0 22 sixes 2 0 0 doubles 20 38 16 0 36 fours 4 2 0 notout 2 0 0 0 4 doubles 2 0 0 notout 4 2 0 the column 'sixes' is missing in the first page and present in the subsequent pages. So, I am trying to move the rows starting from 'fours' to 'not out' to a position down and leave nan's in row 4 for first 5 columns starting from mar2018 to nov2017. I tried the following code but it isn't working. This is moving the values horizontally but not vertically downward. df.iloc[4][0:6] = df.iloc[4][0:6].shift(1) and also df2 = pd.DataFrame(index = 4) df = pd.concat([df.iloc[:], df2, df.iloc[4:]]).reset_index(drop=True) did not work. df['mar2018'] = df['mar2018'].shift(1) But this moves all the values of that column down by 1 row. So, I was wondering if it is possible to shift down rows of specific columns from a specific index?
tagged with: python
has title: shifting down rows of specific columns from a specific index in python
has answer: http://stackoverflow.com/a/49734010
tagged with: pandas

http://stackoverflow.com/comment/86356936
comment on: http://stackoverflow.com/q/49673160
has text: @PanagiotisKanavos it's python 2 's inbuilt `unicode` type which became `str` in python 3.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49684355
tagged with: list
answer count: 1
has comment: http://stackoverflow.com/comment/86380580
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/49684466
has title: Python next nearest specific item (onwards) in a list and check between
type: UnansweredQuestion
tagged with: python
tagged with: nearest-neighbor
has body: A=['a',1,2,3,'b',4,5,'a',6,7,'b'] How do I find the next nearest specific value's index and elements between my current value and it? I want to iterate through the list A, and be able to find the next nearest given value' index and elemnts in-between. Saying, for example, the sepcific value is 'b', if I am at the point of first 'a', then it will return a's index (0) the first b's index (4) and the elements in-between (1,2,3). If I am at the point of the second a, then it will return a's index (7) the first b's index (10) and the elements in-between (67). Thanks
has comment: http://stackoverflow.com/comment/86380630
score: 0

http://stackoverflow.com/comment/86487488
has text: I guess it wont complain @Hai because I am passing the arg to it
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49735956

http://stackoverflow.com/q/49714625
has body: I have a dictionary look like, data = {'A292340': {'comp': 'company_value'},..., 'A196030': {'comp': 'company_value'} The problem is I don't know the keys(those start with "A") and how many they are. I like to make loop which iterates "A"s and get the value. I tried keys() which look like but it didn't worked. foo = data.keys() for f in foo : print(f.values()) Thanks a lot.
favorite count: 0
possible better answer: http://stackoverflow.com/a/49714866
has answer: http://stackoverflow.com/a/49714664
type: Question
has comment: http://stackoverflow.com/comment/86442401
has comment: http://stackoverflow.com/comment/86442422
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49714664
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49714866
answer count: 2
has title: accessing nested dictionary values with unknown number of keys
upvote count: 1
has comment: http://stackoverflow.com/comment/86442426
downvote count: 1
tagged with: loops

http://stackoverflow.com/q/49638305
favorite count: 0
tagged with: opencv
has answer: http://stackoverflow.com/a/50217122
tagged with: python
has answer: http://stackoverflow.com/a/49646404
tagged with: image
has body: I am getting an error in OpenCv - cv2.face has no attribute create LBPHFaceRecognizer I already installed OpenCv contrib Python Python version 3.6 OpenCv version 3.4
tagged with: face-recognition
type: Question
has comment: http://stackoverflow.com/comment/86284541
has title: OpenCv Face Recognition issue
downvote count: 4
answer count: 2
upvote count: 0
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/86284902

http://stackoverflow.com/a/49629315
type: Answer
has comment: http://stackoverflow.com/comment/86298334
has body: First warning on the docs: Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) cannot copy all file metadata. On POSIX platforms, this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. This means that resources will be lost and file type and creator codes will not be correct. On Windows, file owners, ACLs and alternate data streams are not copied. shutil.copytree uses shutil.copy2()by default: Permissions and times of directories are copied with copystat(), individual files are copied using shutil.copy2()
score: 0
answers question: http://stackoverflow.com/q/49629084

http://stackoverflow.com/q/49703785
has title: Counting the values in one column after another column fulfills a criteria
has answer: http://stackoverflow.com/a/49703845
type: Question
tagged with: for-loop
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86420986
tagged with: python
has comment: http://stackoverflow.com/comment/86421000
score: 0
tagged with: pandas
has body: so i have a CSV file with a date column and a positive sentiment column. if the positive sentiment column is positive, the column will show a 1. If not it will show a 0. I need to be able to input a date, and for rows where the dates in the csv are later than the inputted date, i need to count the total positive score from the positive sentiment column. So far i have managed to come up with this import datetime import pandas as pd data = pd.read_csv('rt_Article2.csv') csv_date = pd.to_datetime(data["Date"]) positive_news= (data['Positive']) user_date= datetime.datetime(2018, 4, 1, 00, 00) user_score = 4 neg= 0 pos= 0 count=0 for i in csv_date: if i &gt; user_date: count +=1 for N in positive_news: if N == 1: pos +=1 break print (pos) However, when i print(pos) it just counts everything in the positive column, regardless if it fulfils the date criteria or not. I just started coding a month ago so i'm sorry if the code is messy. Any help will be appreciated. Thanks! Date Positive April 2, 2018 0 April 1, 2018 1 April 1, 2018 0 March 31, 2018 0 Update: i also have to return the date for the first positive score and the last positive score once it reaches the user_score which in this case is 4. In other words, i need to get the date when the score is one, and the date when the score reaches 4.
answer count: 1

http://stackoverflow.com/q/49712100
type: Question
answer count: 2
tagged with: spotipy
tagged with: api
tagged with: spotify
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/62048005
score: 1
has answer: http://stackoverflow.com/a/49712371
favorite count: 0
type: AnsweredQuestion
has body: I'm trying to access music that the user is currently playing using the spotipy Spotify python library. import json import spotipy import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials cid = "xxx" csecret = "xxx" redirectURI = "xxx" username = "xxx" client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=csecret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) scope = 'user-read-currently-playing' token = util.prompt_for_user_token(username, scope, cid, csecret, redirectURI) if token: sp = spotipy.Spotify(auth=token) else: print("Can't get token for", username) current_track = sp.current_user_playing_track() print(json.dumps(current_track, sort_keys=False, indent=4)) I've also tried using sp.currently_playing(). I am able to access other data such as sp.current_user_saved_tracks(limit=3, offset=0). Using what I currently have, it always errors out saying AttributeError: 'Spotify' object has no attribute 'current_user_playing_track'. I've explored using node instead but I really would like to stick with python.
has title: currently_playing not working when using the Spotipy library
possible better answer: http://stackoverflow.com/a/62048005
accepted answer: http://stackoverflow.com/a/49712371
tagged with: python

http://stackoverflow.com/a/49736747
downvote count: 0
score: 2
has body: It looks like your hunch is correct: those constants appear to be missing from typeshed. You should file an issue on the typeshed repo or perhaps even just make a pull request and just add them yourself. If you get them in quickly enough, those changes might be accepted in time for the next mypy release, which I believe is this Friday. (If not, those changes will be a part of the next release, which will be in roughly a month from now?) In the interim, you can likely suppress those errors via some combination of # type: ignore and by configuring how mypy handles imports. See: http://mypy.readthedocs.io/en/stable/command_line.html http://mypy.readthedocs.io/en/stable/config_file.html ...for details. Alternatively, you could clone typeshed, modify it locally, and instruct mypy to use your local copy of typeshed via the --custom-typeshed-dir command line argument.
type: Answer
accepted answer of: http://stackoverflow.com/q/49734577
answers question: http://stackoverflow.com/q/49734577
has comment: http://stackoverflow.com/comment/86645698
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86292354
score: 0
type: AnswerComment
has text: This is about the results from a `namedtuple`'s `_asdict()` method, where the results are considered sorted in ascending order already. All that's needed is reversal, not a resort based on the keys.
comment on: http://stackoverflow.com/a/49642375
type: Comment

http://stackoverflow.com/comment/86288891
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49640586
has text: can you provide the full error trace back please..

http://stackoverflow.com/a/49733330
has body: What is the most efficient way to remove Sarah's row? If possible, I would like to avoid copying the entire file. The most efficient way is to overwrite that row with something that the csv parser ignores. This avoids having to move the rows following the removed one. If your csv parser can ignore empty lines, overwrite that row with \n symbols. Otherwise, if your parser strips whitespace from values, overwrite that row with (space) symbols.
has comment: http://stackoverflow.com/comment/86480391
downvote count: 1
has comment: http://stackoverflow.com/comment/86480437
answers question: http://stackoverflow.com/q/49732826
has comment: http://stackoverflow.com/comment/86480477
score: 1
type: Answer
upvote count: 2

http://stackoverflow.com/comment/86290418
score: 1
comment on: http://stackoverflow.com/q/49641319
type: QuestionComment
type: Comment
has text: This is a (somewhat) commonly-asked question, so it must be a dup of something with an answer that would help the OP here (the answer is basically just `inspect.getmembers(module)`), but every answer that seems relevant, the questioner already knows about `inspect`…

http://stackoverflow.com/comment/86290302
type: QuestionComment
comment on: http://stackoverflow.com/q/49641277
has text: No, you can't really do this with a dict comprehension. In a dictionary comprehension, each key corresponds to one value. Here, you want to collect the sum of the values for a particular key, and the code you have doesn't care whether these values are anywhere near each other. (If they were, there might be a way to gather them up and sum them in one step, and this might make a dict comprehension possible.)
score: 1
type: Comment

http://stackoverflow.com/q/49721830
type: Question
score: 3
has comment: http://stackoverflow.com/comment/86457818
has comment: http://stackoverflow.com/comment/86460178
has answer: http://stackoverflow.com/a/49723843
tagged with: python
has body: Why is it that when I try to pass additional parameters, I get the error: The below works fine! (Without parameters) def first(request): return redirect('confirm') def confirm(request): return render(request, 'template.html') However this is what I need, which doesn't work as expected, and I get the error: Reverse for 'confirm' with keyword arguments '{'email': 'email'}' not found. 1 pattern(s) tried: ['book/booking_confirmation/$'] def first(request): return redirect('confirm', email='some_email') def confirm(request, email): return render(request, 'template.html', { 'email': email} ) urls.py urlpatterns += [ url(r'^booking_confirmation/$', views.confirm, name='confirm'), ]
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/49723843
has comment: http://stackoverflow.com/comment/86458593
answer count: 2
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/86458660
has title: Django redirect() with additional parameters
accepted answer: http://stackoverflow.com/a/49733863
favorite count: 0
has answer: http://stackoverflow.com/a/49733863
tagged with: django-views

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/49657966
type: Tag

http://stackoverflow.com/comment/86406698
comment on: http://stackoverflow.com/a/49696605
type: AnswerComment
score: 1
has text: Sure, but best case rarely matters unless you have a good reason to believe the best case will come up often. The average case is still linear. The only way around that would be to impose sorting or hashability or some other constraint and use a data structure that takes advantage of that constraint (like a set).
type: Comment

ttk
tags question: http://stackoverflow.com/q/49645958
tags question: http://stackoverflow.com/q/49754385
tags question: http://stackoverflow.com/q/49638871
tag name: ttk
tags question: http://stackoverflow.com/q/49637559
type: Tag

http://stackoverflow.com/a/49632175
answers question: http://stackoverflow.com/q/49630772
type: Answer
score: 0
has body: It appears that the site is dynamic i.e a front-end script updates the DOM with values from the backend when opened by the browser. To scrape from a dynamic site, you will need to use a browser manipulation tool such as selenium: from selenium import webdriver d = webdriver.Chrome() import re from bs4 import BeautifulSoup as soup d.get('https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Hong-Kong-and-Mainland-Market-Highlights?sc_lang=en#select3=0&amp;select2=2&amp;select1=28') new_data = [[b.text for b in i.find_all('td')] for i in soup(d.page_source, 'lxml').find_all('tr')][2:-2] Output: [[u'No. of listed companies', u'1,827', u'352', u'1,406', u'51', u'2,096', u'49'], [u'No. of listed H shares', u'230', u'24', u'n.a.', u'n.a.', u'n.a.', u'n.a.'], [u'No. of listed red-chips stocks', u'158', u'6', u'n.a.', u'n.a.', u'n.a.', u'n.a.'], [u'Total no. of listed securities', u'13,527', u'353', u'n.a.', u'n.a.', u'n.a.', u'n.a.'], [u'Total market capitalisation(Bil. dollars)', u'HKD 34,139', u'HKD 264', u'RMB 32,376', u'RMB 91', u'RMB 23,008', u'RMB 74'], [u'Total negotiable capitalisation (Bil. dollars)', u'n.a.', u'n.a.', u'RMB 27,500', u'RMB 91', u'RMB 16,580', u'RMB 73'], [u'Average P/E ratio (Times)', u'12.42', u'42.23', u'17.72', u'21.42', u'32.89', u'11.06'], [u'Total turnover (Mil. shares)', u'232,780', u'1,769', u'17,027', u'22', u'19,244', u'13'], [u'Total turnover (Mil. dollars)', u'HKD 137,287', u'HKD 821', u'RMB 210,972', u'RMB 158', u'RMB 268,838', u'RMB 72'], [u'Total market turnover(Mil. dollars)', u'HKD 138,108', u'RMB 213,189', u'RMB 268,910']]

http://stackoverflow.com/comment/86441205
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49713857
score: 0
has text: What is your definition of 'clean'? You can use `any()` and `itertools.combinations()` to avoid 'manual' comparison but I wouldn't call that clean...

string-to-datetime
tag name: string-to-datetime
type: Tag
tags question: http://stackoverflow.com/q/49756649

http://stackoverflow.com/q/49646796
answer count: 2
has title: printf type formating in Python is not returning expected result
has body: I want to embed the numerical variable inside the string with 2 decimal digits. The code is the following: x = 121.37890 print("The variable x has the value %.2d, which is surprising" % x) It returns: The variable x has the value 121, which is surprising What I am doing wrong?
tagged with: string
linked to: http://stackoverflow.com/q/5082452
type: Question
has answer: http://stackoverflow.com/a/49647571
accepted answer: http://stackoverflow.com/a/49647571
tagged with: python-3.x
tagged with: string-formatting
has answer: http://stackoverflow.com/a/49646822
possible better answer: http://stackoverflow.com/a/49646822
tagged with: python
tagged with: printf
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49639155
tagged with: python-3.x
tagged with: stringio
answer count: 2
downvote count: 0
tagged with: python
score: 2
has title: use stringIO object as ssl key/cert file
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49639288
possible better answer: http://stackoverflow.com/a/49639288
tagged with: twisted.internet
tagged with: twisted
has answer: http://stackoverflow.com/a/49651131
accepted answer: http://stackoverflow.com/a/49651131
has body: I want to pull my ssl certificate and key from environment variables and not store them on the filesystem. But I am running into a road block with twisted ssl from io import StringIO from twisted.internet import reactor, task, threads, ssl key = StringIO() key.write(os.environ['SSLKEY']) cert = StringIO() cert.write(os.environ['SSLCERT']) contextFactory = ssl.DefaultOpenSSLContextFactory(key, cert) gives me the following exception 2018-04-03 16:01:28-0500 [-] TypeError: Path must be represented as bytes or unicode string or contextFactory = ssl.DefaultOpenSSLContextFactory(key.getvalue(), cert.getvalue()) gives me the following exception. 2018-04-03 16:02:44-0500 [-] OpenSSL.SSL.Error: [('system library', 'fopen', 'File name too long'), ('BIO routines', 'file_ctrl', 'system lib'), ('SSL routines', 'SSL_CTX_use_certificate_file', 'system lib')] twisted.internet.ssl is looking for a string or bytes object of the filename and io.StringIO gives me a io.StringIO object. Is there anyway to accomplish this?
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/q/49645296
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/18837262
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/49645385
possible better answer: http://stackoverflow.com/a/49645385
tagged with: python
tagged with: dictionary
has title: Adding columns to a dataframe using a dict
has body: I have a dataframe df1 df1 = pd.DataFrame({'c1': [1], 'c2': [2], 'c3': [3]}) I want to add columns to this dataframe using a dictionary dict my_dict = {'c4': 4, 'c5': 5} so I ultimately want df1 to become df2 = pd.DataFrame({'c1': [1], 'c2': [2], 'c3': [3], 'c4': [4], 'c5': [5]}) What I have found on SO is only example where a dictionary is turned into a DataFrame along the rows, e.g. this thread - and not along columns as in the above question.
has answer: http://stackoverflow.com/a/49645355
accepted answer: http://stackoverflow.com/a/49645355
type: AnsweredQuestion
upvote count: 3
answer count: 2

http://stackoverflow.com/comment/86262645
has text: What are the "right results"? I can't match the results in your question.
type: AnswerComment
comment on: http://stackoverflow.com/a/49614390
score: 0
type: Comment

http://stackoverflow.com/q/49650684
tagged with: python
upvote count: 0
downvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86338239
answer count: 1
has comment: http://stackoverflow.com/comment/86309405
has body: I'm learning Logistic regression in Python and have managed to fit a model to my existing data (stock market data), and the predictions produce a nice result. But I do not know how to convert that predictive model in a way I can apply it to future data. Ie is there a y=ax+b algo I can use to input future samples? How do I use the 'model'? How does one use the prediction for subsequent data? Or am I off track here - is Logistic regression not applied in this manner?
favorite count: 0
tagged with: logistic-regression
type: Question
has title: Python Logistic regression and future samples
score: -2
has answer: http://stackoverflow.com/a/49651183

http://stackoverflow.com/comment/86247072
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49619377
has text: I suggest you change your title to better reflect your actual question. What is happening is the default behavior. But if you append a 3 to your title it will make it clear that you want Python 3 instead of 2.7.10.
score: 0

http://stackoverflow.com/comment/86337740
type: QuestionComment
comment on: http://stackoverflow.com/q/49663796
has text: Hi @versatileparsley, it's output is `0.0`.
score: 0
type: Comment

http://stackoverflow.com/comment/86405389
comment on: http://stackoverflow.com/a/49696269
score: 0
has text: I am aware of that, I will update my answer to clarify, but in a sense, it is the representation of an instance, just as a pointer is.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49742866
has comment: http://stackoverflow.com/comment/86501240
has body: Can someone tell me what is the best method to parse the xml doc.. My XML file looks like below. The XML tags are not consistent across every block and my script is failing because it cant find the key in all the iterations. Im using minidom "No PoolTier Here" Not all the "pool" has "pooltier" Snippet from my code: pools = xmldoc.getElementsByTagName('Pool') for poolname in pools: print(poolname.attributes['name'].value) print(poolname.attributes['poolID'].value) poolnam = poolname.attributes['name'].value poolnum = poolname.attributes['poolID'].value pooluse = poolname.attributes['usageRate'].value pooltiers = xmldoc.getElementsByTagName('PoolTier') print(xmldoc.getElementsByTagName('PoolTier')) for tiername in pooltiers: Tid = tiername.attributes['tierID'].value capKB = tiername.attributes['capacityInKB'].value FreeKB = tiername.attributes['freeCapacityInKB'].value Usage = tiername.attributes['usageRate'].value raid = tiername.attributes['raidLevel'].value rpmval = tiername.attributes['rpm'].value dtype = tiername.attributes['diskType'].value print(tiername.attributes['tierID'].value) #print(tiername.attributes['capacityInKB'].value) #print(tiername.attributes['freeCapacityInKB'].value) #print(tiername.attributes['usageRate'].value) #print(tiername.attributes['raidLevel'].value) #print(tiername.attributes['rpm'].value) print(tiername.attributes['diskType'].value) if dtype == "5": dtype = "FMC" #print (poolname.attributes['basicUsableFMCCapacityTotal'].value) capKB = poolname.attributes['basicUsableFMCCapacityTotal'].value UsedFMC = poolname.attributes['basicUsableFMCCapacityUsed'].value FreeKB = int(capKB) - int(UsedFMC) FMCUsage = float(UsedFMC)/float(capKB) * 100 Usage = int(FMCUsage) elif dtype == "4": dtype = "SAS" else: dtype = "Unknown" The issue is, eventhough it encounters a pool with no pooltier, it somehoe gets into 'if dtype == 5" and failing with "KeyError: 'basicUsableFMCCapacityTotal'"
upvote count: 1
has comment: http://stackoverflow.com/comment/86500579
favorite count: 0
has comment: http://stackoverflow.com/comment/86500633
type: Question
has comment: http://stackoverflow.com/comment/86500409
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86500643
tagged with: python
has title: python XML parsing issue with minidom
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/86500398
answer count: 0
score: 1
downvote count: 0

http://stackoverflow.com/q/49627139
tagged with: node.js
score: 0
tagged with: blender
has comment: http://stackoverflow.com/comment/86297932
has comment: http://stackoverflow.com/comment/86275727
has title: Node sockets won't link
type: Question
has body: this is a rather tricky one to google, hence why I'm putting the question here. I know how to create a compositor tree node and how to link the ouput and input sockets, example: link = links.new(RenderLayerNode.outputs[0], SetAlpha.inputs[0]) This is fine, however I noticed that when I try to link certain sockets, they don't work. In this case, I am trying to link the Ambient Occlusion output socket of the 'Render Layer' node to the Image input socket of a 'Set Alpha' node. The blue lines show the links that won't connect for some reason I created Python code to connect these sockets in question, just like I did for all the other sockets, but they don't appear to work. Does anyone have an idea why these sockets specifically won't connect via Python code? They work just fine if you manually link them.
answer count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/86368551

http://stackoverflow.com/comment/86552905
type: Comment
score: 0
type: AnswerComment
has text: now again try this edited code. I guess you are not showing the image.Try showing using imgfilename.show()
comment on: http://stackoverflow.com/a/49748208

http://stackoverflow.com/comment/86531370
comment on: http://stackoverflow.com/a/49738535
has text: See update where you create indicators for the *AlertKey* value rank and then subset entire dataframe into a, *sub* before `groupby`.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86367786
type: Comment
type: QuestionComment
has text: Thanks Jason. Do you think it'll be wise to use this in production? I just need to be able to communicate between Skype and my Python backed. I know I shouldn't be asking this but any tentative date for the official release?
score: 0
comment on: http://stackoverflow.com/q/49665919

http://stackoverflow.com/comment/86399467
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49693410
has text: Put another way, `B` may inherit `A.__init__`, but it's not using it at all here.
score: 0

http://stackoverflow.com/a/49735965
has comment: http://stackoverflow.com/comment/86491802
upvote count: 51
type: Answer
has comment: http://stackoverflow.com/comment/86485981
has body: Here you go with filter df.groupby('city').filter(lambda x : len(x)&gt;3) Out[1743]: city 0 NYC 1 NYC 2 NYC 3 NYC Solution two transform sub_df = df[df.groupby('city').city.transform('count')&gt;3].copy() # add copy for future warning when you need to modify the sub df
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49735683
has comment: http://stackoverflow.com/comment/116223487
answers question: http://stackoverflow.com/q/49735683
has comment: http://stackoverflow.com/comment/86491528
score: 51

http://stackoverflow.com/comment/86342966
score: 1
type: Comment
has text: You need `df = df.reset_index()`, then is possible use `df'Date','PX_FIRST','PX_FIRST'`
type: AnswerComment
comment on: http://stackoverflow.com/a/49666538

http://stackoverflow.com/comment/86239146
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49610780
has text: After logging on to Teradata submit `SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;` within your session once. Then the default lock will switch to ACCESS instead of READ.
score: 1

http://stackoverflow.com/comment/86301414
score: 0
comment on: http://stackoverflow.com/a/49643258
type: AnswerComment
type: Comment
has text: AFAIU, the lookup query is compatible with version 3.6.

http://stackoverflow.com/q/49615548
downvote count: 3
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86237810
has answer: http://stackoverflow.com/a/49615598
type: Question
has answer: http://stackoverflow.com/a/49615606
answer count: 5
has comment: http://stackoverflow.com/comment/86237808
tagged with: python
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/86237940
has body: I have three strings, each having 361 numbers in them. What I need to do is print the strings into three separate columns in a text file. a = [1, 2, 3, 4, 5] b = [1, 2, 3, 4, 5] c = [1, 2, 3, 4, 5] Becomes, 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
has answer: http://stackoverflow.com/a/49615762
has answer: http://stackoverflow.com/a/49616171
upvote count: 0
has answer: http://stackoverflow.com/a/49623399
has title: Writing strings into three columns into a txt file

http://stackoverflow.com/comment/86249342
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49615808
has text: @GreenCloakGuy: do you upload it manually using the same client (i.e. Python)? If not, have you've tried and are you able to reproduce the problem when just uploading this single file?

http://stackoverflow.com/a/49660061
downvote count: 1
answers question: http://stackoverflow.com/q/49659985
has body: a=np.zeros((3,2,2)) b=np.ones((2,2)) a[1]=b*1 That will produce your output.
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/a/49621637
accepted answer of: http://stackoverflow.com/q/49621313
has body: I think it would be easiest to write a new function following similar principles. Your idea "to track the position of each Methionine of the i.find('M')" is basically what's done below. The difficulty in doing this with the code you're starting with is that the sequences get chopped up with the split('*') and so the DNA starting position is the sum of the reading frame offset plus all the codons of segments previous to the sequence of concern. Per your clarification, I added an enclosing loop to iterate across forward and backward directions. def find_largest_polypeptide_in_DNA(seq, translationTable=1): # Set the record to start with, then try to beat it longest_DNA = '' longest_amino_acid_sequence = 0 for direction in [-1, 1]: forward_DNA = seq[::direction] # Check all three reading frames in this direction. for frame in range(3): trans = str(forward_DNA[frame:].translate(translationTable)) cut_codons = 0 while 'M' in trans: codons_before_Met = trans.find('M') cut_codons += codons_before_Met trans = trans[codons_before_Met:] if '*' in trans: length = trans.find('*') + 1 if length &gt; longest_amino_acid_sequence: longest_amino_acid_sequence = length first_bp = frame + 3*cut_codons last_bp = frame + 3*cut_codons + 3*(length) longest_DNA = str(forward_DNA[first_bp:last_bp+1]) trans = trans[length:] else: # Ignore sequence M... if ORF extends beyond FASTA? trans = '' return longest_DNA
answers question: http://stackoverflow.com/q/49621313
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49663455
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86338932
accepted answer of: http://stackoverflow.com/q/49663415
answers question: http://stackoverflow.com/q/49663415
type: Answer
has body: Why not just make your own function? def my_stdev(df): return df.resample('M').std().mean()*12**(1/2) result = my_stdev(any_df)

http://stackoverflow.com/q/49672676
has answer: http://stackoverflow.com/a/49672985
type: UnansweredQuestion
has title: check several lists with several for loops
has comment: http://stackoverflow.com/comment/86355921
tagged with: python
score: 0
tagged with: list
has body: keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q'] List = ['A','B','C'] I want to make an Operation for every element in List and for every element in keylist : for n in List: for key in keylist: if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P': try: print(n) #placeholder except: pass Basically, I want to check if the first split element of keylist is an element of List but the Output is an error: TypeError: list indices must be integers or slices, not str
answer count: 3
has comment: http://stackoverflow.com/comment/86355836
has answer: http://stackoverflow.com/a/49672916
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/49673403

http://stackoverflow.com/q/49714244
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49714772
has body: I am trying to code something where I first look for some string in a line in a txt file and when it is found I want to skip that row and the row below to get a new txt file without those rows. I really didn't get any solution from other questions here so maybe this will work My code looks like this now: with open("bla.txt", "r+") as f new_f = f.readlines() f.seek(0) for line in new_f: if "abc" not in line: f.write(line) else: pass pass f.truncate() I tried it with next(f) aswell but it didn't work for me. thanks in advance
answer count: 2
has answer: http://stackoverflow.com/a/49714718
has title: skip 2 lines after a match while reading from a file
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: lines
tagged with: match
has comment: http://stackoverflow.com/comment/86442529

http://stackoverflow.com/q/49665324
has answer: http://stackoverflow.com/a/49665935
accepted answer: http://stackoverflow.com/a/49665746
has body: I am using python FTP server and client program. My need is to run Python FTP server on a remote machine that is connected on the same network as my local machine. FTP client will run from local machine, I need to connect FTP server with my FTP client running on local machine. Please help! This is my ftpserver.py: from pyftpdlib.servers import FTPServer from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler authorizer = DummyAuthorizer() authorizer.add_user("lokesh", "123", "current_dir", perm="elradfmw") authorizer.add_anonymous("curent_dir", perm="elradfmw") handler = FTPHandler handler.authorizer = authorizer server=FTPServer(("localhost",8080),handler) server.serve_forever() This is my ftpclient.py that needs to connect with the above server: from ftplib import FTP ftp = FTP('') host='localhost' port=8080 ftp.connect(host,port) ftp.login() print(ftp.getwelcome()) print('Current Directory ',ftp.pwd()) ftp.dir() ftp.quit() When I test my server and client on same machine it worked. But when I run the same server on another machine and tried to connect with my client it gave me error: error: [Errno 10061] No connection could be made because the target machine actively refused it
has answer: http://stackoverflow.com/a/49665746
favorite count: 0
type: Question
upvote count: 4
tagged with: ftp
answer count: 2
tagged with: ftplib
downvote count: 0
tagged with: python
has title: How to connect remote Python FTP server to local Python FTP client
score: 4
possible better answer: http://stackoverflow.com/a/49665935
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/86402919
score: 2
comment on: http://stackoverflow.com/q/49695050
has text: Lambda doesn't have native device driver support for s3:// URIs like that. Write the CSV file to local file system (/tmp) and then use boto3's put_object() method. You can also stream the file contents into S3 using boto3, if preferred.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49600430
answer count: 0
tagged with: forecasting
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: convergence error in facebook prophet in python
score: 4
upvote count: 4
has body: INFO:fbprophet.forecaster:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this. Initial log joint probability = -2.46502 Iter log prob ||dx|| ||grad|| alpha alpha0 # evals Notes 99 402.571 0.000207143 101.815 0.9661 0.9661 136 Iter log prob ||dx|| ||grad|| alpha alpha0 # evals Notes 199 402.966 1.93889e-06 74.3745 0.2165 0.7593 282 Iter log prob ||dx|| ||grad|| alpha alpha0 # evals Notes 217 402.968 8.45346e-06 60.1757 1.2e-07 0.001 339 LS failed, Hessian reset 247 402.968 1.74976e-08 64.7367 0.2863 0.2863 382 Optimization terminated normally: Convergence detected: relative gradient magnitude is below tolerance This output is coming for me. Please help.
tagged with: facebook-prophet

row
tags question: http://stackoverflow.com/q/49691983
tags question: http://stackoverflow.com/q/49755687
tags question: http://stackoverflow.com/q/49673876
tag name: row
tags question: http://stackoverflow.com/q/49713951
type: Tag

http://stackoverflow.com/comment/86332038
type: QuestionComment
has text: try to print data please, your regex is correct and works on a string
score: 0
comment on: http://stackoverflow.com/q/49661089
type: Comment

http://stackoverflow.com/a/49748494
has comment: http://stackoverflow.com/comment/91344523
has comment: http://stackoverflow.com/comment/87212228
has comment: http://stackoverflow.com/comment/108304008
has comment: http://stackoverflow.com/comment/104782972
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/104275799
has comment: http://stackoverflow.com/comment/91343817
has comment: http://stackoverflow.com/comment/91616829
has comment: http://stackoverflow.com/comment/87147542
has comment: http://stackoverflow.com/comment/90074370
has comment: http://stackoverflow.com/comment/114940926
has comment: http://stackoverflow.com/comment/87651819
has comment: http://stackoverflow.com/comment/86658881
has comment: http://stackoverflow.com/comment/117020452
has body: Upgrade pip as follows: curl https://bootstrap.pypa.io/get-pip.py | python Note: You may need to use sudo python above if not in a virtual environment. What's happening: Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac&nbsp;OS&nbsp;X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above. (Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue) This thread explains it (thanks to this Twitter post): Mac users who use pip and PyPI: If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely: curl https://bootstrap.pypa.io/get-pip.py | python and we recommend you do that by April 8th. Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS &lt; 10.13. Official release notes: https://pip.pypa.io/en/stable/news/ Also, the Python status page: Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above: pip install --upgrade setuptools
has comment: http://stackoverflow.com/comment/87744487
has comment: http://stackoverflow.com/comment/89710335
has comment: http://stackoverflow.com/comment/87143447
has comment: http://stackoverflow.com/comment/90102811
has comment: http://stackoverflow.com/comment/91343751
has comment: http://stackoverflow.com/comment/116746891
accepted answer of: http://stackoverflow.com/q/49748063
has comment: http://stackoverflow.com/comment/91343528
has comment: http://stackoverflow.com/comment/90068120
has comment: http://stackoverflow.com/comment/87753104
has comment: http://stackoverflow.com/comment/90101260
has comment: http://stackoverflow.com/comment/97944621
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/100270431
score: 188
has comment: http://stackoverflow.com/comment/128498262
has comment: http://stackoverflow.com/comment/91365958
answers question: http://stackoverflow.com/q/49748063
has comment: http://stackoverflow.com/comment/87035934
has comment: http://stackoverflow.com/comment/99343304
upvote count: 189
has comment: http://stackoverflow.com/comment/91364724

http://stackoverflow.com/comment/86293910
has text: I added explanation of basic lookarounds
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49643098
type: Comment

http://stackoverflow.com/comment/86444988
has text: Ah, guess I was confusing global variables with class variables. Got it, thank you.
type: Comment
comment on: http://stackoverflow.com/a/49715880
score: 0
type: AnswerComment

http://stackoverflow.com/a/49667042
has body: Use: df = df.mask(df &gt; 100) df = df.where(df &lt;= 100) df = pd.DataFrame(np.where(df &gt; 100, np.nan, df), index=df.index, columns=df.columns) print (df) a b c 0 1.0 60.0 15.0 1 NaN 51.0 NaN 2 NaN NaN 1.0 Fast comparison (depends of data): df = pd.concat([df] * 10000, ignore_index=True) In [104]: %timeit pd.DataFrame(np.where(df &gt; 100, np.nan, df), index=df.index, columns=df.columns) The slowest run took 4.37 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 683 µs per loop In [105]: %timeit df[:] = np.where(df.values &lt;= 100, df.values, np.nan) __main__:257: RuntimeWarning: invalid value encountered in less_equal The slowest run took 17.24 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 957 µs per loop In [106]: %timeit df.mask(df &gt; 100) 1000 loops, best of 3: 1.56 ms per loop In [107]: %timeit df.where(df &lt;= 100) The slowest run took 8.01 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 1.84 ms per loop In [108]: %timeit df[df&lt;100] The slowest run took 5.57 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 1.89 ms per loop
upvote count: 4
answers question: http://stackoverflow.com/q/49667026
score: 4
has comment: http://stackoverflow.com/comment/86344009
downvote count: 0
has comment: http://stackoverflow.com/comment/86343974
has comment: http://stackoverflow.com/comment/86344092
has comment: http://stackoverflow.com/comment/86344073
has comment: http://stackoverflow.com/comment/86343937
accepted answer of: http://stackoverflow.com/q/49667026
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/88945285
has text: are you aware of a way to save dash layouts to html that would work?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49979161
score: 0

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/49724939

http://stackoverflow.com/a/49758031
score: 0
has body: When you do Process().get_process_id(), you are creating a new instance of the library. This instance doesn't know about any processes started by the previous instance of the library. You need to get a single instance of the library, and use that consistently. processLib = Process() processLib.start_process(...) var = processLib.get_process_id() The best thing to do is try to get a reference to an existing process library using BuiltIn().get_library_instance, and only create a new one if it doesn't exist.
type: Answer
accepted answer of: http://stackoverflow.com/q/49756797
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49756797

http://stackoverflow.com/comment/86527493
has text: Thanks, but it does not solve the issue of splitting longer session between hours. E.g. if you take the third row, in the output it should be split into two rows, so 2956 seconds should be divided into 170 secs in 8:00 and 2786 in 9:00
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49753942
type: AnswerComment

http://stackoverflow.com/a/49641978
type: Answer
has comment: http://stackoverflow.com/comment/86297817
upvote count: 2
score: 2
has body: These two lines should do it: df['xDiff'] = df.groupby('lineNum').diff()['xPos'] df.loc[df['xDiff'].isnull(), 'xDiff'] = df['xPos'] - minxPos &gt;&gt;&gt; df xPos lineNum xDiff 0 40 1 2.0 1 50 1 10.0 2 75 1 25.0 3 90 1 15.0 4 42 2 4.0 5 75 2 33.0 6 110 2 35.0 7 45 3 7.0 8 70 3 25.0 9 95 3 25.0 10 125 3 30.0 11 38 4 0.0 12 56 4 18.0 13 74 4 18.0
downvote count: 0
has comment: http://stackoverflow.com/comment/86312725
has comment: http://stackoverflow.com/comment/86293009
answers question: http://stackoverflow.com/q/49641907

http://stackoverflow.com/comment/86441369
has text: thank you. Can you please let me know what '^0+' is and where I can learn more about it?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49714038

http://stackoverflow.com/q/49730414
score: 0
accepted answer: http://stackoverflow.com/a/49730489
possible better answer: http://stackoverflow.com/a/49730953
has answer: http://stackoverflow.com/a/49730489
has answer: http://stackoverflow.com/a/49730953
type: Question
type: AnsweredQuestion
has body: I have created a unittest module called test_blbmktdata.py to test some code. I am trying to run it from the console using the following command: run test_blbmktdata.py However I get the error message: ERROR:root:File `'test_blbmktdata.py'` not found. Please see below for the module code. import unittest class TestBlbMktData(unittest.TestCase): staticName='StaticInstrumentData.csv' def print(self,data): print() print(len(data)) print(data.head()) print(data.dtypes) def read(self,name,func): return func(os.path.join(self.current_dir,name)) def setUp(self): self.current_dir=os.path.dirname(os.path.abspath(__file__)) def test_corp_act(self): self.print(self.read(self.corpName,readCorpAction)) if __name__ == '__main__' : unittest.main() How can I run the code from the console?
has title: Trying to run a unittest module
tagged with: python
answer count: 2

http://stackoverflow.com/comment/86299445
score: 0
has text: Not 100% sure, but it is tested in excel? If use some text editer like notepad++ same problem?
comment on: http://stackoverflow.com/q/49645667
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/133865642
comment on: http://stackoverflow.com/a/58349659
type: AnswerComment
score: 0
type: Comment
has text: @NeilG test that's my point. They are in a seperate code base which tools are by no means explicitly required to read. Ergo it's incorrect to suggest Pycharm is "simply wrong". The story is a whole lot more complicated than that.

http://stackoverflow.com/q/49689595
type: Question
has title: Forming C Structure in python
tagged with: python
type: UnansweredQuestion
has body: for small structure sizes ,i am using named tuple and struct.pack in python 2.7 like this format_="i" namedtuple("connections","number") connection(number=0) struct.pack(format_, *connection_tuple) Now i have to frame bigger structures having structure inside structure,we can do by struct.pack but is there any other way we can form the big strucutue data?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86392129
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86391903
has comment: http://stackoverflow.com/comment/86483441

http://stackoverflow.com/comment/86281234
type: AnswerComment
has text: works on my machine ¯\_(ツ)_/¯. AFAIK the difference between w and a is simply creating a new file vs appending. OP seemed to indicate wanting a new file each time so `w` makes more sense to me
comment on: http://stackoverflow.com/a/49636782
score: 0
type: Comment

http://stackoverflow.com/comment/86256485
type: Comment
score: 2
has text: This worked without problem on my installation
comment on: http://stackoverflow.com/q/49624744
type: QuestionComment

http://stackoverflow.com/comment/86302760
score: 0
type: Comment
type: QuestionComment
has text: Hello Adoni. It is only concerning pycurl. I imported other modules like requests without any issue. Yes my virtual env seems properly setup. Waiting for Pycurl I will use requests but this issue is triggering me somehow.
comment on: http://stackoverflow.com/q/49645581

http://stackoverflow.com/comment/86229260
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49611181
has text: Perhaps cx_freeze didn't package the ffmpeg library with your code?
score: 1

http://stackoverflow.com/q/49705523
has title: How to retrieve values from drop down when select tag style attribute is set as display: none; in python selenium
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49705753
tagged with: python
possible better answer: http://stackoverflow.com/a/49706171
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
tagged with: display
has body: I am trying to scrap all combination of categories of drop down from one site. However text attribute of option is coming as blank only. Although while inspecting, I can see text is present for each option. from selenium import webdriver from selenium.webdriver.support.ui import Select driver = webdriver.Chrome() driver.get('https://www.fiyo.nl/') driver.find_element_by_xpath('//*[@id="select_device_chosen"]/a').click() select = Select(driver.find_element_by_xpath('//*[@id="select-device"]')) print ([o.text for o in select.options]) Output: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] if I get text, I want to loop through all values to get different combination of other drop down.
has answer: http://stackoverflow.com/a/49706171
answer count: 2
upvote count: 2
downvote count: 0
tagged with: selenium
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/49705753

http://stackoverflow.com/comment/86488452
score: 0
comment on: http://stackoverflow.com/q/49730922
has text: `np.array(...)` treats a list of tuples the same as a list of lists (unless you specify a compound dtype).
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49698209
answers question: http://stackoverflow.com/q/49698111
has body: You can just use DataFrame.filter with the size function: from pyspark.sql.functions import size df.filter(size('words') &gt; 2).show() +---+---------+ | id| words| +---+---------+ | 1|[a, b, c]| +---+---------+ I would do it before CountVectorizer to avoid having it do work that doesn't need to be done. Spark will pull filter operations earlier in the execution plan if it can determine it safe to do so, but being explicit is always better.
has comment: http://stackoverflow.com/comment/86409730
accepted answer of: http://stackoverflow.com/q/49698111
score: 10
upvote count: 10
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49614238
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
has body: The quickstart code on https://developers.google.com/drive/v3/web/quickstart/python lists 10 files from my Google Drive. What should I do so that it lists only the files that I have publicly shared? Is there any parameter for that purpose?
favorite count: 0
has answer: http://stackoverflow.com/a/49624108
has title: How do I list files publicly shared by me using google drive API?
tagged with: python
type: Question
tagged with: google-drive-api

http://stackoverflow.com/comment/86250335
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49621313
has text: I want the longest segment that begins with a M and ends with Stop codon @BennettBrown
score: 0

http://stackoverflow.com/comment/86522388
has text: Do you want to export the *class definitions* into YAML or the *class instances*?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49747632

http://stackoverflow.com/comment/86228456
has text: Please show the full traceback. Calling `str()` is converting explicitly, not "implicitly", so chances are the error is not happening where you think.
comment on: http://stackoverflow.com/q/49610972
type: QuestionComment
type: Comment
score: 3

http://stackoverflow.com/comment/86365562
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49665056
has text: Hey Hi , I just found out that it has one element then it is treat as an object and if it has multiple element then it is treated as an array. The problem now is that how do I normalise the file because in the same object we have data which belongs to object type and array type .. how shall I normalise that ?

http://stackoverflow.com/comment/110135250
comment on: http://stackoverflow.com/a/49679189
score: 1
type: Comment
type: AnswerComment
has text: Does the Reshape layer propagate masks?

http://stackoverflow.com/comment/86261819
type: Comment
type: QuestionComment
has text: Sorry, I did not mean to be rude, was just trying to understand the question to help. Maybe my sentence is badly written
comment on: http://stackoverflow.com/q/49627281
score: 0

http://stackoverflow.com/q/49687316
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86385835
has body: I am trying to run a script and I want its stdout to be redirected to a file. Script is using logging module for logging. When I try to run python verifyPhone.py -f dupl.csv 1&gt; deleted.txt It starts printing output to screen instead of file. But if I replace logger.info with print, I can see outputs in the file. I am not able to figure out why this is happening. Does logger does not print to stdout ? How I can see output on terminal if my stdout is already redirected to file ?
tagged with: logging
type: Question
has comment: http://stackoverflow.com/comment/86386000
has title: Output redirection with python
has comment: http://stackoverflow.com/comment/86385756
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/14058453

http://stackoverflow.com/q/49659649
has title: How can I reshape this DataFrame with Pivot function?
has comment: http://stackoverflow.com/comment/86331187
has comment: http://stackoverflow.com/comment/86329620
tagged with: pandas
answer count: 0
tagged with: pivot
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86331923
has comment: http://stackoverflow.com/comment/86331284
has comment: http://stackoverflow.com/comment/86331282
has body: I work with this movies dataset containing following information: df.head(10) color director_name num_critic_for_reviews duration director_facebook_likes actor_3_facebook_likes actor_2_name actor_1_facebook_likes gross genres ... num_user_for_reviews language country content_rating budget title_year actor_2_facebook_likes imdb_score aspect_ratio movie_facebook_likes 0 Color James Cameron 723.0 178.0 0.0 855.0 Joel David Moore 1000.0 760505847.0 Action|Adventure|Fantasy|Sci-Fi ... 3054.0 English USA PG-13 237000000.0 2009.0 936.0 7.9 1.78 33000 1 Color Gore Verbinski 302.0 169.0 563.0 1000.0 Orlando Bloom 40000.0 309404152.0 Action|Adventure|Fantasy ... 1238.0 English USA PG-13 300000000.0 2007.0 5000.0 7.1 2.35 0 2 Color Sam Mendes 602.0 148.0 0.0 161.0 Rory Kinnear 11000.0 200074175.0 Action|Adventure|Thriller ... 994.0 English UK PG-13 245000000.0 2015.0 393.0 6.8 2.35 85000 3 Color Christopher Nolan 813.0 164.0 22000.0 23000.0 Christian Bale 27000.0 448130642.0 Action|Thriller ... 2701.0 English USA PG-13 250000000.0 2012.0 23000.0 8.5 2.35 164000 4 NaN Doug Walker NaN NaN 131.0 NaN Rob Walker 131.0 NaN Documentary ... NaN NaN NaN NaN NaN NaN 12.0 7.1 NaN 0 5 Color Andrew Stanton 462.0 132.0 475.0 530.0 Samantha Morton 640.0 73058679.0 Action|Adventure|Sci-Fi ... 738.0 English USA PG-13 263700000.0 2012.0 632.0 6.6 2.35 24000 6 Color Sam Raimi 392.0 156.0 0.0 4000.0 James Franco 24000.0 336530303.0 Action|Adventure|Romance ... 1902.0 English USA PG-13 258000000.0 2007.0 11000.0 6.2 2.35 0 7 Color Nathan Greno 324.0 100.0 15.0 284.0 Donna Murphy 799.0 200807262.0 Adventure|Animation|Comedy|Family|Fantasy|Musi... ... 387.0 English USA PG 260000000.0 2010.0 553.0 7.8 1.85 29000 8 Color Joss Whedon 635.0 141.0 0.0 19000.0 Robert Downey Jr. 26000.0 458991599.0 Action|Adventure|Sci-Fi ... 1117.0 English USA PG-13 250000000.0 2015.0 21000.0 7.5 2.35 118000 9 Color David Yates 375.0 153.0 282.0 10000.0 Daniel Radcliffe 25000.0 301956980.0 Adventure|Family|Fantasy|Mystery…
tagged with: dataset
has comment: http://stackoverflow.com/comment/86329697
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/95760769
has comment: http://stackoverflow.com/comment/86336141
has comment: http://stackoverflow.com/comment/86330906
has comment: http://stackoverflow.com/comment/86332184
has comment: http://stackoverflow.com/comment/86329929
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86331311
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86330918

http://stackoverflow.com/q/49647875
has comment: http://stackoverflow.com/comment/86309691
has answer: http://stackoverflow.com/a/49647987
has comment: http://stackoverflow.com/comment/86367384
score: 16
has comment: http://stackoverflow.com/comment/86304383
favorite count: 0
has answer: http://stackoverflow.com/a/49680162
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87586497
has body: I'm plotting some categorical data using a bar chart. Matplotlib keeps sorting my x-axis alphabetically even when I sort my dataframe values. Here's my code : fig3, new_ax = plt.subplots(1,1, figsize=(25/3,5)) summary = tsa.source.sum().sort_values(ascending=False) new_ax.bar(summary.index, summary.values, color=my_colors) new_ax.legend() bar_heights(new_ax) # custom function to get the values on top of bars simpleaxis(new_ax) # custom function to define an axis to please my boss... new_ax.set_ylabel('Effectifs') new_ax.set_xlabel("Type d'arme") new_ax.grid(False) Output : And yet here's what summary looks like and that's the order I want to see on my chart : famas 2214.0 aut_typebruit 759.0 grena 200.0 flg 78.0 douze 72.0 sept 53.0 dtype: float64 Here's a link to a sample of my data : https://files.fm/u/wumscb4q import it with this line : tsa.source = pd.read_csv('sample.csv', sep=';', index_col=0) And here my functions : def simpleaxis(ax): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() def bar_heights(axes): for rect in axes.containers[0]: height = rect.get_height() rect.axes.text(rect.get_x() + rect.get_width()/2., height+3, '%d' % int(height), ha='center', va='bottom')
type: UnansweredQuestion
upvote count: 18
tagged with: python
has comment: http://stackoverflow.com/comment/92858414
has title: How to prevent alphabetical sorting for python bars with matplotlib?
has comment: http://stackoverflow.com/comment/86322397
answer count: 2
downvote count: 2
tagged with: matplotlib

http://stackoverflow.com/q/49752761
has body: I want to select rows by join several tables on multiples conditions... and it fails. PonyORM seems to limit the number of conditions in "if statement". To reproduce, in estore.py / test_queries (PY3.6, PonyORM 0.73) , a stupid example: result = select(c for c Customer if c.country!='A' and c.country!='A' and c.country!='A' and c.country!='A' and c.country!='A' and ...) If Nbr of c.country! = 'A' &lt;= 24, it works, but &gt;= 25, it failed in decompiling.py How to bypass this limit, annoying for queries with a lot of tables and conditions? Traceback &lt;module&gt; site-packages\pony\orm\examples\estore.py 183 test_queries &lt;string&gt; 2 new_func site-packages\pony\orm\core.py 460 test_queries site-packages\pony\orm\examples\estore.py 169 select &lt;string&gt; 2 cut_traceback site-packages\pony\utils\utils.py 58 select site-packages\pony\orm\core.py 5160 make_query site-packages\pony\orm\core.py 5147 decompile site-packages\pony\orm\decompiling.py 32 __init__ site-packages\pony\orm\decompiling.py 72 decompile site-packages\pony\orm\decompiling.py 90 TypeError: unsupported operand type(s) for &lt;&lt;: 'list' and 'int' EDIT : as a workaround , we can split the query by adding .where result = select(c for c Customer if c.country!='A' and c.country!='A' and c.country!='A' and c.country!='A' and c.country!='A').where(lambda c:c.country!='A' and c.country!='A')
favorite count: 0
type: Question
type: UnansweredQuestion
has title: ponyORM : how to bypass limit in select
has answer: http://stackoverflow.com/a/50991046
tagged with: python
has comment: http://stackoverflow.com/comment/86520731
tagged with: ponyorm
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49613177
score: 3
has comment: http://stackoverflow.com/comment/86295831
type: Answer
has comment: http://stackoverflow.com/comment/86238832
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: Steam stores the result of submitting this form in lastagecheckage and birthtime, cookies, so you may need to enable cookies on your scrapy project or passing them as custom values during the creation of a Request or a FormRequest using the cookies attribute. You can read more about how to sent cookies on the scrapy documentation
accepted answer of: http://stackoverflow.com/q/49612346
answers question: http://stackoverflow.com/q/49612346

http://stackoverflow.com/a/49681506
type: AcceptedAnswer
has body: You are looking for df.loc For example: df.loc[df['col1']==3] Returns all rows where col1 == 3 Or: df.loc[df['col1']==3, ['col2', 'col1']] Returns a dataframe like the one above but it only has col1 and col2
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49681446
accepted answer of: http://stackoverflow.com/q/49681446

http://stackoverflow.com/q/49688681
has body: I write a code to put an imshow in a pyqt environment but the imshow is not centered in the figure: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import numpy as np import sys import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class GenerateCM(QMainWindow): def __init__(self, parent=None): super(GenerateCM, self).__init__() self.CM = np.zeros((10,10)) ####################################### self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self.mainHBOX_param_scene = QHBoxLayout() #CM view layout_plot = QHBoxLayout() self.loaded_plot = CMViewer(self) self.loaded_plot.setMinimumHeight(200) self.loaded_plot.update() layout_plot.addWidget(self.loaded_plot) self.mainHBOX_param_scene.addLayout(layout_plot) self.centralWidget.setLayout(self.mainHBOX_param_scene) class CMViewer(QGraphicsView): def __init__(self, parent=None): super(CMViewer, self).__init__(parent) self.parent=parent self.scene = QGraphicsScene(self) self.setScene(self.scene) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) # self.canvas.setGeometry(0, 0, 1600, 500 ) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.setLayout(layout) self.canvas.show() def update(self): self.connectivityMat = self.parent.CM self.figure.clear() self.axes=self.figure.add_subplot(1,1,1) im = self.axes.imshow(self.connectivityMat) self.figure.colorbar(im) self.axes.axis('off') self.axes.set_title('Loaded Matrix') self.canvas.draw() self.canvas.show() def main(): app = QApplication(sys.argv) ex = GenerateCM(app ) ex.show() sys.exit(app.exec_( )) if __name__ == '__main__': main() Which give me this result. I would like the image to be in the center of the window and not shifted to the rigth as it is for now. I thing…
score: 2
answer count: 0
tagged with: pyqt
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: matplotlib
tagged with: imshow
tagged with: python
has title: Imshow in pyQt is not centered

http://stackoverflow.com/comment/86397273
type: Comment
has text: @PauloAlmeida and how will it include the original image if user lete the previous image attached and update the post?hope you can help
type: QuestionComment
comment on: http://stackoverflow.com/q/49691443
score: 0

http://stackoverflow.com/a/61441768
answers question: http://stackoverflow.com/q/49615715
has body: These steps will work as of April, 2020: Rename your notebook and add ?forceRefresh=true to the url and press enter. Your entire Jupyter notebook will be restarted. Go to the course week and a fresh notebook will be there.
type: Answer
upvote count: 4
score: 4
downvote count: 0

http://stackoverflow.com/comment/86282878
type: Comment
has text: that's bad to return a list or a string depending on the outcome of the tests... please provide input & expected output.
type: QuestionComment
comment on: http://stackoverflow.com/q/49637441
score: 0

http://stackoverflow.com/comment/96487334
comment on: http://stackoverflow.com/q/49600074
has text: Thanks for the suggestion -- I'll give it a try.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49685152
has comment: http://stackoverflow.com/comment/86381959
answer count: 1
has title: Inorder Traversal representation
tagged with: python
accepted answer: http://stackoverflow.com/a/49685364
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/231767
has answer: http://stackoverflow.com/a/49685364
score: 0
has comment: http://stackoverflow.com/comment/86381887
has comment: http://stackoverflow.com/comment/86381846
tagged with: inorder
has body: I am working on an Inorder traversal for my binary search tree and I was wondering if there is any way to print out the content of my inorder traversal all in the same line. So, for example, let's say I want it to come out as [ -1, 1, 3, 6, 8, 10, 14, 90] instead of how it actually does which if one by one. Just looking for ways to make the outcome look nicer. If you have any suggestions let me know. I have tried a few things but they don't seem to work. def __in_order(self, root): if root == None: return else: self.__in_order(root.left_child) print(str(root.value)) self.__in_order(root.right_child)
type: Question
tagged with: binary-search-tree
has comment: http://stackoverflow.com/comment/86381747

http://stackoverflow.com/q/49627267
type: AnsweredQuestion
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49627462
accepted answer: http://stackoverflow.com/a/49627462
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 0
has comment: http://stackoverflow.com/comment/86261446
has body: I am trying to create a image classifier with tensorflow using python. however im getting this strange error with my index being out of range. The program is suppose to grab the files read the first 3 letters are train off whether its a cat or a dog. import cv2 import numpy as np import os from random import shuffle from tqdm import tqdm TRAIN_DIR = 'C:\\Users\\cward\\Desktop\\images\\train' TEST_DIR = 'C:\\Users\\cward\\Desktop\\images\\test' IMG_SIZE = 50 LR = 1e-3 MODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR, '2conv-basic') def label_img(img): word_label = img.split('.')[-2] if word_label == 'cat': return[1,0] elif word_label == 'dog': return[0,1] def create_train_data(): training_data = [] for img in tqdm(os.listdir(TRAIN_DIR)): label = label_img(img) path = os.path.join(TRAIN_DIR, img) img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE,IMG_SIZE)) training_data.append([np.array(img), np.array(label)]) shuffle(traning_data) np.save('train_data.npy', traning_data) return training__data def process_test_data(): testing_data = [] for img in tqdm(os.listdir(TRAIN_DIR)): path = os.path.join(TRAIN_DIR, img) img_num = img.split('.')[0] img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE,IMG_SIZE)) testing_data.append([np.array(img), img_num]) np.save('test_data.npy',testing_data) return testing_data train_data = create_train_data() Here is the error: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-34-40719067ea74&gt; in &lt;module&gt;() ----&gt; 1 train_data = create_train_data() &lt;ipython-input-32-88b70eb23645&gt; in create_train_data() 2 training_data = [] 3 for img in tqdm(os.listdir(TRAIN_DIR)): ----&gt; 4 label = label_img(img) 5 path = os.path.join(TRAIN_DIR, img) 6 img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE,IMG_SIZE)) &lt;ipython-input-31-82bc72a4ed99&gt; in label_img(img) 1 def label_img(img): ----&gt; 2 word_labe…
score: -4
tagged with: machine-learning
tagged with: python
has title: My list index is out of range
downvote count: 4

http://stackoverflow.com/comment/86335650
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49662798
has text: If you want it to not depend on your Python DLL, you need to make a static build. I'm pretty sure the demos show how to do this for Windows. Meanwhile, if you want it to call Python code out of your stdlib, you need to install the stdlib, or at least the part that you use, in some way. You don't need to use py2exe or pyinstaller for that, but if not, you have to do what it does.

http://stackoverflow.com/comment/86325645
score: 5
comment on: http://stackoverflow.com/q/49658210
has text: [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial)?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49678003
has comment: http://stackoverflow.com/comment/86367448
has comment: http://stackoverflow.com/comment/86368576
has comment: http://stackoverflow.com/comment/86368328
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49675696
downvote count: 0
upvote count: 1
has body: You want the command to be the input to the subprocess you created, not the name of a new subprocess. If you have a new enough Python, try output = subprocess.run(['/opt/cdma-msc/sccli'], stdout = subprocess.PIPE, input='show system', check=True, universal_newlines=True).stdout The result returned by run is an object which encapsulates the result code and status of the subprocess as well as the output from it. Its stdout member contains the text produced on standard output. Unfortunately, run was only introduced in Python 3.5 but it's enough of an improvement that you might want to not support older versions of Python. If you have to support older versions, the equivalent code is considerably clunkier: p = subprocess.Popen(['/opt/cdma-msc/sccli'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate('show system') Here, stdout is simply a string with the output. You should generally avoid raw Popen() unless the higher-level wrappers absolutely cannot do what you want. There is also obviously no need for shell=True when there are no wildcards, pipelines, rediections, or even argument parsing (you already broke the command line into a list of strings).
score: 1
has comment: http://stackoverflow.com/comment/86371625
answers question: http://stackoverflow.com/q/49675696
has comment: http://stackoverflow.com/comment/86368783
has comment: http://stackoverflow.com/comment/86371630
type: Answer
has comment: http://stackoverflow.com/comment/86411304

http://stackoverflow.com/comment/86313190
type: AnswerComment
has text: OP's Question is asking to findall "ng-scope" your answer doesn't help achieve that .
type: Comment
comment on: http://stackoverflow.com/a/49652192
score: 0

vector
tags question: http://stackoverflow.com/q/49697854
type: Tag
tags question: http://stackoverflow.com/q/49730152
tag name: vector

http://stackoverflow.com/q/49740139
tagged with: python
has body: 1- How can I select 5 different values inside a column ? Example: **Car** Fiat Fiat Hyundai Mitsubish Kia Kia Hyundai renault porsche How can I select the rows that has (Fiat, hyundai , Kia) for example ? I tried this: df.loc[df['cars'].isin("Fiat", "hyundai" , "Kia")] But no success Second problem: In R we have pipe operator in order to reduce the number of new Copies*. What is the best solution in python ? *Update - Is it a good way to create manipulation data of multiple steps ? In this example: df1 = df1.dropna() df1 = df1[(df1['Meses'] != 'Total') &amp; (df1['Orcado x Realizado'] == 'Realizado') &amp; (df1['Area Negocio'] == 'Total das Áreas de Negócios')] df1['Meses'] = df1['Meses'].replace({'M1': '01', 'M2': '02', 'M3': '03', 'M4': '04', 'M5': '05', 'M4': '04', 'M5': '05', 'M6': '06', 'M7': '07', 'M8': '08', 'M9': '09', 'M10': '10', 'M11': '11', 'M12': '12'}) df1['Date'] = pd.to_datetime(df1.Ano.astype(str) + '-' + df1.Meses.astype(str)) df1['Values'] = (df1['Values'] / 1000000) df1 = df1'Date', 'Contas Resultado', 'Values' Is there a way to make this code shorter, without having to create new variables ?
tagged with: numpy
has comment: http://stackoverflow.com/comment/86494845
has title: How to select certain rows from a dataframe in pandas
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49740213
answer count: 1
has comment: http://stackoverflow.com/comment/86494784
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49740213
tagged with: data-manipulation

http://stackoverflow.com/comment/86371211
type: QuestionComment
comment on: http://stackoverflow.com/q/49657966
score: 0
has text: VMware interface itself can be automated. But the app in the guest OS must be automated inside the virtual machine (i.e. remotely as well). If you have pre-built guest OS image with correct network settings, copying and running automation script on this VM is definitely possible. If OS installation automation is needed, there should be another way like PXE boot. Some install scripts could be integrated into the installation image then.
type: Comment

http://stackoverflow.com/q/49685846
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86382848
has body: I have two df's which I created after executing group by of 2 dataframes. I need to join these two summary outputs to check if there is a difference in hours claimed. df1 = pd.DataFrame({"Week": ["3/30/2018", "3/30/2018", "3/30/2018", "3/23/2018", "3/23/2018","3/16/2018", "3/16/2018", "3/9/2018", "3/9/2018"], "Empl": ["Sam", "John", "Mike", "Sam", "Mike","Sam", "John", "Mike", "Sam"], "Hrs": [11, 12, 2, 13, 5, 14, 15, 16, 7]}) df2 = pd.DataFrame({"Week": ["3/30/2018", "3/30/2018", "3/30/2018", "3/23/2018", "3/16/2018", "3/16/2018", "3/9/2018", "3/9/2018"], "Empl": ["Sam", "John", "Mike", "Sam", "Mike","Sam", "Mike", "Sam"], "Hrs": [16, 12, 2, 13, 5, 15, 21, 7]}) gdF1 = df1.groupby(["Week","Empl"])["Hrs"].sum() gdF2 = df2.groupby(["Week","Empl"])["Hrs"].sum() # need to join gdF1 and gDF2 on Week and Empl for further comparison.
has comment: http://stackoverflow.com/comment/86383007
type: Question
has title: How to compare output of two panda's group by functions
accepted answer: http://stackoverflow.com/a/49685908
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49685908
answer count: 1
tagged with: pandas

http://stackoverflow.com/q/49633359
has answer: http://stackoverflow.com/a/49633839
tagged with: python-unittest
tagged with: python
has answer: http://stackoverflow.com/a/49634631
has comment: http://stackoverflow.com/comment/86274553
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has body: By default django creates a test database when running tests which raises some inconvenience for me: The API that i am writing test for uses a database. When i run the test, a new database is created, some dummy data is being inserted into the test database and a http post request is being sent to the API under test. What happens is that my API under test does not see inserted data. With the problem explained, what are the right solutions / best practices for testing APIs with databases ?
downvote count: 0
tagged with: django
upvote count: 1
score: 1
tagged with: unit-testing
favorite count: 0
has title: Django unittesting different databases for api and for test

http://stackoverflow.com/q/49720618
has comment: http://stackoverflow.com/comment/86486203
tagged with: django-haystack
downvote count: 0
tagged with: django-oscar
favorite count: 0
has comment: http://stackoverflow.com/comment/86486254
type: Question
has title: Django cannot install Django-Oscar
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: django-errors
tagged with: python
has body: I'm trying to install django-oscar, after spending couple hours, and upgraded my pip, and also setuptools, the error is still not going away, I can pip install other packages such as spirit, but just cannot install Oscar, following is the error message, Thanks a mill! Jim Using cached django-haystack-2.8.1.tar.gz Complete output from command python setup.py egg_info: Couldn't find index page for 'setuptools_scm' (maybe misspelled?) No local packages or working download links found for setuptools_scm Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/bm/ghr3m2px1d76gsgd7vkbh5yr0000gn/T/pip-install-LXpkON/django-haystack/setup.py", line 71, in &lt;module&gt; setup_requires=['setuptools_scm'], File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools/__init__.py", line 128, in setup _install_setup_requires(attrs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools/__init__.py", line 123, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools/dist.py", line 513, in fetch_build_eggs replace_conflicting=True, File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pkg_resources/__init__.py", line 774, in resolve replace_conflicting=replace_conflicting File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1057, in best_match return self.obtain(req, installer) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1069, in obtain return installer(requirement) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools/dist.py", line 580, in fetch_build_egg return cmd.easy_install(req) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/…
linked to: http://stackoverflow.com/q/44662881
score: 1
upvote count: 1

http://stackoverflow.com/q/49751619
has body: So I'm having an issue and I'm stuck on it for a while now I'm trying to understand and repeat a jupyter tutorial about adversarial example. However, when I'm loading a model, depending on how is it done I have big differences between the two models accuracy: - when it's loading inside a class, there is no issues - when it's loading on jupyter, the accuracy decrease The class use the following lines: from keras.models import Sequential, load_model class Lenet: def __init__(self, epochs=200, batch_size=128, load_weights=True): self.name = 'lenet' self.model_filename = 'networks/models/lenet.h5' self.num_classes = 10 self.input_shape = 32, 32, 3 self.batch_size = batch_size self.epochs = epochs self.iterations = 391 self.weight_decay = 0.0001 self.log_filepath = r'networks/models/lenet/' if load_weights: try: self._model = load_model(self.model_filename) print('Successfully loaded', self.name) except (ImportError, ValueError, OSError): print('Failed to load', self.name) what I am doing is: modelPath = "networks/models/lenet.h5" lenet2 = keras.models.load_model(modelPath) modelPath2 = "networks/models/resnet.h5" resnet2 = keras.models.load_model(modelPath2) However, when I'm testing the accuracy of the two models: lenet = LeNet() resnet = ResNet() #the class is nearly the same as LeNet models = [lenet, lenet2, resnet, resnet2] network_stats, correct_imgs = helper.evaluate_models(models, x_test, y_test) network_stats = pd.DataFrame(network_stats, columns=['name', 'accuracy', 'param_count']) I'm getting this following result: (network_stats) name accuracy param_count 0 lenet 0.7488 62006 1 sequential_1 0.4800 62006 2 resnet 0.9231 470218 3 model_1 0.1092 470218 link to the picture to explain the picture: on the left, this is the class lenet, that give good results. On the right, my failed try to load the same model Do you have any idea about why is that happening? --edit-- can't post images yet on stackoverflow, so I explained a little bit more the issue --edit2-- can re…
tagged with: python
has title: Keras loading model issue
type: AnsweredQuestion
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/86528640
upvote count: 1
accepted answer: http://stackoverflow.com/a/49755974
answer count: 1
tagged with: keras
downvote count: 1
has answer: http://stackoverflow.com/a/49755974
favorite count: 0
type: Question

http://stackoverflow.com/a/49710157
type: AcceptedAnswer
has body: The website required the requests Session to have gone to the homepage before it tries to submit a login request. Everyone who helped me inch closer to the answer: Thank you. Here is the working code: session = requests.Session() data = { 'acctname':'username', 'pswrd':'password', 'action':'login_test.cfm' } headers = {'User-Agent': 'Mozilla/5.0'} session.get('http://quantumonline.com', headers=headers) #Get cookies response = session.post('http://quantumonline.com/login_test.cfm', headers=headers, data=data)
type: Answer
answers question: http://stackoverflow.com/q/49709434
score: 0
accepted answer of: http://stackoverflow.com/q/49709434

http://stackoverflow.com/q/49668387
favorite count: 0
has comment: http://stackoverflow.com/comment/86347533
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86347184
has comment: http://stackoverflow.com/comment/86347505
tagged with: pandas
has answer: http://stackoverflow.com/a/49669532
accepted answer: http://stackoverflow.com/a/49669532
tagged with: python
type: Question
upvote count: 2
score: 2
tagged with: python-3.x
has title: Type error: cannot convert the series to <class 'float'>
downvote count: 0
tagged with: google-maps
has body: lat long time 0 39.991861 116.344372 2.823611 1 39.979768 116.310597 22.263056 2 31.235001 121.470624 13.141667 3 31.248822 121.460637 1.805278 The above is a dataframe rep_points. When i run the code below, it gives an error Type error: cannot convert the series to &lt;class 'float'&gt; in the line where circle is made. gmap = gmplot.GoogleMapPlotter(rep_points['lat'][0], rep_points['long'][0], 11) gmap.plot(df_min.lat, df_min.lng) gmap.scatter(rep_points['lat'],rep_points['long'],c='aquamarine') gmap.circle(rep_points['lat'],rep_points['long'], 100, color='yellow') gmap.draw("user001_clus_time.html") How should i resolve this error? Ive tried using rep_pints['lat'].astype(float) and rep_pints['long'].astype(float) but it didnt work well
answer count: 1
linked to: http://stackoverflow.com/q/45478070

http://stackoverflow.com/q/49684422
has comment: http://stackoverflow.com/comment/86421213
has comment: http://stackoverflow.com/comment/86380531
favorite count: 0
has comment: http://stackoverflow.com/comment/86380532
has comment: http://stackoverflow.com/comment/86380753
type: Question
has comment: http://stackoverflow.com/comment/86419407
has answer: http://stackoverflow.com/a/49703950
has body: I am now trying to output a data frame written in Serbian. First I try to use the utf-8 or utf-8-sig codec. There are multiple columns, which is correct. However, the output csv file has the garbled problem. Then I try to output the data frame using utf-16. The codec is correct this time. But the output csv just has one column, like: My code is: df1.to_csv('people.csv', encoding = "utf-16",index = False) The head of the original data frame is: If I use utf-8, the output is (correct column but incorrect codec): If I use utf-16, the output is (correct codec but incorrect column): How can I solve the problem. Thanks!
has comment: http://stackoverflow.com/comment/86380719
has comment: http://stackoverflow.com/comment/86380684
has title: Why the output of df.to_csv() just has one column when using utf-16?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86380327
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86419367
has comment: http://stackoverflow.com/comment/86380359
score: 0
has comment: http://stackoverflow.com/comment/86380791
has comment: http://stackoverflow.com/comment/86394949
upvote count: 1
linked to: http://stackoverflow.com/q/6002256

http://stackoverflow.com/a/49658433
upvote count: 1
answers question: http://stackoverflow.com/q/49656859
has comment: http://stackoverflow.com/comment/86329455
accepted answer of: http://stackoverflow.com/q/49656859
has comment: http://stackoverflow.com/comment/86329538
type: Answer
score: 1
type: AcceptedAnswer
has body: This answer will not spell it out for you, but it should be enough to unblock you. From the looks of the Django documentation, you can use a built in method to get the temporary file path of a "TemporaryUploadedFile": TemporaryUploadedFile.temporary_file_path() To wrap this all up, you'll have to have some logic in your code to identify if it is an "InMemoryUploadedFile" or a "TemporaryUploadedFile". From there, you can look at each object differently to assess the columns.
downvote count: 0

http://stackoverflow.com/q/49728912
score: 6
has answer: http://stackoverflow.com/a/49729774
tagged with: python
has body: I am writing a simple socket server using socketserver module, all seems to work just fine except just one small thing. I bind the server to some port and then set server.allow_reuse_address = True to reuse the same port without having to wait for the kernel to release the underlying port. However it does not work if modify the variable server.allow_reuse_address = True after creating the server instance, but if i create the custom class for the server and then override the variable in it, everything works. Below is my code. import socketserver import sys class MyTCPRequestehandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024) while self.data: print('Received {} from {}'.format(self.data.decode().strip(), self.client_address)) self.request.send(self.data.upper()) self.data = self.request.recv(1024) if __name__ == '__main__': try: server = socketserver.TCPServer(('', 12345), MyTCPRequestehandler) ip, port = server.server_address server.allow_reuse_address = True print(server.allow_reuse_address) print('Server listening on port {}'.format(port)) # server.handle_request() server.serve_forever() except KeyboardInterrupt: sys.exit() I get this error if re-run the application, just after disconnecting File "/Documents/PythonPrograms/network-modules/socketServer/simplesocketserver.py", line 16, in &lt;module&gt; server = socketserver.TCPServer(('', 12345), MyTCPRequestehandler) File "/spare/ssd/rbhanot/anaconda3/lib/python3.6/socketserver.py", line 453, in __init__ self.server_bind() File "/spare/ssd/rbhanot/anaconda3/lib/python3.6/socketserver.py", line 467, in server_bind self.socket.bind(self.server_address) OSError: [Errno 98] Address already in use However if i do something like below everything works. class MyTcpServer(socketserver.TCPServer): allow_reuse_address = True def __init__(self, address, request_handler_class): self.address = address self.request_handler_class = request_handler_class super().__init__(self.address, s…
upvote count: 6
type: AnsweredQuestion
has title: socketserver - allow_reuse_address to rebind existing port number not working without overriding class variable
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49729774

http://stackoverflow.com/q/49740566
has comment: http://stackoverflow.com/comment/86495917
has title: Python3 Casting
tagged with: python
has comment: http://stackoverflow.com/comment/86495725
has comment: http://stackoverflow.com/comment/86495676
possible better answer: http://stackoverflow.com/a/49740852
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49740799
has comment: http://stackoverflow.com/comment/86495729
tagged with: casting
has comment: http://stackoverflow.com/comment/86495643
upvote count: 1
downvote count: 1
has body: In this code, casting from float to int is not working. It always prints a float; all integers are printed with .0 afterwards. What is wrong? s = str(input()) if (len(s)/2)%2 == 0: print(len(s)/2) else: print(int(round(len(s)/2/2)))
has comment: http://stackoverflow.com/comment/86495584
favorite count: 0
accepted answer: http://stackoverflow.com/a/49740799
tagged with: int
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49740852
score: 0
has comment: http://stackoverflow.com/comment/86495658
has comment: http://stackoverflow.com/comment/86496237

http://stackoverflow.com/comment/86264553
type: AnswerComment
comment on: http://stackoverflow.com/a/49628099
score: 1
type: Comment
has text: Are we forced to use su? Is it possible to enable the script user to issue this command instead of using root? That would also be the best choice, security-wise.

http://stackoverflow.com/comment/86317245
comment on: http://stackoverflow.com/q/49654234
has text: I think you want to play with `topdown=False` option.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49713052
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86445524
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86439530
has answer: http://stackoverflow.com/a/49713732
score: 0
has body: I have a Python script that asks me to select the input folder. I am running it on OSX. The issue is that when I try to write the input path it gives me back an error. Let's say that the input folder is "Documents", here what it says: MBPAdmin:moviep3 Admin$ python merge_videos.py Enter path to input folder: /Documents Traceback (most recent call last): File "merge_videos.py", line 13, in &lt;module&gt; input_folder = input(input_folder_label) File "&lt;string&gt;", line 1 /Documents ^ SyntaxError: invalid syntax Any help please? Edit: Here's part of the code, if it helps. from moviepy.editor import VideoFileClip, concatenate_videoclips import time import os import sys input_folder_label = 'Enter path to input folder: ' output_folder_label = 'Enter path to output folder: ' video_to_be_merged_label = 'Enter path to video that should be merged at the end of each video: ' default_output_folder_name = 'merged_videos' + str(time.time()) input_folder = input(input_folder_label) input_folder = '/Users/burlicconi/Downloads/filmovi' try: assert os.path.exists(input_folder) except AssertionError as exc: print("Input folder was not found at {}".format(input_folder)) sys.exit() print('Input folder exists: {}'.format(input_folder))
has title: Script asks for a file path but gives back error
tagged with: python
tagged with: moviepy
has comment: http://stackoverflow.com/comment/86439605
tagged with: python-3.x
tagged with: python-2.7

http://stackoverflow.com/a/49661438
answers question: http://stackoverflow.com/q/49661070
type: Answer
has comment: http://stackoverflow.com/comment/86372395
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: It looks like the asl package is actually broken. I'd use the syslog executable that ships with OSX: from subprocess import check_output cmd = 'syslog -f /private/var/log/asl/2018.04.03.U501.asl' log = check_output(cmd.split()) print(log)
accepted answer of: http://stackoverflow.com/q/49661070

http://stackoverflow.com/q/49701468
has body: max_gust_speed = data[(data['Spd of Max Gust (km/h)'].astype(float) &gt;= 50.0)] Most data in this column is an integer or float. However, there are some other values (like the string '&lt;32') Is it possible to deal with these edge cases in this line, or do I need to go through the dataframe beforehand and convert these? Can I coerce in this line?
type: AnsweredQuestion
tagged with: python
tagged with: regex
type: Question
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49701585
score: 1
has title: pandas - reading column as float, converting invalid entries
accepted answer: http://stackoverflow.com/a/49701749
downvote count: 0
has answer: http://stackoverflow.com/a/49701585
has answer: http://stackoverflow.com/a/49701749
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/49606213
tagged with: path
has title: AttributeError raises when tried to read an image from text file
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50068575
tagged with: opencv
linked to: http://stackoverflow.com/q/28894060
has answer: http://stackoverflow.com/a/50068575
has body: I am trying to read images from a text file. Text file contains the paths for those images. Images are in different directories, I checked that they do exist there. PATH_IN = 'D:\\user\\data\\Augmentation' path_out = 'D:\\user\\data\\Augmentation\\images_90t' try: if not os.path.exists('images_90t'): os.makedirs('images_90t') except OSError: print ('Error: Creating directory of data') with open('filelist.txt', 'r') as f: for image_path in f.readlines(): image = cv2.imread(image_path, 1) print("The type of image is: " , type(image)) # OUTPUT: The type of image is: &lt;class 'NoneType'&gt; (h, w) = image.shape[:2] center = (w / 2, h / 2) M = cv2.getRotationMatrix2D(center, 90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) #cv2.imshow("rotated", rotated) cv2.imwrite(path_out, rotated) cv2.waitKey(0) I looked for the answers in 1 and 2 but there was no solution. Most of the times, folks suggest editing the \ to \\ or something similar because paths to images might be wrong. I think I have tried every combination, but still, no solution. The error raises in line (h, w) = image.shape[:2] saying AttributeError: 'NoneType' object has no attribute 'shape' I suppose the path to cv2.imread() can't open it as an image, and giving Nonetype object. Here are some samples from my text file: D:\user\data\16_partitions_annotated\partition1\images\073-1\073-1_00311.jpg D:\user\data\ImageNet_Utils-master\images\n03343560_url\2077528821_231f057b3f.jpg D:\user\data\lighter\images\webcam-fire3\scene00211.jpg D:\user\data\smoke\11\images\scene07341.jpeg D:\user\data\smoke\11\images\scene07351.jpeg I am on Windows 7, 64. Can anyone help? Thank you.
linked to: http://stackoverflow.com/q/39833796
type: AnsweredQuestion
downvote count: 0
score: 1
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/125051946
comment on: http://stackoverflow.com/a/49689600
has text: i have reached question limit
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86529391
type: Comment
comment on: http://stackoverflow.com/q/49755433
type: QuestionComment
has text: But the above code gives the following error. `sort: write failed: 'standard output': Broken pipe sort: write error` how to resolve this.
score: 0

http://stackoverflow.com/comment/86416427
has text: No problem! Yeah it's kind of weird. I like this part of the `numpy` docs: *"there is no way to convert a month unit into days, because different months have different numbers of days"*, `relativedelta` apparently does the impossible!
type: Comment
score: 1
comment on: http://stackoverflow.com/a/49701043
type: AnswerComment

http://stackoverflow.com/q/49681470
score: 1
tagged with: python
has body: I'm new to python coding. And I'm trying to play around with python and Selenium in chrome. And I have this code where I'm trying to move a webpage up and down. But it isn't working. body_elem = browser.find_element_by_tag_name('body') for __ in range(3): body_elem.send_keys(Keys.END) sleep(2) body_elem.send_keys(Keys.HOME) sleep(2) All I get is this long error message: Traceback (most recent call last): File "selenium_test.py", line 34, in &lt;module&gt; body_elem.send_keys(Keys.HOME) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 479, in send_keys 'value': keys_to_typing(value)}) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 628, in _execute return self._parent.execute(command, params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document Anybody got an idea of whats is wrong?
type: Question
tagged with: python-3.x
has title: Python selenium send_keys not working in chrome
answer count: 1
tagged with: selenium
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49682136
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49682136

http://stackoverflow.com/q/49601005
has answer: http://stackoverflow.com/a/76844150
tagged with: cx-oracle
downvote count: 0
possible better answer: http://stackoverflow.com/a/68983053
accepted answer: http://stackoverflow.com/a/49601455
score: 4
has answer: http://stackoverflow.com/a/49601455
type: AnsweredQuestion
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/68983053
has body: I am calling PL/SQL stored procedure from python using cx_Oracle package. The PL/SQL stored procedure is returning a SYS_REFCURSOR as OUT parameter. I am able to get the values of the REF_CURSOR, but I am not able to get the name of the column along with values. PFB my code result_set = self.__cursor__.callproc(call_procedure, parameters) result_set[index].fetchall() fetchall() is only returning values in an array like [ "John", "B", "Doe", "111223333", "Fri, 09 May 1997 00:00:00 GMT", "212 Main St, Orlando, FL", "M", 25000, "333445555" ] but i want something like this { "FirstName": "John", "MInit": "B", "LastName": "Doe", "SSN": "111223333", "DOE": "Fri, 09 May 1997 00:00:00 GMT", "Addr": "212 Main St, Orlando, FL", "Sex": "M", "Sal": 25000, "DNO": "333445555" }
has title: Getting Column name along with data when calling stored procedure from python
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/comment/86293920
comment on: http://stackoverflow.com/a/49643098
type: Comment
has text: Thanks Tomas.. i wasn't aware of that in regex.. Now its clear. :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/49687220
has body: Change your script to the function. And call the function when user entered something in the browser. def elastic_search(text): word = input(text) res = es.search(index="pastebin-*", ...) return res # View function @app.route('/key', methods=['POST', 'GET']) def key(): if requests.method == 'POST': result = request.form['key'] resp = elastic_search(result) return render_template('key.html', resp=resp)
has comment: http://stackoverflow.com/comment/86390743
has comment: http://stackoverflow.com/comment/86390396
has comment: http://stackoverflow.com/comment/86388229
answers question: http://stackoverflow.com/q/49687071
has comment: http://stackoverflow.com/comment/86388012
has comment: http://stackoverflow.com/comment/86387162
has comment: http://stackoverflow.com/comment/86387860
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86390197
has comment: http://stackoverflow.com/comment/86387593
has comment: http://stackoverflow.com/comment/86386800
has comment: http://stackoverflow.com/comment/86387990
has comment: http://stackoverflow.com/comment/86390430
has comment: http://stackoverflow.com/comment/86386936
has comment: http://stackoverflow.com/comment/86387480
has comment: http://stackoverflow.com/comment/86387048
has comment: http://stackoverflow.com/comment/86387949
has comment: http://stackoverflow.com/comment/86387304
has comment: http://stackoverflow.com/comment/86386998
has comment: http://stackoverflow.com/comment/86390679
has comment: http://stackoverflow.com/comment/86387140
has comment: http://stackoverflow.com/comment/86387586
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86388064

http://stackoverflow.com/a/49735211
answers question: http://stackoverflow.com/q/49734903
score: 0
has body: Try updating your selenium version using this command, maybe it helps: python -m pip install -U selenium
has comment: http://stackoverflow.com/comment/86484384
type: Answer

http://stackoverflow.com/comment/86330960
comment on: http://stackoverflow.com/q/49659945
type: Comment
type: QuestionComment
score: 0
has text: @BruceWayne Fair point. I hadn't heard of an XY problem before, but that sounds like what this is. I guess the only reason not to save would be to avoid file clutter. I was using this to display the contents of a database table in Excel. There are probably a lot of better ways to solve the problem then what I'm doing, but I don't have any real experience to lean on. I'm just trying to solve the problems that I run into the best I can.

http://stackoverflow.com/comment/86240446
score: 2
type: QuestionComment
has text: replace image by actual data please
type: Comment
comment on: http://stackoverflow.com/q/49616277

http://stackoverflow.com/comment/86274903
type: QuestionComment
score: 0
has text: @kpie ubuntu 16.04, but that doesn't matter(?) cause i am running it on a remote cluster with a high end gpu
type: Comment
comment on: http://stackoverflow.com/q/49632852

http://stackoverflow.com/comment/86374090
comment on: http://stackoverflow.com/q/49680934
type: QuestionComment
has text: *Iterable* -> you use the `__iter__` method to produce the iterator. *iterator* -> you use the `__next__` method to do the iterating. Iterators also have a `__iter__` method, because that makes it so much easier to handle both types (just call `iter()` on either and you know you have something with a `__next__` method returned).
type: Comment
score: 0

http://stackoverflow.com/comment/86488448
type: QuestionComment
comment on: http://stackoverflow.com/q/49736440
score: 0
has text: Yes, I did restart the kernel and deactivate/activate the virtual environment.
type: Comment

http://stackoverflow.com/q/49634016
accepted answer: http://stackoverflow.com/a/49634277
has comment: http://stackoverflow.com/comment/86298738
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/20845213
has answer: http://stackoverflow.com/a/49634277
tagged with: pandas.excelwriter
duplicate of: http://stackoverflow.com/q/19781609
has title: why do I get a row as header like [0, 1, 2, ...] when writing an excel file in python?
has comment: http://stackoverflow.com/comment/86275892
tagged with: python
type: AnsweredQuestion
has body: I have imported an excel file, changed B1 and exported it, but I don't want to have a row (the first row) as a Header. I would like to write my data in the first row of my DataFrame exactly in the row number 1 of my excel sheet. here is what I wrote: # import df = pd.read_excel("DataName.xlsx", sheetname=0, header=None) # setting the field B1 to a string df.iloc[0,1] = "my text" # Export writer = pd.ExcelWriter(mypath, engine='xlsxwriter') df.to_excel(writer, sheet_name= new_sheet, index=False) writer.save() but the exported Excel fale doesn't contain "my text" in B1. instead contains "1" and has a Header in row one like [0, 1, 2, ...] "my text" is written to B2. `
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/19781609
upvote count: 1

resources
tags question: http://stackoverflow.com/q/49721621
tags question: http://stackoverflow.com/q/49677414
type: Tag
tag name: resources

http://stackoverflow.com/a/49835151
has body: You can simply use this !unzip file_location There is also an optional flag which specifies where to extract the files: !unzip "/file/location" -d "/extract/file/loaction"
has comment: http://stackoverflow.com/comment/123693428
type: Answer
answers question: http://stackoverflow.com/q/49685924
downvote count: 1
upvote count: 134
score: 133
has comment: http://stackoverflow.com/comment/123638047

http://stackoverflow.com/q/49737835
upvote count: 2
has comment: http://stackoverflow.com/comment/86490007
has body: It appears if I use PEP-526 for class-level variables I must document them in the class's docstring in which case I need to pick my favorite way to do this. Python 3.6.4 pylint==1.8.4 class Joe(object): counter: int = 0 """This is a counter""" pylint says (correctly, regardless of whether the variable is assigned to): W: 3, 2: String statement has no effect (pointless-string-statement)
tagged with: pylint
tagged with: python
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49752605
score: 1
tagged with: type-hinting
has answer: http://stackoverflow.com/a/49752605
downvote count: 1
tagged with: docstring
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49738020
tagged with: python-3.x
has title: PEP-526 Is not compatible with docstrings for class variables?
has answer: http://stackoverflow.com/a/49738020

http://stackoverflow.com/comment/86322755
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49656220
has text: Can you add details about how you tried to use `distinct`? It seems like exactly what you need.
type: Comment

http://stackoverflow.com/comment/86517761
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49751627
score: 0
has text: Actually i need a generic RE for this because i may have other strings where location of the codes may occur at different place and it is also possible that there is only one code

http://stackoverflow.com/q/49620638
type: Question
tagged with: pyinstaller
downvote count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 6
score: 6
linked to: http://stackoverflow.com/q/49732801
has answer: http://stackoverflow.com/a/73126529
has comment: http://stackoverflow.com/comment/90972247
has answer: http://stackoverflow.com/a/52532131
has answer: http://stackoverflow.com/a/52157618
has answer: http://stackoverflow.com/a/51990994
has body: Trying to distribute a program that relies on tensorflow... Using tensorflow it works nicely both as script and with pyinstaller. Using tensorflow-gpu it works as script but not with pyinstaller. The cuda and cudnn dlls have been copied into the bundle folder by pyinstaller. I use python 3.6.5 and tensorflow 1.7.0. (Can change version if it helps...) Error message: Traceback (most recent call last): File "site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in File "c:\users\aleks\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.dict) File "site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in File "site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in swig_import_helper File "importlib__init__.py", line 126, in import_module ModuleNotFoundError: No module named 'tensorflow.python._pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "interface.py", line 14, in File "c:\users\aleks\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.dict) File "site-packages\tensorflow__init__.py", line 24, in File "c:\users\aleks\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.dict) File "site-packages\tensorflow\python__init__.py", line 49, in File "c:\users\aleks\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.dict) File "site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in ImportError: Traceback (most recent call last): File "site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in File "c:\users\aleks\appdata\local\programs\python\pyth…
has title: Tensorflow-gpu with pyinstaller
tagged with: tensorflow
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86332692
has comment: http://stackoverflow.com/comment/87970489
answer count: 4

http://stackoverflow.com/comment/86433024
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49709714
has text: @Hai Vu already tried datetime.datetime.strptime but it is not working

http://stackoverflow.com/a/49628546
has comment: http://stackoverflow.com/comment/86270494
answers question: http://stackoverflow.com/q/49628442
type: Answer
has body: You can create a simple seen list to store your values as you iterate over them and then export to the new list only the dictionaries whose values you haven't seen before, e.g. def filter_dicts(target, key): seen = set() # a temporary set to store already visited values return [d for d in target if d[key] not in seen and not seen.add(d[key])] You can test it with: l = [ {'a': 123, 'b': 456}, {'a': 322, 'b': 44454}, {'a': 123, 'b': 134} ] k = filter_dicts(l, "a") # [ # {'a': 123, 'b': 456}, # {'a': 322, 'b': 44454} # ] The order doesn't have to match as dict is, generally, an unordered structure.
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86270601

http://stackoverflow.com/q/49707878
has answer: http://stackoverflow.com/a/49784675
type: Question
upvote count: 8
has body: I'm trying to read my joystick capability by using the winmm.dll library. Here is how I'm doing it... from ctypes import windll, Structure, c_uint, c_ushort, c_char, c_ulong WORD = c_ushort UINT = c_uint TCHAR = c_char winmm = windll.LoadLibrary('winmm.dll') class JOYCAPS(Structure): _fields_ = [ ('wMid', WORD), ('wPid', WORD), ('szPname', TCHAR * MAXPNAMELEN), # originally szPname[MAXPNAMELEN] ('wXmin', UINT), ('wXmax', UINT), ('wYmin', UINT), ('wYmax', UINT), ('wZmin', UINT), ('wZmax', UINT), ('wNumButtons', UINT), ('wPeriodMin', UINT), ('wPeriodMax', UINT), ('wRmin', UINT), ('wRmax', UINT), ('wUmin', UINT), ('wUmax', UINT), ('wVmin', UINT), ('wVmax', UINT), ('wCaps', UINT), ('wMaxAxes', UINT), ('wNumAxes', UINT), ('wMaxButtons', UINT), ('szRegKey', TCHAR * MAXPNAMELEN), # originally szRegKey[MAXPNAMELEN] ('szOEMVxD', TCHAR * MAX_JOYSTICKOEMVXDNAME) # originally szOEMVxD[MAX_JOYSTICKOEMVXDNAME] ] joyinf = JOYCAPS() err = winmm.joyGetDevCaps(0, pointer(joyinf), sizeof(joyinf)) if err == JOYERR_NOERROR: for l in [s for s in dir(joyinf) if "_" not in s]: print(l, getattr(joyinf, l)) When I try to do so I get an error... function 'joyGetDevCaps' not found After searching in the source code I found that joyGetDevCapsW is for unicode and the joyGetDevCapsA is not. I tried them both and got the same result. When trying to read them I get an error number of 165 which is not listed in the original function MSDN site but is an error code for JOYERR_PARMS which means... The specified joystick identifier is invalid I'm using windows 10 and python 3.6 The code is working when using the joyGetPos and joyGetPosEx. Thank you
has comment: http://stackoverflow.com/comment/86667985
tagged with: python
has comment: http://stackoverflow.com/comment/86455752
score: 8
tagged with: python-3.x
tagged with: ctypes
has comment: http://stackoverflow.com/comment/86671908
tagged with: msdn
has title: Reading joystick capability
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86704505
answer count: 1
downvote count: 0
tagged with: joystick
has comment: http://stackoverflow.com/comment/86639406
favorite count: 0

http://stackoverflow.com/comment/86471971
type: QuestionComment
comment on: http://stackoverflow.com/q/49729087
has text: @GianlucaMicchi Done the indentation:)
type: Comment
score: 0

http://stackoverflow.com/q/49735344
has title: Sudden error of PyWin32 script
has comment: http://stackoverflow.com/comment/86524292
type: Question
tagged with: winlogon
type: UnansweredQuestion
has body: Python script is tracking logins on a Windows machine, based on (but is not exactly the same as) this implementation. It uses PyWin32, which was a bit tricky to set up properly, but once it was done the script had been running smoothly for months - until it suddenly stopped working, seemingly without a reason. I am unable to determine why the script stopped working. Since there are multiple users I checked if someone 'tampered' with path/system variables or python installation or something similar. Settings have remained the same and used to work without a problem. Of course PyWin was installed in env used: (py27) C:\Users\Username&gt;conda list # packages in environment at C:\ProgramData\Anaconda3\envs\py27: # pip 9.0.1 py27_1 pypiwin32 219 &lt;pip&gt; python 2.7.13 1 pywin32 221 &lt;pip&gt; requests 2.14.2 py27_0 setuptools 27.2.0 py27_1 vs2008_runtime 9.00.30729.5054 0 wheel 0.29.0 py27_0 And additional system variables/paths have also been set at the beginning and haven't been changed: Error: Lately the script always fails, producing the following error when running in PyCharm: C:\ProgramData\Anaconda3\envs\py27\python.exe C:/Python27/LoginTracker/wtsmonitor-svc.py File "C:\ProgramData\Anaconda3\Lib\site.py", line 177 file=sys.stderr) ^ SyntaxError: invalid syntax Process finished with exit code 1 However, when running monitor-svc.py from CMD directly, it produced a little bit different error: C:\Projects\LoginTracker&gt;wtsmonitor-svc.py start 'import site' failed; use -v for traceback wtsmonitor-svc: PyWin32 modules not found Any ideas why does this happen? No installations were changed (that I know of) and can't figure out the reason for the error.
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86513435
answer count: 0
has comment: http://stackoverflow.com/comment/86484713
tagged with: pywin32
has comment: http://stackoverflow.com/comment/86520853

http://stackoverflow.com/q/49734694
has comment: http://stackoverflow.com/comment/86617873
has body: I'm a bioinformatics student and I have a problem to upload a file from an html script. I tried using different templates I found on the internet, and I couldn't fix my problem searching other topics on this website. This is a fragment of my html form script to upload the file: Upload your sequence(s) file And this is part of the blast_parser.cgi I'm using to upload the file to the server: #!/usr/bin/env python # -*- coding: utf-8 -*- import cgi, os import cgitb; cgitb.enable() import glob, subprocess, shlex, sys, re try: # Windows needs stdio set for binary mode. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass def fbuffer(f, chunk_size=10000): while True: chunk = f.read(chunk_size) if not chunk: break yield chunk form = cgi.FieldStorage() fileitem = form['file'] if fileitem.filename: fn = os.path.basename(fileitem.filename) f = open('/opt/lampp/htdocs/server_v1/uploads/' + fn, 'wb', 10000) for chunk in fbuffer(fileitem.file): f.write(chunk) f.close() message = 'The file "' + fn + '" was uploaded successfully' else: message = 'No file was uploaded' print """\ Content-Type: text/html\n %s """ % (message,) So the output is: 'No file was uploaded'. The problem is that the test if fileitem.filename: renders None always because fileitem is MiniFieldStorage('file', 'Acinetobacter_pittii_protein.faa') when I upload a file called Acinetobacter_pittii_protein.faa I'm using Ubuntu 16.04 LTS and XAMPP 7.1.10 for Linux. I just want to upload the file to a server so I can process it. I don't know if you need the rest of the code, I didn't put it all because they are quite long. I would really appreciate any help with this! :)
has comment: http://stackoverflow.com/comment/94838182
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: How to upload files to server from html form using python cgi
type: Question
upvote count: 2
tagged with: bioinformatics
has answer: http://stackoverflow.com/a/49801182
accepted answer: http://stackoverflow.com/a/49801182
answer count: 1
tagged with: cgi
downvote count: 0
favorite count: 0
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49599920
has comment: http://stackoverflow.com/comment/86206889
has answer: http://stackoverflow.com/a/49602763
has comment: http://stackoverflow.com/comment/86208361
downvote count: 1
has answer: http://stackoverflow.com/a/49601741
favorite count: 0
type: Question
answer count: 2
has body: def cell(s): a=len(s) for i in range(len(s)): if i==0: if s[i+1]==0: s[i]=1 else: s[i]=0 elif i==a-1: if s[a-2]==0: s[i-1]=1 else: s[a-1]=0 else: if s[i-1]==s[i+1]: s[i]=1 else: s[i]=0 l=[list(map(int,input().split()))] n=int(input()) for i in range(n): cell(l) print(l) I am sharing the link of geeksforgeeks ide where i have written the code https://ide.geeksforgeeks.org/ In the above code constantly getting EOFerror l=[list(map(int,input().split()))] EOFError: EOF when reading a line
upvote count: 2
type: UnansweredQuestion
has title: EOF error in Python 3
tagged with: python
has comment: http://stackoverflow.com/comment/86206904
has comment: http://stackoverflow.com/comment/86211361
score: 1

http://stackoverflow.com/comment/87397695
comment on: http://stackoverflow.com/a/50035506
type: Comment
type: AnswerComment
has text: Thanks so much. Good luck to you!
score: 0

raspberry-pi
tags question: http://stackoverflow.com/q/49687583
tags question: http://stackoverflow.com/q/49740741
tags question: http://stackoverflow.com/q/49722187
tags question: http://stackoverflow.com/q/49709993
tags question: http://stackoverflow.com/q/49621613
type: Tag
tags question: http://stackoverflow.com/q/49682777
tags question: http://stackoverflow.com/q/49756393
tags question: http://stackoverflow.com/q/49627214
tags question: http://stackoverflow.com/q/49641412
tags question: http://stackoverflow.com/q/49738321
tags question: http://stackoverflow.com/q/49642651
tags question: http://stackoverflow.com/q/49691763
tags question: http://stackoverflow.com/q/49654775
tags question: http://stackoverflow.com/q/49607346
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/49705020
tags question: http://stackoverflow.com/q/49707262
tags question: http://stackoverflow.com/q/49722837
tags question: http://stackoverflow.com/q/49625006
tags question: http://stackoverflow.com/q/49708190
tags question: http://stackoverflow.com/q/49622184
tags question: http://stackoverflow.com/q/49713414
tags question: http://stackoverflow.com/q/49712038
tags question: http://stackoverflow.com/q/49683692
tags question: http://stackoverflow.com/q/49639644
tags question: http://stackoverflow.com/q/49688181
tags question: http://stackoverflow.com/q/49638005

http://stackoverflow.com/comment/86236185
type: QuestionComment
comment on: http://stackoverflow.com/q/49614798
score: 0
has text: May we use libraries like Pandas, or should answers be limited to the standard vanilla libraries?
type: Comment

http://stackoverflow.com/comment/86259122
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49625694
score: 0
has text: @MartijnPieters is any way to fix that? I've broken my head

http://stackoverflow.com/comment/86488292
comment on: http://stackoverflow.com/q/49735807
type: Comment
type: QuestionComment
has text: Did you do `sudo -H python -m pip install docx` ?
score: 0

http://stackoverflow.com/comment/86223475
has text: Please post some sample input and expected output
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49608461

http://stackoverflow.com/q/49720345
accepted answer: http://stackoverflow.com/a/49720556
has comment: http://stackoverflow.com/comment/86453887
upvote count: 0
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/2988017
has body: When the program goes to level one, and the game begins, I input the correct answer, but it does not work. The answer to the first quote is "death". The if else statement is supposed to acquire the answer of the user, and, if it is correct, display a message and move on to the next level. However, it does not. It displays another message telling me I lost. I don't understand what is going on, especially since the if else statement picks up whether or not the user wants to view the rules. Just to be safe, I am going to write one last clarification in a more straightforward form. When I input the correct answer on level one, and I know for a fact it is the correct answer, it does not display the congrats_message, but it displays the loss_message. welcome_message = "Hello! Welcome to Quote Game by Chandler Morell!" version = "0.0.1" congrats_message = "Congratulations! You passed level one!" loss_message = "Sorry. You did not succeed. One life has been lost." win_game_message = "Congratulations! You won the game!" lost_game_message = "You made it to the end, but you did not win. Give it another go!" lives = 3 def game_won(): print("") print(win_game_message) def game_lost(): print("") print(lost_game_message) def update_lives(): global lives lives = lives - 1 if lives is 0: print("You have ran out of lives. Game over.") game_lost() exit(0) def view_rules(): rules = ["1. Do not look up quotes online.", "2. You have three lives.", "3. You will have three words to choose from.", "4. Type the WORD not the NUMBER"] print("") for i in rules: print(i) def ask_view_rules(): rules_answer = input("Would you like to view the rules? (y/n): ") if rules_answer is "y": view_rules() else: print("") print("Okay, let's begin!") def level_one(): print("Lives: ", lives) print("We will start with an easy quote. Fill in the blank.") print("") choices = ["1. death", "2. torture", "3. nothing"] for i in choices: print(i) print("") choice = input("Give me liberty or give me _____! - Patrick He…
has comment: http://stackoverflow.com/comment/86453906
type: Question
has comment: http://stackoverflow.com/comment/86453994
has answer: http://stackoverflow.com/a/49720556
score: -2
has comment: http://stackoverflow.com/comment/86453939
has comment: http://stackoverflow.com/comment/86453787
has comment: http://stackoverflow.com/comment/86453810
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86453862
has title: User input comparison isn't working
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/a/49758108
accepted answer of: http://stackoverflow.com/q/49680271
has body: Well, I was reloading my checkpoint during inference, and somehow tensorflow would complain if I did not call the initializer after starting my session like this: init = tf.global_variables_initializer() lstm_sess.run(init) Somehow that seems to randomly initialize my weights rather than reloading the last used weight values. So what I did instead is freezing my graph as soon as I finish training, and now during inference I reload my graph, so I get the same performance as the performance I got with my test dataset during training. It's kinda weird. Maybe I am not saving/reloading my checkpoint correctly?
type: Answer
answers question: http://stackoverflow.com/q/49680271
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86373919
has text: There are plenty of IPC/RPC solutions you can pick from in dependence of your needs - I'd recommend [ZeroMQ](http://zeromq.org/) if you really want to do something fancy with your daemon, including a complex multi-origin control over network and robust authentication. Even structures in the built-in [`multiprocessing.connection`](https://docs.python.org/2/library/multiprocessing.html#connection-objects) are more than enough for your use case. They all, more or less, use network sockets beneath all the convenience stuff, tho.
score: 0
comment on: http://stackoverflow.com/q/49679592
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49720344
tagged with: pandas
tagged with: pyinstaller
has title: Control PyInstaller build size including pandas
tagged with: python
type: Question
answer count: 0
has body: I want to build single-file executable on Windows 10 that uses pandas. Following is the totality of my single-file script TrivialTest.py: import numpy as np import pandas as pd np.random.seed(456) j = [(a, b) for a in ['A','B','C'] for b in pd.date_range('2018-01-01', periods=5, freq='W')] i = pd.MultiIndex.from_tuples(j, names=['Name','Num']) df = pd.DataFrame(np.random.randn(15), i, columns=['Vals']) df.to_csv('Test.csv') Initial PyInstaller builds, whether --onefile or --onedir, produce .exe files approaching 300MB in size. Note here claims that running PyInstaller in a minimal python environment can get a trivial pandas script standalone .exe under 20MB. This claims to have gotten one to 15MB using pyinstaller --onefile --exclude matplotlib --exclude scipy --exclude pandas --exclude numpy --exclude IPython --exclude django. So I ran pyinstaller --onefile --exclude matplotlib --exclude scipy --exclude pandas --exclude numpy --exclude IPython --exclude django TrivialTest.py, but the resulting dist\TrivialTest.exe is still 237MB. How can I whittle PyInstaller executables to a reasonable size? E.g.: Is there a way I can figure out what PyInstaller is putting in the final .exe that I doubt is needed so that I can explicitly exclude it? If the answer has to do with the contents of build\xref-trivialtest.html I think I would be lost: That file alone is over 2.5MB! Can I work from the other direction: Figure out independently exactly what is required and then tell PyInstaller to only include that? Am I just "doing it wrong?"
upvote count: 2
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/36678903
favorite count: 0
score: 2

http://stackoverflow.com/q/49604864
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49604925
has comment: http://stackoverflow.com/comment/86216808
score: 0
tagged with: pandas
has body: I am doing some work about sentiment analysis, here I have three arrays:the content of the sentences, the sentiment score and the key words. I want to display them as a dataframe by pandas, but I got : "ValueError: arrays must all be same length" Here are some of my codes: print(len(text_sentences),len(score_list),len(keyinfo_list)) df = pd.DataFrame(text_sentences,score_list,keyinfo_list) print(df) Here are the results: 182 182 182 ValueError Traceback (most recent call last) &lt;ipython-input-15-cfb70aca07d1&gt; in &lt;module&gt;() 21 print(len(text_sentences),len(score_list),len(keyinfo_list)) 22 ---&gt; 23 df = pd.DataFrame(text_sentences,score_list,keyinfo_list) 24 25 print(df) E:\learningsoft\anadonda\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy) 328 else: 329 mgr = self._init_ndarray(data, index, columns, dtype=dtype, --&gt; 330 copy=copy) 331 else: 332 mgr = self._init_dict({}, index, columns, dtype=dtype) E:\learningsoft\anadonda\lib\site-packages\pandas\core\frame.py in _init_ndarray(self, values, index, columns, dtype, copy) 472 raise_with_traceback(e) 473 --&gt; 474 index, columns = _get_axes(*values.shape) 475 values = values.T 476 E:\learningsoft\anadonda\lib\site-packages\pandas\core\frame.py in _get_axes(N, K, index, columns) 439 columns = _default_index(K) 440 else: --&gt; 441 columns = _ensure_index(columns) 442 return index, columns 443 E:\learningsoft\anadonda\lib\site-packages\pandas\core\indexes\base.py in _ensure_index(index_like, copy) 4015 if len(converted) &gt; 0 and all_arrays: 4016 from .multi import MultiIndex -&gt; 4017 return MultiIndex.from_arrays(converted) 4018 else: 4019 index_like = converted E:\learningsoft\anadonda\lib\site-packages\pandas\core\indexes\multi.py in from_arrays(cls, arrays, sortorder, names) 1094 for i in range(1, len(arrays)): 1095 if len(arrays[i]) != len(arrays[i - 1]): -&gt; 1096 raise ValueError('all arrays must be same length') 1097 1098 from pandas.core.categori…
tagged with: dataframe
tagged with: python
has title: Error: all arrays must be same length. But they ARE the same length
type: Question

http://stackoverflow.com/a/49662190
answers question: http://stackoverflow.com/q/49661495
has comment: http://stackoverflow.com/comment/86348657
has comment: http://stackoverflow.com/comment/86356028
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87401692
score: 1
downvote count: 0
has body: tf.cond and tf.while loops work by calling the true/false function or loops condition/body functions only once. Those functions return some OP, or group of OPs perform some function such as check a condition and return true/false or in the case of the while body perform some set of actions. Tensorflow only needs to call your function once to get the definition of the operations it will need. Tensorflow will handle calling that set of operations in a loop or as is necessary. Notice that this means that the dependency graph is static, nothing is changing while the loop executes. Tensorflow is simply adjusting dependencies and what the next step in the dependency graph is. So, if you were to create a variable as part of the loop you would be changing the structure of the dependency graph - this isn't how the loops/conditions are designed to be used. You need to define your variable outside of the condition or loop function. You can access the variable from within the loop function, but not create it there. Notice in an RNN/GRU that you only have one set of weights that are applied at every time step. So you don't need to be calling tf.get_variable inside the condition/while function, you certainly can create the 3 variables you need one time up front. Also, I expect that the way you defined your function as a class is wrong. Since tensorflow is only every calling that function once the whole class is overkill and probably confusing matters. Here's an example of a tf while loop that I coded a while back that may give you a good example to follow. I would try to simplify it to follow this example format (e.g. remove the class). Tensorflow: How to implement cumulative maximum?

http://stackoverflow.com/comment/86230742
score: 0
type: Comment
type: QuestionComment
has text: Added a sample of the tables I'm working with and also a summary at the top. Hope that makes it more clear. I'll check out pulp. Thanks for the recommendation! Open to other comments~
comment on: http://stackoverflow.com/q/49610050

http://stackoverflow.com/comment/86433321
comment on: http://stackoverflow.com/a/49709739
type: AnswerComment
has text: I mean it should work, the code is correct and I have tested it also.
score: 0
type: Comment

http://stackoverflow.com/a/49618935
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49618886
has body: Are they essentially the same? No. The second code block will append a new line in the output, the first won't. What are the advantages/disadvantages of each? print has more features. It allows you to use non-string objects, *args with custom separators, etc. If all you are doing is writing/printing a single string, then there is not much difference and no particular reason to choose one over the other. But do be aware of the trailing newline in the print (i.e. the default end argument of the print function).
type: AcceptedAnswer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/49618886

http://stackoverflow.com/comment/86296521
score: 0
comment on: http://stackoverflow.com/q/49644242
type: Comment
type: QuestionComment
has text: If you are chasing performance without having written a line of code, why are you looking at just WSGI. And why Python 2.7. Look at Python 3 and aiohttp instead. https://aiohttp.readthedocs.io/en/stable/

http://stackoverflow.com/a/49622311
type: Answer
has comment: http://stackoverflow.com/comment/86252328
has comment: http://stackoverflow.com/comment/86252025
score: 2
upvote count: 2
has body: You can add this fields to StudentResistrationForm and TeacherRegistrationForm and add custom validation for it in clean_fieldname method to make it required: StudentResistrationForm(ModelForm): class Meta: model = StudentRegistration fields = ( 'instrument', 'skill', 'experience_in_years', 'is_student', ) def clean_is_student(self): is_student = self.cleaned_data.get('is_student') if not is_student: raise forms.ValidationError('This field is required') return is_student Also in view instead of getting raw data from request.POST you can use forms to create student and teacher objects: new_user = User.objects.create_user(username=username, email=email, password=password) teacher = form.save(commit=False) teacher.user = new_user teacher.save()
has comment: http://stackoverflow.com/comment/86252029
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86252200
has comment: http://stackoverflow.com/comment/86252171
accepted answer of: http://stackoverflow.com/q/49622241
has comment: http://stackoverflow.com/comment/86252265
answers question: http://stackoverflow.com/q/49622241

http://stackoverflow.com/q/49745485
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
has body: model.py class SaleE(models.Model): qty = models.CharField(max_length=250) rate = models.CharField(max_length=250) tax = models.CharField(max_length=250,null="True") slno= models.CharField(max_length=250) ptype =models.CharField(max_length=250) pdiscription = models.CharField(max_length=250) pname = models.CharField(max_length=250) amount = models.CharField(max_length=10) Serializer.py class SaleESerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SaleE fields = ('id','slno','pname','ptype','pdiscription','qty','rate','tax','amount') Here i want to do a simple calculation for an example if i give a amount 200 in addition result should be like 400 in backend itself it should calculate so how to do that.
has title: How to do a simple calculation in Django RestFrameWork
score: 0
tagged with: django-views
answer count: 1
has answer: http://stackoverflow.com/a/49745841
tagged with: django-rest-framework
type: Question

http://stackoverflow.com/q/49600463
answer count: 1
tagged with: mayavi.mlab
accepted answer: http://stackoverflow.com/a/50217817
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50217817
has title: mayavi points3d renering incorectly
tagged with: python
has body: I have code like this: import mayavi.mlab as mlab import numpy as np import random #white blackground mlab.figure(fgcolor=(0., 0., 0.), bgcolor=(1, 1, 1)) x1 = y1 = z1 = size1 = [] # number of points number = 21 for i in range(1,number): x1.append(random.randint(-10,11)) y1.append(random.randint(-10,11)) z1.append(random.randint(-10,11)) size1.append(i) #create spheres mlab.points3d(x1, y1, z1, size1, resolution=30) #render mlab.show() And the result renders with more points, than 20: What I am doing incorrectly? Why spheres are not in random positions and the numbers of spheres? When number == 2, the render is with 3 spheres:
tagged with: 3d

http://stackoverflow.com/comment/86444278
score: 1
type: QuestionComment
has text: Best answer turned out to be even simpler than I thought. If you just replace `scatter` with `plot` then everything should work as is. If you set a few options correctly (`ls`, `marker`, and `ms`), calling `plot` will produce a scatter plot.
comment on: http://stackoverflow.com/q/49714660
type: Comment

http://stackoverflow.com/comment/86494318
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49739591
score: 1
has text: This is pretty sure a bug. Report it to BS.

http://stackoverflow.com/comment/86340223
comment on: http://stackoverflow.com/q/49665155
type: Comment
type: QuestionComment
has text: My boto version is 2.48.0
score: 0

http://stackoverflow.com/comment/86485084
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49697190
has text: I'm running from your high level description, which makes it sound like you're OK with the Python process to be on its own (remote) server. So I would have that process offer a RESTful interface using just BaseHTTPServer or any wrapping middleware which you like. Then you can have the client POST work to this server (being Python, multiple threads is easy) and then GET with long polling to hear back when a given computation has results. Being a single RESTful server you're free to POST and GET from the same JS context, different threads, even different machines.
type: Comment

http://stackoverflow.com/comment/86244939
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49618808
type: QuestionComment
has text: I always find it useful to add `print()` statements around all the lines that aren't doing what you expect. Then you can see what values are existing behind the variables.

http://stackoverflow.com/comment/86436461
comment on: http://stackoverflow.com/q/49701131
has text: Did Vishal's answer clarify it? To reiterate, the point was to remove `polls` from the project and restore its functionality by installing the package you created.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86373309
score: 0
comment on: http://stackoverflow.com/a/49640102
type: AnswerComment
has text: i recieve this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Att ributeError: 'Context' object has no attribute 'server'
type: Comment

http://stackoverflow.com/q/49626554
has body: I have a dataset looking like this one: import pandas as pd pd.DataFrame({"A": [2, 2, 1, 0, 5, 3, 0, 4, 5], "B": [1, 0, 0, 0, 1, 1, 1, 0, 0]}) A B 0 2 1 1 2 0 2 1 0 3 0 0 4 5 1 5 3 1 6 0 1 7 4 0 (I know that A is between 0 and 5; B is only 0 or 1) I would like to transform it and get: A0_B0 A1_B0 A2_B0 A3_B0 ... A5_B1 0 0 0 0 0 ... 1 0 0 1 0 ... 2 0 1 0 0 ... ... (knowing which column correspond to which combination is important) with a method that can be integrated with sklearn Pipeline and/or sklearn_pandas DataFrameMapper (need to be reproducible on a test sample). For now, I have tried using OneHotEncoder or LabelBinarizer but they apply to A or B columns without mixing them. I have also tried to it manually with a custom transformer, but DataFrameMapper looses column names: from sklearn.base import BaseEstimator, TransformerMixin class ABTransformer(BaseEstimator, TransformerMixin): def fit(self, x, y=None): return self def transform(self, x): A = x.A B = x.B A0_B0 = np.logical_and((A==0), (B == 0)) A1_B0 = np.logical_and((A==1), (B == 0)) ... data = pd.DataFrame(np.stack((A0_B0, A1_B0,.... ), axis=1), columns=["A0_B0", "A1_B0", ...] ) return data mapper = DataFrameMapper([ (["A", "B"], [ABTransformer()] , {'input_df':True, "alias": None}), ], df_out=True, sparse=False) At the end, the data I get are labelled: "A_B_0", "A_B_1", etc... Is there a way to achieve the desired output?
tagged with: python
score: -1
tagged with: sklearn-pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49635928
downvote count: 2
answer count: 1
upvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has title: How to binary encode tow mixed features?
has answer: http://stackoverflow.com/a/49635928

http://stackoverflow.com/comment/86422116
type: Comment
has text: Thank you so much for your answer!I further investigated and here comes some more comments. First, moving avg is calculated during training but if I got it right are moving averages NOT updated in the function. The user has to do it manually, which is a big drawback of the function. Second, I actually never could make it work when I tried to set the any reuse param to sth in any function. But it works if I go for "with tf.variable_scope(...)" option. Do you know why? And third, seemingly the given batch has to have a fixed size when calling the function. Otherwise not working. Do you know why?
type: AnswerComment
comment on: http://stackoverflow.com/a/49704170
score: 0

http://stackoverflow.com/q/49677073
tagged with: python
linked to: http://stackoverflow.com/q/14159337
accepted answer: http://stackoverflow.com/a/49678291
tagged with: qscrollarea
type: AnsweredQuestion
score: 0
tagged with: pyqt
has title: pyqt5 QScrollArea inheritance
answer count: 1
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/49678291
has body: I'm having a hard time understanding how to use scroll bars in PyQt5. I have an arbitrary layout to experiment with, which is just some blocks of colors. I'd like to have the layout of colors to have a minimum size, and when the window is smaller than that, the scroll bars appear (or the scroll bars are just present all the time). I found this example: PyQt: Put scrollbars in this and changed it to work with PyQt5: #!/usr/bin/env python #-*- coding:utf-8 -*- from PyQt5 import QtCore, QtGui from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QScrollArea, QVBoxLayout, QWidget class myDialog(QDialog): _buttons = 0 def __init__(self, parent=None): super(myDialog, self).__init__(parent) self.pushButton = QPushButton(self) self.pushButton.setText("Add Button!") self.pushButton.clicked.connect(self.on_pushButton_clicked) self.scrollArea = QScrollArea(self) self.scrollArea.setWidgetResizable(True) self.scrollAreaWidgetContents = QWidget(self.scrollArea) self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247)) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.addWidget(self.pushButton) self.verticalLayout.addWidget(self.scrollArea) self.verticalLayoutScroll = QVBoxLayout(self.scrollAreaWidgetContents) ''' verticalLayoutScroll is a child of scrollAreaWidgetContents scrollAreaWidgetContents is a child of scrollArea scrollArea is child of self verticalLayout is also a child of self has the widgets pushButton and scrollArea ''' @QtCore.pyqtSlot() def on_pushButton_clicked(self): self._buttons += 1 pustButtonName = u"Button {0}".format(self._buttons) pushButton = QPushButton(self.scrollAreaWidgetContents) pushButton.setText(pustButtonName) self.verticalLayoutScroll.addWidget(pushButton) if __name__ == "__main__": import sys app = QApplication(sys.argv) app.setApplicationName('myDialog') main = myDialog() main.show() sys.exit(app.exec_()) Here is my code: # -*- coding: utf-8 -*- """ Creat…

http://stackoverflow.com/a/49789123
has comment: http://stackoverflow.com/comment/86615121
accepted answer of: http://stackoverflow.com/q/49722029
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86617628
answers question: http://stackoverflow.com/q/49722029
has body: TL;DR The method doesn't exist because process_monitor.py is out of date; download the newest copy from boofuzz and try again. Thank you for the thorough debug information in your question. If process_monitor.py printed a stack trace, including that would also have helped. :) I searched the code base for "PED-RPC> remote" and found it in boofuzz/pedrpc.py on line 2 (permalink): sys.stderr.write('PED-RPC&gt; remote method "{0}" of {1} cannot be found\n'.format(method_name, self)) Notice the slight difference, that little of {1} not present in your output. This suggests your process_monitor.py is from an old version of boofuzz. git blame shows this changed happened at e4723204d43bd758077f56df419af1c7c7424f14, which was first included in v0.0.8. Downloading the latest process_monitor.py should do the trick. This might have been avoided if the process monitor announced its version; I filed an issue.
has comment: http://stackoverflow.com/comment/86610312
has comment: http://stackoverflow.com/comment/86612932
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/a/49724759
has comment: http://stackoverflow.com/comment/86502130
has comment: http://stackoverflow.com/comment/86497429
has comment: http://stackoverflow.com/comment/86502190
score: 0
has body: You can solve your problems by using a hashset, which will let you check for values being present in constant time. Edit: You wanted a more specific example Imports and setting up your files: import openpyxl wb = openpyxl.load_workbook('Test.xlsx') first_sheet = wb.sheetnames[0] Data = wb.get_sheet_by_name(first_sheet) second_sheet = wb.sheetnames[1] Dictionary = wb.get_sheet_by_name(second_sheet) Read each value in Dictionary into memory, creating a dictionary data structure that matches each value in Dictionary that isn't in the first column to the value of the first column in that particular row. Dict = {} for row in range(2, Dictionary.max_row + 1): for col in range(2, Dictionary.max_column + 1): cell_value = Dictionary.cell(row=row, col=col).value Dict[cell_value] = Dictionary.cell(row=row, col=1).value now iterate through Data and perform your operations using Dict: for row in range(2, Data.max_row+1): for col in range(2, Data.max_column + 1): cell_value = Data.cell(row=row, col=col).value if cell_value in Dict: #if it was elsewhere in Dictionary #I'm not sure what you meant by next to so here it just overwrites #The value with the corresponding 1st row in Dictionary Data.cell(row=row, col=col).value = Dict[cell_value] wb.save('Test.xlsx') #save once at the end
has comment: http://stackoverflow.com/comment/86502558
accepted answer of: http://stackoverflow.com/q/49724714
type: Answer
has comment: http://stackoverflow.com/comment/86502408
has comment: http://stackoverflow.com/comment/86502481
has comment: http://stackoverflow.com/comment/86502227
has comment: http://stackoverflow.com/comment/86502457
answers question: http://stackoverflow.com/q/49724714
has comment: http://stackoverflow.com/comment/86502336
has comment: http://stackoverflow.com/comment/86502254
type: AcceptedAnswer

http://stackoverflow.com/comment/89576106
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49649938
has text: Because when I asked this question, This pep was reserved in the first pep and never created as a pep as a web page. Guess they just made it
score: 0

http://stackoverflow.com/a/49600211
score: 1
type: Answer
has body: There are generally two approaches used in practice that I'm aware of: The first one is dropping these counts (i.e. setting "0*log(0) = 0") The second one is adding a some small value e to every count: p -&gt; p+e and renormalizing.
answers question: http://stackoverflow.com/q/49600169
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/133948290
score: 0
comment on: http://stackoverflow.com/a/49749281
has text: @TheophinJohnson assuming you have `from tqdm import tqdm`, you'd simply change the for-loop: `for blob in tqdm(blobs)`
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49722716
tagged with: mod-wsgi
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Troubles with running django app via wsgi on ubuntu 17
has body: I need your help. I have an error when trying to run on wsgi my django project. I'm using Ubuntu 17, Apache2, Django 2.0, Python 3.6 When I running from manage.py, everything is working, but when via wsgi got the next error : AH01276: Cannot serve directory /var/cardsite/cardsite/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive And don't know why, because I guess set everything correct. Bellow my configuration : apache.conf &lt;VirtualHost *:80&gt; CustomLog /var/log/apache2/cardsite-access.log common ErrorLog /var/log/apache2/cardsite-error.log DocumentRoot /var/cardsite/cardsite/ Alias /static /var/cardsite/cardsite/static/ &lt;Directory /var/cardsite/cardsite/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /var/cardsite/cardsite&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] WSGIDaemonProcess cardsite python-path=/var/cardsite/ python-home=/var/venv_python36/ WSGIProcessGroup cardsite WSGIScriptAlias / /var/cardsite/cardsite/wsgi.py &lt;/VirtualHost&gt; wsgi.py import os import sys PROJECT_DIR = '/var/cardsite' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cardsite.settings") def execfile(filename): globals = dict( __file__ = filename ) exec( open(filename).read(), globals ) activate_this = os.path.join( '/var/venv_python36/bin', 'activate_this.py' ) execfile( activate_this ) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() P.S. Permissions I have give on folder and all which inside. P.S.S. Packages like "libapache2-mod-wsgi-py3" or "mod-wsgi" via pip3 also installed. Thank you all for the any suggestion what's it can be
type: UnansweredQuestion
tagged with: wsgi
tagged with: apache
tagged with: django
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/49722802

http://stackoverflow.com/comment/86280733
type: Comment
type: QuestionComment
has text: @Wen, Ah! I misunderstood! Now it makes sense. Still... `transform('first')` is a handy tool that I wish I could find the keyword args for `transform`! If you have any links, I'd much appreciate a link to that doc~
comment on: http://stackoverflow.com/q/49636200
score: 0

http://stackoverflow.com/q/49614096
has comment: http://stackoverflow.com/comment/86234906
has comment: http://stackoverflow.com/comment/86235515
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86234815
has comment: http://stackoverflow.com/comment/86235940
score: 0
has answer: http://stackoverflow.com/a/49614199
answer count: 1
type: Question
has body: i use windows and pycharm 3.6 and for some reason i can't import the csv package to my code. it just goes gray tried to use pip to install, didn't work. if someone can help or otherwise recommend a different package that does the same thing, it would be highly appreciated.
tagged with: pycharm
has title: Installing csv package in pycharm 3.6
type: UnansweredQuestion

http://stackoverflow.com/q/49627458
has answer: http://stackoverflow.com/a/64301879
has answer: http://stackoverflow.com/a/67654274
favorite count: 0
type: Question
tagged with: selenium-chromedriver
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49627941
tagged with: python
tagged with: selenium-webdriver
has title: Python Selenium download images (jpeg, png) or PDF using ChromeDriver
answer count: 3
score: 3
upvote count: 3
has body: I have a Selenium script in Python (using ChromeDriver on Windows) that fetches the download links of various attachments(of different file types) from a page and then opens these links to download the attachments. This works fine for the file types which ChromeDriver can't preview as they get downloaded by default. But images(JPEG, PNG) and PDFs are previewed by default and hence aren't automatically downloaded. The ChromeDriver options I am currently using (work for non preview-able files) : chrome_options = webdriver.ChromeOptions() prefs = {'download.default_directory' : 'custom_download_dir'} chrome_options.add_experimental_option('prefs', prefs) driver = webdriver.Chrome("./chromedriver.exe", chrome_options=chrome_options) This downloads the files to 'custom_download_dir', no issues. But the preview-able files are just previewed in the ChromeDriver instance and not downloaded. Are there any ChromeDriver Settings that can disable this preview behavior and directly download all files irrespective of the extensions? If not, can this be done using Firefox for instance?
tagged with: selenium

http://stackoverflow.com/comment/86328805
has text: I did it on the interactive shell so this is all i have. "Automate the boring stuff with python"(The book) Has the same example, and it works
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49659606
type: QuestionComment

http://stackoverflow.com/comment/86240500
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49616250
score: 0
has text: Thank you for pointing that out. It seems like none of those formats support time zone. How would you go about defining your own date pattern? This seems like the better approach for this scenario.

http://stackoverflow.com/comment/86374080
type: Comment
comment on: http://stackoverflow.com/q/49681114
type: QuestionComment
score: 0
has text: in python you use `def` keyword to define functions

http://stackoverflow.com/a/49753906
has comment: http://stackoverflow.com/comment/86545723
has comment: http://stackoverflow.com/comment/86553238
has body: Use from ...lib import talk. Your import lib.talk doesn't work since lib is a package because of __init__.py inside lib dictionary. You can also use path appending way, but you need to get it something like this: import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'libs'))) This way you will always append path to libs dynamically no matter where your Python code is stored.
has comment: http://stackoverflow.com/comment/86553566
answers question: http://stackoverflow.com/q/49752378
type: Answer
has comment: http://stackoverflow.com/comment/86553682
score: 0

http://stackoverflow.com/comment/86363848
score: 0
type: AnswerComment
has text: I'm trying to practice programming instead of using existing tools @shahaf
type: Comment
comment on: http://stackoverflow.com/a/49676332

http://stackoverflow.com/comment/86410823
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49698836
score: 1
has text: I honestly think you should ask this in a community that is about Python or general programming questions not about TeX.

http://stackoverflow.com/comment/86286647
score: 0
type: AnswerComment
type: Comment
has text: @PatrikPlecho Alright. what would your expected CSV look like for the data in the question? Json keys can be arbitary, and there isn't a way of knowing if they are all going to be common across the board.
comment on: http://stackoverflow.com/a/49639172

http://stackoverflow.com/comment/86220982
type: QuestionComment
score: 0
has text: "As per my knowledge, the linear layer flattens the image". Did you test this assumption? Since, it doesn't seem to be true.
comment on: http://stackoverflow.com/q/49606482
type: Comment

http://stackoverflow.com/comment/115084610
score: 0
type: Comment
comment on: http://stackoverflow.com/a/65094607
type: AnswerComment
has text: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.

http://stackoverflow.com/a/49698733
has comment: http://stackoverflow.com/comment/86447391
accepted answer of: http://stackoverflow.com/q/49698691
has comment: http://stackoverflow.com/comment/86410759
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86411528
has comment: http://stackoverflow.com/comment/86410718
score: 0
has comment: http://stackoverflow.com/comment/86411710
answers question: http://stackoverflow.com/q/49698691
has comment: http://stackoverflow.com/comment/86412013
type: Answer
has body: You can use the following xpath: //tspan[text() = 'Download CSV']

http://stackoverflow.com/q/49697056
has comment: http://stackoverflow.com/comment/86407165
has comment: http://stackoverflow.com/comment/86407224
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/86407078
answer count: 2
linked to: http://stackoverflow.com/q/1373164
downvote count: 0
has title: How to split a dataframe based on column values, sort or groupby for string values?
accepted answer: http://stackoverflow.com/a/49697764
has body: Completely new to coding and pandas. df Date Particulars Inwards Code 1 2017-04-01 EFG 12800 01 2 2017-07-22 ABC 100 01 3 2017-09-05 BCD 10000 01 4 2018-03-13 ABC 2000 01 I wanted to output 3 dataframes from this df based on the df['Particulars'] column, i.e. Output: df1 Date Particulars Inwards Code 2 2017-07-22 ABC 100 01 4 2018-03-13 ABC 2000 01 df2 Date Particulars Inwards Code 1 2017-04-01 EFG 12800 01 df3 Date Particulars Inwards Code 3 2017-09-05 BCD 10000 01 I have a way of doing it through: df1 = df1.append(df.loc[df['Particulars'] == 'ABC'], ignore_index=False) while I initialise a list of Particulars and make dataframes and then do the above command using a for loop. But I am wondering if sort or groupby would be better options? And how exactly to apply them I tried groupby and sort but can't get the dataframe.
possible better answer: http://stackoverflow.com/a/49697757
favorite count: 0
has answer: http://stackoverflow.com/a/49697757
tagged with: pandas-groupby
type: Question
tagged with: pandas
score: 3
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49697764

http://stackoverflow.com/q/49716841
score: 1
has title: Creating new arrays based on unique keys and condition in Python
upvote count: 1
has comment: http://stackoverflow.com/comment/86446876
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49717243
has body: I'm planning to calculate large amount of data in Python instead of Excel, but I'm stuck since I know the Excel command and I have great difficulties to replicating it in Python. Essentially, I'd like to import CSV file, identify the location of column C, and then for all unique values in column A, sum all values in C that apply to the condition 1990 &lt; x &lt; 2000 in B A,B,C 9,1952,125 2,1994,69 3,1973,72 5,1992,85 1,1994,38 1,1994,95 4,1992,29 8,1984,94 I begin with: import csv with open('TestCase.txt', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') row1 = next(reader) Instead of writing multiple if statements, I'd like to create new arrays, composed from 0 and 1, and then sum all values in C. Given another condition the result would look like this 1980&lt;x&lt;1989 94 1990&lt;x&lt;2000 316 Extra bonus would be the total number of unique values in A, that represent the total sum UniqueValues Condition TotalSum 1 1980&lt;x&lt;1989 94 4 1990&lt;x&lt;2000 316
has comment: http://stackoverflow.com/comment/86447404
has answer: http://stackoverflow.com/a/49717252
downvote count: 0
tagged with: python
tagged with: match
has comment: http://stackoverflow.com/comment/86447086
has comment: http://stackoverflow.com/comment/86446711
tagged with: excel
possible better answer: http://stackoverflow.com/a/49717243
tagged with: indexing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49717199
has comment: http://stackoverflow.com/comment/86446854
answer count: 3
has answer: http://stackoverflow.com/a/49717199

http://stackoverflow.com/q/49608252
type: Question
downvote count: 0
tagged with: nuke
linked to: http://stackoverflow.com/q/4128144
answer count: 1
has answer: http://stackoverflow.com/a/49700793
has comment: http://stackoverflow.com/comment/86279167
type: AnsweredQuestion
has title: Batch convert Maya files
has comment: http://stackoverflow.com/comment/86230146
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49700793
tagged with: maya
tagged with: python
has body: I'm actually working on a script to convert a very basic Maya .ma scene to Nuke .nk project using Maya batch mode (mayapy.exe) I have found how to select, search infos from camera but I don't know how to export them in a text file, as a text file with .nk extention works in Nuke. For the moment I use this to export the camera as FBX : outputFilename = os.path.splitext(current)[0]+'.fbx' print "Output file: ", outputFilename cmds.file(outputFilename, exportSelected=True, typ="FBX export", force=True, options="v=0;", es=1) But that cant work for text file or .nk file as Maya doesn't have this option in export settings. Any idea how I can specify to write in a text file with the .nk extention ? Thank you.
favorite count: 0

http://stackoverflow.com/comment/86331311
has text: Oh that looks nice, thanks!
comment on: http://stackoverflow.com/q/49659649
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49688951
answers question: http://stackoverflow.com/q/49688181
score: 0
has body: The datasheet is quite clear: in Ng mode you can measure +/-Ng. So, depending on selected range, you will be able to measure up to 8g not 20-50g you need. And of course greater range means less precision. About you calculation is 8g mode, the module has a 8bit output OR 10bit output for the 8g mode. 2^10*0.016 gives about 16. As the result is signed the range is +/-8g.
has comment: http://stackoverflow.com/comment/86408120
has comment: http://stackoverflow.com/comment/86411775
type: Answer

http://stackoverflow.com/q/49646879
has comment: http://stackoverflow.com/comment/86316279
has comment: http://stackoverflow.com/comment/86312317
has comment: http://stackoverflow.com/comment/86307758
has body: I am trying to fit a LRC Circuit Transfer Function but curve_fit doesn't seem to be able to make a fit. I have tried different initial values as well as trying to implement scipy.optimize.differential_evolution. Below is my fit attempt which produces this after plotting. import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.optimize import differential_evolution def f(freq, R, L, C): w = 2*np.pi*np.array(freq) # Convert frequency to angular frequency return R*w*C/np.sqrt((1-C*L*w**2)**2+(C*w*R)**2) # Series Transfer Function name = ['R', 'L', 'C'] p0 = [1000,0.07,0.0000001] # Actual values of circuit components. params, covariance = curve_fit(f, np.array(x), np.array(y), p0) print(params) I'm not quite sure if the issue lies with my initial parameters, or if the Levenberg-Marquardt algorithm is doing something completely different. When I tried limiting my fit to the strictly increasing portion of the function, the fit seemed to work perfectly, leading me to think my error must be related to the shape of the function. Does anyone have a hint as to why I would be getting such strange fits?
has comment: http://stackoverflow.com/comment/86314292
tagged with: physics
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/86314375
has comment: http://stackoverflow.com/comment/86304672
accepted answer: http://stackoverflow.com/a/49667041
has answer: http://stackoverflow.com/a/49667041
has comment: http://stackoverflow.com/comment/86307606
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86315907
has comment: http://stackoverflow.com/comment/86313223
has comment: http://stackoverflow.com/comment/86316342
has comment: http://stackoverflow.com/comment/86314058
has comment: http://stackoverflow.com/comment/86313352
answer count: 1
tagged with: scipy
has title: Python scipy.optimize.curve_fit Failing to Fit Function
type: Question
has comment: http://stackoverflow.com/comment/86315866
has comment: http://stackoverflow.com/comment/86306730

http://stackoverflow.com/comment/86253484
type: Comment
type: QuestionComment
score: 0
has text: Can you add some data samples and expected output? I think [mcve](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/49623249

http://stackoverflow.com/a/49750826
type: AcceptedAnswer
has body: When you're accessing the image through a web server, the image url must be relative to the web root. You're using the full file path of the image, but this is not accessible to the application in a web context. Flask has a neat way of generating URLs for static files: @app.route("/viz") def viz(): img_url = url_for('static', filename='histo_visual.svg') return render_template('app.html', image_url=img_url) or alternatively, simply render this directly in the Jinja template: &lt;object type="image/svg+xml" data="{{ url_for('static', filename='histo_visual.svg') }}"&gt; &lt;/object&gt;
type: Answer
answers question: http://stackoverflow.com/q/49750711
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86516582
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49750711

spark-streaming
tags question: http://stackoverflow.com/q/49703022
tag name: spark-streaming
tags question: http://stackoverflow.com/q/49742065
tags question: http://stackoverflow.com/q/49720956
type: Tag

http://stackoverflow.com/q/49668550
tagged with: reproducible-research
has answer: http://stackoverflow.com/a/49668770
tagged with: python
type: AnsweredQuestion
tagged with: random
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
has body: If I fit a LassoCV using sklearn, I can do model_LassoCV = LassoCV(cv=3,random_state=2018).fit(X, y) and get reproducible splits for the cross-validation. However, if I do model_LassoCV = LassoLarsCV(cv=3,random_state=2018).fit(X, y) according to the documentation, LassoLarsCV does not have a random_state. So how to get reproducible results with LassoLarsCV ?
tagged with: random-seed
favorite count: 0
type: Question
has title: how to get reproducible splits using LassoLarsCV in sklearn?
accepted answer: http://stackoverflow.com/a/49668770

http://stackoverflow.com/comment/86478753
comment on: http://stackoverflow.com/q/49732538
type: Comment
score: 0
has text: @PeterLeimbigler Yep Edit done, I missed one line in the example, sorry.
type: QuestionComment

http://stackoverflow.com/q/49602396
has title: replace all “\” with “” python
has comment: http://stackoverflow.com/comment/86212061
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49602517
linked to: http://stackoverflow.com/q/1436703
has comment: http://stackoverflow.com/comment/86212041
has comment: http://stackoverflow.com/comment/86211971
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86211995
linked to: http://stackoverflow.com/q/6486918
has answer: http://stackoverflow.com/a/49603243
has comment: http://stackoverflow.com/comment/86212040
has comment: http://stackoverflow.com/comment/86212089
has comment: http://stackoverflow.com/comment/86212070
upvote count: 1
has body: I have the below sentence, where I want to remove the "\" from the word "don'\t". in order to be able to replace don't with do not. a= "To say, "don\'t hate foot" is as dumb as saying "don\'t" my_dict ={"don't":'do not'} print(a.replace(r'\\', "")) out: To say, "don\\\'t hate foot" is as dumb as saying "don\\\'t print(re.sub(r'\\', "",a)) out: To say, "don\'t hate foot" is as dumb as saying "don\'t but I would like: To say, "don't hate foot" is as dumb as saying "don't in order to apply ' '.join([my_dict.get(word, word) for word in x.split()])) I am cleaning a lot of sentences on one go so I would like something stable that will not affect other syntax
has comment: http://stackoverflow.com/comment/86212106
score: -1
tagged with: string
has comment: http://stackoverflow.com/comment/86212001
favorite count: 0
tagged with: replace
type: Question
has comment: http://stackoverflow.com/comment/86211999

http://stackoverflow.com/a/49682448
has comment: http://stackoverflow.com/comment/86376620
has comment: http://stackoverflow.com/comment/86376749
type: Answer
has comment: http://stackoverflow.com/comment/86380225
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86392350
has comment: http://stackoverflow.com/comment/130628098
has body: Well, it prints function, because you literally are printing out the function, not calling it. But that function is not meant to be called by you, but it will be called by the WebSocketApp when you actually have a message and someone has connected to your socket. If you, however, really want to call it, you can probably just do it by changing print(ws.on_message) to ws.on_message(None, 'your message').
answers question: http://stackoverflow.com/q/49682398

http://stackoverflow.com/comment/86268493
type: QuestionComment
comment on: http://stackoverflow.com/q/49630723
type: Comment
has text: Personally, I prefer nested if statements. `if (you have rock)... Indent... if-else (what computer has)`
score: 0

http://stackoverflow.com/comment/86347297
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49667831
has text: Oh, and one more thing, aRemove will never be false. Using reverse logic there, note aRemove and bRemove are initialized True.

http://stackoverflow.com/q/49602394
has comment: http://stackoverflow.com/comment/86212114
tagged with: python
downvote count: 1
favorite count: 0
tagged with: node.js
has comment: http://stackoverflow.com/comment/86212276
score: 0
has comment: http://stackoverflow.com/comment/86212119
has answer: http://stackoverflow.com/a/49603026
tagged with: hex
type: Question
tagged with: binary
has body: I have the file with lines like this: \x8b\xe2=V\xa2\x050\x10\x1f\x11lvCh\x80\xf8z\xf8%\tHKE\xf2\xc8\x92\x12\x83\xe8R\xd3\xc8 I need convert this string to hex code: 0x8be23d56a20530101f116c76436880f87af82509484b45f2c8921283e852d3c8 I tried do this in python and nodejs. But if I do this in console mode - all work fine, if I reading from file, I have wrong result, because from file reads as quoted string.
answer count: 2
has title: Read binary string from file and save as hex
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49605895

http://stackoverflow.com/q/49728926
has body: In the below code, I am trying to take the path name (inclusive of file name) and converting them to another path name with text file. Now I would like to pass both variable as argument for another py which will take it as argument import os thisdir=[os.path.join(r,file) for r,d,f in os.walk("C:\\Users\\vnitin\\OneDrive - NetApp Inc\\IDP\\Files\\") for file in f] for i in range(len(thisdir)): text_path = thisdir[i].replace('pdf', 'txt') print(text_path) os.system('py pdf2txt.py -o text_path thisdir[i]') But individual command for pdf2txt.py works very well. py .\pdf2txt.py -o 'C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files\11.txt' 'C:\Users\vnitin\OneDrive - NetApp Inc\IDP\Files\11.pdf'
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49729417
answer count: 3
tagged with: pdfminer
has comment: http://stackoverflow.com/comment/86471757
has title: Execute python file from another python file by passing argument as variable
accepted answer: http://stackoverflow.com/a/49729052
has answer: http://stackoverflow.com/a/49729170
possible better answer: http://stackoverflow.com/a/49729170
type: Question
has comment: http://stackoverflow.com/comment/86471859
tagged with: python
has answer: http://stackoverflow.com/a/49729052

http://stackoverflow.com/comment/86283359
score: 0
comment on: http://stackoverflow.com/a/49625825
type: Comment
type: AnswerComment
has text: Don't you mean `__future__.CO_FUTURE_PRINT_FUNCTION`, not `__future__.print_function`?

http://stackoverflow.com/a/49717829
score: 1
has body: @NishantThakur 's answer should solve your question as the &lt;input&gt; tag with type as submit is separate from the &lt;input&gt; tag with type as hidden. Additionally as the &lt;input&gt; tag with type as submit is located within the following &lt;form&gt; : &lt;form action=atmos.cgi method=get&gt; To click on the element with type as submit you can use either of the following lines of code : Using click() : driver.findElement(By.xpath("//form[@action='atmos.cgi']//input[@type='submit']")).click(); Using submit() : driver.findElement(By.xpath("//form[@action='atmos.cgi']//input[@type='submit']")).submit();
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49714285
accepted answer of: http://stackoverflow.com/q/49714285

http://stackoverflow.com/comment/94597256
has text: did you figure out how to get the test DB to build XMLTYPE columns? so that, for instance, Oracle XQUERY functions in views work in tests?
comment on: http://stackoverflow.com/q/49684795
score: 0
type: Comment
type: QuestionComment

decode
tag name: decode
tags question: http://stackoverflow.com/q/49617605
tags question: http://stackoverflow.com/q/49739591
tags question: http://stackoverflow.com/q/49755180
type: Tag

http://stackoverflow.com/comment/101321908
has text: Message: invalid argument: log type 'har' not found
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49678384
type: Comment

http://stackoverflow.com/a/49675479
has body: The map object in 3.6 returns an iterator. You need to iterate all its values either by printing each single item, or simply wrapping it into a list( map(...., ...)) statement: n = int(input()) mat = [] for i in range(n): row = list ( map(int, input().split()) ) # iterate all the values immediately mat.append(row) print(mat) For python 2.x the map command produces a list directly. See https://docs.python.org/3/library/functions.html#map
score: 4
answers question: http://stackoverflow.com/q/49675412
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/86426333
has text: how do you want to save the data to a csv file?
score: 0
comment on: http://stackoverflow.com/q/49702923
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49749928
has answer: http://stackoverflow.com/a/49750575
has body: I have a list: mylist=["one","two","three","slgrmff","signaff","huslness"] and a dataframe: busy quicksilver sign 0 huslness qulzkslwx slgrmff 1 NaN NaN signaff I am trying to replace items in mylist if with the column name in the dataframe, if the column has the item. My expected output is: ["one","two","three","sign","sign","busy"]
score: 1
accepted answer: http://stackoverflow.com/a/49750444
tagged with: dataframe
type: Question
possible better answer: http://stackoverflow.com/a/49750575
downvote count: 0
has answer: http://stackoverflow.com/a/49750444
upvote count: 1
tagged with: python
has title: How to replace an item in a list with a dataframe column if column contains the item
tagged with: dictionary
favorite count: 0
type: AnsweredQuestion
answer count: 2
tagged with: list
tagged with: pandas

http://stackoverflow.com/comment/86485717
type: Comment
type: QuestionComment
has text: Also, you should mention the version of `zict` that is already installed on your system.
comment on: http://stackoverflow.com/q/49735311
score: 0

http://stackoverflow.com/comment/86445076
has text: Can u paste your code aswell.
comment on: http://stackoverflow.com/q/49716044
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49603012
upvote count: 1
accepted answer: http://stackoverflow.com/a/49603077
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49603077
answer count: 2
has answer: http://stackoverflow.com/a/49722917
downvote count: 0
tagged with: python
has title: How to write values in csv based on quotation mark and ignore commas inside the quotation?
possible better answer: http://stackoverflow.com/a/49722917
type: AnsweredQuestion
has body: I would like to write some items of a list in a csv, the items are within quotation marks and have commas in between. How can I write them so that the items are not separated due to commas? I looked at many questions that are similar but did not find particular solution to my problem. ['Saks, Lord &amp; Taylor data breach may affect 5 million customers', (u'By Mike Murphy', u'April 1, 2018, 5:24 p.m. EST')] ['Why The China Hustle is a finance documentary all U.S. investors need to see', (u'By MarketWatch', u'NewsWatch')] ['Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets', (u'By Mike Murphy', u'April 1, 2018, 4:49 p.m. EST')] Expected answer: first column = 'Saks, Lord &amp; Taylor data breach may affect 5 million customers' 'Why The China Hustle is a finance documentary all U.S. investors need to see' 'Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets' second column = 'By Mike Murphy' 'By MarketWatch' 'By Mike Murphy' third column = 'April 1, 2018, 5:24 p.m. EST' 'NewsWatch' 'April 1, 2018, 4:49 p.m. EST'
score: 1

http://stackoverflow.com/comment/86215314
type: Comment
type: QuestionComment
has text: @jarmod what exactly should I have set up?
comment on: http://stackoverflow.com/q/49603710
score: 0

http://stackoverflow.com/a/49728737
has comment: http://stackoverflow.com/comment/86472274
has comment: http://stackoverflow.com/comment/86471339
has comment: http://stackoverflow.com/comment/86472802
upvote count: 3
score: 3
has body: You can use this: for line in list_input.split('\n'): print(space_split(line)) If the input comes from a file: with open('file_path', 'r') as your_file: for line in your_file.readlines(): print(space_split(line)) For write these in a file: with open('output_file', 'w') as your_file: for line in list_input.split('\n'): output_file.write(space_split(line) + '\n')
type: Answer
has comment: http://stackoverflow.com/comment/86471708
has comment: http://stackoverflow.com/comment/86471762
downvote count: 0
answers question: http://stackoverflow.com/q/49728544

http://stackoverflow.com/comment/86324619
comment on: http://stackoverflow.com/a/49657458
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/168243/discussion-between-mehul-jain-and-tinkinc).
score: 0
type: Comment

http://stackoverflow.com/a/49602647
has comment: http://stackoverflow.com/comment/86213656
has comment: http://stackoverflow.com/comment/86213225
type: Answer
has comment: http://stackoverflow.com/comment/86213452
has comment: http://stackoverflow.com/comment/86213213
has comment: http://stackoverflow.com/comment/86215953
has comment: http://stackoverflow.com/comment/86214823
has body: Your VB code is just passing 1 as a command-line argument, which is fine—although you may need to change it to add a space after the script name. So, in your Python code, sys.argv[1] will be the string "1", because that's the string representation of the number 1. You can convert that back into a number with int or float (depending on whether it's always going to be an integer, or may be something like 1.5). For some reason, you've copied argv into another variable named script, and then into another one named msg, and then ignored it, replaced msg with the string "Hello Wolrd", and just assigned the constant 1 to arg1. Instead of all that, do this: from sys import argv arg1 = float(argv[1]) That's it. But… I eventually want to pass a pointer to Python as I am going to pass an array, and I assume and array is easier to pass as a pointer if it is about 100x100 floats. That you can't do. Command-line arguments can only be a few short-ish strings, not giant things, and not thing you can't easily convert to and from a string, and definitely not pointers into your own memory. What you usually want to do in that case is either: Have VB export the array as a file in some nice format (like CSV or JSON), pass the filename as a command-line argument, and have Python import the array from the file. Have VB convert the array to a string in some nice format and pass it as the standard input to Python, and have Python parse it from sys.stdin. The first one is probably a bit simpler (because you don't have to learn how to write to the stdin pipe of a child process). I don't know how to write the VB side of that, but the Python side would look like this: import json import sys with open(sys.argv[1], 'rb') as f: arr = json.load(f) And then, if you want to, say, convert that from a list of lists into a numpy 2D array, you do it the same as for any other value: arr = np.array(arr)
has comment: http://stackoverflow.com/comment/86214817
answers question: http://stackoverflow.com/q/49602095
score: 0

http://stackoverflow.com/q/49662850
has answer: http://stackoverflow.com/a/49663428
type: UnansweredQuestion
tagged with: python
tagged with: audio
tagged with: pyaudio
has answer: http://stackoverflow.com/a/49663053
answer count: 2
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86335830
has body: I'm working on a project where I need to get the current system audio output level within Python. Basically, I want to know how loud the current sound coming out of the speakers are using Python on a Linux system. I don't need to know the exact volume level of the speakers, the relative volume is what I'm looking for. I haven't found any good resources online for this.
favorite count: 0
has comment: http://stackoverflow.com/comment/86335981
tagged with: python-3.x
linked to: http://stackoverflow.com/q/11553131
type: Question
has comment: http://stackoverflow.com/comment/86336057
has comment: http://stackoverflow.com/comment/113909199
has title: How do I get the system output volume in python?

http://stackoverflow.com/a/49660046
has comment: http://stackoverflow.com/comment/86329852
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86329682
has comment: http://stackoverflow.com/comment/86330130
has comment: http://stackoverflow.com/comment/86329968
answers question: http://stackoverflow.com/q/49659881
has body: Its mostly easy. You can split the text the user enters, but you need to worry about files with spaces in their names. The shlex lets you split a line the same way a unix-like shell would, which gives you the rules you need. import shlex fileList = [] while True: filePaths = input('Enter files to save. Enter "Done" to end.--&gt;') if filePaths.lower() == "done": break for filePath in shlex.split(filePaths): if not os.path.exists(filePath): print("'{}' not found".format(filePath)) else: fileList.append(filePath)

http://stackoverflow.com/a/49621642
has body: using python3 before my command fixed the problem
type: Answer
score: -1
accepted answer of: http://stackoverflow.com/q/49621613
upvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49621613
downvote count: 1

http://stackoverflow.com/comment/86445901
score: 0
type: Comment
type: QuestionComment
has text: `wat=="Another" or "another" or "more"` does not do what you think it does. You'd use `wat in {"Another", "another", "more"}` instead.
comment on: http://stackoverflow.com/q/49716442

http://stackoverflow.com/a/49758312
type: Answer
accepted answer of: http://stackoverflow.com/q/49739356
has body: You should use Conv1D instead of Conv2D for that. Conv2D is named 2-dimensional because it's designed to process images. However, the input to Conv2D is actually 4-dimensional - (batch, width, height, channels); the channels can be 3 for RGB or 1 for grey-scale images. That's why keras is complaining: ValueError: Input 0 is incompatible with layer conv2d_10: expected ndim=4, found ndim=3 Conv1D accepts 3-dimensional input and that's exactly what you have (provided that you expand your df_x to (15772, 16, 1)). Also the input_shape argument must match the size of each row. Try this: model.add(Conv1D(5, 5, input_shape=(df_x.shape[1], 1)))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86569516
downvote count: 0
has comment: http://stackoverflow.com/comment/86568012
answers question: http://stackoverflow.com/q/49739356
has comment: http://stackoverflow.com/comment/86569375
has comment: http://stackoverflow.com/comment/86568457
has comment: http://stackoverflow.com/comment/86569240
upvote count: 5
score: 5

http://stackoverflow.com/a/62850538
downvote count: 3
answers question: http://stackoverflow.com/q/49722785
has body: I had the same trouble last time. I searched some answers of and got one. You can use self.__delete__(). This delete method that has two underscores around it can only delete an object, so you are good to go!!!
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/111154289
upvote count: 0

http://stackoverflow.com/comment/86329548
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49658000
has text: Does what I've provided work when you run it on the toy data? If so, then it is your data. If it doesn't work on the toy data then it is versioning. I'm running Python 3.6 and pandas 0.22. If it works on toy data, then you should provide enough data such that the error occurs but keep it minimal.
score: 1

python-asyncio
tags question: http://stackoverflow.com/q/49647799
tags question: http://stackoverflow.com/q/49692635
tags question: http://stackoverflow.com/q/49708101
tags question: http://stackoverflow.com/q/49660129
tags question: http://stackoverflow.com/q/49724965
tags question: http://stackoverflow.com/q/49622924
tags question: http://stackoverflow.com/q/49686286
tag name: python-asyncio
type: Tag
tags question: http://stackoverflow.com/q/49728699
tags question: http://stackoverflow.com/q/49736999
tags question: http://stackoverflow.com/q/49715252

http://stackoverflow.com/q/49700457
has comment: http://stackoverflow.com/comment/86414725
type: AnsweredQuestion
tagged with: pandas
tagged with: stack
has title: Pandas multi-index and stack from list of dataframes
tagged with: database
accepted answer: http://stackoverflow.com/a/49701263
tagged with: python
linked to: http://stackoverflow.com/q/49620538
favorite count: 0
type: Question
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86414284
upvote count: 2
has body: I have 3 lists, say A, B, &amp; C that look like this: A = ["Jan", "Feb", "Mar"] B = ["location1", "location2", "location3"] C = [pd.DataFrame(np.random.randn(2, 3), columns=list('ABC'))]*3 How do I create a multiindex dataframe with 3 levels of indexing, i.e. of A, B and the two indices (0 to 1) of C? What I've tried so far is creating a dictionary with all the three indices by looping through all the 3 lists and the dataframe columns, and then, when I have to slice the data, again looping over the keys with a condition. This works but seems pretty inefficient as I have 10 million items in my dictionary. I was wondering if there was a one liner Pandas syntax for this using multiindex and stack. I saw the documentation for these, but the syntax is not clear to me yet. Am I missing any other Pandas function that can help with this? And should I use a database instead?
answer count: 1
has answer: http://stackoverflow.com/a/49701263

http://stackoverflow.com/comment/86259478
type: QuestionComment
comment on: http://stackoverflow.com/q/49626150
score: 0
has text: I forgot to write. Python ver. is 3.6.
type: Comment

http://stackoverflow.com/q/49629330
has answer: http://stackoverflow.com/a/49629488
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86764576
answer count: 4
upvote count: 13
score: 12
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49632113
type: UnansweredQuestion
has title: DataFrame calculating by group for log return of each stock
downvote count: 1
has answer: http://stackoverflow.com/a/49631431
favorite count: 0
has answer: http://stackoverflow.com/a/49629357
has body: As an example, I have created a dataframe that looks like this: date price ticker volume 0 2018-01-01 1.323 AI 2000 1 2018-01-02 1.525 AI 1500 2 2018-01-03 1.045 AI 500 3 2018-01-01 2.110 BOC 3201 4 2018-01-02 2.150 BOC 5200 5 2018-01-03 2.810 BOC 1980 6 2018-01-01 5.199 CAT 2000 7 2018-01-02 4.980 CAT 450 8 2018-01-03 4.990 CAT 3000 So there are 3 stocks and spanning over three days. I want to calculate the daily log returns for each stock between 2018-01-01 and 2018-01-03. My current code is: df["logret"] = df.groupby("ticker").apply(np.log(df.price) - np.log(df.price.shift(1))) But it's throwing me an error message that the Series objects are mutable, thus they cannot be hashed. Can someone please explain to me what this error is pointing towards pls? And how to solve it to be able to compute the log returns by ticker names for each stock?
tagged with: pandas

http://stackoverflow.com/comment/86403812
comment on: http://stackoverflow.com/q/49691714
has text: Your first row `d` would be 0 because you're starting at 1, and the first row's index is 0. What would you want to do when the row above doesn't exist?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86342947
type: QuestionComment
comment on: http://stackoverflow.com/q/49656343
type: Comment
has text: @eyllanesc Yes, it is. I didn't include it here 'coz the Game(Widget) class is fairly extensive.
score: 0

http://stackoverflow.com/q/49711323
has answer: http://stackoverflow.com/a/49711356
has comment: http://stackoverflow.com/comment/86436214
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86436434
linked to: http://stackoverflow.com/q/23759202
tagged with: python
tagged with: operator-precedence
upvote count: 2
score: 0
has title: print(a ** b ** c) - wrong precedence order - Python
downvote count: 2
tagged with: exponential
has body: I tried to print(2 ** 3 ** 2) to test precedence order, but in Python then Python returned me 512.0 as result. I expected Python would take 2 first, then to the power 3 = 8. Then 8, to the power 2 returning 64 as result (since operations are read from left to the right). But instead, Python read 2 ** 3 ** 2 = 2 ** 9 = 512 (from right to the left). Could someone explain why did this happen?
has comment: http://stackoverflow.com/comment/86436608
tagged with: function
type: UnansweredQuestion
tagged with: double
answer count: 1

http://stackoverflow.com/comment/86266046
comment on: http://stackoverflow.com/q/49629657
type: Comment
has text: So your question is...
type: QuestionComment
score: 0

http://stackoverflow.com/q/49715746
accepted answer: http://stackoverflow.com/a/49721248
possible better answer: http://stackoverflow.com/a/49721541
has body: I just have a quick question about Python loop conditions in the while loop. I am looking to take input from the user in the form of (score/max score) eg (13/15). I am looking to put this into a while loop that will continuously ask the user to enter the input in this form until they do it right. So far, I have this num1 = 0 while num1 !='?/?': num1 = raw_input("Please enter your score in the form socre/max(eg. 30/50)") I know how to check if a condition is true with a single number, such as: while x > 18, or if the condition is a string, such as: while x != 'Start'. I am not sure what to use as the parameters for the condition of 15/20, where these two numbers will be input in this exact form 15/20. Any help would be greatly appreciated. Thank you
has comment: http://stackoverflow.com/comment/86446427
has comment: http://stackoverflow.com/comment/86446533
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49721541
score: 0
tagged with: while-loop
answer count: 3
has comment: http://stackoverflow.com/comment/86444654
has title: Python while-loop conditions
has comment: http://stackoverflow.com/comment/86444578
has comment: http://stackoverflow.com/comment/86446326
has comment: http://stackoverflow.com/comment/86444546
has comment: http://stackoverflow.com/comment/86444561
type: Question
has answer: http://stackoverflow.com/a/49721248
tagged with: conditional-statements
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/86444587
has answer: http://stackoverflow.com/a/49732327
tagged with: python

http://stackoverflow.com/comment/86240196
comment on: http://stackoverflow.com/q/49616506
type: Comment
type: QuestionComment
score: 0
has text: @Megalng , My python version is 32 bit.

http://stackoverflow.com/q/49628420
has comment: http://stackoverflow.com/comment/86269821
has comment: http://stackoverflow.com/comment/86263669
has comment: http://stackoverflow.com/comment/86268885
tagged with: split
answer count: 0
has comment: http://stackoverflow.com/comment/86263717
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: data-science
favorite count: 0
has title: Split column into date and values
type: Question
has comment: http://stackoverflow.com/comment/86292153
has body: I have dataframe as below: I need to split this into date and value. If someone experienced this problem, please help
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86264229
tagged with: dataframe
tagged with: python
duplicate of: http://stackoverflow.com/q/44773714

http://stackoverflow.com/a/49677963
has body: I'd recommend to create a startup file as you suggested, and include it via %load ~/.jupyter/startup.py This will paste the content of the file into the cell, which you can then execute. Alternatively, you can write a minimal, installable package that contains all your startup code. Pro: Doesn't clutter your notebook Con: More difficult to make small changes.
type: Answer
answers question: http://stackoverflow.com/q/49677847
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49677847
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86513843
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49749709
score: 0
has text: This is very confusing. Can you give an *example* of an input array, what you are doing currently, what you want as desired output? It helps to *show* us, if possible, instead of describe.

http://stackoverflow.com/a/74812593
answers question: http://stackoverflow.com/q/49726243
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: This is how I solved it: # make sure to cd into the git repo foler import subprocess import sys import os msg = input('Type the commit message (+ ENTER):') repo_directory = os.getcwd() subprocess.run(["git", "add", "."], cwd=repo_directory) # commit file subprocess.run(["git", "commit", "-m", msg], cwd=repo_directory) # push subprocess.run(["git", "push"], cwd=repo_directory)

http://stackoverflow.com/comment/86467895
comment on: http://stackoverflow.com/q/49727037
type: Comment
has text: What *have* you tried? You do know that the naive solution using a `for` loop (like `for fruit in current_fruits: ...`) is "dynamic"?
score: 1
type: QuestionComment

http://stackoverflow.com/a/49715313
downvote count: 1
has comment: http://stackoverflow.com/comment/86444007
answers question: http://stackoverflow.com/q/49715287
type: Answer
has comment: http://stackoverflow.com/comment/86443933
score: 0
has body: There is no function for formatting lists as human-friendly strings You have to format lists yourself: names = ",".join(r'\"{}\"'.format(name) for name in list_names) print(names) #\"Alex\",\"John\",\"Joseph J\" print('Hi my name is ({})'.format(names)) #Hi my name is (\"Alex\",\"John\",\"Joseph J\")
has comment: http://stackoverflow.com/comment/86444024
upvote count: 1

http://stackoverflow.com/comment/86435059
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49710698
has text: @OmarEinea I've updated the question.

http://stackoverflow.com/comment/86405031
type: QuestionComment
comment on: http://stackoverflow.com/q/49695960
has text: Your `name='test'` URL pattern looks OK, it should be available at `/test/`. Note that you are missing `^` from the beginning of some regexes. It's a good idea to use `$` at the end of regexes for individual views as well (but not for `include()`, `admin.site.urls` or routers). At the moment, `r'debug'` matches `/debug/` but also it also matches `/foo/debug/bar/`.
score: 0
type: Comment

http://stackoverflow.com/comment/86386975
comment on: http://stackoverflow.com/q/49682296
type: Comment
type: QuestionComment
score: 0
has text: @Sean OK, I thought you were asking how to hide your private variables even from yourself. Now I have some more idea of what you're trying to do, and where your confusion is, so I wrote an answer.

http://stackoverflow.com/a/49691843
answers question: http://stackoverflow.com/q/49691154
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86395812
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49691154
type: Answer
has body: It's probably better to read the file line by line. That way, you won't run into issues with overloading your memory if the file is too big, and you can also run the 4 digit check on the line itself without the awkward splitting. doc = 0 towrite = "" with open("somefile.txt", "r") as f: for i, line in enumerate(f): if len(line.strip()) == 4 and line.strip().isdigit(): if i &gt; 0: # write txt from prior parse wfile = open("{}.txt".format(doc), "w") wfile.write(towrite) wfile.close() doc = line.strip() towrite = "" # reset else: towrite += line wfile = open("{}.txt".format(doc), "w") wfile.write(towrite) wfile.close() Test file: 1234 43267583291483 1234 3213213 57489367483929 32133248 3728913 3267 32163721837362 4723 3291832 42189323471911 321113 3211111132 326189183828327 3218484828283 828238281 21838282387 3726173 6278 1111 1236274818 327813678 32167382167894829013 321 Results in: 1234.txt 43267583291483 1234 3213213 57489367483929 32133248 3728913 3267.txt 32163721837362 4723 3291832 42189323471911 321113 3211111132 326189183828327 3218484828283 828238281 21838282387 3726173 6278 1111.txt 1236274818 327813678 32167382167894829013 321

http://stackoverflow.com/comment/86419097
type: Comment
comment on: http://stackoverflow.com/q/49701541
type: QuestionComment
score: 1
has text: @AfsanAbdulaliGujarati this code seems to be for standard smtp API.

http://stackoverflow.com/comment/86366324
has text: updated the question here https://stackoverflow.com/questions/49677554/dict-items-getting-error-message-keyerror-%e4%b8%80-in-pandas-python
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49663391
type: Comment

http://stackoverflow.com/comment/86409199
type: Comment
comment on: http://stackoverflow.com/a/49697530
type: AnswerComment
score: 0
has text: At 84 there is a sign change or there iis it the end of the array? If it is the end of the array, will it happen systematically? Now the slice edges are `[(None, 16), (16, 53), (53, 84), (84, None)]`, therefore, if the last one is empty, it must mean that 84 is the last row

http://stackoverflow.com/comment/86435128
type: Comment
score: 1
type: QuestionComment
has text: Either way, you still don't have any dynamic elements in the path itself so your url is literally just `r'^activate$'`.
comment on: http://stackoverflow.com/q/49710698

http://stackoverflow.com/q/49622894
tagged with: python
duplicate of: http://stackoverflow.com/q/6284396
has comment: http://stackoverflow.com/comment/86253035
type: UnansweredQuestion
has title: Efficient permutation of large arrays under symmetry constraints in Python
linked to: http://stackoverflow.com/q/6284396
tagged with: performance
score: 0
has comment: http://stackoverflow.com/comment/86266458
has body: I have an array [1, 1, 2, 3, 3, 3, 0, 0, 0, 0, 0]. I want to generate all permutations under considerations of symmetry/repetition (i.e. for a smaller example: [1, 1] has only one permutation, not two for exchanging the 1s.) Enumerating all permutations with itertools (see code below) is not efficient, especially since I want to go to larger sets. from itertools import permutations p = permutations([1, 1, 2, 3, 3, 3, 0, 0, 0, 0, 0]) j = 0 for i in list(p): print(i) j += 1 # reduce all permutations e.g. with set(). Is there an elegant way of enumerating all combinations? How can I implement it in an efficient way (may largest case has about 100 elements in the array)? Thanks for the help.
tagged with: combinatorics
has comment: http://stackoverflow.com/comment/86258549
type: Question
answer count: 0

http://stackoverflow.com/comment/104800602
type: Comment
has text: Why was this marked as a duplicate? The referenced answers refer only to matplotlib, this question here is about seaborn.
type: QuestionComment
comment on: http://stackoverflow.com/q/49715719
score: 3

http://stackoverflow.com/a/49720591
answers question: http://stackoverflow.com/q/49720530
has body: When you call: print mystr * 5 the number 5 is an integer. In your code, number is a string since you have just split the input. In order to multiply the string by this as an integer, you need to explicitly convert it to one: number = int(p[1])
upvote count: 1
score: 1
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49720530

http://stackoverflow.com/a/49641169
answers question: http://stackoverflow.com/q/49641150
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49641150
score: 0
has body: You can use ast.literal_eval: import ast s = ['(0.027725, 0.0088202301), (0.00055000000000000003, 0.0040760101), (0.1666, 0.0020067799), (0.00545, 0.021263899)'] new_s = ast.literal_eval('[{}]'.format(s[0])) Output: [(0.027725, 0.0088202301), (0.00055, 0.0040760101), (0.1666, 0.0020067799), (0.00545, 0.021263899)]

http://stackoverflow.com/comment/86296576
type: AnswerComment
has text: why do you need `l.append([]) l.append([])`?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49644210

http://stackoverflow.com/comment/86453201
has text: Ayodhyankit Paul, one more thing, every sublist belongs to another class, so every sublist is an object when i try these methods i always end up getting the error [ object is not iterable ] , how can i fix this problem?
comment on: http://stackoverflow.com/a/49719062
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86360448
comment on: http://stackoverflow.com/a/49674226
type: Comment
score: 2
type: AnswerComment
has text: Be sure `time_left` is positive before calling `time.sleep`, though.

http://stackoverflow.com/comment/86292877
comment on: http://stackoverflow.com/q/49642542
has text: Also, it's a bit confusing to call the elements of a list `el` in one line, and then call the elements of the same list `item` in the next. It forces the reader to stop and verify that they really are iterating the same thing, rather than seeing what your code is actually doing.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86530202
has text: The first string represents boys and their age then the second string represents girls and their age.
score: 0
comment on: http://stackoverflow.com/q/49757499
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86208607
type: Comment
type: QuestionComment
has text: What do you mean for "right"?
score: 0
comment on: http://stackoverflow.com/q/49600700

http://stackoverflow.com/comment/86266803
has text: @AngusWilliams - Yes, you are right.
type: QuestionComment
comment on: http://stackoverflow.com/q/49629992
score: 0
type: Comment

http://stackoverflow.com/comment/86422601
type: AnswerComment
comment on: http://stackoverflow.com/a/49704631
score: 0
type: Comment
has text: for instance say that i want to ensure that no rows in the date col have date in format other than 7April,2018 and at the same time no row should be empty can i do that in one go

http://stackoverflow.com/comment/86481975
has text: @PapeK24 `# do sth in list_a` can be moved after inner loop and after break command
comment on: http://stackoverflow.com/q/49733850
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86315528
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49652460
has text: The issue is stated in log you posted `ModuleNotFoundError: No module named 'django'` which means that django isn't installed in the venv if thats the case you''ll need to install the requirements.txt checkout this guide on deployment https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

http://stackoverflow.com/comment/86283505
type: Comment
score: 0
type: AnswerComment
has text: Not sure why you'd be told to use `loc` here?
comment on: http://stackoverflow.com/a/49637147

http://stackoverflow.com/q/49675279
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I'm attempting to subclass a built-in Qt ui class. In QtDesigner I "promote" a QGraphicsView to a "ResultView" and add an include in the class where the UI is loaded and using uic.loadUi('mainwindow.ui', self) to load the ui sheet Just so I can make sure its loading correctly the subclass only looks like this from PyQt5 import QtWidgets class ResultView(QtWidgets.QGraphicsView): def __init__(self): super(ResultView, self).__init__() Which, unless I'm missing something will simply just create a qgraphicsview that has a different name. However, I'm getting an error TypeError: __init__() takes 1 positional argument but 2 were given what second argument am I sending? Demoting back to the qgraphicsview fixes the error, so I am pretty sure its within this class that is causing it. Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.2\helpers\pydev\pydevd.py", line 1596, in &lt;module&gt; globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.2\helpers\pydev\pydevd.py", line 1023, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.2.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/swalsh/Desktop/Mandelbrot/main.py", line 89, in &lt;module&gt; window = MainWindow() File "C:/Users/swalsh/Desktop/Mandelbrot/main.py", line 15, in __init__ uic.loadUi('mainwindow.ui', self) File "C:\Users\swalsh\Anaconda3\lib\site-packages\PyQt5\uic\__init__.py", line 226, in loadUi return DynamicUILoader(package).loadUi(uifile, baseinstance, resource_suffix) File "C:\Users\swalsh\Anaconda3\lib\site-packages\PyQt5\uic\Loader\loader.py", line 72, in loadUi return self.parse(filename, resource_suffix, basedir) File "C:\Users\swalsh\Anaconda3\lib\site-packages\PyQt5\uic\uiparser.py", line 1000, in parse ac…
answer count: 1
downvote count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86361560
accepted answer: http://stackoverflow.com/a/49675526
has title: subclassing: __init__() takes 1 positional argument but 2 were given
favorite count: 0
has answer: http://stackoverflow.com/a/49675526
type: Question

http://stackoverflow.com/a/69074237
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49691410
type: Answer
score: 1
has body: You can use the zip function to get adjacent pairs: for a, b in zip(my_list[:-1], my_list[1:]): if a == "one": print(b)

http://stackoverflow.com/comment/86423898
type: QuestionComment
has text: You should make sure that your `X` (and `Y`) lists contain only number elements (or at least elements that support arithmetic operands), as it stands now `X` contains strings which is what Python complains about (i.e. doesn't know how to rise a string to a power of two in your case).
comment on: http://stackoverflow.com/q/49705263
score: 0
type: Comment

http://stackoverflow.com/q/49673685
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/86376896
has comment: http://stackoverflow.com/comment/86417646
tagged with: right-click
has comment: http://stackoverflow.com/comment/86418419
tagged with: python
has comment: http://stackoverflow.com/comment/86374950
has comment: http://stackoverflow.com/comment/86426395
tagged with: windows-10
has comment: http://stackoverflow.com/comment/86358902
has comment: http://stackoverflow.com/comment/86358633
tagged with: command-line
type: Question
tagged with: contextmenu
has comment: http://stackoverflow.com/comment/86417815
has comment: http://stackoverflow.com/comment/86359552
has body: My goal is to be able to 'right click' a file in file explorer, bring up the context menu and 'left click' to select an option from that menu. My, so far unsuccessful idea, has been to use os.system to get into command prompt from os import system system(r'cd C:\Users\UserName\Documents &amp;&amp; RIGHT CLICK SOME DOCUMENT AND SELECT AN OPTION') But my idea falls short after the &amp;&amp; in the above raw string. Where usually just putting a filename e.g. 'doc.txt' after the &amp;&amp; would left click and open the file, I want to right click. I realise that my solution so far is not strictly python related but an issue with the command line. However I'm very open to and would be very appreciative of pointers towards a python module that might help. (I'm talking about Windows 10 command line here) Thanks!
answer count: 0
upvote count: 2
has title: Python: 'Right click' a file in File Explorer to bring up context menu and 'left click' an option from that menu
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86417557
has comment: http://stackoverflow.com/comment/86418531

http://stackoverflow.com/q/49637221
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49639223
has answer: http://stackoverflow.com/a/62560312
has comment: http://stackoverflow.com/comment/86283570
has comment: http://stackoverflow.com/comment/86282924
type: AnsweredQuestion
answer count: 3
has body: So I'm working on a 3D scanner, and I made some 3D reconstruction code. Here is the code. But because I'm more of a noob, I'm not sure how I could export the point cloud, and afterwards use it a 3d modelling program, like blender.
tagged with: point-clouds
score: 1
has title: How to export a point cloud?
favorite count: 0
possible better answer: http://stackoverflow.com/a/49644281
type: Question
tagged with: 3d-modelling
has answer: http://stackoverflow.com/a/49644281
downvote count: 0
accepted answer: http://stackoverflow.com/a/49639223

http://stackoverflow.com/q/49645499
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: UnansweredQuestion
has body: The code I'm using is following. The screenshot is an output I am getting currently. I want expand CVE_Items column as well. import pandas as pd df = pd.read_json('nvdcve-1.0-modified.json') df.to_csv("test.csv") Format of JSON. This is an NVD data from NVD website. { "CVE_data_type" : "CVE", "CVE_data_format" : "MITRE", "CVE_data_version" : "4.0", "CVE_data_numberOfCVEs" : "1000", "CVE_data_timestamp" : "2018-04-04T00:00Z", "CVE_Items" : [ { "cve" : { "data_type" : "CVE", "data_format" : "MITRE", "data_version" : "4.0", "CVE_data_meta" : { "ID" : "CVE-2001-1594", "ASSIGNER" : "cve@mitre.org" }, "affects" : { "vendor" : { "vendor_data" : [ { "vendor_name" : "gehealthcare", "product" : { "product_data" : [ { "product_name" : "entegra_p&amp;r", "version" : { "version_data" : [ { "version_value" : "*" } ] } } ] } } ] } }, "problemtype" : { "problemtype_data" : [ { "description" : [ { "lang" : "en", "value" : "CWE-255" } ] } ] }, "references" : { "reference_data" : [ { "url" : "http://apps.gehealthcare.com/servlet/ClientServlet/2263784.pdf?DOCCLASS=A&amp;REQ=RAC&amp;DIRECTION=2263784-100&amp;FILENAME=2263784.pdf&amp;FILEREV=5&amp;DOCREV_ORG=5&amp;SUBMIT=+ACCEPT+" }, { "url" : "http://www.forbes.com/sites/thomasbrewster/2015/07/10/vulnerable-breasts/" }, { "url" : "https://ics-cert.us-cert.gov/advisories/ICSMA-18-037-02" }, { "url" : "https://twitter.com/digitalbond/status/619250429751222277" } ] }, "description" : { "description_data" : [ { "lang" : "en", "value" : "GE Healthcare eNTEGRA P&amp;R has a password of (1) entegra for the entegra user, (2) passme for the super user of the Polestar/Polestar-i Starlink 4 upgrade, (3) 0 for the entegra user of the Codonics printer FTP service, (4) eNTEGRA for the eNTEGRA P&amp;R user account, (5) insite for the WinVNC Login, and possibly other accounts, which has unspecified impact and attack vectors. NOTE: it is not clear whether this password is default, hardcoded, or dependent on another system or product that requires a fixe…
has comment: http://stackoverflow.com/comment/86299944
has title: How to convert nested JSON file into CSV using pandas
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49648986
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/49664719
type: Answer
accepted answer of: http://stackoverflow.com/q/49664603
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49664603
has body: A local variable is deleted when the program leaves its scope, and in your case Window() is a local variable that when it finishes executing the constructor is eliminated. For that variable not to be destroyed, it must be related to another variable that has a larger scope. In this case it is appropriate to set the Window() with the centralWidget of QMainWindow. import sys from PyQt4 import QtGui from PyQt4 import QtCore class Window(QtGui.QGraphicsView): def __init__(self, parent=None): QtGui.QGraphicsView.__init__(self, parent) self.scene = QtGui.QGraphicsScene(self) self.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.darkGray, QtCore.Qt.SolidPattern)) self.setScene(self.scene) self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.viewport().setCursor(QtCore.Qt.CrossCursor) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) class CityscapesLabelTool(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) centralwidget = Window() self.setCentralWidget(centralwidget) app = QtGui.QApplication(sys.argv) GUI = CityscapesLabelTool() GUI.show() sys.exit(app.exec_())
score: 1

http://stackoverflow.com/comment/86465061
has text: Nope, its a number. Besides, I got rid of the `if parsed` and it still doesn't work.
comment on: http://stackoverflow.com/q/49725522
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49637504
score: 0
has comment: http://stackoverflow.com/comment/86282825
answer count: 1
has title: Hash Table searching for spell checker in python
type: Question
tagged with: python-3.x
has body: I have the following code which tries to spell check words using a hash table algorithm . It compares the file to be spell checked to a file which is a dictionary and returns all misspelled words. I have successfully carries out this task with a binary and linear search but am finding this more challenging. The dictionary used is 1 word per line and the testfile is lots of text import re dictionary = {} document = [] with open('dict.txt') as f: for word in f: dictionary[word] = 1 with open("testfile.txt" , encoding="utf8") as f: content = f.read().split(" ") content = [item.lower() for item in content] content = ' '.join(content) content = re.findall("[a-z]+", content) for line in content: document.append(line) for line in document: for word in line: if word not in dictionary: print("{} on line #{} is spelled wrong!".format(word, document.index(line))) the code is giving an output of: t on line #0 is spelled wrong! h on line #0 is spelled wrong! e on line #0 is spelled wrong! c on line #1 is spelled wrong! o on line #1 is spelled wrong! m on line #1 is spelled wrong! p on line #1 is spelled wrong! l on line #1 is spelled wrong! e on line #1 is spelled wrong! t on line #1 is spelled wrong! which is spelling out the test file letter by letter as you can see it says "the complete". It seems to be treating each letter in the testfile as a word which is not correct.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86282739
has comment: http://stackoverflow.com/comment/86282758
tagged with: python
has comment: http://stackoverflow.com/comment/86282814
has answer: http://stackoverflow.com/a/49637579

http://stackoverflow.com/comment/86462716
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49724192
has text: This worked. Thank you. Looks like I need to brush up on anonymous lambda functions.
score: 0

http://stackoverflow.com/q/49753225
type: Question
has comment: http://stackoverflow.com/comment/86526114
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86526446
has title: django.core.exceptions.AppRegistryNotReady Error
tagged with: django
has comment: http://stackoverflow.com/comment/86525516
favorite count: 0
has body: I am using Django 2.0.3 version with python 3.4. I am following simple Polls Tutorial and I am getting following error in models file. Errors in polls/models.py: Traceback (most recent call last): File "E:\Mysite\mysite\polls\models.py", line 4, in &lt;module&gt; class Questions(models.Model): File "C:\Python34\lib\site-packages\django\db\models\base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Python34\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Then I searched the internet due to which I checked wsgi file and there also I got ImportError. I didn't make any changes in wsgi file. Errors in wsgi: Traceback (most recent call last): File "E:\Mysite\mysite\mysite\wsgi.py", line 16, in &lt;module&gt; application = get_wsgi_application() File "C:\Python34\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Python34\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python34\lib\importlib\__init__.py", line 104, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2231, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2214, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;",…
linked to: http://stackoverflow.com/q/25680803
tagged with: django-2.0
has comment: http://stackoverflow.com/comment/86526279
has comment: http://stackoverflow.com/comment/86521116
score: 1
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86526993
has comment: http://stackoverflow.com/comment/86527452
answer count: 0
downvote count: 0

http://stackoverflow.com/a/49605216
has body: The sixth line doesn't start with your target string TTU Back Panel - there's other text. So you need .*? before it: &gt;&gt;&gt; text = '''[01112017 110228 359][1][INFO]&gt; Get Cash Unit Info [01112017 110228 400][1][INFO]&gt; ---Cash Unit Info Ready True''' # etc. &gt;&gt;&gt; re.search('([^\n]*\n){5}.*?TTU Back Panel', text) &lt;_sre.SRE_Match object; span=(312, 829), match='[01112017 110228 700][1][INFO]&gt; Cash Unit Info - &gt;
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49605180

http://stackoverflow.com/q/49624819
has comment: http://stackoverflow.com/comment/86257458
has comment: http://stackoverflow.com/comment/86257015
tagged with: psychopy
has comment: http://stackoverflow.com/comment/86257386
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: In my experiment, participants have to make a series of ratings in a visual rating scale. First I initialize the screen and add the corresponding visual components. My variable recall creates the rating scale which provides 2 choices: "Yes" and "No". Later, with the vasTitle variable a title is created which asks 'Do you remember this painting?' and they have to answer "Yes" or "No" on the scale that appears on the same screen as the question. Now I would like to condition my recall statement depending on whether the participant answered "Yes" or "No" but I have no idea on how to do it. If participants answer "No" I would like to address their confidence of their previous answer (this is where the problem is, in this condition). This I do by creating another scale where they have to answer either "yes" or "no" they feel confident about their previous answer to whether they recall the painting or not. When I run my code it breaks at the moment I condition the recall variable. You can see at the end of the code what I have tried, but it doesn't seem to work. from psychopy import visual # Intialize screen win = visual.Window(size=(1440, 900), fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor', color=[0,0,0], colorSpace='rgb', blendMode='avg', useFBO=True, units='deg') # Initialize Visual Components recall = visual.RatingScale(win, choices=("Yes", "No"), markerStart=0.5, singleClick=False, disappear=False, respKeys=['left', 'right'], showAccept=False, acceptKeys='up') vasTitle = visual.TextStim(win=win, ori=0, name='vasTitle', text=u'+', font=u'Arial', pos=[0, 5], height=1.0, wrapWidth=None, color=u'white', colorSpace='rgb', opacity=1, depth=0.0) vasScore = visual.TextStim(win=win, ori=0, name='vasScore', text=u'+', font=u'Arial', pos=[0, -3], height=1.0, wrapWidth=None, color=u'white', colorSpace='rgb', opacity=1, depth=0.0) confidence2 = visual.RatingScale(win, low=1, high=6, labels=("Sure I don't know", "Sure I know"), marker='glow', ma…
has comment: http://stackoverflow.com/comment/86258197
has comment: http://stackoverflow.com/comment/86258284
tagged with: python
type: UnansweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/86256810
upvote count: 0
has title: if statement condition depending on response psychopy
has answer: http://stackoverflow.com/a/49626739

http://stackoverflow.com/comment/86237056
score: 0
comment on: http://stackoverflow.com/q/49605789
type: QuestionComment
type: Comment
has text: Just created a `post_save` signal that simply calls `CapabilityRelationshipCompleteNumber.objects.all().delete()`. I can verify it's working, but it's doing the same thing as when I override `save()`; that is, if I output `CapabilityRelationshipCompleteNumber.objects.all()` before and after calling `delete()`, it appears that it's empty, but it's not actually deleting anything.

http://stackoverflow.com/a/49722105
downvote count: 0
answers question: http://stackoverflow.com/q/49720662
has body: Looking at the documentation it looks like you must use nodejs6.10 runtime for cloudfront to work with lambda. You must create functions with the nodejs6.10 runtime property.
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/49720662
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49643793
has comment: http://stackoverflow.com/comment/86295968
has comment: http://stackoverflow.com/comment/86295224
has answer: http://stackoverflow.com/a/49645205
tagged with: configuration
has comment: http://stackoverflow.com/comment/86295482
score: 10
has answer: http://stackoverflow.com/a/49644279
has body: I realise this question as been asked before (What&#39;s the best practice using a settings file in Python?) but seeing as this was asked 7 years ago, I feel it is valid to discuss again seeing as how technologies have evolved. I have a python project that requires different configurations to be used based on the value of an environment variable. Since making use of the environment variable to choose a config file is simple enough, my question is as follows: What format is seen as the best practice in the software industry for setting up a configuration file in python, when multiple configurations are needed based on the environment? I realise that python comes with a ConfigParser module but I was wondering if it might be better to use a format such as YAML or JSON because of there raise in popularity due to their ease of use across languages. Which format is seen as easier to maintain when you have multiple configurations?
tagged with: python
linked to: http://stackoverflow.com/q/5055042
has answer: http://stackoverflow.com/a/61153824
has title: What is the best method for setting up a config file in Python
has answer: http://stackoverflow.com/a/49643959
upvote count: 11
has answer: http://stackoverflow.com/a/70137347
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86295179
has answer: http://stackoverflow.com/a/78942851
tagged with: yaml
tagged with: http://stackoverflow.com/tag/json
answer count: 7
possible better answer: http://stackoverflow.com/a/61153824
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/62651115
accepted answer: http://stackoverflow.com/a/49645205
has comment: http://stackoverflow.com/comment/86296125

http://stackoverflow.com/comment/86310712
has text: Which compiler do you use? I tried g++ and it gave me 0.042s on your code with no modifications except g++-specific fixes like `int main`
comment on: http://stackoverflow.com/q/49650962
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86254294
comment on: http://stackoverflow.com/q/49623249
has text: @DyZ, I thing this could be the ans can you post answer with example.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49705590
tagged with: python
has title: Loss decreases but weights don't appear to change during tensorflow gradient descent
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86428256
has comment: http://stackoverflow.com/comment/86425276
answer count: 1
downvote count: 0
tagged with: tensorflow
score: 8
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33640581
has body: I have set up a very simple multi-layer perceptron with a single hidden layer using a sigmoid transfer function, and mock data with 2 inputs. I have tried to set up using the Simple Feedforward Neural Network using TensorFlow example on Github. I won't post the whole thing here but my cost function is set up like this: # Backward propagation loss = tensorflow.losses.mean_squared_error(labels=y, predictions=yhat) cost = tensorflow.reduce_mean(loss, name='cost') updates = tensorflow.train.GradientDescentOptimizer(0.01).minimize(cost) Then I simply loop through a bunch of epochs, the intention being that my weights are optimised via the updates operation at every step: with tensorflow.Session() as sess: init = tensorflow.global_variables_initializer() sess.run(init) for epoch in range(10): # Train with each example for i in range(len(train_X)): feed_dict = {X: train_X[i: i + 1], y: train_y[i: i + 1]} res = sess.run([updates, loss], feed_dict) print "epoch {}, step {}. w_1: {}, loss: {}".format(epoch, i, w_1.eval(), res[1]) train_result = sess.run(predict, feed_dict={X: train_X, y: train_y}) train_errors = abs((train_y - train_result) / train_y) train_mean_error = numpy.mean(train_errors, axis=1) test_result = sess.run(predict, feed_dict={X: test_X, y: test_y}) test_errors = abs((test_y - test_result) / test_y) test_mean_error = numpy.mean(test_errors, axis=1) print("Epoch = %d, train error = %.5f%%, test error = %.5f%%" % (epoch, 100. * train_mean_error[0], 100. * test_mean_error[0])) sess.close() I would expect the output of this program to show that at each epoch and for each step the weights would be updated, with a loss value that would broadly decrease over time. However, while I see the loss value and errors decreasing, the weights only ever change after the first step, and then remain fixed for the remainder of the program. What is going on here? Here is what is printed to screen during the first 2 epochs: epoch 0, step 0. w_1: [[0. 0.] [0. 0.]], loss: 492.52563…
has comment: http://stackoverflow.com/comment/86425402
upvote count: 8
has answer: http://stackoverflow.com/a/49753935
accepted answer: http://stackoverflow.com/a/49753935
has comment: http://stackoverflow.com/comment/86424891

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/49706284

http://stackoverflow.com/comment/86208313
type: QuestionComment
has text: Have you searched this site for questions and answers related to `PY_VAR0`?
comment on: http://stackoverflow.com/q/49600546
type: Comment
score: 0

http://stackoverflow.com/comment/86469859
score: 0
type: QuestionComment
has text: Are you adding ``SetEnv`` directives to Apache for ``VAR_1`` and ``VAR_2``? If using mod_wsgi, that or using mod_rewrite or mod_headers in fancy ways is the only way to pass ``environ`` variables in a request to the WSGI application.
type: Comment
comment on: http://stackoverflow.com/q/49727381

http://stackoverflow.com/comment/86390158
type: Comment
type: QuestionComment
has text: @Mathieu, I think this may be a smart way to go about this.
score: 0
comment on: http://stackoverflow.com/q/49689275

http://stackoverflow.com/q/49621313
has body: I have a FASTA file with a bunch of sequences with the following format: BMRat|XM_008846946.1 ATGAAGAACATCACAGAAGCCACCACCTTCATTCTCAAGGGACTCACAGACAATGTGGAACTACAGGTCA TCCTCTTTTTTCTCTTTCTAGCGATTTATCTCTTCACTCTCATAGGAAATTTAGGACTTATTATTTTAGT TATTGGGGATTCAAAACTCCACAACCCTATGTACTGTTTTCTGAGTGTATTGTCTTCTGTAGATGCCTGC TATTCCTCAGACATCACCCCGAATATGTTAGTAGGCTTCCTGTCAAAAAACAAAGGCATTTCTCTCCATG GATGTGCAACACAGTTGTTTCTCGCTGTTACTTTTGGAACCACAGAATGCTTTCTGTTGGCGGCAATGGC TTATGACCGCTATGTAGCCATCCATGACCCACTTCTCTATGCAGTGAGCATGTCACCAAGGATCTATGTG CCGCTCATCATTGCTTCCTATGCTGGTGGAATTCTGCATGCGATTATCCACACCGTGGCCACCTTCAGCC TGTCCTTCTGTGGATCTAATGAAATCAGTCATATATTCTGTGACATCCCTCCTCTGCTGGCTATTTCTTG TTCTGACACTTACATCAATGAGCTCCTGTTGTTCTTCTTTGTGAGCTCCATAGAAATAGTCACTATCCTC ATCATCCTGGTCTCTTATGGTTTCATCCTTATGGCCATTCTGAAGATGAATTCAGCTGAAGGGAGGAGAA AAGTCTTCTCTGCATGTGGGTCTCACCTAACTGGAGTGTCCATTTTCTATGGGACAAGCCTTTTCATGTA TGTGAGACCAAGCTCCAACTATTCCTTGGCACATGACATGGTAGTGTCGACATTTTATACCATTGTGATT CCCATGCTGAACCCTGTCATCTACAGTCTGAGGAACAAAGATGTGAAAGAGGCAATGAGAAGATTTTTGA AGAAAAATTTTCAGAAACTTTAA The code implemented using biopython http://biopython.org/wiki/Seq allows me to find the longest sequence of amino acids that starts with Methionine and ends with a Stop codon, of each sequence in the FASTA file. The function is find_largest_polypeptide_in_DNA. Basically it translates the DNA sequence to an amino acid sequence using the 3 different forward reading frames, and in the variable allPossibilities it saves the segments that starts with M (a particular amino acid) and end in a stop codon. Then it compares the lengths of the possibilities and selects the longest possibility, returning the protein sequence of that segment. def find_largest_polypeptide_in_DNA(seq, translationTable=1): allPossibilities = [] for frame in range(3): trans = str(seq[frame:].translate(translationTable)) framePossibilitiesF = [i[i.find("M"):] for i in trans.split("*") if "M" in i] allPossibilities += framePossibilitiesF allPossibilitiesLengths = [len(i) for i in…
has comment: http://stackoverflow.com/comment/86250149
tagged with: python
has comment: http://stackoverflow.com/comment/86249888
tagged with: biopython
tagged with: dna-sequence
has comment: http://stackoverflow.com/comment/86276136
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/86249749
upvote count: 2
has answer: http://stackoverflow.com/a/49621637
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86250311
has title: How to track the position of a start codon (ATG) in a nucleotide sequence after using the translate function of Biopython?
tagged with: sequence
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49621637
has comment: http://stackoverflow.com/comment/86250335

http://stackoverflow.com/a/53600010
answers question: http://stackoverflow.com/q/49665919
score: 2
upvote count: 2
downvote count: 0
has body: I would suggest using opsdroid with the opsdroid-skype extension. It uses the Microsoft bot framework SDK v4 for Python. To deploy the bot, create and configure a Bot Channels Registration resource in Azure. Make sure you: enter the correct full 'Messaging endpoint' URL in settings test the bot (see 'Test in Web Chat') enter the bot Microsoft Application Id &amp; Password into your opsdroid config; you may need to click the 'Manage' link in the bot registration settings to access the password add a Skype 'channel' to the registration resource (there is NO NEED to configure it in any way or publish it!) After completing the above steps, visit your bot endpoint using a web browser; you will be redirected to a Microsoft-hosted page for adding the bot as a Skype contact.
type: Answer

linux
tags question: http://stackoverflow.com/q/49691828
tags question: http://stackoverflow.com/q/49696486
tags question: http://stackoverflow.com/q/49708993
tags question: http://stackoverflow.com/q/49690321
tags question: http://stackoverflow.com/q/49668361
tag name: linux
tags question: http://stackoverflow.com/q/49646130
tags question: http://stackoverflow.com/q/49609473
tags question: http://stackoverflow.com/q/49617465
tags question: http://stackoverflow.com/q/49688273
tags question: http://stackoverflow.com/q/49601803
tags question: http://stackoverflow.com/q/49695990
tags question: http://stackoverflow.com/q/49721813
tags question: http://stackoverflow.com/q/49665668
tags question: http://stackoverflow.com/q/49675458
tags question: http://stackoverflow.com/q/49654856
tags question: http://stackoverflow.com/q/49608573
tags question: http://stackoverflow.com/q/49756369
tags question: http://stackoverflow.com/q/49707469
tags question: http://stackoverflow.com/q/49752192
tags question: http://stackoverflow.com/q/49664631
tags question: http://stackoverflow.com/q/49604073
type: Tag
tags question: http://stackoverflow.com/q/49602156
tags question: http://stackoverflow.com/q/49697157
tags question: http://stackoverflow.com/q/49701927
tags question: http://stackoverflow.com/q/49604763
tags question: http://stackoverflow.com/q/49683692

http://stackoverflow.com/comment/86356231
type: QuestionComment
comment on: http://stackoverflow.com/q/49672081
type: Comment
has text: @ScottBoston Thanks for trying, I'm using 0.22.0 and tried multiple times with different datasets but as I said I have no clue why it does what it does
score: 0

http://stackoverflow.com/a/49691133
has body: If you are happy to use a 3rd party library, numpy provides one way. This assumes your list elements have the same length. import numpy as np A = np.array([[0,0,2],[1,0,1],[2,1,0],[2,1,3]]) res = A.max(axis=0) # array([2, 1, 3])
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49690982
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49690982

http://stackoverflow.com/comment/86406931
type: AnswerComment
has text: @CGully, if you have any number of columns, e.g. cat / dog / fish / bird / etc, then have a look at my solution. But I'm sure Wen can come up with a generic pandas solution too.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49696764

http://stackoverflow.com/a/49699125
has body: fig, r = plt.subplots(nrows=1, ncols=3, figsize=(14,4)) for ax, col in zip(r, ['I_Base', 'U_Win', 'Occ']): df[df.index.month == 1].plot(kind='scatter', x=col, y='Energy', ax=ax, alpha=.5, color='r') This will do the scatter plot where index's Datetime is Jan. Please read this about reproducible data.
downvote count: 0
has comment: http://stackoverflow.com/comment/86415020
accepted answer of: http://stackoverflow.com/q/49697991
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49697991
type: Answer
has comment: http://stackoverflow.com/comment/86414985

http://stackoverflow.com/q/49703305
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86420148
linked to: http://stackoverflow.com/q/1816958
favorite count: 0
type: Question
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86420100
has comment: http://stackoverflow.com/comment/86420665
has comment: http://stackoverflow.com/comment/86420251
has body: How do I call a method from a different class (different module) with the use of Multiprocess pool in python? My aim is to start a process which keep running until some task is provide, and once task is completed it will again go back to waiting mode. Below is code, which has three module, Reader class is my run time task, I will provide execution of reader method to ProcessExecutor. Process executor is process pool, it will continue while loop until some task is provided to it. Main module which initiates everything. Module 1 class Reader(object): def __init__(self, message): self.message = message def reader(self): print self.message Module 2 class ProcessExecutor(): def run(self, queue): print 'Before while loop' while True: print 'Reached Run' try: pair = queue.get() print 'Running process' print pair func = pair.get('target') arguments = pair.get('args', None) if arguments is None: func() else: func(arguments) queue.task_done() except Exception: print Exception.message main Module from process_helper import ProcessExecutor from reader import Reader import multiprocessing import Queue if __name__=='__main__': queue = Queue.Queue() myReader = Reader('Hi') ps = ProcessExecutor() pool = multiprocessing.Pool(2) pool.apply_async(ps.run, args=(queue, )) param = {'target': myReader.reader} queue.put(param) Code executed without any error: C:\Python27\python.exe C:/Users/PycharmProjects/untitled1/main/main.py Process finished with exit code 0 Code gets executed but it never reached to run method. I am not sure is it possible to call a method of the different class using multi-processes or not I tried apply_async, map, apply but none of them are working. All example searched online are calling target method from the script where the main method is implemented. I am using python 2.7 Please help.
type: AnsweredQuestion
has title: How to call method from different class using multiprocess pool python
has comment: http://stackoverflow.com/comment/86420865
has comment: http://stackoverflow.com/comment/86420882
has answer: http://stackoverflow.com/a/49703866
accepted answer: http://stackoverflow.com/a/49703866

http://stackoverflow.com/a/49711140
answers question: http://stackoverflow.com/q/49709130
has body: GridSearchCV does not take into account your test set (looking closely, you'll see that you don't pass your test set in tree.fit()); the score it reports, best_score_, comes from a cross-validation (CV) in your training set. From the docs: best_score_ : float Mean cross-validated score of the best_estimator This score itself (0.955 in your example) is the mean value of the score in each one of the (default, since you have not specified the cv argument) 3 CV folds. Your accuracy_score, on the other hand, comes from your test set. That clarified, it should be obvious that these two numbers are not the same; on the other hand, and provided that both the CV procedure and the train-test split have been performed correctly, they should not be much different, too, which is arguably your case here.
type: Answer
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49709130
score: 4

http://stackoverflow.com/comment/86470286
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49728132
has text: `\u....` in *string literals* are being interpreted, read from text files they're not.
score: 0

http://stackoverflow.com/comment/86271501
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49631555
has text: my file is a .csv: Unnamed: 0 Start Time End Time Trip Duration \ 0 1423854 2017-06-23 15:09:32 2017-06-23 15:14:53 321 1 955915 2017-05-25 18:19:03 2017-05-25 18:45:53 1610 Start Station End Station User Type \ 0 Wood St & Hubbard St Damen Ave & Chicago Ave Subscriber 1 Theater on the Lake Sheffield Ave & Waveland Ave Subscriber Gender Birth Year 0 Male 1992.0 1 Female 1992.0
type: Comment

http://stackoverflow.com/q/49719673
has body: I found this piece of code in the subprocess documentation, where one process's stdout is being piped into another process: p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] And I'm confused by that stdout.close() call. Surely closing the stdout handle prevents the process from producing any output? So I ran an experiment, and to my surprise the process wasn't affected by it at all: from subprocess import Popen, PIPE p1 = Popen(['python', '-c', 'import time; time.sleep(5); print(1)'], stdout=PIPE) p2 = Popen(['python', '-c', 'print(input()*3)'], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. print('stdout closed') print('stdout:', p2.communicate()[0]) # output: # stdout closed # [5 second pause] # stdout: b'111\n' What's going on here? Why can the process write to a closed pipe?
downvote count: 1
has comment: http://stackoverflow.com/comment/86452841
has comment: http://stackoverflow.com/comment/86453011
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49720527
has title: Why can a subprocess still write to stdout after it's been closed?
accepted answer: http://stackoverflow.com/a/49720509
tagged with: pipe
has answer: http://stackoverflow.com/a/49720509
has comment: http://stackoverflow.com/comment/86452538
tagged with: python
score: 7
possible better answer: http://stackoverflow.com/a/49720527
favorite count: 0
has comment: http://stackoverflow.com/comment/86453265
type: Question
has comment: http://stackoverflow.com/comment/86452721
answer count: 2
upvote count: 8
tagged with: subprocess

http://stackoverflow.com/comment/86332633
has text: @Carcigenicate Thanks for the response, code is attached.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49661229

http://stackoverflow.com/a/49709702
downvote count: 0
type: Answer
upvote count: 1
has body: return all players whose last observation was for team on date. rather than constructing a dataframe to use DataFrame.loc, you can define a custom loc function Given a date n, we can get the last team for all the players using: last_team = df[df.DATE&lt;=n].groupby('PLAYER').TEAM.agg('last') Then we can select the players in a given team last_team.index[last_team.TEAM=='A'].values Combine the two steps above in a function call as you need. def myloc(frame, date, team): last_team = frame[frame['DATE']&lt;=date].groupby('PLAYER')['TEAM'].agg('last') return last_team.index[last_team == team].values Example outputs: In [11]: myloc(df, 0, 'A') Out[10]: array(['John', 'Tom'], dtype=object) In [11]: myloc(df, 1, 'A') Out[11]: array(['George', 'John', 'Tom'], dtype=object) In [12]: myloc(df, 2, 'A') Out[12]: array(['George', 'John', 'Rob', 'Tom'], dtype=object) In [13]: myloc(df, 0, 'B') Out[13]: array(['Chris', 'Rob'], dtype=object) In [14]: myloc(df, 1, 'B') Out[14]: array(['Chris', 'Rob'], dtype=object) In [15]: myloc(df, 2, 'B') Out[15]: array(['Chris'], dtype=object) A higher performing approach would be to use pd.merge_asof to construct a table of players and their most recent team membership on a given date. First, we have to build a table of all possible players &amp; dates. df2 = pd.DataFrame(index=pd.MultiIndex.from_product([df.DATE.unique(), df.PLAYER.unique()])).reset_index() df2.columns = ['DATE', 'PLAYER'] df3 = pd.merge_asof(df2, df, on='DATE', by='PLAYER').set_index(['DATE', 'TEAM']).sort_index() df3 # outputs PLAYER DATE TEAM 0 A John A Tom B Chris B Rob NaN George 1 A John A Tom A George B Chris B Rob 2 A John A Tom A Rob A George B Chris Then you can use loc to get the players who were last observed playing for a team df3.loc[0, 'A'].PLAYER.values # outputs: array(['John', 'Tom'], dtype=object)
has comment: http://stackoverflow.com/comment/86433044
score: 1
has comment: http://stackoverflow.com/comment/86433023
answers question: http://stackoverflow.com/q/49706818

http://stackoverflow.com/q/49709405
type: AnsweredQuestion
tagged with: pandas
score: 2
answer count: 1
tagged with: dataframe
favorite count: 0
tagged with: jupyter-notebook
type: Question
has answer: http://stackoverflow.com/a/49709783
upvote count: 2
has body: I have a dataframe based on football players. I am finding duplicate rows for when a player has transferred mid-season. My aim is to add the points the accumalted in both leagues and add them together to make just one row. Here is a sample of the data: name full_name club Points Start Sub 84 S. Mustafi Shkodran Mustafi Arsenal 76 26 1 85 S. Mustafi Shkodran Mustafi Arsenal -2 0 1 89 Bruno Bruno Soriano Llido Villarreal CF 43 15 16 90 Bruno Bruno Gonzalez Cabrera Getafe CF 43 15 16 119 Oscar Oscar dos Santos Emboaba NaN 16 5 8 120 Oscar Oscar dos Santos Emboaba NaN 1 0 2 121 Oscar Oscar Rodriguez Arnaiz Real Madrid CF 16 5 8 122 Oscar Oscar Rodriguez Arnaiz Real Madrid CF 1 0 2 188 C. Bravo Claudio Bravo Manchester City 61 22 8 189 C. Bravo Claudio Bravo Manchester City 1 1 0 193 Naldo Ronaldo Aparecido Rodrigues FC Schalke 04 58 19 1 194 Naldo Edinaldo Gomes Pereira RCD Espanyol 58 19 1 200 G. Castro Gonzalo Castro Borussia Dortmund 79 23 6 201 G. Castro Gonzalo Castro Malaga CF 79 23 6 209 Juanfran Juan Francisco Torres Belen Atletico Madrid 86 21 8 210 Juanfran Juan Francisco Torres Belen Atletico Madrid 74 34 2 211 Juanfran Juan Francisco Moreno Fuertes RC Coruna 86 21 8 212 Juanfran Juan Francisco Moreno Fuertes RC Coruna 74 34 2 My goal dataframe would have players like for example Mustafi's Points Start and Sum values added together to give just one player. Players like Bruno are clearly not the same person so I don't want to add the two brunos together. name full_name club Points Start Sub 84 S. Mustafi Shkodran Mustafi Arsenal 74 26 2 89 Bruno Bruno Soriano Llido Villarreal CF 43 15 16 90 Bruno Bruno Gonzalez Cabrera Getafe CF 43 15 16 119 Oscar Oscar dos Santos Emboaba NaN 17 5 10 121 Oscar Oscar Rodriguez Arnaiz Real Madrid CF 17 5 10 188 C. Bravo Claudio Bravo Manchester City 62 23 8 193 Naldo Ronaldo Aparecido Rodrigues FC Schalke 04 58 19 1 194 Naldo Edinaldo Gomes Pereira RCD Espanyol 58 19 1 200 G. Castro Gonzalo Castro Borussia Dortmund 158 46 12 209…
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49709783
has title: Combine certain rows values of duplicate rows Pandas

http://stackoverflow.com/q/49683143
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49683534
tagged with: group-by
has body: I need to do a consecutive group-by involving multiple columns in a pandas dataframe. I've found answers on how to do a consecutive group-by with a single column, but I'm not sure how to extend it to multiple columns. For exmaple, my data looks like: Time Object Status 1 A On 2 A Off 3 A On 4 B On 5 B On I want to count consecutive observations with the same Object and Status. Object Status Duration 1 A On 1 2 A Off 1 3 A On 1 , 4 B On 2 Thanks
tagged with: python
has title: Python Pandas Group By Consecutive Multiple Columns
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 2
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/49683534
downvote count: 1

http://stackoverflow.com/comment/86579538
has text: I just want to make video instead of taking pictures by using that buffer code. I tried to modify but didn't worked. Do you want me to make a another question or you can solve it here ?
type: AnswerComment
comment on: http://stackoverflow.com/a/49716983
score: 0
type: Comment

http://stackoverflow.com/q/49669212
downvote count: 0
tagged with: gevent
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/15556718
possible better answer: http://stackoverflow.com/a/74883624
has body: I am new to gevent.I have read introduction from gevent They have provided simple examples but I am struggling to understand what greenlet is.From Learning Concurrency. Greenlets are a very lightweight coroutine written in C that are cooperatively scheduled. They provide us with a very lightweight thread- like object that allows us to achieve concurrent execution within our Python programs without incurring the cost of spinning up multiple threads. Greenlets are not threads? How is synhronisation point defined? Could somone explain with examples?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49701723
has answer: http://stackoverflow.com/a/49701723
tagged with: python
duplicate of: http://stackoverflow.com/q/15556718
has title: What is greenlet?
score: 11
upvote count: 11
answer count: 2
has answer: http://stackoverflow.com/a/74883624

http://stackoverflow.com/a/49652307
type: Answer
has comment: http://stackoverflow.com/comment/86315143
has comment: http://stackoverflow.com/comment/86314635
score: 0
has comment: http://stackoverflow.com/comment/86315337
has body: First, it's hard to say if 600 images is a sufficiently large dataset to train your model. It may be that the problem is harder and it requires more examples. The scores themselves don't say much. It can be that the examples are just confusing or they are too different from the training data set (again pointing to you-need-more-examples). You also don't show anything to suggest you are not over-fitting. So consider some of the following: Consider switch to softmax for the prediction layer (makes the scores add up to 1.) Compute precision and recall per class and per data set. Compare the numbers between training set and validation set. If you see a big difference you are probably over-fitting or you need more examples. Compute a confusion matrix. Once you identified potential problematic points (recall low for class '3' for example), look at the examples. It may be something really obvious.
has comment: http://stackoverflow.com/comment/86315292
answers question: http://stackoverflow.com/q/49651354

http://stackoverflow.com/q/49664978
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/86339844
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49665056
has answer: http://stackoverflow.com/a/49665056
tagged with: dataframe
tagged with: python
has body: I am facing one of the problem here. I have data set which is nested { "members": [ { "firstname": "John", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-1234", "mobile": "", }, { "firstname": "Jane", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-4321", "mobile": "916-555-7890", }, "teamname": "1", "team_size": "5", "team_status": "low" } and another one which is not nested { "members": [ { "firstname": "John", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-1234", "mobile": "", }, "teamname": "1", "team_size": "5", "team_status": "low" } I have handled the nested one through the code df2 = pd.DataFrame.from_dict(json_normalize(json_file2), orient='columns') print(df2) df3 = pd.concat([json_normalize(x) for x in df2['members'].values.tolist()], keys= df2.index) df3 = df2.drop('members', 1).join(df3.reset_index(level=1, drop=True)).reset_index(drop=True) I am getting the error saying "saying “TypeError: 'float' object is not subscriptable”" Can you please help me out with the issue. { "teams": [ { "members": [ { "firstname": "John", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-1234", "mobile": "", }, { "firstname": "Jane", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-4321", "mobile": "916-555-7890", }, "teamname": "1", "team_size": "5", "team_status": "low" }, { "members": [ { "firstname": "Mickey", "lastname": "Moose", "orgname": "Moosers", "phone": "916-555-0000", "mobile": "916-555-1111", }, "teamname": "2", "team_size": "5", "team_status": "low" ] } ] }
has comment: http://stackoverflow.com/comment/86340001
type: AnsweredQuestion
has title: Converting the Nested Json format/ file into Flat files using Pandas Dataframe

http://stackoverflow.com/comment/86237698
has text: What's `runfile` and where does it come from? Why would you _expect_ it to be defined?
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49615426

http://stackoverflow.com/a/49654626
has comment: http://stackoverflow.com/comment/86319178
has comment: http://stackoverflow.com/comment/86319725
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49653765
has body: You can define a class and override its __float__ class MyFloat: def __init__(self, num, upper=20, lower=10): self.num = num self.upper = upper self.lower = lower def __float__(self): if self.lower &lt;= self.num &lt;= self.upper: return float(self.num) else: return (self.upper - self.lower) / 2 Then while importing your data you can do &gt;&gt;&gt; data = [1,2,3,10,11,12,21,22,23] &gt;&gt;&gt; [float(MyFloat(d)) for d in data] &gt;&gt;&gt; [5.0, 5.0, 5.0, 10.0, 11.0, 12.0, 5.0, 5.0, 5.0]
has comment: http://stackoverflow.com/comment/86319961

http://stackoverflow.com/comment/86282601
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49637354
has text: A range does work - but you have to know ahead of time how many columns there are.
type: Comment

http://stackoverflow.com/comment/86528968
has text: I'm downvoting this because eval is naughty generally, and the fact that it appears to be JSON and could come from a remote source increases the security threat.
type: AnswerComment
comment on: http://stackoverflow.com/a/49756401
score: 1
type: Comment

http://stackoverflow.com/a/49667974
has body: you can add your SimpleRNN as first layer and after your first change your train data shape like this: trainX=trainX.reshape(trainX.shape[0],1,trainX.shape[1]) model = Sequential() model.add(SimpleRNN(4, input_shape=(trainX.shape[1:]))) model.add(Dense(output_dim=HIDDEN_LAYERS)) model.add(Activation("relu")) model.add(Dense(output_dim=4)) model.add(Activation("softmax")) ... or add a Reshape layer without reshaping trainX, like this: from keras.layers import Reshape model = Sequential() model.add(Dense(output_dim=HIDDEN_LAYERS, input_dim=trainX.shape[1])) model.add(Activation("relu")) model.add(Reshape((1,4))) model.add(SimpleRNN(4)) model.add(Dense(output_dim=4)) model.add(Activation("softmax")) ...
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/116124142
score: 1
has comment: http://stackoverflow.com/comment/86346431
upvote count: 1
answers question: http://stackoverflow.com/q/49667337

http://stackoverflow.com/comment/86392010
has text: Thanks, This was for a project.
score: 0
comment on: http://stackoverflow.com/a/49689869
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86407138
comment on: http://stackoverflow.com/a/49696972
has text: My apologies, I should have stated my question better. I want to remove the rows with zeros not the columns or perhaps replace the zeros with the mean of that particular column.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49726243
has answer: http://stackoverflow.com/a/76157856
linked to: http://stackoverflow.com/q/13385690
possible better answer: http://stackoverflow.com/a/74812593
tagged with: python
score: 4
has title: How to automate git push processes using python?
tagged with: git
accepted answer: http://stackoverflow.com/a/49726373
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36585496
tagged with: bash
has answer: http://stackoverflow.com/a/49726373
answer count: 3
has body: I'm trying to automate the git push processes using python. I've succeeded automating all except entering the username and password after the git push command. This is my code so far: import subprocess import sys add: str = sys.argv[1] commit: str = sys.argv[2] branch: str = sys.argv[3] def run_command(command: str): print(command) process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) print(str(process.args)) if command.startswith("git push"): output, error = process.communicate() else: output, error = process.communicate() try: output = bytes(output).decode() error = bytes(error).decode() if not output: print("output: " + output) print("error: " + error) except TypeError: print() def main(): global add global commit global branch if add == "" or add == " ": add = "." if branch == "": branch = "master" print("add: '" + add + "' commit: '" + commit + "' branch: '" + branch + "'") command = "git add " + add run_command(command) commit = commit.replace(" ", "''") command = 'git commit -m "' + commit + '"' run_command(command) command = "git push origin " + branch run_command(command) if __name__ == '__main__': main() Is there any way to send the information to the command?
downvote count: 0
has answer: http://stackoverflow.com/a/74812593
linked to: http://stackoverflow.com/q/1456269
has comment: http://stackoverflow.com/comment/86466483
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/q/49746822
tagged with: python
has comment: http://stackoverflow.com/comment/86507865
has body: Is this allowed syntax? for bit in binary_string: is_zero = bit == '0' ... Edit: My IDE Python in terminal is throwing syntax error. I found it here: https://github.com/johnmee/codility/blob/master/ex-1-1-binarygap.py#L33 edit: &gt;&gt;&gt; N = 1004 &gt;&gt;&gt; binary_string = str(bin(N))[2:] &gt;&gt;&gt; for bit in binary_string: ... is = bit == '0' File "&lt;stdin&gt;", line 2 is = bit == '0' ^ SyntaxError: invalid syntax
has comment: http://stackoverflow.com/comment/86507984
possible better answer: http://stackoverflow.com/a/49746968
downvote count: 2
has answer: http://stackoverflow.com/a/49746968
linked to: http://stackoverflow.com/q/13650293
has comment: http://stackoverflow.com/comment/86508043
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86508129
has title: Python: assignment operator and double-equals in the same line
has comment: http://stackoverflow.com/comment/86507946
has comment: http://stackoverflow.com/comment/86507848
accepted answer: http://stackoverflow.com/a/49746957
upvote count: 1
has comment: http://stackoverflow.com/comment/86507888
has comment: http://stackoverflow.com/comment/86508176
has comment: http://stackoverflow.com/comment/86507992
favorite count: 0
has answer: http://stackoverflow.com/a/49746957
score: -1
type: Question
has comment: http://stackoverflow.com/comment/86508122
answer count: 2

http://stackoverflow.com/q/49624208
tagged with: python
has comment: http://stackoverflow.com/comment/86256665
has comment: http://stackoverflow.com/comment/86260083
has body: I have the following function: ((sin(((x-8)**2+y**2)**0.5))/((((x-8)**2+y**2)**0.5)))+0.8*((sin(((x+8)**2+y**2)**0.5))/(((x+8)**2+y**2)**0.5)) I want to find the global maxima and minima of this function using brute force approach in Python. I have looked on scipy.optimize.brute but I am not sure on how to do the same for a function of 2 variables. y = np.linspace(-20,20,1000) x = np.linspace(-20,20,1000) def f(x,y): return (((sin(((x-8)**2+y**2)**0.5))/((((x-8)**2+y**2)**0.5)))+0.8*((sin(((x+8)**2+y**2)**0.5))/(((x+8)**2+y**2)**0.5))) rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25)) val = scipy.optimize.brute(f, rranges, finish=optimize.fmin) This is my code so far. It gives an error : Traceback (most recent call last): File "C:/Users/Aravind_Sampathkumar/Desktop/PY/Bruteforce.py", line 11, in &lt;module&gt; val = scipy.optimize.brute(f, rranges, finish=optimize.fmin) File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 2825, in brute Jout = vecfunc(*grid) File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 2755, in __call__ return self._vectorize_call(func=func, args=vargs) File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 2834, in _vectorize_call res = array(outputs, copy=False, subok=True, dtype=otypes[0]) ValueError: setting an array element with a sequence. Any help is appreciated
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49624953
has comment: http://stackoverflow.com/comment/86256714
has title: Python brute force for a function of 2 variables
upvote count: 2
has answer: http://stackoverflow.com/a/49624953
downvote count: 0
answer count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/86260605
favorite count: 0
has comment: http://stackoverflow.com/comment/86255394
type: Question
has comment: http://stackoverflow.com/comment/86255749

http://stackoverflow.com/comment/86473549
has text: @Kubuntuer82 I wasn't planning to write my own answer from the start. I thought that your answer would be alright if you got rid of the repeated string concatenation, but after you made the edit I realized that there were still significant improvements to make. I'm sorry I made you waste time improving it. (P.S. I didn't start from your algorithm. What I have posted here is the obvious way to implement it. I really didn't need to copy anything from you.)
comment on: http://stackoverflow.com/a/49709607
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49711153
has body: Aaron Swartz played an important role in shaping the internet during its earlier years. For those familiar with Aaron, you likely know he committed suicide after facing up to 35 years in prison for downloading a massive number of articles from jstor's archive, a digital library of academic journals and books. The script he used to download the articles was released and is pictured below. (Here's a link Aaron's documentary for those interested.) This is the code: import subprocess, urllib, random class NoBlocks(Exception): pass def getblocks(): r = urllib.urlopen("http://{?REDACTED?}/grab").read() if '&lt;html' in r.lower(): raise NoBlocks return r.split() import sys if len(sys.argv) &gt; 1: prefix = ['--socks5', sys.argv[1]] else: prefix = []#'-interface','eth0:1'] line = lambda x: ['curl'] + prefix + ['-H', "Cookie: TENACIOUS=" + str(random.random())[3:], '-o', 'pdfs/' + str(x) + '.pdf', "http://www.jstor.org/stable/pdfplus/" + str(x) + ".pdf?acceptTC=true"] while 1: blocks = getblocks() for block in blocks: print block subprocess.Popen(line(block)).wait() I guess this is a tribute of sorts. I have always been extremely affected by Aaron's story and his passing. He was a brilliant pioneer of the internet, founding creative commons, the web feed format RSS, and Reddit, all before taking his own life at 26 years old. I want to understand as much as I can about the event that led to the death of a man who did many great things for the internet and its growing community of users. Context Jstor is a large library of academic publications. When Aaron downloaded articles from their archive in 2010, JSTOR was freely available to MIT Students, but not freely available to the public. While we don't know exactly what Aaron wanted to do with the information, it's a safe bet he wanted to spread it to those without access. My Question I see he created a function Getblocks() that used the urllib module to access Jstor's digital archives, read the HTML of the web pages into a vari…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49711333
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/49719141
upvote count: 9
has answer: http://stackoverflow.com/a/49711333
has title: Dissecting the script Aaron Swartz used to download several thousand articles from Jstor's archive
favorite count: 0
score: 9
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49719141
downvote count: 0
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/86325045
type: AnswerComment
type: Comment
has text: @C.Wang You should not be doing this to begin with.
comment on: http://stackoverflow.com/a/49657919
score: 2

http://stackoverflow.com/comment/86320981
comment on: http://stackoverflow.com/q/49655861
type: Comment
has text: take a look at Flask http://flask.pocoo.org/
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86268638
score: 0
has text: It would seem that was the case after all, after removing the call to commit db changes which necessitated the app context in the first place, the error appears to be gone. Thank you for the help! Back to the design board for me I guess.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49627471

http://stackoverflow.com/a/49700785
has comment: http://stackoverflow.com/comment/86564886
downvote count: 0
answers question: http://stackoverflow.com/q/49694833
type: Answer
score: 3
has body: Is this a clean &amp; fresh new venv? If not, one thing to try is making a new venv, then first installing numpy and after that pandas. BTW: I'd suggest switching to Python 3.
upvote count: 3

http://stackoverflow.com/comment/86249339
has text: https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49616095
score: 1

http://stackoverflow.com/comment/86499006
comment on: http://stackoverflow.com/q/49742047
type: QuestionComment
has text: Also, welcome to SO. Take some time to review the help center for example here https://stackoverflow.com/help/how-to-ask
type: Comment
score: 0

http://stackoverflow.com/a/49662098
answers question: http://stackoverflow.com/q/49661771
has comment: http://stackoverflow.com/comment/86334591
has body: A stream of JSON documents, one-per-line, is a format also known as JSONL. This is distinct from "JSON" as such, which only permits one document to a file. You can easily convert your file into this format by running jq -c . &lt;in.json &gt;out.json. jq is a command-line tool for processing JSON and JSONL documents; the -c flag enables "compact" mode, which puts each one document on each line of output. Even easier, you can have that done in-line, having your Python code directly iterate over the output of jq: import subprocess with open("learning_data/{}/RC_{}".format(timeframe.split('-')[0], timeframe)) as f: p = subprocess.Popen(['jq', '-c', '.'], stdin=f, stdout=subprocess.PIPE) for line in p.stdout: content = json.loads(line) # ...process your line's content here.
has comment: http://stackoverflow.com/comment/86335048
has comment: http://stackoverflow.com/comment/86334437
has comment: http://stackoverflow.com/comment/86334841
accepted answer of: http://stackoverflow.com/q/49661771
type: Answer
has comment: http://stackoverflow.com/comment/86334748
downvote count: 0
has comment: http://stackoverflow.com/comment/86335094
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86335199

http://stackoverflow.com/a/49619471
has comment: http://stackoverflow.com/comment/86246241
has body: MyVar2 = 'value2' def fun1(): global MyVar2 print(MyVar2) fun1() The fix needs to be done in script 2 actually.
score: -1
has comment: http://stackoverflow.com/comment/86246139
answers question: http://stackoverflow.com/q/49619074
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86246099
downvote count: 1
has comment: http://stackoverflow.com/comment/86246167

http://stackoverflow.com/a/49625825
has comment: http://stackoverflow.com/comment/86283502
has comment: http://stackoverflow.com/comment/86258765
type: Answer
answers question: http://stackoverflow.com/q/49625774
has body: from __future__ imports are really compiler switches, and only apply to single units being compiled. You have two separate exec() calls, future statements do not carry across. Compilation flags are not stored in the global or local namespace you execute code in. So yes, you'd need to prepend the line for each call to exec(). You could also use the compile() function to first produce a code object, that you then pass to exec(); compile() lets you set flags instead of having to spell out the switches as from __future__ import lines: import __future__ flags = __future__.print_function.compiler_flag exec(compile("print('hello', 'world')", '', 'exec', flags=flags))
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86283517
downvote count: 0
has comment: http://stackoverflow.com/comment/86283359
has comment: http://stackoverflow.com/comment/86260005

http://stackoverflow.com/comment/86344422
type: Comment
comment on: http://stackoverflow.com/a/49647700
score: 0
type: AnswerComment
has text: @Rocky, please share your solution with the community. You can post an answer yourself, even accept it if there is a significant difference to the others. This helps other users.

http://stackoverflow.com/comment/86276390
type: Comment
type: QuestionComment
has text: I'd advise against using `root` for anything other than your local development machine. Always provision a user specifically for your application. That being said, I'm not sure the lower-case `y` is valid if you're using Flask-MySQL.
score: 0
comment on: http://stackoverflow.com/q/49634105

http://stackoverflow.com/comment/86302222
score: 0
has text: First create a virtualenv: https://conda.io/docs/user-guide/tasks/manage-environments.html#creating-an-environment-with-commands Then install `tensorflow` inside the virtualenv https://www.tensorflow.org/install/install_windows. Then configure Pycharm to use this virtualenv: https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html.html. The 2 first steps should be done in the command line (windows/linux)
type: QuestionComment
comment on: http://stackoverflow.com/q/49646211
type: Comment

http://stackoverflow.com/comment/86423848
has text: Is there a way to address the sort in the date column?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49702773

http://stackoverflow.com/q/49731259
tagged with: python
score: 17
tagged with: tweepy
favorite count: 0
type: Question
has title: tweepy get tweets between two dates
downvote count: 0
upvote count: 17
accepted answer: http://stackoverflow.com/a/49731413
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86477299
possible better answer: http://stackoverflow.com/a/61821356
has answer: http://stackoverflow.com/a/49731413
has answer: http://stackoverflow.com/a/73508797
has comment: http://stackoverflow.com/comment/86476645
answer count: 3
has answer: http://stackoverflow.com/a/61821356
has body: I have the following code in Python: import tweepy consumer_key = "..." consumer_secret = "..." access_token = "..." access_token_secret = "..." auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) start_date = datetime.datetime(2018, 1, 19, 12, 00, 00) end_date = datetime.datetime(2018, 1, 19, 13, 00, 00) api = tweepy.API(auth) for tweet in tweepy.Cursor(api.user_timeline, screen_name="@IBM", since=start_date, until=end_date).items(): print("ID TWEET: " + str(tweet.id)) Is there a way to get tweets between start_date and end_date, by modifying the cursor with tweepy? I have already tried to use the since= and until= parameters, but they have not worked. Thank you in advance.
linked to: http://stackoverflow.com/q/26205102

http://stackoverflow.com/comment/86231780
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49612437
has text: the most simple way of doing this is to have a dictionary at hand and comparing a given string with different string distance metrics also an idea would be `word2vec` also you could create a few regexs that match words
type: Comment

http://stackoverflow.com/a/49626374
answers question: http://stackoverflow.com/q/49626230
has comment: http://stackoverflow.com/comment/86290729
has comment: http://stackoverflow.com/comment/86296150
downvote count: 0
upvote count: 1
has body: Your OS administrates the read/write access on files. When you first get the writing access to the file outside your loop, you will never get it back inside your loop once it is taken by another process or thread. So setup the file object inside your loop. import sys while True : raw_input() with open('tmp.txt', 'ab') as f : f.write('this is a test\n') For file objects it is recommended to use a context manager (with-Statement). It will automatically open and close the object.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86290616
has comment: http://stackoverflow.com/comment/86290762
accepted answer of: http://stackoverflow.com/q/49626230
score: 1
type: Answer

http://stackoverflow.com/a/70242846
has body: Use PythonVirtualenvOperator. You need to provide a python function to be run and a requirements.txt of the virtual environment.
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49738173
has comment: http://stackoverflow.com/comment/124171288

http://stackoverflow.com/q/49659348
has comment: http://stackoverflow.com/comment/86328558
tagged with: pandas
score: 0
linked to: http://stackoverflow.com/q/31617845
has comment: http://stackoverflow.com/comment/86329749
has body: I have two pandas series as shown below, df1 = index value 2014-05-23 00:00:00 NaN 2014-05-23 01:00:00 NaN 2014-05-23 02:00:00 0.00 2014-05-23 03:00:00 NaN ... 2018-01-01 05:00:00 0.59 2014-01-01 06:00:00 0.43 2014-01-01 07:00:00 1.00 and df2 df2 = index value 2014-05-23 00:00:00 9.9 2014-05-23 01:00:00 23 2014-05-23 02:00:00 4.3 2014-05-23 03:00:00 10.6 ... 2018-01-01 05:00:00 8.3 2014-01-01 06:00:00 0.3 2014-01-01 07:00:00 0.0 and relationship between df1 and df2 is one by one , I would like to plot the figure with x value (df1) and y value (df2) but only choose the value in df1 bigger than 0 and smaller than 1 (directly ignore the NaN). I just know how to find the value with one condition df.loc[lambda df: df != 1] or df.loc[lambda df: df != 0] but it doesn't work when I write df.loc[lambda df: df != 1 and != 0] or df.loc[lambda df: 1&gt; df &gt; 0] and I don't know how to match the values found in df1 to df2, in order to plot it. Anyone have ideas? Thanks in advance !
has comment: http://stackoverflow.com/comment/86328371
has comment: http://stackoverflow.com/comment/86329842
duplicate of: http://stackoverflow.com/q/13611065
has comment: http://stackoverflow.com/comment/86329866
duplicate of: http://stackoverflow.com/q/31617845
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/86328638
has title: Selecting pandas Series Based On Conditions
tagged with: python
tagged with: sorting
type: UnansweredQuestion

http://stackoverflow.com/comment/86381093
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49683692
has text: Do you actually want the string? Or are you just trying to get it to print right?

http://stackoverflow.com/q/49708476
linked to: http://stackoverflow.com/q/49638507
upvote count: 3
possible better answer: http://stackoverflow.com/a/49709299
downvote count: 0
has comment: http://stackoverflow.com/comment/86430525
has answer: http://stackoverflow.com/a/49709299
favorite count: 0
has answer: http://stackoverflow.com/a/49708564
tagged with: optimization
type: AnsweredQuestion
score: 3
tagged with: performance
has body: I have a string which is a combination of "S"s and "C"s. There is at least one occurrence of each. I want to find the last occurrence of "CS" and change it to "SC". I have two methods (so far): P = P[::-1].replace("SC", "CS", 1)[::-1] and P = P[:P.rfind("CS")] + "SC" + P[P.rfind("CS") + 2:] Which line is likely to be faster? Also, is there a quicker way to achieve what I'm doing?
has title: Which method is faster for replacing the last occurrence of a substring in a string?
tagged with: python
has comment: http://stackoverflow.com/comment/86430394
accepted answer: http://stackoverflow.com/a/49708564
type: Question
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/comment/86235320
has text: @MooingRawr. While you are at it: https://meta.stackoverflow.com/a/256331/2988730, https://meta.stackexchange.com/a/98026/346663
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49614329

http://stackoverflow.com/a/49716712
accepted answer of: http://stackoverflow.com/q/49716687
has body: You can safely share .py modules between Python 2 and Python 3, provided the code is compatible with both versions of the language. That's because Python 3 uses a different scheme to cache bytecode, where the files are minor-version specific; you'll have separate .pyc files for your Python 2 and Python 3 interpreters. See this Python programming FAQ entry: When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a .pyc file containing the compiled code should be created in a __pycache__ subdirectory of the directory containing the .py file. The .pyc file will have a filename that starts with the same name as the .py file, and ends with .pyc, with a middle component that depends on the particular python binary that created it. (See PEP 3147 for details). Even if that wasn't the case, the two interpreters could still run side by side because .pyc files are read into memory in one step and contain version information in them too and they'd just be replaced each time either interpreter imports a module with an incorrect cache file version. You can use the pickle module to serialise and deserialise across Python versions, provided you pick a compatible protocol version and stick to a known codec for your Python 2 string data. See Unpickling a python 2 object with python 3 for details on the latter.
type: Answer
has comment: http://stackoverflow.com/comment/86446771
has comment: http://stackoverflow.com/comment/86446536
answers question: http://stackoverflow.com/q/49716687
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86446670

http://stackoverflow.com/comment/86209725
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49600284
has text: Replacing a well-defined Unicode character with random 8-bit characters whose semantics you apparently don't understand is not an improvement.
type: AnswerComment

http://stackoverflow.com/q/49729087
answer count: 2
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49729263
has comment: http://stackoverflow.com/comment/86471971
favorite count: 0
has answer: http://stackoverflow.com/a/49729263
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49729602
type: Question
tagged with: python
has title: Multiple counter from previous lists
has comment: http://stackoverflow.com/comment/86471944
has comment: http://stackoverflow.com/comment/86471848
possible better answer: http://stackoverflow.com/a/49729602
tagged with: list
has body: Here I have two piece of codes that I am trying to merge them together, In the first I have a list of letter from which two letters are being chosen randomly and added to the former list: import random def randMerge(l:list, count:int) -&gt; list: return l + [random.sample(l,k=count)] num = 2 aList = ['A','B','C','D'] newList = aList[:] for _ in range(2): print(newList) newList = randMerge(newList,num) print(newList) This gives me the following output: ['A', 'B', 'C', 'D'] ['A', 'B', 'C', 'D', ['A', 'C']] ['A', 'B', 'C', 'D', ['A', 'C'], ['D', ['A', 'C']]] Now I want to count each letters in each lists, so I did: import collections l1 = newList def flatten(d): return [i for b in [[c] if not isinstance(c, list) else flatten(c) for c in d] for i in b] for _ in range(2): new_counts = collections.Counter(flatten(l1)) print(new_counts) Which I get: Counter({'A': 3, 'C': 3, 'D': 2, 'B': 1}) Which shows the number of elements only in the last list. I wonder how one can count the letter for all lists for example to get something like: Counter({'A': 1, 'C': 1, 'D': 1, 'B': 1}) Counter({'A': 2, 'C': 2, 'D': 1, 'B': 1}) and etc.
type: AnsweredQuestion

http://stackoverflow.com/q/49727290
has answer: http://stackoverflow.com/a/49727826
type: AnsweredQuestion
tagged with: pyinstaller
tagged with: windows
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49832196
score: -1
has comment: http://stackoverflow.com/comment/86469319
type: Question
answer count: 2
has title: Qt platform plugin fails to load for other computers
upvote count: 0
tagged with: python
has body: I have created an .exe from a python app with pyinstaller in Windows. This app opens some matplotlib windows. At first, at the opening of the matplotlib windows, it throwed me the error "This application failed to start because it could not load the Qt platform plugin 'Windows'". I did some digging around and found out that I had to set an enviromental variable 'QT_PLUGIN_PATH' to the value 'C:\Users\user\Miniconda2\Library\plugins'. It worked right but on my PC only. When I open the .exe in other PCs and open the matplotlib windows, it shows me the same error. Is there a way to make it work for every computer?
downvote count: 1
possible better answer: http://stackoverflow.com/a/49727826
has answer: http://stackoverflow.com/a/49832196
favorite count: 0
tagged with: qt

http://stackoverflow.com/q/49689214
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86395903
linked to: http://stackoverflow.com/q/38753737
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86393100
tagged with: python
has comment: http://stackoverflow.com/comment/86391856
has comment: http://stackoverflow.com/comment/86392881
has title: why is an integer is being saved(shown) as binary in database, other values aren't- sqlalchemy
has body: I am reading a csv and saving(trying) certain columns into the my database. I did that and wanted to double check a row in my database, to see if everything was ok. However one of my columns was saved as b'd\x00\x00\x00\x00\x00\x00\x00'. I was unsure what that meant and googled and found that it's binary(is that finding correct?) This really confused me. The value in that specific column and row in the csv file is 100 and in my model that specific column was indicated as an Integer. edit I'm using Flask with sqlalchemy. Here's the relavant code: my model class DesiredClass(db.model): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) speed = db.Column(db.Float, nullable=False) # in m/s direction = db.Column(db.Float, nullable=False) # in degrees different_value = db.Column(db.Integer, nullable=False) # in percent example row in csv with their respective columns speed; direction; different_value 32.2; 52.4; 100 reading csv and saving to db df = pd.read_csv(filename, sep=';') for i in df.index: m = DesiredClass( speed=df.loc[i, 'SPEED'], direction=df.loc[i, 'DIRECTION'], different_value=df.loc[i, 'DIFFERENT_VALUE'], ) db.session.add(m) # add to db db.session.commit() # perform them all I then checked on my notebook to see what had been saved. And saw b'd\x00\x00\x00\x00\x00\x00\x00' in the column for different_value. All the other one's were saved in the correct format. Therefore, 1) I'm confused why it shows that way, and that didn't happen to the other columns. 2) Where to even start? I doubled checked the csv and looked at that specific row that I was looking at to see if there was something weird. However it just has the value 100. Thanks in advance. Update I'm using flask_sqlalchemy and sqlite. To check I used the jupyter notebook, ran what I had and then did the following there result = DesiredClass.query.with_entities(DesiredClass.id, DesiredClass.speed, DesiredClass.direction, DesiredClass.dif…
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/86390567
answer count: 0
type: UnansweredQuestion
tagged with: sqlite
has comment: http://stackoverflow.com/comment/86390324
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86406852
comment on: http://stackoverflow.com/q/49696980
has text: Look up `.split(" ")` ( you can omit the " ") to split up your input and translate each seperate word. `List comprehensions` might get handy as well - look up that as well. If they are too complicated, experiment with `for someWord in user_input.split():\n print(someWord)` ..
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49699160
has comment: http://stackoverflow.com/comment/86447525
score: 0
has comment: http://stackoverflow.com/comment/86412400
answers question: http://stackoverflow.com/q/49699061
has comment: http://stackoverflow.com/comment/86419791
has body: If you want to print all the child elements, you can use a cssSelector: stocks.find_elements_by_css_selector("*")
has comment: http://stackoverflow.com/comment/86446605
type: Answer

http://stackoverflow.com/comment/86231769
type: QuestionComment
has text: Define "quick". What have you tried that isn't quick enough?
score: 0
comment on: http://stackoverflow.com/q/49612553
type: Comment

http://stackoverflow.com/a/49707475
has comment: http://stackoverflow.com/comment/86428234
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86428391
has body: It sounds like a better data structure for you to use would be collections.Counter (which is in the standard library): import collections counts = collections.Counter(mylist) counts[0] = 1 mylist = list(counts.elements())
answers question: http://stackoverflow.com/q/49707401
has comment: http://stackoverflow.com/comment/86428216
has comment: http://stackoverflow.com/comment/86428230
downvote count: 0
has comment: http://stackoverflow.com/comment/86428255
has comment: http://stackoverflow.com/comment/86428342

http://stackoverflow.com/comment/86544442
comment on: http://stackoverflow.com/q/49738007
score: 0
has text: See also:https://stackoverflow.com/questions/6146963/when-is-del-useful-in-python (or in a nutshell: using del all over the place really feels like a code smell ... are you sure you can't just pop the item and let GC handle it?)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86416492
type: QuestionComment
score: 0
has text: can your add a new column with your hash value and do filter by it?
comment on: http://stackoverflow.com/q/49701383
type: Comment

http://stackoverflow.com/comment/119126437
type: Comment
comment on: http://stackoverflow.com/q/49725273
type: QuestionComment
score: 0
has text: Does this answer your question? [How to do a conditional count after groupby on a Pandas Dataframe?](https://stackoverflow.com/questions/45752601/how-to-do-a-conditional-count-after-groupby-on-a-pandas-dataframe)

http://stackoverflow.com/q/49749959
has body: I am running Django 2.0 app with uWSGI 2.0.17 and python 3.4 on an openSUSE Leap 42.3 x86-64 server and it's working fine the problem is when trying to send http request using python requests librarys uWSGI segmentation fault occures here is the log from uwsgi 2018-04-10 06:46:15,136 | DEBUG | Starting new HTTPS connection (1): www.googleapis.com !!! uWSGI process 30352 got Segmentation Fault !!! *** backtrace of 30352 *** /usr/bin/uwsgi(uwsgi_backtrace+0x2e) [0x46b92e] /usr/bin/uwsgi(uwsgi_segfault+0x21) [0x46bcc1] /lib64/libc.so.6(+0x34940) [0x7fb169878940] /home/pw/venv/lib64/python3.4/lib-dynload/_ssl.cpython-34m.so(+0xb2aa) [0x7fb1661542aa] /home/pw/venv/lib64/python3.4/lib-dynload/_ssl.cpython-34m.so(+0xcd0f) [0x7fb166155d0f] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x413c) [0x7fb169f1673c] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3fe5) [0x7fb169f165e5] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x3a36) [0x7fb169f16036] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x619) [0x7fb169f1c3b9] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalFrameEx+0x2364) [0x7fb169f14964] /usr/lib64/libpython3.4m.so.1.0(PyEval_EvalCodeEx+0x2b0) [0x7fb169f1c050] /usr/lib64/libpython3.4m.so.1.0(+0xd7854) [0x7fb169ef7854] /usr/lib64/libpython3.4m.so.1.0(PyObject_Call+0x4a) [0x7fb169ef2eca] /usr/lib64/libpython3.4m.s…
has comment: http://stackoverflow.com/comment/86515485
has title: uWSGI segmentation fault when using Django and python requests
has comment: http://stackoverflow.com/comment/86515212
linked to: http://stackoverflow.com/q/53498240
tagged with: uwsgi
favorite count: 0
type: Question
upvote count: 2
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86514693
tagged with: django
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/86514903
has comment: http://stackoverflow.com/comment/104120873

http://stackoverflow.com/q/49624631
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49625149
tagged with: python
has comment: http://stackoverflow.com/comment/86256939
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86257647
tagged with: tkinter
has title: How to change the function of 'x' button of a tkinter window ( one in the title bar )?
answer count: 1
upvote count: 1
has body: A tkinter window has a title bar with a button 'x' that closes the window when pressed. Is there any way possible, that does not involve removal of geomertry (such as use of overideredirect()) to change the function related to button 'x'? Following is a simple window: from tkinter import* root=Tk() def en(event): l=Label(root,text="name") l.grid(row=0) e=Entry(root) e.grid(row=0,column=1) frame=Frame(root,width=300,height=250) frame.bind("&lt;Button-1&gt;",en) frame.grid() root.mainloop()
accepted answer: http://stackoverflow.com/a/49625149
downvote count: 1

http://stackoverflow.com/q/49727381
type: UnansweredQuestion
tagged with: wsgi
tagged with: django
has comment: http://stackoverflow.com/comment/86474458
has comment: http://stackoverflow.com/comment/86469298
tagged with: python
has comment: http://stackoverflow.com/comment/86474506
has comment: http://stackoverflow.com/comment/86470040
downvote count: 0
has comment: http://stackoverflow.com/comment/86468735
answer count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/19754834
has title: Cant get environ variables on settings file after set them on WSGI
has comment: http://stackoverflow.com/comment/86469383
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86469859
has comment: http://stackoverflow.com/comment/86470019
has body: I use django 1.11 and this is my wsgi.py file # -*- coding: utf-8 -*- import os import sys from django.core.wsgi import get_wsgi_application PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)))) if PATH not in sys.path: sys.path.append(PATH) os.environ['DJANGO_SETTINGS_MODULE'] = 'cms.settings.qa' ENV_VARIABLES_TO_PASS = ['VAR_1', 'VAR_2'] _application = get_wsgi_application() def application(environ, start_response): # pass the WSGI environment variables on thzrough to os.environ for var in ENV_VARIABLES_TO_PASS: os.environ[var] = environ.get(var, '1') return _application(environ, start_response) and when i try to get the env on settings file its allways return None. os.getenv('VAR_1') = None &amp; os.getenv('VAR_2') = None why is that happend? thanks a lot.

http://stackoverflow.com/comment/86365536
comment on: http://stackoverflow.com/q/49676876
type: QuestionComment
has text: @PeterWood Yes I usually use either of those but I'm affraid it's checking for the file handle only and not the actual content. I'm not sure open performs better if you don't try a `read` too though...
type: Comment
score: 0

http://stackoverflow.com/comment/86366003
type: Comment
comment on: http://stackoverflow.com/a/49677156
score: 0
type: AnswerComment
has text: didn't knew greedy `*` gives characters back as needed.

http://stackoverflow.com/comment/86348302
has text: @nerak99 I ask you to review basic OOP concepts, otherwise we will be speaking in different *languages*.
comment on: http://stackoverflow.com/a/49668757
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49777902
answers question: http://stackoverflow.com/q/49752809
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49752809
score: 1
upvote count: 1
type: AcceptedAnswer
has body: This works for me (Python 3.6 and bokeh 0.12.13): import pandas as pd from bokeh.layouts import row from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import Button, DataTable, TableColumn from bokeh.io import curdoc from io import StringIO import base64 dict1 = { 'x':[0]*6, 'y':[1,1,1,2,2,2] } table_source = ColumnDataSource(data=dict1) columns = [ TableColumn(field="x", title="x"), TableColumn(field="y", title="y") ] data_table = DataTable( source=table_source, columns=columns, width=800, editable=True ) file_source = ColumnDataSource({'file_contents':[], 'file_name':[]}) def file_callback(attr, old, new): print('filename:', file_source.data['file_name']) raw_contents = file_source.data['file_contents'][0] # remove the prefix that JS adds prefix, b64_contents = raw_contents.split(",", 1) file_contents = base64.b64decode(b64_contents) # print("B64 decoded: file_contents : %s" % file_contents) # Remove byte order mask and decode to str file_contents = file_contents.decode("utf-8-sig") # print("Decoded file_contents : %s" % file_contents) file_io = StringIO(file_contents) # Separator might need to be adjusted df = pd.read_csv(file_io, sep=";") table_source.data = table_source.from_df(df) print("Table source data: %s" % table_source.data) file_source.on_change('data', file_callback) button = Button(label="Upload", button_type="success") button.callback = CustomJS(args=dict(file_source=file_source), code = """ function read_file(filename) { var reader = new FileReader(); reader.onload = load_handler; reader.onerror = error_handler; // readAsDataURL represents the file's data as a base64 encoded string reader.readAsDataURL(filename); } function load_handler(event) { var b64string = event.target.result; file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]}; file_source.trigger("change"); } function error_handler(evt) { if(evt.target.error.name == "NotReadableError") { alert("Can't read file!"); } } var input = do…
type: Answer
has comment: http://stackoverflow.com/comment/86592297

http://stackoverflow.com/a/61979699
downvote count: 0
has body: Lets say, we want to download FINALFOLDER from the storage path: gs://TEST_BUCKET_NAME/FOLDER1/FOLDER2/FINALFOLDER After downloading, the final path will look like: D:\\my_blob_data\FINALFOLDER from os import makedirs from os.path import join, isdir, isfile, basename from google.cloud import storage # if your environment was authenticated, the default config will be picked up storage_client = storage.Client() # comment this line if you want to use service account # uncomment the line below if you have a service account json # storage_client = storage.Client.from_service_account_json('creds/sa.json') bucket_name = 'TEST_BUCKET_NAME' prefix = 'FOLDER2' dst_path = 'D:\\my_blob_data' if isdir(dstPath) == False: makedirs(dstPath) bucket = storage_client.bucket(bucket_name=bucket_name) blobs = bucket.list_blobs(prefix=prefix) # Get list of files for blob in blobs: blob_name = blob.name dst_file_name = blob_name.replace('FOLDER1/FOLDER2', dst_path) #.replace('FOLDER1/FOLDER2', 'D:\\my_blob_data') # extract the final directory and create it in the destination path if it does not exist dst_dir = dst_file_name.replace('/' + basename(dst_file_name), '') if isdir(dst_dir) == False: makedirs(dst_dir) # download the blob object blob.download_to_filename(dst_file_name)
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49748910
score: 2
has comment: http://stackoverflow.com/comment/131273045

http://stackoverflow.com/comment/86493708
has text: Actually it is `[3:-1]` because of the leading `\n`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49739594
type: Comment

http://stackoverflow.com/comment/86435082
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49710728
type: Comment
has text: that doesn't seem to work... i get only the results that match `charlimit` as before

keras
tags question: http://stackoverflow.com/q/49644124
tags question: http://stackoverflow.com/q/49664069
tags question: http://stackoverflow.com/q/49743142
tags question: http://stackoverflow.com/q/49708945
tags question: http://stackoverflow.com/q/49744112
tags question: http://stackoverflow.com/q/49665757
tags question: http://stackoverflow.com/q/49751619
tags question: http://stackoverflow.com/q/49750367
tags question: http://stackoverflow.com/q/49716558
tags question: http://stackoverflow.com/q/49688134
tags question: http://stackoverflow.com/q/49609247
tags question: http://stackoverflow.com/q/49611307
tags question: http://stackoverflow.com/q/49630178
tags question: http://stackoverflow.com/q/49678302
tags question: http://stackoverflow.com/q/49705084
tags question: http://stackoverflow.com/q/49696981
tags question: http://stackoverflow.com/q/49702026
tags question: http://stackoverflow.com/q/49603498
tags question: http://stackoverflow.com/q/49623436
tags question: http://stackoverflow.com/q/49717115
tags question: http://stackoverflow.com/q/49738758
tags question: http://stackoverflow.com/q/49603311
tags question: http://stackoverflow.com/q/49755316
tags question: http://stackoverflow.com/q/49633321
tags question: http://stackoverflow.com/q/49755826
tags question: http://stackoverflow.com/q/49757285
tags question: http://stackoverflow.com/q/49645151
tags question: http://stackoverflow.com/q/49605666
tags question: http://stackoverflow.com/q/49642607
tags question: http://stackoverflow.com/q/49643371
tags question: http://stackoverflow.com/q/49699242
tags question: http://stackoverflow.com/q/49704545
tags question: http://stackoverflow.com/q/49611510
tags question: http://stackoverflow.com/q/49628739
tags question: http://stackoverflow.com/q/49731355
tags question: http://stackoverflow.com/q/49700247
tags question: http://stackoverflow.com/q/49667863
tags question: http://stackoverflow.com/q/49615991
tags question: http://stackoverflow.com/q/49646304
tags question: http://stackoverflow.com/q/49719429
tags question: http://stackoverflow.com/q/49746321
tags question: http://stackoverflow.com/q/49633382
tags question: http://stackoverflow.com/q/49679602
tags question: http://stackoverflow.com/q/49684508
tags question: http://stackoverflow.com/q/49657455
tags question: http://stackoverflow.com/q/49683083
tags question: http://stackoverflow.com/q/49755610
tags question: http://stackoverflow.com/q/49729522
tags question: http://stackoverflow.com/q/49630609
tags question: http://stackoverflow.com/q/49654739
tags question: http://stackoverflow.com/q/49696933
tags question: http://stackoverflow.com/q/49743487
tags question: http://stackoverflow.com/q/49610336
tags question: http://stackoverflow.com/q/49757054
tags question: http://stackoverflow.com/q/49672249
tags question: http://stackoverflow.com/q/49705406
tags question: http://stackoverflow.com/q/49746668
tags question: http://stackoverflow.com/q/49624167
tags question: http://stackoverflow.com/q/49670832
tags question: http://stackoverflow.com/q/49667337
tags question: http://stackoverflow.com/q/49652568
tags question: http://stackoverflow.com/q/49615401
tags question: http://stackoverflow.com/q/49630143
tags question: http://stackoverflow.com/q/49721691
tags question: http://stackoverflow.com/q/49658423
tags question: http://stackoverflow.com/q/49684379
tags question: http://stackoverflow.com/q/49607704
tags question: http://stackoverflow.com/q/49721810
tags question: http://stackoverflow.com/q/49661612
tags question: http://stackoverflow.com/q/49726971
tag name: keras
tags question: http://stackoverflow.com/q/49662869
tags question: http://stackoverflow.com/q/49638685
tags question: http://stackoverflow.com/q/49631404
tags question: http://stackoverflow.com/q/49690066
tags question: http://stackoverflow.com/q/49712244
tags question: http://stackoverflow.com/q/49661708
type: Tag
tags question: http://stackoverflow.com/q/49672457
tags question: http://stackoverflow.com/q/49739356

http://stackoverflow.com/a/49711071
answers question: http://stackoverflow.com/q/49708525
has body: You are missing ? before currPage, it should look like that: https://www.julian-fashion.com/en-US/men/shoes/sneakers?currPage={}.? indicates a start of the query string. Now your code will work. You also can omit page 0, because this site starts pagination from 1 and providing 0 gives 404 Page not found. Besides that, you don't need while True because you want to execute this block of code only once. For loop takes care of changing pages and it is enough. There is a bug here: for s in keywords: if s not in link.a["href"]: found = False break you break from the loop if a keyword is not in link.a['href']. Notice that if the first keyword from your list is not there, it doesn't mean one of the next ones won't. Your code after a few fixes: import requests from bs4 import BeautifulSoup headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" } keywords = ["nike", "air"] base_url = "https://www.julian-fashion.com" for page in range(1, 11): print(f'[PAGE NR {page}]') url = "https://www.julian-fashion.com/en-US/men/shoes/sneakers?currPage={}".format(page) r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") all_links = soup.find_all("li", attrs={"class": "product in-stock"}) for link in all_links: if any(key in link.a["href"] for key in keywords): print("Product found.") print(base_url + link.a["href"]) print(link.img["title"]) print(link.div.div.ul.text) Here is my version of the code, I used .select() instead of .find_all(). This is better, because if the creators of the page will add some new classes to the elements you search for, .select() that uses CSS selectors will still be able to target these elements. I also used urljoin to create absolute links, see here why. from bs4 import BeautifulSoup import requests from urllib.parse import urljoin keywords = ["nike", "air"] base_url = "https://www.julian-fashion.com" for page in range(1, 11): print(f'[PAGE NR {page}…
type: Answer
has comment: http://stackoverflow.com/comment/86491146
has comment: http://stackoverflow.com/comment/86516024
has comment: http://stackoverflow.com/comment/86437124
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86437093
accepted answer of: http://stackoverflow.com/q/49708525
has comment: http://stackoverflow.com/comment/86491721
has comment: http://stackoverflow.com/comment/86518813
has comment: http://stackoverflow.com/comment/86477686

http://stackoverflow.com/a/63617002
downvote count: 1
has body: Superset can’t query external data API’s directly. Superset has to work with a supported database or data engine (https://superset.incubator.apache.org/installation.html#database-dependencies). This means that you need to find a way to fetch data out of the API and store it in a supported database / data engine. Some options: Build a little Python pipeline that will query the data API, flatten the data to something tabular / relational, and upload that data to a supported data source - https://superset.incubator.apache.org/installation.html#database-dependencies - and set up Superset so it can talk to that database / data engine. For more robust solutions, you may want to work with an devops / infrastructure to stand up a workflow scheduler like Apache Airflow (https://airflow.apache.org/) to regularly ping this API and store it in a database of some kind that Superset can talk to. If you want to regularly query data from a popular 3rd party API, I also recommend checking out Meltano and learning more about Singer taps. These will handle some of the heavy lifting of fetching data from an API regularly and storing it in a database like Postgres. The good news is that there's a Singer tap for Google Analytics - https://github.com/singer-io/tap-google-analytics Either way, Superset is just a thin layer above your database / data engine. So there’s no way around the reality that you need to find a way to extract data out of an API and store it in a compatible data source.
score: 10
answers question: http://stackoverflow.com/q/49612340
upvote count: 11
type: Answer

http://stackoverflow.com/q/49667532
favorite count: 0
has comment: http://stackoverflow.com/comment/86345017
tagged with: logic
possible better answer: http://stackoverflow.com/a/49667679
has body: I have a CSV file like: item1,item2 A,B B,C C,D E,F I want to compare this two column and find the similar content from the two columns item1 and item2. The output should be like this: item B C I have tried this code with open('output/id.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) for line in csvreader: if (line[0] == line[1]): print line else: print("not match") I am new to programming. I don't know what the logic should be and how to solve this problem. please help.
has answer: http://stackoverflow.com/a/49667679
type: Question
has comment: http://stackoverflow.com/comment/86345313
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49667736
has comment: http://stackoverflow.com/comment/86345077
tagged with: python
has comment: http://stackoverflow.com/comment/86345610
has title: Compare two column from CSV file using python
has comment: http://stackoverflow.com/comment/86345548
accepted answer: http://stackoverflow.com/a/49667736
type: AnsweredQuestion
score: 0
answer count: 3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49667677

http://stackoverflow.com/a/49655513
has body: This doesn't really fit into the for/else paradigm, because you don't want to break the outer loop. So just use a variable to track whether something was done, as in your original code. Instead of the second loop, use a single expression that finds the first matching object. See Python: Find in list for ways to do this. didSomething = false for key in keys: found = next((obj for obj in objects if &lt;obj fits to key&gt;), None) if found: doSomething(found, key) didSomething = true if not didSomething: doSomethingDifferent()
accepted answer of: http://stackoverflow.com/q/49655375
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86320018
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/86320828
answers question: http://stackoverflow.com/q/49655375
has comment: http://stackoverflow.com/comment/86324582

http://stackoverflow.com/comment/86530724
type: QuestionComment
comment on: http://stackoverflow.com/q/49757833
score: 0
has text: And what is your question exactly?
type: Comment

http://stackoverflow.com/comment/86241482
score: 0
type: Comment
type: QuestionComment
has text: Have you looked at this? https://python-docx.readthedocs.io/en/latest/
comment on: http://stackoverflow.com/q/49617178

http://stackoverflow.com/a/49692395
score: 0
answers question: http://stackoverflow.com/q/49691983
type: Answer
has body: My solution would be to first read the csv in as a normal file, filter that file line by line and then use io.StringIO to read the "edited csv" in as dataframe. Caution: this will not be suitable for big files. For example: import io import pandas as pd new_csv = [] with open('csv.csv') as f: for line in f: if len(line.split(',')) &gt;= 4: new_csv.append(line) file_io = io.StringIO('\n'.join(new_csv)) df = pd.read_csv(file_io)

http://stackoverflow.com/a/68593137
answers question: http://stackoverflow.com/q/49735127
score: 0
has body: Oversampling can be easily achieved with following code: resampled_ds = tf.data.experimental.sample_from_datasets([pos_ds, neg_ds], weights=[0.7, 0.3]) Tensorflow has a good guide on dealing with unbalanced data you can find more ideas here: https://www.tensorflow.org/tutorials/structured_data/imbalanced_data#oversampling
type: Answer

http://stackoverflow.com/comment/86318236
comment on: http://stackoverflow.com/q/49654597
type: QuestionComment
type: Comment
has text: Guys this is obviously a player of CodeGolf... Look how short and messy it iss!
score: 1

http://stackoverflow.com/comment/86331840
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49660507
has text: can u give me another advice on how to set this up its the mose important thing left to be dont in my project.

http://stackoverflow.com/comment/86476430
type: AnswerComment
score: 0
has text: If you're using Python 2, this is expected as it does not rely on UTF-8 by default.
type: Comment
comment on: http://stackoverflow.com/a/49729871

http://stackoverflow.com/q/49615833
answer count: 2
has comment: http://stackoverflow.com/comment/86238625
upvote count: 2
has body: How can I create a tuple using a for in loop in python? I tried running the following: &gt;&gt;&gt; x = (i for i in range(15)) &gt;&gt;&gt; x &lt;generator object &lt;genexpr&gt; at 0x00000198CAC95A40&gt; But this gives a generator object instead of a tuple. Any ideas on how to get this? Not just needed to get the sequence of ints from 0 to 14 but other operations as well.
has comment: http://stackoverflow.com/comment/86238533
downvote count: 0
linked to: http://stackoverflow.com/q/16940293
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49615871
has answer: http://stackoverflow.com/a/49615871
has title: Creating tuples using for..in loops in python
duplicate of: http://stackoverflow.com/q/16940293
accepted answer: http://stackoverflow.com/a/49615846
tagged with: python
has answer: http://stackoverflow.com/a/49615846
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49663106
score: 0
answer count: 2
tagged with: pandas
tagged with: string
has body: I have a dataframe of which one column ('entity) contains various names of countries and non-state entities. I need to clean the column because the string values (provided by manual data-entry) are all lower-case (china instead of China). I can't just perform the .title() operation on the column since there are string values for which I want nothing to done (e.g., al Something should not be turned into AL Something). I'm have trouble creating a function to help me with this problem and could use some guidance from the community. In the past I've used dictionaries to help map/replace incorrect strings with correct strings, and I can still revert to that way of doing things, but I thought creating this function might be more straightforward and efficient and plus I wanted to challenge myself. But no changes occurs to the entity column when I execute the function. Thanks in advance! myString = ['al Group1', 'al Group2'] entities = df['entity'] def title_fix(entities): new_titles = [] for entity in entities: if entity in myString: new_titles.append(myString) else: new_title.append(entity.title()) return new_title title_fix(df)
type: Question
has answer: http://stackoverflow.com/a/49663815
tagged with: python
accepted answer: http://stackoverflow.com/a/49663738
has title: How to conditionally modify string values in dataframe column - Python/Pandas
possible better answer: http://stackoverflow.com/a/49663815
has answer: http://stackoverflow.com/a/49663738
type: AnsweredQuestion

http://stackoverflow.com/comment/86506718
comment on: http://stackoverflow.com/a/49745894
has text: Is there a way to accommodate for that problem too, in case the art doesn't have the same width on all lines?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49752457
score: 5
answers question: http://stackoverflow.com/q/49752255
downvote count: 0
has comment: http://stackoverflow.com/comment/86521046
has comment: http://stackoverflow.com/comment/86524510
has body: Check your Message. There are following limitations on deleting messages by bots: A message can only be deleted if it was sent less than 48 hours ago. Bots can delete outgoing messages in groups and supergroups. Bots granted can_post_messages permissions can delete outgoing messages in channels. If the bot is an administrator of a group, it can delete any message there. If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. Returns True on success.
upvote count: 5
type: Answer

http://stackoverflow.com/q/49652950
accepted answer: http://stackoverflow.com/a/49653409
answer count: 4
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-3.x
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49653309
downvote count: 0
has title: Adding elements to list based on condition of previous elements
has answer: http://stackoverflow.com/a/49653314
has answer: http://stackoverflow.com/a/49653409
favorite count: 0
has answer: http://stackoverflow.com/a/49653704
possible better answer: http://stackoverflow.com/a/49653704
type: Question
has body: I have a txt file that I am reading with the following format: Event B 0 40 Event B 0 75 Event B 1 30 Event A Event B 1 50 Event B 1 70 Event A Event A Event B 2 40 I am trying to code the following logic: For every Event A: print columns 1 and 2 of first Event B SINCE the last Event A So the output would be the following: Event B 0 40 Event B 0 75 Event B 1 30 Event A 0 40 Event B 1 50 Event B 1 70 Event A 1 50 Event A N/A N/A Event B 2 40 etc... I can read in the file ok as a list: with open(event_file) as schedule: schedule = schedule.readlines() for i in range(0, len(schedule)): if schedule[i][0] == 'Event A': if schedule[i-X][0] == 'Event A': print(schedule[i-X+1]) # Where X is how many lines before Event A the last one was... but I really dont know how to determine this.. Nor do I know if any of this is the right way to go about it. I hope I'm making sense.
tagged with: python

http://stackoverflow.com/q/49601062
answer count: 1
accepted answer: http://stackoverflow.com/a/49601095
has answer: http://stackoverflow.com/a/49601095
favorite count: 0
type: Question
tagged with: numpy
has title: Using np.any() to capture outliers
upvote count: 1
tagged with: python
has body: I am trying to pull all upper and lower outliers from a data frame. I can do it in separate lines, assigning a variable to the uppers (ex. hi_outs = (sepal_outliers &gt; 4.05)) and another variable to the lowers (ex. lo_outs = (sepal_outliers &lt; 2.05)). But I wanted to try and grab both in one variable. sepal_outliers = x[:,1] outliers = np.any(sepal_outliers &lt; 2.05, sepal_outliers &gt; 4.05) df[outliers] I'm not sure why I've gotten the following error. TypeError: only integer scalar arrays can be converted to a scalar index any thoughts? How might I make this work? I'll keep reading up in the meantime...
downvote count: 1
has comment: http://stackoverflow.com/comment/86209259
has comment: http://stackoverflow.com/comment/86209327
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86209392
score: 0

http://stackoverflow.com/comment/86525945
score: 0
type: AnswerComment
has text: Thank you for your answer. However, I am not familiar with <after>. Can you show an example of how to handle this? Thanks!
comment on: http://stackoverflow.com/a/49755445
type: Comment

http://stackoverflow.com/q/49731156
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/86475731
tagged with: python-2.7
has body: I want user to not be able to write characters other than 'y'and 'n' I have read from a lot of sources but none of them seems to be explaining this case. ready = raw_input('\nOK, Ready? (y/n)\n')
type: UnansweredQuestion
has title: What is the best way to restrain user input to only wanted characters
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49731297
linked to: http://stackoverflow.com/q/23294658
score: 1

google-maps
tags question: http://stackoverflow.com/q/49637186
tag name: google-maps
tags question: http://stackoverflow.com/q/49668387
tags question: http://stackoverflow.com/q/49725367
type: Tag
tags question: http://stackoverflow.com/q/49704679

http://stackoverflow.com/a/49674759
has comment: http://stackoverflow.com/comment/86404936
has comment: http://stackoverflow.com/comment/86365751
has comment: http://stackoverflow.com/comment/86367409
has comment: http://stackoverflow.com/comment/86365478
has comment: http://stackoverflow.com/comment/86399844
has comment: http://stackoverflow.com/comment/86399060
has comment: http://stackoverflow.com/comment/86366962
has body: Create a mapping for the category: def catMapper(cat): if cat in [1,2,3]: return "Error" # or "ERROR" to save the .upper() below elif cat in [4,5,6]: return "..." # Incorrect? ValidationError? pick one. elif cat in [7,8]: return "Warning" raise ValueError('No mapping for {}'.format(cat)) # or return a default of your liking And use it when creating your error message. print "[ %s ] %s" % (catMapper(output).upper(), MSG[output].capitalize()) You could also mapp each Errorcode to another Constant "CategoryType" in a dict - similar to what you do with your error messages, but I would probably do it inside a function, not a dict-lookup. Advantage for dicts (Dict-Code taken from comment by @BlackJack) using timeit: setupDict = """ CAT_TO_NAME = {cat: name for name, cats in [('Error', [1, 2, 3]), ('Incorrect', [4, 5, 6]), ('Warning', [7,8])] for cat in cats} """ testDict = """ for c in range(1,9): getIt = CAT_TO_NAME[c] """ setupFunc = """ def catMapper(cat): if cat in [1,2,3]: return "Error" # or "ERROR" to save the .upper() below elif cat in [4,5,6]: return "..." # Incorrect? ValidationError? pick one. elif cat in [7,8]: return "Warning" raise ValueError('No mapping for {}'.format(cat)) # or return a default of your liking """ testFunc = """ for c in range(1,9): getIt = catMapper(c) """ import timeit print(timeit.timeit(testDict,setup = setupDict)) print(timeit.timeit(testFunc,setup = setupFunc)) Output: 0.974066972733 # dictionary lookup 3.08595490456 # functional lookup Result: Dict-Lookup is 3 times as performant .... looking up all codes, once each, 1 million times takes not quite 1s for dict and 3s for functional lookup. So if your main task is looking up this string 9 million times as fast as possible, you shave off 2s doing so by using a dictionary ...
type: Answer
has comment: http://stackoverflow.com/comment/86399108
score: 0
answers question: http://stackoverflow.com/q/49674654
has comment: http://stackoverflow.com/comment/86400504

http://stackoverflow.com/comment/86439085
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49712680
has text: This is a great answer. I love the advise that "segfaults are part of learning". Reminds me of when a friend and I as freshman CS students went back and forth trying to make the smallest Hello World program that would run on our Linux systems. I think we managed to get it down to something like 30 bytes by embedding the code and the string inside an incomplete ELF header (which of course ended up with lots of bogus values, that amazingly didn't cause it to crash). You know you're having fun when you're hand-writing machine code with a hex editor.
type: Comment

http://stackoverflow.com/a/49619629
score: 0
accepted answer of: http://stackoverflow.com/q/49619281
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86248562
has comment: http://stackoverflow.com/comment/86246272
has comment: http://stackoverflow.com/comment/86271955
type: Answer
has body: I would recommend using Pillow module for working with images but if you insist on your current way try this code below: from tkinter import * import base64 import os if os.path.isfile("example.png"): #if the user has created this type of image.. with open("example.png", "rb") as image_file: image_data_base64_encoded_string = base64.b64encode(image_file.read()) f = open("example_save.txt",'a+') f.write(image_data_base64_encoded_string.decode("utf-8")+"\n") f.close() filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = ((".txt files","*.txt"),("all files","*.*"))) with open(filename) as f: image_import = f.readlines()[3].strip() image_imported = PhotoImage(data=image_import) You see your string needs to be utf-8 and that trailing newline character is also preventing PhotoImage() from interpreting your image data as image.
has comment: http://stackoverflow.com/comment/86246280
has comment: http://stackoverflow.com/comment/86279871
answers question: http://stackoverflow.com/q/49619281

http://stackoverflow.com/comment/86480855
type: Comment
comment on: http://stackoverflow.com/q/49732898
type: QuestionComment
has text: You can increase the log level of SQLAlchemy so that it logs the actual SQL being rendered/sent to the DB. You can then run the same sql on you DB with explain on, and then you can look at the query plan to decide if the DB is doing what you expect/want it to be doing.
score: 0

http://stackoverflow.com/comment/86367571
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49676944
type: Comment
has text: To me it looks like pd.DataFrame.update is made exactly for what is asked, is simpler to understand, can update multiple columns at once, and can be used more generally due to the presence of parameters.

http://stackoverflow.com/a/49700817
answers question: http://stackoverflow.com/q/49700647
score: 0
type: Answer
has body: I'd suggest capturing the data you DO want, since it's pretty particular, and the data you do NOT want could be anything. Your pattern should look something like this: ^\w{4}-\w{4}-\w{3}(?:-\d{3})? https://regex101.com/r/NtH2Ut/2 I'd recommend being more specific than \w where possible. (Like ^[A-Z]\w{3}) if you know the beginning four character chunk should start with a letter. edit Sorry, I may not have read your input and output literally enough: https://regex101.com/r/NtH2Ut/3 ^(?:\d+\s+\w{4}-\w{4}-\w{3}(?:-\d{3})?)|^\s+.*

http://stackoverflow.com/a/49711755
has comment: http://stackoverflow.com/comment/86456888
downvote count: 0
has comment: http://stackoverflow.com/comment/86439696
has body: I would use itertools.groupby to group consecutive runs of the same letter. Then use a generator expression within join to create a string representation of the count and letter for each run. from itertools import groupby def summarize(s): return ''.join(str(sum(1 for _ in i[1])) + i[0] for i in groupby(s)) Examples &gt;&gt;&gt; summarize(string1) '5A4B3C2D' &gt;&gt;&gt; summarize(string2) '2C1B1A5D1B1A1C1D1C' &gt;&gt;&gt; summarize(string3) '1D1A1B1C1B1E1D2C1A1E1D2B'
has comment: http://stackoverflow.com/comment/86440000
has comment: http://stackoverflow.com/comment/86439325
type: Answer
answers question: http://stackoverflow.com/q/49711722
has comment: http://stackoverflow.com/comment/86437277
has comment: http://stackoverflow.com/comment/86437414
score: 2
upvote count: 2

http://stackoverflow.com/q/49672249
type: UnansweredQuestion
answer count: 1
tagged with: keras
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49672649
has comment: http://stackoverflow.com/comment/86355560
linked to: http://stackoverflow.com/q/21494489
score: 1
has title: Lock a variable value after a random use
tagged with: python
has body: I'm dealing with a stacked denoising autoencoder in keras. So for after generating the noised input using random tool, I noticed that even if I use a checkpointer to save the weights of the model, I got different encoded data each time I run the script, while when I'm dealing with normal auotencoder, I don't have such issue. So I think that the problem comes from the generated noised input data. How can I fix the values of this noised data input once for all. Here is how I generated the noised input: mu, sigma = 2, 3 noise_noy = np.random.normal(mu, sigma, [7412,48]) noise_test = np.random.normal(mu, sigma, [3600,48]) noised_noyau_y = df_noyau_yes + noise_noy noised_test_y = df_test_yes + noise_test print(noised_noyau_y) And this the denoising autoencoder checkpointer = ModelCheckpoint(filepath="modelyes.h5", verbose=0, save_best_only=True, save_weights_only=True) tensorboard = TensorBoard(log_dir='/tmp/autoencoder', histogram_freq=0, write_graph=True, write_images=True) input_enc = Input(shape=(input_size,)) hidden_1 = Dense(hidden_size1, activation='relu')(input_enc) hidden_11 = Dense(hidden_size2, activation='relu')(hidden_1) code = Dense(code_size, activation='relu')(hidden_11) hidden_22 = Dense(hidden_size2, activation='relu')(code) hidden_2 = Dense(hidden_size1, activation='relu')(hidden_22) output_enc = Dense(input_size, activation='tanh')(hidden_2) D_autoencoder_yes = Model(input_enc, output_enc) D_autoencoder_yes.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) history_D_yes = D_autoencoder_yes.fit(df_noised_noy_norm_y, df_noyau_norm_y, epochs=200, batch_size=batch_size, shuffle = True, validation_data=(df_noised_test_norm_y, df_test_norm_y), verbose=1, callbacks=[checkpointer, tensorboard]).history D_autoencoder_yes.save_weights("modelyes.h5") D_autoencoder_yes.load_weights("modelyes.h5") generating the encoded data encoder_yes = Model (inputs = input_enc,outputs = code) encoded_input = Input(shape=(code_size, )) encoded_data_yes …
downvote count: 0
tagged with: autoencoder
upvote count: 1

http://stackoverflow.com/q/49711931
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/41251729
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86437517
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/86437411
has comment: http://stackoverflow.com/comment/86437396
has body: When I try to unpack lists in a list comprehension: [*parent.rules for parent in parents if hasattr(parent, "rules")] I get the error: SyntaxError: iterable unpacking cannot be used in comprehension While I understand there are other ways to do this, this seems like the most obvious and Pythonic way. Why does Python disallow this behaviour?
has title: Why can't iterable unpacking be used in a list comprehension?
has comment: http://stackoverflow.com/comment/86437860
answer count: 0
score: 7
downvote count: 3
tagged with: iterable-unpacking
upvote count: 10
favorite count: 0
has comment: http://stackoverflow.com/comment/86437478
type: Question

http://stackoverflow.com/comment/86257182
type: Comment
type: QuestionComment
has text: To get better answers, please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) including the expected output.
comment on: http://stackoverflow.com/q/49621994
score: 0

http://stackoverflow.com/q/49753894
has answer: http://stackoverflow.com/a/49756354
answer count: 1
has body: I have a simple pyside QMenu which is being populated with QActions when the application starts. Each menu action represents a class object. How can I create a new instance of the class object based on the Menu Item clicked, and append that new object to a list, which in this example is called ACTIVE_BAKERS = [] import sys from PySide import QtGui, QtCore ################################################################################ # Bakers ################################################################################ class Baker(QtGui.QWidget): def __init__(self, name): self.name = name class Baker_John(Baker): def __init__(self): Baker.__init__(self, name='John') class Baker_Amy(Baker): def __init__(self): Baker.__init__(self, name='Amy') class Baker_Makela(Baker): def __init__(self): Baker.__init__(self, name='Makela') class Baker_Jeff(Baker): def __init__(self): Baker.__init__(self, name='Jeff') ################################################################################ # Action ################################################################################ class MyAction(QtGui.QAction): on_action = QtCore.Signal(dict) def __init__(self, user_info, *args, **kwargs): super(MyAction, self).__init__(*args, **kwargs) self.ui = user_info self.triggered.connect(self.on_triggered) def on_triggered(self): print('UI:', self.ui) self.on_action.emit(self.ui) class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.resize(200, 300) # OBJECTS - variable containing list of class objects created ACTIVE_BAKERS = [] # CONTROLS self.ui_items = QtGui.QListView() self.ui_items.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.ui_items.customContextMenuRequested.connect(self.open_tasks_contextmenu) self.setCentralWidget(self.ui_items) self.create_context_menu_ui() # dynamically create the menu def create_context_menu_ui(self): self.add_baker = QtGui.QMenu("Add") AVAILABLE_BAKERS = [Baker_John(), Baker_Amy(), …
type: Question
tagged with: pyside
tagged with: python
tagged with: qaction
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49756354
score: 0
has title: Dynamically created QActions creating class object

http://stackoverflow.com/q/49657455
has comment: http://stackoverflow.com/comment/86326227
tagged with: python
tagged with: keras
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86353969
answer count: 1
downvote count: 1
has title: Keras model.fit throws ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
favorite count: 0
type: Question
has body: My following code throws an error in my newest environment and I can't figure out why: def train(memory, total_reward): for state, action, reward, next_state, done in memory: if done: target = reward else: target = reward + gamma * model.predict(next_state)[0].max() y = model.predict(state) y[0][action] = target model.fit(state, y, verbose=0) total_reward += reward The Error: ValueError Traceback (most recent call last) &lt;ipython-input-56-679fed838f2b&gt; in &lt;module&gt;() 2 for i in range(1000): 3 memory, total_reward = episode() ----&gt; 4 train(memory, total_reward) 5 rewards.append(total_reward) 6 if i == 1 or i % 10 == 0: &lt;ipython-input-55-9d409e360844&gt; in train(memory, total_reward) 37 y[0][action] = target 38 ---&gt; 39 model.fit(state, y, verbose=0) 40 41 total_reward += reward /home/ntzioras/VirtualEnvironments/DeepLearning/lib/python2.7/site-packages/keras/models.pyc in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 961 initial_epoch=initial_epoch, 962 steps_per_epoch=steps_per_epoch, --&gt; 963 validation_steps=validation_steps) 964 965 def evaluate(self, x=None, y=None, /home/ntzioras/VirtualEnvironments/DeepLearning/lib/python2.7/site-packages/keras/engine/training.pyc in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 1628 sample_weight=sample_weight, 1629 class_weight=class_weight, -&gt; 1630 batch_size=batch_size) 1631 # Prepare validation data. 1632 do_validation = False /home/ntzioras/VirtualEnvironments/DeepLearning/lib/python2.7/site-packages/keras/engine/training.pyc in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 1478 output_shapes, 1479 check_batch_axis=False, -&gt; 1480 exception_prefix='target') 1481 sa…
has answer: http://stackoverflow.com/a/49736563
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/86353777
type: QuestionComment
comment on: http://stackoverflow.com/q/49671464
type: Comment
score: 0
has text: Have you tried `message.get_body(preferencelist=('html','plain'))`: https://docs.python.org/3/library/email.message.html#email.message.EmailMessage.get_body

http://stackoverflow.com/q/49737552
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
has title: OpenAI-gym how to implement a timer for a certain action in step()
tagged with: python
tagged with: pygame
has body: One of the actions I want the agent to do needs to have a delay between every action. For context, in pygame I have the following code for shooting a bullet: if keys[pygame.K_SPACE]: current_time = pygame.time.get_ticks() # ready to fire when 600 ms have passed. if current_time - previous_time &gt; 600: previous_time = current_time bullets.append([x + 25, y + 24]) I've set a timer to prevent bullet spamming, how would I construct this to work with the step() method? My other actions are moving up, down, left, right. This is my first time creating a project with OpenAI-gym so I'm not sure what the capabilities of the toolkit are, any help would be greatly appreciated.
type: Question
accepted answer: http://stackoverflow.com/a/49760991
tagged with: openai-gym
score: 1
has answer: http://stackoverflow.com/a/49760991
answer count: 1

python-xarray
tags question: http://stackoverflow.com/q/49639101
tags question: http://stackoverflow.com/q/49656909
tags question: http://stackoverflow.com/q/49620140
tags question: http://stackoverflow.com/q/49600180
tags question: http://stackoverflow.com/q/49620757
type: Tag
tag name: python-xarray
tags question: http://stackoverflow.com/q/49756981
tags question: http://stackoverflow.com/q/49701623

http://stackoverflow.com/comment/86362236
type: Comment
type: QuestionComment
has text: I think that if you unzip from the terminal, you can do `unzip -j` the `-j` meaning not to create a target folder
comment on: http://stackoverflow.com/q/49674382
score: 0

http://stackoverflow.com/a/49683447
accepted answer of: http://stackoverflow.com/q/49683312
type: Answer
answers question: http://stackoverflow.com/q/49683312
score: 0
has body: Worth mentioning was that you use Python 2.7. word='الو' for w in newStopWords1d: if word == w.decode("utf-8"): print 'found' Even better solution is to use either the open function from io import io with io.open('stop_word_Tiba.txt', encoding="utf-8") as f: ... or codecs module import codecs with codecs.open('stop_word_Tiba.txt', encoding="utf-8") as f: ... as the built-in open function in Python 2.7 doesn't support specifying the encoding.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86379558

http://stackoverflow.com/a/49686282
has comment: http://stackoverflow.com/comment/86384230
answers question: http://stackoverflow.com/q/49686013
has comment: http://stackoverflow.com/comment/86385555
upvote count: 6
type: Answer
score: 6
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49686013
has body: This is how you do it in scikit-image. from skimage import io im = io.imread(self.file_image) However, according to scipy's documentation "imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead." So the better option is to use imageio to read images. You can install imageio if not already installed by using pip install imageio

http://stackoverflow.com/comment/86254990
type: Comment
comment on: http://stackoverflow.com/q/49623765
type: QuestionComment
has text: You should try to `del` your variables after use and add some manual garbage collection. Also try to manually decompress before and process that problematic file alone.
score: 0

http://stackoverflow.com/q/49626572
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49626715
accepted answer: http://stackoverflow.com/a/49626715
linked to: http://stackoverflow.com/q/23463240
tagged with: python
has title: computation cannot be performed with standard 32-bit LAPACK
type: Question
answer count: 2
has body: I am training my dataset using VGG as below. It worked well without zca whitening, but after adding zca, it cause an error called "computation cannot be performed with standard 32-bit LAPACK" . As you can see, I tried to train the number of batchsize..etc.. to 1, and even just train with 6 images, but it still din not work. What should I do? Here is my code. import os from keras.applications.vgg16 import VGG16 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, Model from keras.layers import Input, Activation, Dropout, Flatten, Dense from keras.preprocessing.image import ImageDataGenerator from keras import optimizers import numpy as np import time from PIL import Image import csv import shutil # 分類するクラス classes = ['sugi', 'hinoki'] nb_classes = len(classes) img_width, img_height = 256, 256 # トレーニング用とバリデーション用の画像格納先 train_data_dir = 'dataset/train1' #validation_data_dir = 'dataset/validation' # 今回はトレーニング用に200枚、バリデーション用に50枚の画像を用意した。 nb_train_samples = 1998 #nb_validation_samples = 50 batch_size = 32 nb_epoch = 10 gen_tr_batches = 4 folder = './output' result_dir = 'results' if not os.path.exists(result_dir): os.mkdir(result_dir) train_imagelist = os.listdir(train_data_dir) def vgg_model_maker(): """ VGG16のモデルをFC層以外使用。FC層のみ作成して結合して用意する """ # VGG16のロード。FC層は不要なので include_top=False input_tensor = Input(shape=(img_width, img_height, 3)) vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor) # FC層の作成 top_model = Sequential() top_model.add(Flatten(input_shape=vgg16.output_shape[1:])) top_model.add(Dense(256, activation='relu')) top_model.add(Dropout(0.5)) top_model.add(Dense(nb_classes, activation='softmax')) # VGG16とFC層を結合してモデルを作成 model = Model(input=vgg16.input, output=top_model(vgg16.output)) return model def image_generator(): """ ディレクトリ内の画像を読み込んでトレーニングデータとバリデーションデータの作成 """ gen_train = (ImageDataGenerator(rescale=1.0 / 255.).flow_from_directory(train_data_dir, target_size=(img_width, img_height), #color_m…
linked to: http://stackoverflow.com/q/32228967
tagged with: tensorflow
has answer: http://stackoverflow.com/a/56693335
possible better answer: http://stackoverflow.com/a/56693335

http://stackoverflow.com/a/49709556
answers question: http://stackoverflow.com/q/49709522
has comment: http://stackoverflow.com/comment/86432543
downvote count: 0
upvote count: 1
has body: You could use a heapq and keep popping elements until 25% of the container has been removed. Then, filter the contents of the original list import heapq, copy s = [1,5,6,72,3,4,9,11,3,8] new_s = copy.deepcopy(s) heapq.heapify(s) count = 0 last_items = set() while count/float(len(new_s)) &lt;= 0.25: last_items.add(heapq.heappop(s)) count += 1 final_s = [i for i in new_s if i not in last_items] Output: [5, 6, 72, 4, 9, 11, 8]
has comment: http://stackoverflow.com/comment/86432786
score: 1
type: Answer

http://stackoverflow.com/a/49647123
accepted answer of: http://stackoverflow.com/q/49646848
has comment: http://stackoverflow.com/comment/86304645
answers question: http://stackoverflow.com/q/49646848
has comment: http://stackoverflow.com/comment/86303633
has comment: http://stackoverflow.com/comment/86303559
has comment: http://stackoverflow.com/comment/86302861
type: Answer
has comment: http://stackoverflow.com/comment/86303070
score: 10
upvote count: 10
has body: Use the date_trunc() function to truncate your dates to month precision: month = func.date_trunc('month', Loan_Amendment.AmendDate) AmendObj = db.session.query(func.sum(Loan_Amendment.Amount).label('Amount'), month).\ group_by(month).\ first() # Did you mean all()? Another option that's less DB dependent is to use EXTRACT(): from sqlalchemy import extract AmendObj = db.session.query(func.sum(Loan_Amendment.Amount).label('Amount'), extract('year', Loan_Amendment.AmendDate), extract('month', Loan_Amendment.AmendDate)).\ group_by(extract('year', Loan_Amendment.AmendDate), extract('month', Loan_Amendment.AmendDate)).\ first() Since your date columns are actually text, you need a cast first. If you're using a version of SQLAlchemy that has the ColumnElement.cast() shortcut, 1.0.7 or above, then just func.date_trunc('month', Loan_Amendment.AmendDate.cast(Date)) but if not, then from sqlalchemy import cast func.date_trunc('month', cast(Loan_Amendment.AmendDate, Date)) Naturally the same applies if using EXTRACT. A hacky solution given your model and data would be to simply take the substring that includes the year and month part and group by it: month = func.substr(Loan_Amendment.AmendDate, 1, 7)
has comment: http://stackoverflow.com/comment/86303169
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86304015

http://stackoverflow.com/comment/86411678
type: QuestionComment
has text: show your MyClass ?
comment on: http://stackoverflow.com/q/49699267
score: 1
type: Comment

http://stackoverflow.com/comment/86492344
score: 0
type: Comment
type: AnswerComment
has text: It seems that this function get all the data inside the list, into a dataframe, but the only column that was already a dataframe, disappears
comment on: http://stackoverflow.com/a/49738889

http://stackoverflow.com/a/49742901
has comment: http://stackoverflow.com/comment/86583745
answers question: http://stackoverflow.com/q/49742593
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/111242678
has body: The issue you're experiencing is probably because your spectra are not zero-centered; their RMS value looks to be about 100 in whichever units you're plotting, instead of 0. The reason this is an issue is because numpy.correlate works by "sliding" imag_data over temp_data to get their dot product at each possible offset between the two series. (See the wikipedia on cross-correlation to understand the operation itself.) When using mode='same' to produce an output that is the same length as your first input (temp_data), NumPy has to "pad" a bunch of dummy values--zeroes--to the ends of imag_data in order to be able to calculate the dot products of all the shifted versions of the imag_data. When we have any non-zero offset between the spectra, some of the values in temp_data are being multiplied by those dummy zero-padding values instead of the values in image_data. If the values in the spectra were centered around zero (RMS=0), then this zero-padding would not impact our expectation of the dot product, but because these spectra have RMS values around 100 units, that dot product (our correlation) is largest when we lay the two spectra on top of one another with no offset. Notice that your cross-correlation result looks like a triangular pulse, which is what you might expect from the cross-correlation of two square pulses (c.f. Convolution of a Rectangular "Pulse" With Itself. That's because your spectra, once padded, look like a step function from zero up to a pulse of slightly noisy values around 100. You can try convolving with mode='full' to see the entire response of the two spectra you're correlating, or, notice that with mode='valid' that you should only get one value in return, since your two spectra are the exact same length, so there is only one offset (zero!) where you can entirely line them up. To sidestep this issue, you can try either subtracting away the RMS value of the spectra so that they are zero-centered, or manually padding the beginning and end of …
has comment: http://stackoverflow.com/comment/86583973
type: Answer
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/86583297
accepted answer of: http://stackoverflow.com/q/49742593
has comment: http://stackoverflow.com/comment/86501706
has comment: http://stackoverflow.com/comment/86509121

http://stackoverflow.com/q/49620189
tagged with: django
tagged with: django-rest-framework
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49620268
has title: django.core.exceptions.ImproperlyConfigured: Field name `id` is not valid for model
upvote count: 9
has answer: http://stackoverflow.com/a/49620268
has body: I'm having troubles with one of my serializer. I'm trying to return all the data of a PriceUnit object but DRF refuses to serve the id. This id is automatically generated and I'm not modifying it. serializer.py class PriceUnitSerializer(serializers.ModelSerializer): product_id = serializers.SerializerMethodField() def get_product_id(self, obj): if obj.product is not None: return obj.product.id return None class Meta: model = PriceUnit fields = ('id', 'name', 'formula', 'product_id') urls.py url(r'^price_units/$', price_unit_view.PriceUnitCreateUpdate.as_view()), url(r'^price_units/(?P&lt;pk&gt;[0-9]+)/$', price_unit_view.PriceUnitList.as_view()), models.py class PriceUnit(models.Model): UNIT = 'Unit' SQUAREMATER = 'm2' CUBEMETER = 'm3' LINEARMETER = 'ml' KILOGRAM = 'kg' PRICE_UNITS_CHOICES = ( (UNIT, 'Unit'), (SQUAREMATER, 'm2'), (CUBEMETER, 'm3'), (LINEARMETER, 'ml'), (KILOGRAM, 'kg'), ) name = models.CharField(max_length=50, choices=PRICE_UNITS_CHOICES, default=UNIT,) formula = models.CharField(max_length=400, blank=True) product = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True,) def __str__(self): return 'Price unit : ' + self.name + ' - Product #' + str(self.product.pk) price_unit_view.py class PriceUnitList(APIView): """ Retrieve a PriceUnit. """ permission_classes = (permissions.IsAuthenticated,) def get(cls, request, pk, format=None): price_unit_list = PriceUnit.objects.filter(pk=pk) if price_unit_list: serializer = PriceUnitSerializer(price_unit_list[0]) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(data={}, status=status.HTTP_204_NO_CONTENT) Request (using httpie) : http GET http://127.0.0.1/api/price_units/1/ "Authorization: Token ba4ee2628669a9cc0d6e715b12660003f748c674" Error : ERROR [django.request:135] Internal Server Error: /price_units/1/ Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_resp…
has comment: http://stackoverflow.com/comment/122594854
possible better answer: http://stackoverflow.com/a/49620456
tagged with: python
has answer: http://stackoverflow.com/a/49620456
favorite count: 0
type: Question
answer count: 2
score: 9
downvote count: 0

http://stackoverflow.com/comment/86246516
comment on: http://stackoverflow.com/a/49610249
score: 0
type: Comment
has text: I did, but I realise now that I misunderstood what they were asking.
type: AnswerComment

http://stackoverflow.com/comment/86337780
type: QuestionComment
comment on: http://stackoverflow.com/q/49663720
type: Comment
score: 0
has text: Also found a way to validate uuid4 in python: https://gist.github.com/ShawnMilo/7777304, and assume there isn't a much better way short of using probability/statistics. Thank you for all the help

http://stackoverflow.com/q/49746240
has answer: http://stackoverflow.com/a/49746433
score: 1
upvote count: 1
has title: extracting gpsd output from terminal using python program
type: Question
accepted answer: http://stackoverflow.com/a/49746433
answer count: 1
tagged with: raspberry-pi3
tagged with: python
tagged with: gpsd
has body: I did run a command from the python program which is related to GPS. sudo gpsd /dev/ttyS0 -F /var/run/gpsd.sock cgps -s Now i want to use this information like latitude and longitude in my python code. How can i get these data? And these latitude and longitude values will be continuously varying. So can i get the value using python? Output from the above command gives like this ┌───────────────────────────────────────────┐┌─────────────────────────────────┐ │ Time: 2018-04-10T05:49:46.000Z ││PRN: Elev: Azim: SNR: Used: │ │ Latitude: 12.945873 N ││ 1 08 177 23 Y │ │ Longitude: 77.569187 E ││ 3 35 195 29 Y │ │ Altitude: 913.1 m ││ 7 22 313 09 Y │ │ Speed: 1.2 kph ││ 8 54 127 24 Y │ │ Heading: 0.0 deg (true) ││ 9 44 335 25 Y │ │ Climb: 0.0 m/min ││ 11 20 168 21 Y │ │ Status: 3D FIX (158 secs) ││ 16 15 032 00 Y │ │ Longitude Err: +/- 12 m ││ 18 10 154 00 Y │ │ Latitude Err: +/- 6 m ││ 22 21 175 26 N │ │ Altitude Err: +/- 17 m ││ 23 75 038 10 N │ │ Course Err: n/a ││ 27 37 068 14 N │ │ Speed Err: +/- 87 kph ││ 28 18 231 00 N │ │ Time offset: 0.727 ││ 30 08 292 00 N │ │ Grid Square: MK82sw ││ │ └───────────────────────────────────────────┘└─────────────────────────────────┘
favorite count: 0
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/49613558
downvote count: 1
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86233672
answers question: http://stackoverflow.com/q/49613360
has body: My solution &gt;&gt;&gt; initialList=[1,2,3,5] &gt;&gt;&gt; sum(([num]*count for num, count in enumerate(initialList)), []) [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]
upvote count: 1

http://stackoverflow.com/a/49706933
upvote count: 1
has body: Note that df['last_payout'].dt.year &gt; 2016 just returns a boolean series, so plotting this will indeed show a bar chart of the number of dates for which this is or not. Try first creating a relevant df: relevant_df = df[(df['last_payout'].dt.year &gt; 2016) &amp; (df['last_payout'].dt.year &lt;= 2017)] (use strict or not inequalities depending on what you want, of course.) then performing the plot on it: relevant_df['last_payout'].groupby(relevant_df['last_payout'].dt.year).count().plot(kind="bar")
type: Answer
answers question: http://stackoverflow.com/q/49706852
score: 1
downvote count: 0

http://stackoverflow.com/comment/86431914
comment on: http://stackoverflow.com/q/49708993
score: 0
type: Comment
has text: Show us your current attempt so we can see where you went wrong.
type: QuestionComment

http://stackoverflow.com/comment/86640236
type: Comment
type: QuestionComment
has text: @Blender Is there one that you have already tested?
score: 0
comment on: http://stackoverflow.com/q/49751135

http://stackoverflow.com/q/49628384
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49628866
has answer: http://stackoverflow.com/a/49628912
downvote count: 3
has body: In python , i want to generate a random time between two intervals using randrange function and using the step parameter. I want the time to be generated at 5 minute intervals using randrange. Is it possible? Or is there any other function in python which can achieve the same? import datetime import time import random start = datetime.datetime(2017,4,25,8,0) end = datetime.datetime(2017,4,25,11,30) steptime = datetime.datetime(2017,4,25,0,5) totalnum=10 start_ts = int(time.mktime(start.timetuple())) end_ts = int(time.mktime(end.timetuple())) step = int(time.mktime(steptime.timetuple())) for val in range(totalnum): random_ts = random.randrange(start_ts, end_ts,step) RANDOMTIME = datetime.datetime.fromtimestamp(random_ts) print(RANDOMTIME.strftime("%Y-%m-%d %H:%M")) As mentioned above im not able to find a way to generate time within 5 minute intervals. TIA
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/3463930
accepted answer: http://stackoverflow.com/a/49629372
upvote count: 0
tagged with: random
has title: randrange python step parameter in minutes
answer count: 3
possible better answer: http://stackoverflow.com/a/49628866
linked to: http://stackoverflow.com/q/553303
score: -3
has comment: http://stackoverflow.com/comment/86263655
has comment: http://stackoverflow.com/comment/86263834
has comment: http://stackoverflow.com/comment/86263737
favorite count: 0
has answer: http://stackoverflow.com/a/49629372
type: Question

http://stackoverflow.com/q/49713826
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86569259
has comment: http://stackoverflow.com/comment/86441008
tagged with: docker
score: 1
has title: Docker compose errors using volumes
has comment: http://stackoverflow.com/comment/86533188
downvote count: 0
has comment: http://stackoverflow.com/comment/86441054
has comment: http://stackoverflow.com/comment/86479901
favorite count: 0
type: Question
has body: Here's the deal: I want to create an image based on python:latest, for Django development. I want to create the Django project INSIDE THE CONTAINER and make it reflect on a host folder, via docker volumes. I want to use the python interpreter from the container for development. This way, I can have only my Dockerfile, docker-compose.yml and requirements.txt on my project folder, not depending on Python, virtualenvs or anything like that on my host. Here's my Dockerfile: FROM python:latest ARG requirements=requirements/production.txt COPY ./app /app WORKDIR /app RUN pip install --upgrade pip && \ pip install --no-cache-dir -r $requirements && \ django-admin startproject myproject . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And here's my docker-compose.yml: version: '3' services: web: build: context: . args: requirements: requirements/development.txt networks: - main depends_on: - postgres environment: - PYTHONUNBUFFERED=1 ports: - "8000:8000" volumes: - "./app:/app:rw" postgres: image: postgres:latest networks: - main ports: - "5432:5432" environment: - POSTGRES_PASSWORD=123 volumes: - ./data:/var/lib/postgresql/data networks: main: The main issue are the volumes in web. If I build the image via docker build -t somename:sometag . the build works fine. If I run docker run -it my_image bash it shows me all the files created inside /app. But if I try docker-compose up it fails the web part, saying that could not find manage.py, and exiting with code 2. Only Postgres is running after that. So, finally, my questions are: This kind of workflow is possible? Is it the best option, since it does not depend on Python on the host? Thanks a lot.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86475602
tagged with: django

http://stackoverflow.com/comment/86245757
type: QuestionComment
score: 2
has text: Can you show us what the expected result is as a dict? What you posted there is 50% dict and 50% list and 0% valid syntax.
comment on: http://stackoverflow.com/q/49619330
type: Comment

http://stackoverflow.com/comment/86282978
score: 0
has text: Hi Mahal - while your question is valid I think you'd be better off rephrasing this as separate questions, and showing your work for each. See: https://stackoverflow.com/help/how-to-ask
type: Comment
comment on: http://stackoverflow.com/q/49637222
type: QuestionComment

http://stackoverflow.com/a/49706171
type: Answer
has body: If you try like the following, the style tag is not a barrier to consider. from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.fiyo.nl/') driver.find_element_by_xpath('//*[@id="select_device_chosen"]/a').click() items = ' '.join([item.get_attribute("textContent") for item in driver.find_elements_by_xpath("//*[@class='chosen-results']//*[@class='active-result']")]) print(items.split()) driver.quit()
answers question: http://stackoverflow.com/q/49705523
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86390326
type: AnswerComment
comment on: http://stackoverflow.com/a/49688803
score: 0
type: Comment
has text: Thanks for that, makes things a bit clearer to me now. Using your example for `b'\x41\x42\x43'` actually outputs `b'ABC'`. So in this case the interpreter seeks to display as this as a sequence of characters and can do, so displays it as `b'ABC'`

http://stackoverflow.com/a/49678668
has body: I have no experience with the pygame library and no knowledge of its internal workings, that may have some influence on what code needs to run where, so I'm not 100% sure on all of that. But, it's good to just start with some intuitive understanding of roughly what should be happening where: __init__() should run any one-time setup. I can imagine something like pygame.init() may have to go in here, but this I'm not 100% sure on because I'm not familiar with pygame. step() should be called whenever an agent selects an action, and then run a single ''frame'' of the game, move it forwards given the action selected by the agent. Alternatively, if you have a game where a single action takes multiple frames, you should run multiple frames here. Essentially: keep the game moving forwards until you hit a point where the agent should get to choose a new action again, then return the current game state. reset() should... well, reset the game. So, revert back to the (or a random, whatever you want) initial game state, run any cleanup that may be required. I could, for example, also imagine pygame.init() belonging in here. It depends on what exactly that function does. If it only needs to be run once, it belongs in __init__(). If it needs to run at the start of every new game/"episode", ir belongs in reset(). render() should probably contain most of your graphics related code. You can try to take inspiration from, for example, the cartpole environment in gym, which also draws some rather simple graphics here. It looks like it should draw exactly one frame. Now, looking at the code you're starting from, there seems to be a signifant amount of User Interface code... all kinds of code related to buttons, pausing/unpausing, a fancy (animated?) intro at the start of the game. I don't know if you can afford to get rid of all this? If you're doing purely Reinforcement Learning, you probably can. If you still need user interaction, you probably can't, and then things become a whole lot…
has comment: http://stackoverflow.com/comment/86446096
type: Answer
has comment: http://stackoverflow.com/comment/86446973
has comment: http://stackoverflow.com/comment/86446376
has comment: http://stackoverflow.com/comment/86380898
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86447070
has comment: http://stackoverflow.com/comment/86426391
has comment: http://stackoverflow.com/comment/86435554
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49637378
has comment: http://stackoverflow.com/comment/86434224
has comment: http://stackoverflow.com/comment/86370596
has comment: http://stackoverflow.com/comment/86425566
answers question: http://stackoverflow.com/q/49637378
has comment: http://stackoverflow.com/comment/86370846

http://stackoverflow.com/a/49664602
score: -1
upvote count: 1
answers question: http://stackoverflow.com/q/49664518
downvote count: 2
type: Answer
has body: You can use python builtin module os.walk: for root, dirs, files in os.walk(".", topdown=False): for name in files: print(os.path.join(root, name)) for name in dirs: #this will get your all directories within the path print(os.path.join(root, name)) For more info visit this link : os.walk
has comment: http://stackoverflow.com/comment/86339052

http://stackoverflow.com/q/49652758
has body: I would like after creating a user to run a method and create content in other tables of this user that was created but I do not have a user model since I use the default model for the record. Problems: -I do not have user model (use the default model) -I want to choose the newly created user to create the other records in other tables -I'm not an expert in django (I'm just trying to solve a problem in another area and this would help) I like the way to do it in this post: https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html Creating a signals.py to control the signals
tagged with: django-models
tagged with: python
tagged with: django-signals
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: django
has title: Signal for the default user registration of django
type: Question
accepted answer: http://stackoverflow.com/a/49653320
has answer: http://stackoverflow.com/a/49653320

http://stackoverflow.com/comment/86326763
type: QuestionComment
comment on: http://stackoverflow.com/q/49658670
type: Comment
has text: Can you give a specific example?
score: 0

http://stackoverflow.com/q/49680473
has answer: http://stackoverflow.com/a/49680590
has answer: http://stackoverflow.com/a/49680662
favorite count: 0
type: Question
score: 3
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: python-2.7
has body: I'm looking for a way to essentially strip out the extra period if a value is null or None. If myvar doesn't exist, it should print abc.xyz myvar="def" print "abc.{0}.xyz".format(myvar) abc.def.xyz myvar="" print "abc.{0}.xyz".format(myvar) abc..xyz
possible better answer: http://stackoverflow.com/a/49680558
accepted answer: http://stackoverflow.com/a/49680550
upvote count: 3
has title: How to deal with null values using Python format
has answer: http://stackoverflow.com/a/49680558
downvote count: 0
has answer: http://stackoverflow.com/a/49680550
has comment: http://stackoverflow.com/comment/86373497

http://stackoverflow.com/comment/86278936
type: Comment
type: QuestionComment
has text: @mikkola sure. As far as I can tell, reading the CSV line by line would require that I create a list of length 200 every time I wanted to read a file (```record_defaults = [[0],[0],...,[0]]```) and then do something like ```cols = tf.decode_csv(csv_row, record_defaults=record_defaults)``` and ```data = tf.stack(cols)```. Which seemed like a lot of overhead for every file.
comment on: http://stackoverflow.com/q/49635269
score: 0

http://stackoverflow.com/comment/86392276
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49690276
type: Comment
has text: Yeah I know, not really an answer, but too long for the comments. I also voted to close the Q as too broad (and probably not fixable for SO with the amount of data provided...)

http://stackoverflow.com/comment/86271934
comment on: http://stackoverflow.com/a/49632180
has text: @snow_fall - Do you need `MultiIndex` ? then add `df = df.set_index(['city','name'])`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49706015
has answer: http://stackoverflow.com/a/49707454
has comment: http://stackoverflow.com/comment/86428281
linked to: http://stackoverflow.com/q/16768290
has comment: http://stackoverflow.com/comment/86425323
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86425404
downvote count: 0
has title: How to pass arguments to subprocess
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86425360
has comment: http://stackoverflow.com/comment/86425418
linked to: http://stackoverflow.com/q/30830642
has comment: http://stackoverflow.com/comment/86425395
has comment: http://stackoverflow.com/comment/86425482
has comment: http://stackoverflow.com/comment/86425679
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86425350
score: 1
linked to: http://stackoverflow.com/q/89228
answer count: 1
has comment: http://stackoverflow.com/comment/86425439
has comment: http://stackoverflow.com/comment/86425327
has body: I want run a process called client.sh in gnome-terminal via python script and want to pass the arguments as input to execute it. Below is my code import os import subprocess import time from subprocess import Popen,PIPE import pexpect process = subprocess.Popen('sudo gnome-terminal -x ./client.sh', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) process.communicate(input = "1") my intension is to send input as "1" to client.sh process. But with above code my process[client.sh] didn't get any input. How can i send inputs to my sub process process?.
has comment: http://stackoverflow.com/comment/86425426
favorite count: 0
type: Question

http://stackoverflow.com/comment/86342286
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49666050
has text: `[numbers("a"), numbers("b")]'
type: Comment

http://stackoverflow.com/q/49755153
type: Question
tagged with: nltk
type: UnansweredQuestion
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/86556277
has body: I'm trying to build a POS Tagger for a Voise Assistant. However, the nltk's pos tagger nltk.pos_tag doesn't work well for me. For example: sent = 'open Youtube' tokens = nltk.word_tokenize(sent) nltk.pos_tag(tokens, tagset='universal') &gt;&gt;[('open', 'ADJ'), ('Youtube', 'NOUN')] In the above case I'd want the word open to be a verb and not an adjective. Similarly, it tags the word 'close' as an adverb and not a verb. I have also tried using an n-gram tagger train_sents = brown_tagged_sents[:size] test_sents = brown_tagged_sents[size:] default_tagger = nltk.DefaultTagger('NOUN') unigram_tagger = nltk.UnigramTagger(train_sents, backoff = default_tagger) bigram_tagger = nltk.BigramTagger(train_sents, backoff = unigram_tagger) trigram_tagger = nltk.TrigramTagger(train_sents, backoff = bigram_tagger) I have used the brown corpus from nltk. But it still gives the same result. So I'd like to know: Is there a better tagged corpus to train a tagger for making a voice/virtual assistant? Is there a higher n-gram than trigram i.e. that looks at 4 words or more together like trigram and bigram look at 3 and 2 words together respectively. Will it improve the performance? How can I fix this?
has answer: http://stackoverflow.com/a/49802707
has comment: http://stackoverflow.com/comment/86528463
score: 1
downvote count: 0
answer count: 1
tagged with: machine-learning
upvote count: 1
has title: POS Tagger for a Virtual Assistant
tagged with: nltk-book
favorite count: 0

http://stackoverflow.com/comment/86210087
type: Comment
score: 1
type: QuestionComment
has text: You can't see variables after a script exits, no.
comment on: http://stackoverflow.com/q/49601425

http://stackoverflow.com/a/49703383
has comment: http://stackoverflow.com/comment/86420423
type: Answer
has body: Your code isn't setting a limit on the size of the cache, but on the number of calls to the wrapper: if number not in cache: cache[number] = func(number) count += 1 In other words, you increment count whether the number was already in the cache or not. To fix that, you just need to indent that increment. On top of that, the count doesn't get reset for each new cache, because the only place you set it to 0 is in outer function: def memoize(limit, *, message = 'Limit exceded'): count = 0 def inner(func): cache = {} To fix that, you need to move the count = 0 from memoize to inner. (Or, if you prefer, add a nonlocal count and reset it with count = 0 in inner, but that's just extra work for the same effect.) But an even simpler fix to both of these problem is to get rid of count entirely. You're trying to count whether you've hit the storage limit in the cache? Just check if len(cache) &lt; limit:.
answers question: http://stackoverflow.com/q/49703263
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86420360
accepted answer of: http://stackoverflow.com/q/49703263
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/104923034
has text: Brilliant! Just awesome! This is a great answer.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49727952
type: AnswerComment

http://stackoverflow.com/q/49683262
score: 0
linked to: http://stackoverflow.com/q/12307099
has comment: http://stackoverflow.com/comment/86378940
type: Question
tagged with: python-3.x
has body: I have been trying to update all rows value of a specific column where another column's value matches with a specific value.I have followed this link:Modifying a subset of rows in a pandas dataframe Using this just changes the very last row value,but all the other row values remain unchanged. Here is my code: def update_status(self, isbn=0, status='yes'): print("\nUpdating Status\n") df = self.data ndf = df[df['ISBN']==isbn] if len(ndf) &gt; 0: print(df) df.loc[df.ISBN==(isbn), 'STATUS'] = status print(df) print("\nUpdated\n") self.data=df'ID', 'AUTHOR', 'ISBN', 'TITLE', 'YEAR', 'STATUS'.copy() os.remove(self.filname) self.data.to_csv(self.filname, sep=',', encoding='utf-8') else: print("No Book Found\n") Here is the output where ISBN=9332549532 and status='yes' output instead of changing 2 rows ,only the last row is getting changed It will be really helpful if i get the solution. Thanks
has comment: http://stackoverflow.com/comment/86379126
type: UnansweredQuestion
tagged with: python
has title: updating value of specific depending on other column value match pandas
answer count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391

http://stackoverflow.com/comment/86395129
type: Comment
has text: I think you need to split on a line that is equal to 4 digits. Try `r'(?m)^\d{4}$[\r\n]*'`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49691154

http://stackoverflow.com/q/49650152
tagged with: win32com
score: 1
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23864234
has title: win32com com_error library not found
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86308357
downvote count: 0
has body: I am trying to use a Python API which makes use of the win32com library. I am using a sample code provided by the site, which works fine in one computer but fails in another. I am running it on Windows 7. Specifically it fails while checking for some binaries: import win32event import win32com.client from win32com.client import constants win32com.client.gencache.EnsureModule('{51F35562-AEB4-4AB3-99E8-AC9666344B64}', 0, 4, 0) win32com.client.gencache.EnsureModule('{4D454F08-B770-11D4-A18E-00C04F6BB385}', 0, 17, 12801) I have been looking around the internet but although there are similar questions I haven't found the answer to my problem. At first I though it was because some 32-64 bits difference in the Windows or Python distributions. I checked that the Windows version was the same in both computers (64-bit Windows 7) and that I was using the same Python version. I haven't found neither which module corresponds to the codes inside EnsureModule(). I am a newby in these aspects and I don't know well the COM objects, so sorry my description is not accurate enough. Thanks in advance. Edit: The import of win32com works well. It doesn't return an error for example using the code of the question referenced as possible duplicate: from win32com.client import Dispatch xlApp = win32com.client.Dispatch("Excel.Application") this doesn't return any error. The exact code and error displayed is : win32com.client.gencache.EnsureModule('{51F35562-AEB4-4AB3-99E8-AC9666344B64}', 0, 4, 0) Traceback (most recent call last): File "&lt;ipython-input-2-18c1ec54bb40&gt;", line 1, in &lt;module&gt; win32com.client.gencache.EnsureModule('{51F35562-AEB4-4AB3-99E8-AC9666344B64}', 0, 4, 0) File "C:\Users\jredondo\AppData\Local\Continuum\anaconda3\lib\site-packages\win32com\client\gencache.py", line 518, in EnsureModule module = MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden) File "C:\Users\jredondo\AppData\Local\Conti…
tagged with: python
has comment: http://stackoverflow.com/comment/86308556
has comment: http://stackoverflow.com/comment/86310680
has comment: http://stackoverflow.com/comment/86308366
answer count: 0
tagged with: com

http://stackoverflow.com/comment/86372731
has text: If you just want to unwrap the tuple, you could use `self.id[self.currentQ][0]`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49674017
type: Comment

http://stackoverflow.com/q/49648269
has body: I am making simple application by django that the counters go up one by one if user click button. When I ran following code, then it displays the error message "invalid literal for int() with base 10: 'game_count'" what is the cause of this problem? models.py class User(models.Model): game_count = models.IntegerField(default=0) views.py from django.shortcuts import render from .models import User from .forms import CountForm def user(request): form = CountForm(request.POST or None) game_count = User.objects.get(game_count='game_count') if request.method == 'POST' and form.is_valid(): game_count += 1 game_count.save() return render(request, 'app/user.html', {'count':game_count}) forms.py from django import forms from .models import User class CountForm(forms.ModelForm): class Meta: model = User fields = ("game_count",) user.html {{ count }} go {% csrf_token %}
type: AnsweredQuestion
has title: django invalid literal for int() with base 10: 'game_count'
score: 1
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49648476
has answer: http://stackoverflow.com/a/49648476
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1

http://stackoverflow.com/q/49651501
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86311377
has body: I'm trying to create a data structure for each tweet and I have troubles with the following code: with open('tweets.csv', 'rb') as csvfile: reader = csv.reader('tweets.csv', delimiter=',') next(reader) for row in reader: tweet= dict() tweet['ID'] = row[0] tweet['Tweet'] = row[1] tweet['Tweet cleaned'] = row[2] tweet['Ticker'] = row[3] tweet['date'] = int(float(row[4])) tweet['Return'] = int(float(row[5])) It returns an error on the line tweet['Tweet'] = row[1] : list index out of range. I'm new to python and after googling the solution couldn't really find anything that works. Thank you!
tagged with: http://stackoverflow.com/tag/csv
score: -2
tagged with: python
tagged with: twitter
has comment: http://stackoverflow.com/comment/86311138
has answer: http://stackoverflow.com/a/49655912
type: AnsweredQuestion
tagged with: tweets
upvote count: 1
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86311790
accepted answer: http://stackoverflow.com/a/49655912
has comment: http://stackoverflow.com/comment/86311688
has title: list index out of range CSV for twitter
favorite count: 0
type: Question

http://stackoverflow.com/q/49664069
has comment: http://stackoverflow.com/comment/86340937
has body: I'm trying to implement a siamese network is Keras for textual similarity, but my network doesn't seem to be symmetrical. When I'm testing, the similarity score it is giving for A, B is different from B, A. How can I fix it? I have tried dot mode as well, as well as all Dense layers. My code is, def contrastive(y_true, y_pred): margin = 1 return K.mean(y_true * K.square(y_pred) + (1 - y_true) * K.square(K.maximum(margin - y_pred, 0))) def network(): encoder = Sequential() encoder.add(Embedding(27, 15, input_length=15)) encoder.add(LSTM(15)) encoder.add(Dense(15)) return encoder l_twin = network() r_twin = network() merged = Merge([l_twin, r_twin], mode='cos', dot_axes=1) siamese = Sequential() siamese.add(merged) siamese.add(Dense(1, activation="sigmoid")) siamese.compile(loss=contrastive, optimizer='adam', metrics=['accuracy']) history = siamese.fit([l_encodings, r_encodings], target, epochs=5, batch_size=50) siamese.save("siamese.h5") siamese.save_weights("siamese_weights.h5")
has comment: http://stackoverflow.com/comment/86338135
accepted answer: http://stackoverflow.com/a/49666256
tagged with: lstm
has answer: http://stackoverflow.com/a/49666256
upvote count: 3
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
has title: Siamese network in Keras symmetry issue
type: AnsweredQuestion
score: 3
tagged with: python

http://stackoverflow.com/a/49688123
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Problem was indeed the nested array of coordinates. Like suggested by cardelling representing the 10 2d coordinates as 20 features worked. To flatten the list I used numpy.ravel()
answers question: http://stackoverflow.com/q/49673029

http://stackoverflow.com/comment/86517859
type: AnswerComment
comment on: http://stackoverflow.com/a/49750123
score: 0
has text: I like that the speed of your 3rd method, but is there a way to extend it to include a first column containing the dates?
type: Comment

http://stackoverflow.com/comment/86217231
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49599917
type: Comment
has text: Do you have a `head` block in your base template? Where is `custom.css` stored in your project tree?

http://stackoverflow.com/comment/86223091
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49608160
has text: Stackoverflow does not provide homework solution. Please include what you have tried so far to solve the problem.

http://stackoverflow.com/comment/86360098
type: AnswerComment
has text: Thanks, but I'm pretty new to Java..could you detail it??
comment on: http://stackoverflow.com/a/49674469
score: 0
type: Comment

http://stackoverflow.com/a/49747916
has comment: http://stackoverflow.com/comment/86515627
answers question: http://stackoverflow.com/q/49746131
has comment: http://stackoverflow.com/comment/86566045
has comment: http://stackoverflow.com/comment/86518815
has comment: http://stackoverflow.com/comment/86518500
has comment: http://stackoverflow.com/comment/86516050
has comment: http://stackoverflow.com/comment/86515805
has body: Try this: script: $.ajax({ type: "POST", url: "http://127.0.0.1:5000/crawler", data: {testUrl: testUrl}, dataType: 'json', success: function (response) { console.log(response.objt) alert(JSON.stringify(response.objt)) }, failure: function (response) { alert("failure") } }); flask: from flask import Flask, request, jsonify from selenium import webdriver from q_learn import Q from configparser import ConfigParser app = Flask(__name__) @app.route('/crawler', methods = ['POST']) def crawler(): url = request.form.get('testUrl') print('url is: ',url) parser = ConfigParser() parser.read('...Crawler\\config_prop\\config.ini') path = parser.get('driver', 'executable_path') driver = webdriver.Chrome(executable_path=path) URL = url q = Q(driver, URL) obj = q.QLearn(0.8, 0.8, 0.01, 0.3, 5, 15) print(obj) driver.close() return jsonify(objt=obj) if __name__ == "__main__": app.run()
score: 0
type: Answer

http://stackoverflow.com/a/49616171
type: Answer
answers question: http://stackoverflow.com/q/49615548
has body: You can zip all-list element-wise into one-list of "tuple" zip(a,b,c) the result will look like this: [(1,1,1), (2,2,2), ... ] then you can "map" the result from "tuple" to "string" map(lambda tup: "%s %s %s" % tup, zip(a,b,c)) Pythonically, ["%s %s %s" % tup for tup in zip(a,b,c)] Now you will get a list of string. Then you can now write to file. In order to make it multilines, we need '\n' char. We can use handy "join" function to join list and separate them by newline char. So my solution gonna be like this: a = [1, 2, 3, 4, 5] b = [1, 2, 3, 4, 5] c = [1, 2, 3, 4, 5] with open("targetfile.txt", "w") as f: f.write("\n".join(["%s %s %s" % tup for tup in zip(a,b,c)]))
score: 0

http://stackoverflow.com/a/74883624
has body: A greenlet is block of sequential frames on the CPython C stack that can be swapped out to the heap. This is the general fundamental building block needed to implement coroutines. The native coroutine implementation in Python does not save C frames to the heap. It's designed to not have important data on the C stack, and then uses send() and yield [from] to unwind/rebuild each frame of the C stack as you suspend/resume the coroutine. The downside to this is that you need to unnecessarily spam chains of yield from's throughout your codebase, and suffer the all the overhead of the stack unwinding/rebuilding. Overall, native python generators are pretty weak in terms of performance and syntactic support. Stackless python avoids using the C stack for Python function calls all together (because if there's no useful context, what's the point?). All the needed context is stored in Python frames (which has the python stack, IP, local vars, return frames...etc). PyPy contains Stackless Python, which is part of the reasons it's performance is so much better. Greenlets were inspired by Stackless python. As an extension module for CPython, the C stack is still used for Python function calls, but you can swap out blocks of frames (this block "is" the coroutine/greenlet) to the heap on-demand. Now you can mix execution of coroutines however you'd like to achieve your goals. This way you can get something better than generators in CPython without having to completely switch to PyPy.
answers question: http://stackoverflow.com/q/49669212
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/49731961
has body: I am currently working on my scrapy project, where I scrap content from internet forums. I want my application to offer different scenarios of scraping, so I wrote a method that should handle these scenarios based on some input flags def work_executor(self, response): yield from self.parse_categories(response) if not parse_only_categories: yield from self.parse_topics() Parse topics method should read categories from mongodb and send request to each category and parse posts. However the parse_topics method is never executed although flag is set. Work executor is called from parse method of my spider def parse(self, response): yield from self.work_executor(response) Earlier I did it this way, which worked def parse_categories(self, response): #some working code yield scrapy.Request(url=self.base_domain +link,callback=self.parse_topics) This solution is hovewer not generic enough for my project so that I am looking for alternatives of how to achieve this efect in the way I tried (and described in the first part of my post) Any help would be greatly appreciated.
tagged with: scrapy
has comment: http://stackoverflow.com/comment/86481267
has comment: http://stackoverflow.com/comment/86478534
has comment: http://stackoverflow.com/comment/86479191
tagged with: python
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/9708902
score: 0
type: UnansweredQuestion
has title: Different scenarios of scraping - scrapy

http://stackoverflow.com/a/49683641
has body: Try doing this: grocery_item = dict() grocery_history = [] choice = 0 stop = True while stop == True: current_item = dict() current_item['name'] = str(input('Item name: ')) current_item['quantity'] = int(input('Amount purchased: ')) current_item['cost'] = float(input('Price per item: ')) grocery_history.append(current_item) choice = str(input('Press c to continue or q to quit')) if choice == 'c': stop = True else: stop = False print(grocery_history) By creating a new dictionary in each loop you'll avoid the duplicate error that you're seeing.
answers question: http://stackoverflow.com/q/49683609
type: Answer
accepted answer of: http://stackoverflow.com/q/49683609
has comment: http://stackoverflow.com/comment/86378886
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86235383
type: Comment
score: 0
type: QuestionComment
has text: There's nothing technically wrong with your code. The problem is that you want your algorithm to perform better in terms of accuracy against some desired set of outputs. StackOverflow isn't the place to ask a question like that; start by looking into how other people accomplish this task (e.g., did the first image you posted come along with an article, paper, or tutorial of how they accomplished their lane detection?), and maybe return on the [Data Science exchange](https://datascience.stackexchange.com/) to ask about how to improve your model.
comment on: http://stackoverflow.com/q/49610140

http://stackoverflow.com/comment/86381571
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49685092
has text: @HarshaW Similar, but not by a lot. Read the question carefully.
score: 0

http://stackoverflow.com/q/49709237
has comment: http://stackoverflow.com/comment/86432007
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86432281
tagged with: python
has body: The Dataframe consists of table, the format of which is shown in the Attached image. I apologize for not being able to type the format here as while trying to type the format of the Dataframe, it was getting messed up due to long decimal values, so i thought to attach its snapshot. Country names are the index of the data frame and the cell values consists of corresponding GDP value. The intent is to calculate the average of all the rows for each country. When np.average was applied - #name of Dataframe - GDP def function_average() GDP['Average'] = np.average(GDP.iloc[:,0:]) return GDP function_average() The new column got created reflecting all the values as NaN. I assumed its probably due to the inappropriately formatted cell values. I tried truncating that using the following code - GDP = np.round(GDP, decimals =2) And yet, there was no change in values. The code ran successfully though and there was no error. Please advise, how to proceed in this case, should i try to make change in the spreadsheet itself or attempt to format cell values in Dataframe? I regret for any inconvenience caused for not being able to provide any other required information at this point. please let me know if any other detail is required.
type: Question
tagged with: numpy
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86431940
answer count: 1
has answer: http://stackoverflow.com/a/49709291
accepted answer: http://stackoverflow.com/a/49709291
has title: Trying to truncate decimal values in all the cells of dataframe, but not working
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/a/49691799
score: 3
answers question: http://stackoverflow.com/q/49691342
type: Answer
accepted answer of: http://stackoverflow.com/q/49691342
has body: Your depth1 is an Object type, so you can use: a.depth1 = a.depth1.astype(float) &gt;&gt;&gt; pd.merge(a, b, left_on='depth1', right_on='depth2', how='right').drop('depth1', axis=1) label depth2 0 a 0.0 1 b 0.5 2 b 0.5 3 b 0.5 4 b 0.5 5 c 1.0 6 d 1.5 7 d 1.5 8 d 1.5 9 e 2.0 10 e 2.0 11 f 2.5
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49738678
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49738602
answers question: http://stackoverflow.com/q/49738602
type: Answer
has body: I think you want to include the processing.js in your html template ... this has nothing to do with python or anyother language and is just about how to include script src tags in your html Hello World! processing.py is used to render desktop processing programs in python(using pygame or maybe just OpenGL) ... if you want web you need js ...

http://stackoverflow.com/comment/86409866
comment on: http://stackoverflow.com/a/49697256
has text: There needs to be a foriegn key to `Product` or `Variation` in the `ProductImage`
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/49754826
answers question: http://stackoverflow.com/q/49754349
has body: The result you want can be achieved using numpy.log1p. It computes log(1 + x) with a better numerical precision than numpy.log(1 + x), or, as the docs say: For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy. With this your code becomes: import numpy as np min_f, max_f = -32, -15 f = np.logspace(min_f, max_f, max_f - min_f + 1) y = np.log(2)/(-1*np.log1p(-f)) This can be evaluated consistently: import matplotlib.pyplot as plt plt.loglog(f, y) plt.show() This function will only stop working if your values of f leave the range of floats, i.e. down to 1e-308. This should be sufficient for any physical measurement (especially considering that there is such a thing as a smallest physical time-scale, the Planck-time t_P = 5.39116(13)e-44 s).
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49754349
score: 5
upvote count: 5
type: Answer

transaction-log
tag name: transaction-log
type: Tag
tags question: http://stackoverflow.com/q/49667164

http://stackoverflow.com/q/49605457
has title: 'int' object is not subscriptable in lambda python
has answer: http://stackoverflow.com/a/49605553
downvote count: 0
upvote count: 1
tagged with: sorting
tagged with: lambda
has answer: http://stackoverflow.com/a/49605548
type: AnsweredQuestion
has body: I have created a list of dict which I want to sort according to one element (Period) in the dict T=dict() def TaskGenerator(N): for i in range (0,N): ExcTime=randint(1,20) Period=randint(1,20)+ExcTime Uterlization=ExcTime/Period T[i]={'ID':i+1 , 'ExcTime' : ExcTime, 'Period' : Period, 'Uterlization':Uterlization} sorted(T,key=lambda x:x['Period']) TaskGenerator(6) However, It gives me an error: Traceback (most recent call last): File "C:\Users\wei.du\Desktop\real-time\RMLS.py", line 33, in &lt;module&gt; TaskGenerator(6) File "C:\Users\wei.du\Desktop\real-time\RMLS.py", line 17, in TaskGenerator sorted(T,key=lambda x:x['Period']) File "C:\Users\wei.du\Desktop\real-time\RMLS.py", line 17, in &lt;lambda&gt; sorted(T,key=lambda x:x['Period']) TypeError: 'int' object is not subscriptable I think it means that in "sorted" function, in lambda function, "x" is an integer. But I do not really understand, isn't "x" an instant of T[i] (eg.T[1], which is of a dict type in python). why it complaints about "x" being an integer?
has answer: http://stackoverflow.com/a/49605598
tagged with: python
score: 1
answer count: 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49605637
has answer: http://stackoverflow.com/a/49605637
possible better answer: http://stackoverflow.com/a/49605598

http://stackoverflow.com/q/49647205
has comment: http://stackoverflow.com/comment/86303257
has body: When I run the code in the in the doWork method, by clicking the button1, the progress bar works as expected. However, when I pass the list to the doWork method from other methods (i.e. btn2, btn3), the progress bar just jumps to 100% after it starts. from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys from selenium import webdriver class SeleniumWorker(QtCore.QObject): progressChanged = QtCore.pyqtSignal(int) def doWork(self, lst=['http://www.somesite.com/', 'http://www.somesite.com/page2', 'http://www.somesite.com/page3']): progress = 0 browser = webdriver.Firefox() links = lst for link in links: browser.get(link) progress += 100 / len(links) self.progressChanged.emit(progress) browser.close() class Widget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) lay = QtWidgets.QHBoxLayout(self) progressBar = QtWidgets.QProgressBar() progressBar.setRange(0, 100) button1 = QtWidgets.QPushButton("Start1") button2 = QtWidgets.QPushButton("Start2") button3 = QtWidgets.QPushButton("Start3") lay.addWidget(progressBar) lay.addWidget(button1) lay.addWidget(button2) lay.addWidget(button3) self.thread = QtCore.QThread() self.worker = SeleniumWorker() self.worker.moveToThread(self.thread) self.thread.started.connect(self.worker.doWork) button1.clicked.connect(self.thread.start) button2.clicked.connect(self.btn2) button3.clicked.connect(self.btn3) self.worker.progressChanged.connect(progressBar.setValue) def btn2(self): self.lst2 = ['http://www.somesite.com/page4', 'http://www.somesite.com/page5', 'http://www.somesite.com/page6'] self.worker.doWork(self.lst2) def btn3(self): self.lst3 = ['http://www.somesite.com/page7', 'http://www.somesite.com/page8', 'http://www.somesite.com/page9'] self.worker.doWork(self.lst3) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86303440
linked to: http://stackoverflow.com/q/49631464
tagged with: pyqt
score: 1
has comment: http://stackoverflow.com/comment/86303572
has comment: http://stackoverflow.com/comment/86302925
has title: PyQt progress jumps to 100% after it starts
answer count: 1
tagged with: selenium
tagged with: pyqt5
tagged with: qprogressbar
upvote count: 1
has comment: http://stackoverflow.com/comment/86303460
accepted answer: http://stackoverflow.com/a/49647769
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49647769
has comment: http://stackoverflow.com/comment/86303707
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/86430047
comment on: http://stackoverflow.com/a/49708110
has text: It works well, Thanks! Could I ask a follow-up question please? I have many files, and for each file I extract those characters. I would like to print the those characters +filename into one text file called"outfile.txt". My code doesn't work:print(text[m.start():m.end()+30],filename, file=open('outfile.txt', 'a'))
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86307472
type: AnswerComment
type: Comment
score: 2
has text: A discussion about this can be found in [this ticket](https://code.djangoproject.com/ticket/5373#comment:30). Sadly the status is `wontfix` due to not backwards compatible, but the comments give another option by supplying verbose_name as `verbose_name=ModelA._meta.verbose_name`.
comment on: http://stackoverflow.com/a/49646922

http://stackoverflow.com/comment/86404811
comment on: http://stackoverflow.com/a/49670828
type: Comment
type: AnswerComment
has text: Thanks Umair got it so basically I have to make an ajax call request.post(ur, headers, cookies, data). Thank you so much.
score: 0

http://stackoverflow.com/comment/86470692
type: Comment
type: QuestionComment
has text: If you reached the deadlock, communicate won't 'fix' it. You should use communicate in the first place, which avoids reaching the deadlock.
comment on: http://stackoverflow.com/q/49728472
score: 1

http://stackoverflow.com/comment/86543957
comment on: http://stackoverflow.com/a/49758241
has text: Also, I don't regret asking the question because it was useful to me, but because the background to the question (virtual machine out of my control) was so unique to me I doubt it will serve many others on here. For that reason I plan to delete this question before I suffer too many more down votes.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86247364
type: QuestionComment
comment on: http://stackoverflow.com/q/49620178
has text: Wow, seriously? The author of that program should be slapped with a wet fish. Like, how does that even happen?
score: 0
type: Comment

http://stackoverflow.com/comment/86243445
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49618055
has text: you'd like using udp or tcp? it seems udp&tcp method mixed up in above codes.

http://stackoverflow.com/comment/86439747
has text: Thank you! :) I've got a long loop to implement, so I will check this out later. Thank you again!!:)
type: Comment
comment on: http://stackoverflow.com/a/49709724
type: AnswerComment
score: 0

http://stackoverflow.com/a/49642538
has body: Change this line: url(r'^HomePage/',include('HomePage.urls')), to url(r'^HomePage/',include('homepage.urls')), in your urls.py file, as you have 'homepage' as an app listed in your INSTALLED_APPS not 'HomePage'
downvote count: 0
has comment: http://stackoverflow.com/comment/86294649
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86300078
has comment: http://stackoverflow.com/comment/86295047
has comment: http://stackoverflow.com/comment/86293797
answers question: http://stackoverflow.com/q/49642388

http://stackoverflow.com/comment/87154038
type: Comment
comment on: http://stackoverflow.com/q/49742962
type: QuestionComment
has text: @DyZ I implemented an answer that does what you suggested.
score: 0

http://stackoverflow.com/q/49701161
upvote count: 3
has answer: http://stackoverflow.com/a/49701349
answer count: 1
downvote count: 0
favorite count: 0
type: Question
score: 3
has title: Plotting in python using group by and sum
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49701349
has body: I am trying to plot a graph using the below data. I need to have graph Year vs Txns Original Data which is dataset1= in the code WeekDay Day Month Year Time Txns 1 5 1 2015 3 1 1 5 1 2015 4 4 1 5 1 2015 5 1 1 5 1 2015 7 2 This is the data after group by and sum which is plot= in the code Index Txns (2014, 12) 5786 (2015, 1) 70828 (2015, 2) 63228 (2015, 3) 74320 my code: plot = dataset1.groupby(['Year', 'Month'])['Txns'].sum() plot_df = plot.unstack('Month').loc[:, 'Txns'] plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='2015') plot_df.plot() I get this error everytime: KeyError: 'the label [Txns] is not in the [columns]' How can I fix this?

http://stackoverflow.com/q/49692615
favorite count: 0
tagged with: numpy
has body: I have 5 arrays I want to repeat 600 times and then make into one big array lenE=600 E=array([49.73199462, 49.73799861, 49.74400261, 49.74894938, 49.7500066 ....]) Lat3E=[E]*lenE I do this for all my arrays A, B, C, D and E. E is shorter then the other arrays. When I try to combine then the error is: lat=np.concatenate((Lat3A,Lat3B,Lat3C,Lat3D,Lat3E)) ValueError: all the input array dimensions except for the concatenation axis must match exactly. This is because Lat3E is a combination of 600 arrays. It looks like this: [array([49.73199462, 49.73799861,....)],array([49.73199462, 49.73799861,....]),array([49.73199462, 49.73799861,...)],...] How do I make this long 600 array into 1 long array to make the error go away? Thanks in advance.
has title: Concatenate error after repeating array
type: Question
tagged with: repeat
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/49692847
has comment: http://stackoverflow.com/comment/86397693
has comment: http://stackoverflow.com/comment/86397497
has answer: http://stackoverflow.com/a/49692847
tagged with: concatenation
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49692733
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49692733
upvote count: 1
has comment: http://stackoverflow.com/comment/86397455
has comment: http://stackoverflow.com/comment/86397312

http://stackoverflow.com/comment/86346275
type: Comment
has text: @N08 - It is possible select by `loc` with `df11` with `MultiIndex`. But `merge` is more clean in my opinion.
type: AnswerComment
comment on: http://stackoverflow.com/a/49668092
score: 1

http://stackoverflow.com/a/49688132
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49687914
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86387662
has body: re.match(r"[0-9]{4}\s", file.readline()) This reads one line of the file and matches the regex against it,. .split(...) then uses the result of that as a static delimiter to split the entire file. This has no relation to what you want to achieve. (it actually doesn't even do that because the entire file has already been read, but that's not the point) Perhaps you were thinking of doing something like .split(re.compile(...))? In any case that doesn't work either, str.split doesn't deal with regexes. Try re.split(r"\b[0-9]{4}\s+", file.read()) to split the file into pieces separated by 4-digit numbers. The \b means 'word boundary' and prevents it from splitting on 4 digits that are just the ends of longer numbers. Note that if your file starts with a 4-digit number, the first piece will be empty.
has comment: http://stackoverflow.com/comment/86387715
type: Answer
score: 3
answers question: http://stackoverflow.com/q/49687914

http://stackoverflow.com/comment/86364626
has text: @Dportology There are two solutions to this problem that I can think of. Either prevent users from viewing records that other users are viewing or allow for the use of READ UNCOMITTED. http://satvasolutions.com/deadlock-entity-framework-sql-server/
comment on: http://stackoverflow.com/q/49675751
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49629657
tagged with: python
type: UnansweredQuestion
has body: I need to port an script from python 3 to python 2, the script just take a word and generate all posible segmentations of the words and return the most probable one. When generating the candidates for the segmentation python2 and python3 give very different results. Here is the code I am using: def splits(text, start=0, s=20): """Return a list of all (first, rest) pairs; start &lt;= len(first) &lt;= L.""" return [(text[:i], text[i:]) for i in range(start, min(len(text), s)+1)] def __segment__(self, text): """Return a list of words that is the most probable segmentation of text.""" if not text: return [] else: candidates = [[first] + self.__segment__(rest) for (first, rest) in splits(text, 1)] print(candidates) return max(candidates, key=self.p_words) When printing the candidates I get this answers, the word I was trying to segment is 'casadecampo', the results should be 'casa de campo': Python2 u'o' [[u'p', u'o'], [u'po']] [[u'm', u'p', u'o'], [u'mp', u'o'], [u'mpo']] [[u'a', u'm', u'p', u'o'], [u'am', u'p', u'o'], [u'amp', u'o'], [u'ampo']] [[u'c', u'a', u'm', u'p', u'o'], [u'ca', u'm', u'p', u'o'], [u'cam', u'p', u'o'], [u'camp', u'o'], [u'campo']] [[u'e', u'c', u'a', u'm', u'p', u'o'], [u'ec', u'a', u'm', u'p', u'o'], [u'eca', u'm', u'p', u'o'], [u'ecam', u'p', u'o'], [u'ecamp', u'o'], [u'ecampo']] [[u'd', u'e', u'c', u'a', u'm', u'p', u'o'], [u'de', u'c', u'a', u'm', u'p', u'o'], [u'dec', u'a', u'm', u'p', u'o'], [u'deca', u'm', u'p', u'o'], [u'decam', u'p', u'o'], [u'decamp', u'o'], [u'decampo']] [[u'a', u'd', u'e', u'c', u'a', u'm', u'p', u'o'], [u'ad', u'e', u'c', u'a', u'm', u'p', u'o'], [u'ade', u'c', u'a', u'm', u'p', u'o'], [u'adec', u'a', u'm', u'p', u'o'], [u'adeca', u'm', u'p', u'o'], [u'adecam', u'p', u'o'], [u'adecamp', u'o'], [u'adecampo']] [[u's', u'a', u'd', u'e', u'c', u'a', u'm', u'p', u'o'], [u'sa', u'd', u'e', u'c', u'a', u'm', u'p', u'o'], [u'sad', u'e', u'c', u'a', u'm', u'p', u'o'], [u'sade', u'c', u'a', u'm', u'p', u'o'], [u'sadec', u'…
has comment: http://stackoverflow.com/comment/86266046
has title: List comprehension difference between python 2 and 3
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86269050
has comment: http://stackoverflow.com/comment/86266189
has comment: http://stackoverflow.com/comment/86266244
score: 1
has comment: http://stackoverflow.com/comment/86266173
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49631720
type: Question
upvote count: 2

http://stackoverflow.com/comment/86266173
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/49629657
has text: you're not too far from a [mcve]. Remove the self stuff, create an input and make a program that runs without external data or user interaction.
type: Comment

http://stackoverflow.com/q/49697035
has title: Addition of multiple image of one product variation django eCommerce app
type: Question
tagged with: django-templates
type: UnansweredQuestion
tagged with: django
has body: I am trying to make a django eCommerce app in which a product has different variations. For example, a product T-shirt has different colors (red, green...). For each variation I would like to upload at least three different images. At the moment, I can only upload one image per variation. Code of my app: class Product(models.Model): title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) default_image = models.ImageField(upload_to=image_upload_to_prod, blank=True, null=True) slug = models.SlugField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Products:SingleProduct', kwargs={'pk': self.pk}) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) DEFAULT = 'DEFAULT' RED = 'RED' BLUE = 'BLUE' TYP = ( (DEFAULT, 'DEFAULT'), (RED, 'RED'), (BLUE, 'BLUE'), ) color = models.CharField(max_length=100, choices=TYP, default=DEFAULT) image = models.ImageField(upload_to=upload_location, blank=True, null=True) def get_price(self): if self.sale_price is not None: return self.sale_price else: return self.price def get_image(self): if self.image is not None: return self.product.default_image else: return self.image def get_absolute_url(self): return self.product.get_absolute_url() def upload_location(object, filename): title = object.product.title slug = slugify(title) return "products/%s" % (slug) How can I add multiple images and show them in the template?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49697256
tagged with: python

http://stackoverflow.com/a/49716468
has comment: http://stackoverflow.com/comment/86457904
score: 0
has body: It looks like there is a problem with input/output. Try to run it from cmd or bash if you are on Ubuntu.If that doesn't work try from Python IDLE.
type: Answer
answers question: http://stackoverflow.com/q/49701932

http://stackoverflow.com/comment/86452757
score: 0
comment on: http://stackoverflow.com/q/49719616
type: Comment
type: QuestionComment
has text: I don't know if this will help with the problem, but the way you are building your network is a problem. Remove the sigmoid nonlinearity from the last layer. The softmax needs logits to work properly. If you push it through a sigmoid, it can't work as well as it should. ` def forwardprop(X, w_1, w_2, w_3): h_1 = tf.nn.sigmoid(tf.matmul(X, w_1)) h_2 = tf.nn.sigmoid(tf.matmul(h_1, w_2)) yhat = tf.matmul(h_2, w_3) return yhat `

http://stackoverflow.com/a/55667399
upvote count: 1
answers question: http://stackoverflow.com/q/49685775
type: Answer
has body: I had a similar problem the other day. First, you can try running python -m pip install &lt;module_name&gt;. Sometimes depending on how your environment is set up, just running pip install &lt;module_name&gt; doesn't work. If that doesn't fix your problem you can uninstall Python and manually delete all related directories that were created upon install (mine was located in C:\Users\username\AppData\Local\Programs\Python). I did this and upon reinstall, I no longer had the error.
score: 1
downvote count: 0

http://stackoverflow.com/q/49742317
has body: I am trying to implement a k-means clustering algorithm from scratch using python. I am having problems updating the centroid values for each cluster. The code below shows where I am up to so far. I have initially clustered each data point into one of k clusters. AllData contains 329 rows; each row is a word followed by 300 features followed by the number of the cluster it has been assigned to (values 1 to 4). What I am trying to do in my loop is start off by creating an array A which only holds the rows from AllData that have been assigned to the first cluster. Then I want to take the mean of each of the feature columns in A and update the centroid to this. The loop should iteratively do this for all 4 clusters. k = 4 i = 1 while (i &lt;= k): A = AllData[:,1:301][AllData[:,301] == i] centroids[i-1:i,:] = A.mean(axis=0) i = i + 1 The values of the 4 rows in the centroids array are updating correctly. The problem I am having is that the 4 updated centroid values are also rewriting over the first 4 rows of AllData. I don't want this to happen. The AllData array should remain unchanged. Any help would be much appreciated!
has answer: http://stackoverflow.com/a/49746592
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: k-means
tagged with: cluster-analysis
has title: Updating centroid values k-means clustering Python
tagged with: python
upvote count: 2
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86437292
has text: Anyway, nobody can tell you what's the "best" way to do this. The answer depends on a lot of different things—from details about your server and requests that we don't know, to which style of programming you feel more comfortable with or find easier to learn. So you'll have to look through the examples yourself to get a feel for what seems like it'll work for you, then try to build something.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49711843
type: Comment

http://stackoverflow.com/a/49759405
has body: Your guess is right, the response image is a sort of accumulator, the higher the value, the more "cornery" the pixel is. To extract the corners location, you can call the function corner_peaks on the result returned by corner_fast About the how to is it computed, the documentation gives these two references: [1] Edward Rosten and Tom Drummond “Machine Learning for high-speed corner detection”, http://www.edwardrosten.com/work/rosten_2006_machine.pdf [2] Wikipedia, “Features from accelerated segment test”, https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test Finally, just know that scikit-image is open source and you can therefore go see the details of the code itself https://github.com/scikit-image/scikit-image/tree/master/skimage
answers question: http://stackoverflow.com/q/49690962
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86394306
comment on: http://stackoverflow.com/a/49691262
score: 0
has text: thank you for the reaction. I tried that but not it does not split at all anymore. Trying to make it file.readline() in stead of file.read()
type: AnswerComment
type: Comment

mysql
tags question: http://stackoverflow.com/q/49755066
tags question: http://stackoverflow.com/q/49653155
tags question: http://stackoverflow.com/q/49722608
tags question: http://stackoverflow.com/q/49631156
tags question: http://stackoverflow.com/q/49615914
type: Tag
tag name: mysql
tags question: http://stackoverflow.com/q/49722064
tags question: http://stackoverflow.com/q/49738452
tags question: http://stackoverflow.com/q/49627534
tags question: http://stackoverflow.com/q/49709143
tags question: http://stackoverflow.com/q/49634105
tags question: http://stackoverflow.com/q/49613287
tags question: http://stackoverflow.com/q/49750354
tags question: http://stackoverflow.com/q/49735296
tags question: http://stackoverflow.com/q/49653199
tags question: http://stackoverflow.com/q/49750220
tags question: http://stackoverflow.com/q/49744560
tags question: http://stackoverflow.com/q/49684136
tags question: http://stackoverflow.com/q/49713561
tags question: http://stackoverflow.com/q/49642091
tags question: http://stackoverflow.com/q/49738576
tags question: http://stackoverflow.com/q/49719333
tags question: http://stackoverflow.com/q/49708302
tags question: http://stackoverflow.com/q/49619531
tags question: http://stackoverflow.com/q/49736428
tags question: http://stackoverflow.com/q/49604929
tags question: http://stackoverflow.com/q/49610591
tags question: http://stackoverflow.com/q/49644252
tags question: http://stackoverflow.com/q/49692172
tags question: http://stackoverflow.com/q/49632876
tags question: http://stackoverflow.com/q/49620031
tags question: http://stackoverflow.com/q/49643578
tags question: http://stackoverflow.com/q/49620503
tags question: http://stackoverflow.com/q/49629508
tags question: http://stackoverflow.com/q/49636382
tags question: http://stackoverflow.com/q/49696346
tags question: http://stackoverflow.com/q/49688208
tags question: http://stackoverflow.com/q/49718241
tags question: http://stackoverflow.com/q/49657732

amazon-kinesis
tags question: http://stackoverflow.com/q/49713393
type: Tag
tag name: amazon-kinesis

http://stackoverflow.com/comment/86375464
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49676420
has text: You have win_unicode_console, so why use codepage 65001? The console's implementation of codepage 65001 is broken in so many ways across versions of Windows.
type: QuestionComment

http://stackoverflow.com/a/49641346
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49625006
has body: Sending Images in Realtime over PubNub Typically your main challenge is image size. Your image will be too big. And PubNub allows ~34KB max. What you can do is compress and shrink the image before sending. Modern compression works nicely these days. Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height). The proper size is oldsize*ratio. There is of course also a library method to do this: the method Image.thumbnail. Below is an (edited) example from the PIL documentation. import Image size = 512, 512 # change this to match (check aspect ratio) im = Image.open('./path/to/file.png') im.resize( size, Image.ANTIALIAS ) im.save( './path/to/file.jpg', 'JPEG' ) im.close() Now you can base64 encode the new .jpg file to send over PubNub.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86457874
has text: Please offer a _minimal_ working example. This is to much code for such a simple problem.
comment on: http://stackoverflow.com/q/49722187
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49602688
has title: Install third party package using conda
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49602920
has comment: http://stackoverflow.com/comment/86212663
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86212621
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49602920
tagged with: anaconda
has comment: http://stackoverflow.com/comment/86212906
has body: I have installed a package using command: pip3 install --upgrade ShopifyAPI Requirement already up-to-date: ShopifyAPI in /usr/local/lib/python3.5/dist-packages Requirement already up-to-date: pyactiveresource>=2.1.2 in /usr/local/lib/python3.5/dist-packages (from ShopifyAPI) Requirement already up-to-date: PyYAML in /usr/local/lib/python3.5/dist-packages (from ShopifyAPI) Requirement already up-to-date: six in /usr/local/lib/python3.5/dist-packages (from ShopifyAPI) Also I wanted to use it in jupyter notebook: conda install -c conda-forge ShopifyAPI Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: - shopifyapi Current channels: - https://conda.anaconda.org/conda-forge/linux-64 - https://conda.anaconda.org/conda-forge/noarch - https://repo.anaconda.com/pkgs/main/linux-64 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/free/linux-64 - https://repo.anaconda.com/pkgs/free/noarch - https://repo.anaconda.com/pkgs/r/linux-64 - https://repo.anaconda.com/pkgs/r/noarch - https://repo.anaconda.com/pkgs/pro/linux-64 - https://repo.anaconda.com/pkgs/pro/noarch Is there any way I can use the package in notebook that was installed using pip3 install command or install those packages using conda?
has comment: http://stackoverflow.com/comment/86212704

http://stackoverflow.com/comment/86446431
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49704170
has text: Yes, I did... well, `reduce_sum(x, axis=0)` means summing up each row, thus resulting in a column vector; `reduce_mean` is just `reduce_sum` divided by N; `batch_norm(x, axis=0)` means normalizing each row. You said "When I set the axis to 0, it is giving the average of each column", it is literally wrong; it is giving the average of rows/each row.

http://stackoverflow.com/q/49738053
has comment: http://stackoverflow.com/comment/86490527
has answer: http://stackoverflow.com/a/49738299
has title: Python dataframe: Finding a value in same row as a defined value in a different column
score: 8
has body: I have a large Pandas dataframe: Time P T R H 00000.0 1004.6 12.2 96 12 00001.0 1004.2 12.1 96 15 00002.0 1003.5 11.9 96 21 00003.0 1002.8 12.0 96 27 00004.0 1002.0 12.1 96 34 00005.0 1001.4 12.1 96 39 00006.0 1000.3 12.2 96 48 00007.0 999.5 12.1 96 55 00008.0 998.9 12.2 96 59 00009.0 998.0 12.1 96 67 00010.0 997.3 13.1 96 73 00011.0 996.9 13.2 97 76 00013.0 995.3 13.3 97 90 00014.0 994.6 13.6 97 96 00015.0 994.3 13.5 97 98 00016.0 993.6 13.5 96 104 00017.0 992.5 13.3 96 114 00018.0 991.8 13.3 96 119 00019.0 991.7 13.7 97 120 I want to find the value in a row when a value in another column (same row) has a defined value. For example, I want to write a code that find what the "T" value is in same row where the "P" value is 1002.8.
answer count: 2
has comment: http://stackoverflow.com/comment/86490484
accepted answer: http://stackoverflow.com/a/49738144
downvote count: 0
has answer: http://stackoverflow.com/a/49738144
favorite count: 0
type: Question
tagged with: indexing
type: AnsweredQuestion
upvote count: 8
tagged with: if-statement
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49738299
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/86524468
has text: Thanks @ImportanceOfBeingErnest this solved the problem indeed: ax.set_yticks([4.5,5.5,6.5,7.5,8.5])
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49749778
score: 0

point-clouds
tags question: http://stackoverflow.com/q/49637221
tag name: point-clouds
type: Tag
tags question: http://stackoverflow.com/q/49645003
tags question: http://stackoverflow.com/q/49636643

http://stackoverflow.com/comment/86515143
has text: imdecode does not need to know the compression type, it will look at the data header to decide which compression technique has to be used. If you want to re-encode the image with the same codec, you'll probably have to evaluate the image header (or maybe the http header??) yourself.
comment on: http://stackoverflow.com/q/49749294
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49677790
has answer: http://stackoverflow.com/a/49677855
score: 6
has title: Convert Python Bytes to String Without Encoding
has answer: http://stackoverflow.com/a/49677839
has body: I am using Python 3.6 and I have an image as bytes: img = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00' I need to convert the bytes into a string without encoding so it looks like: raw_img = '\xff\xd8\xff\xe0\x00\x10JFIF\x00' The goal is to incorporate this into an html image tag: &lt;img src="'data:image/png;base64," + base64.b64encode(raw_img) + "' /&gt;"
linked to: http://stackoverflow.com/q/606191
has answer: http://stackoverflow.com/a/49677853
upvote count: 7
has answer: http://stackoverflow.com/a/70966529
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49677935
has answer: http://stackoverflow.com/a/71074307
type: UnansweredQuestion
tagged with: python
answer count: 6

http://stackoverflow.com/comment/86319292
type: Comment
has text: It was worth a shot. This is odd. What is the result if you select `now - Record.date` and `now - delta`? See if those values are being computed as you expect.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49654885

http://stackoverflow.com/comment/86566447
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49751989
has text: Can you try `conda install --offline notebook-5.0.0.tar.bz2`?

http://stackoverflow.com/comment/86317145
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49653854
has text: I also added a config to change some configuration with Apache. I had an issue with the http not redirected to https and I solved that with the config. If you need that I can update the answer.

http://stackoverflow.com/a/49637357
upvote count: 105
has comment: http://stackoverflow.com/comment/86282487
has comment: http://stackoverflow.com/comment/89680857
score: 104
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/124397155
has comment: http://stackoverflow.com/comment/94393090
accepted answer of: http://stackoverflow.com/q/49637086
has comment: http://stackoverflow.com/comment/93320723
answers question: http://stackoverflow.com/q/49637086
has comment: http://stackoverflow.com/comment/93324909
type: Answer
has body: Queue.task_done is not there for the workers' benefit. It is there to support Queue.join. If I give you a box of work assignments, do I care about when you've taken everything out of the box? No. I care about when the work is done. Looking at an empty box doesn't tell me that. You and 5 other guys might still be working on stuff you took out of the box. Queue.task_done lets workers say when a task is done. Someone waiting for all the work to be done with Queue.join will wait until enough task_done calls have been made, not when the queue is empty. eigenfield points out in the comments that it seems really weird for a queue to have task_done/join methods. That's true, but it's really a naming problem. The queue module has bad name choices that make it sound like a general-purpose queue library, when it's really a thread communication library. It'd be weird for a general-purpose queue to have task_done/join methods, but it's entirely reasonable for an inter-thread message channel to have a way to indicate that messages have been processed. If the class was called thread_communication.MessageChannel instead of queue.Queue and task_done was called message_processed, the intent would be a lot clearer. (If you need a general-purpose queue rather than an inter-thread message channel, use collections.deque.)
has comment: http://stackoverflow.com/comment/86283954
has comment: http://stackoverflow.com/comment/86283799
has comment: http://stackoverflow.com/comment/86282530

http://stackoverflow.com/q/49744453
tagged with: tweepy
has body: I am creating a twitter bot with Python to retweet to any mention with a message. Below is the part of code that I am using to retweet: twitter_client = API(auth_handler) publish = True if publish: # print(data) twitter_client.retweet(tweet['id']) This is doing retweet correctly, but I am not sure which field (from on_data) to use so that my retweet goes with a message like "Thanks for your mention, we are happy to serve you"
type: Question
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49744761
downvote count: 0
upvote count: 1
tagged with: python
has title: Want to re-tweet with a message using Python
favorite count: 0
score: 1
tagged with: twitter

http://stackoverflow.com/comment/86409085
comment on: http://stackoverflow.com/a/49683957
type: AnswerComment
has text: From playing a little more I think that the histogram just isn't going to work, it doesn't seem to accurately portray density
score: 0
type: Comment

http://stackoverflow.com/comment/86422986
score: 0
has text: @eternity1 - For you too!
type: Comment
comment on: http://stackoverflow.com/a/49704738
type: AnswerComment

http://stackoverflow.com/comment/86633845
type: AnswerComment
has text: @Cracoras The problem is that `process_function` is sometimes invoking async functions, and those need to be awaited. In other words, while you can mix ordinary and async functions, async ones always need to be awaited, so if you do a dispatch that passes through a single code path, `process_function` does, all of its callees must be async, and you need to await them. As a quick fix, you can use `iscoroutine` to see if the result needs to be awaited, [like this](https://pastebin.com/LAtxBsEi).
comment on: http://stackoverflow.com/a/49665627
score: 0
type: Comment

http://stackoverflow.com/q/49658423
score: 2
has body: I am trying to build a LSTM model on sequential data having 500 timestamp with 6M sequences. Due to the limitations of hardware configuration I can't convert the entire data into numpy array. In kears, is it okay if I create data in chunks and feed the model. Below is the method I am using. For epoch in range(10): While I&lt;6000000: Data1=np.array(datax[I:I+100000]) Data2=np.array(datay[I:I+100000]) Model.fit(Data1, Data2, epochs=1, batch_size=100) I=I+100000 Is this method correct?
has answer: http://stackoverflow.com/a/49658625
downvote count: 0
answer count: 1
tagged with: recurrent-neural-network
tagged with: keras
favorite count: 0
type: Question
has title: Keras LSTM model on huge data
upvote count: 2
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
tagged with: lstm

http://stackoverflow.com/comment/86279344
score: 0
comment on: http://stackoverflow.com/q/49635931
has text: 33k rows might just fit in memory, can you use `pandas`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86364788
comment on: http://stackoverflow.com/a/49676704
type: Comment
score: 0
has text: `t.split("\n")` is just a stand-in for `file` in this answer, to provide a sequence of strings to iterate over.
type: AnswerComment

http://stackoverflow.com/comment/86397216
type: Comment
has text: ok it's a valid logical operation, but why in this case it print the result on the screen? since the first part was evaluated to `None` then the second evaluation `None and (True or False)` shouldn't print anything unless i run it in the shell. for example: running `None and (True or False)` wouldn't print the result to user if it run in a code editor like SublimeText3
comment on: http://stackoverflow.com/a/49692056
type: AnswerComment
score: 0

http://stackoverflow.com/a/54727648
score: 35
answers question: http://stackoverflow.com/q/49704364
type: Answer
has comment: http://stackoverflow.com/comment/120255853
has body: Changing the default python version system wide can break some applications that depend on python2. The alternative solution would be to create an alias. If you are using zsh (the default on Mac OS) run the following from terminal: echo 'alias python="python3"' >> ~/.zshrc echo 'alias pip="pip3"' >> ~/.zshrc If you're still using bash, echo into .bash_profile instead: echo 'alias python="python3"' >> ~/.bash_profile echo 'alias pip="pip3"' >> ~/.bash_profile Note that the alias won't be defined until a new terminal session is started. To have the changes take affect within the same terminal window, you'll need to source your profile first: source ~/.zshrc or for bash: source ~/.bash_profile
has comment: http://stackoverflow.com/comment/132702640
has comment: http://stackoverflow.com/comment/120261672
has comment: http://stackoverflow.com/comment/120255935
upvote count: 35
downvote count: 0

http://stackoverflow.com/a/49721309
has body: x = [12, 37, 64, 159, 205, 225, 239, 252, 257] print([i for i in zip(x[::1], x[1::])]) Output: [(12, 37), (37, 64), (64, 159), (159, 205), (205, 225), (225, 239), (239, 252), (252, 257)] In slicing you need to be careful with step number as you used 2 as step number it will always used 2nd element for it's position. so instead writing x[::2] you are supposed to write x[::1] now the default step for slice is 1 hence you don't need to mention it so you can write only x instead of x[::1] and for next you can just write x[1:] instead of x[1::]
downvote count: 1
answers question: http://stackoverflow.com/q/49721261
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/86358680
type: QuestionComment
comment on: http://stackoverflow.com/q/49673723
score: 0
has text: @Chris_Rands Yes, see my edit from a few seconds ago.
type: Comment

http://stackoverflow.com/q/49684290
downvote count: 1
has title: Web Scraping Nytimes
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49684324
has answer: http://stackoverflow.com/a/49684324
has body: My code: url="https://www.nytimes.com/reuters/2018/04/05/business/05reuters-usa- tradechina-ip.html" html = urlopen(url).read() soup = BeautifulSoup(html,'html.parser') def text_from_html(body): texts = soup.find_all('p',class_="story-body-text story-content") return texts print(text_from_html(html)[0]) My Output: How can I print just the text and not the other information?
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
answer count: 1
tagged with: web-scraping

http://stackoverflow.com/comment/86529120
has text: @kab if your string can contains more than what's in your question, do yourself and the world a favour: edit your post to make this point clear and post a couple (eventually shortened) examples of __real__ data.
comment on: http://stackoverflow.com/a/49756968
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49677177
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49677114
has body: When working with sets, > and &lt; are relational operators. hence, these operations are used to see if one set is the proper subset of the other, which is False for as neither is the proper subset of the other.
upvote count: 2

http://stackoverflow.com/comment/86239092
type: QuestionComment
comment on: http://stackoverflow.com/q/49616162
score: 0
has text: in what format you want to arrange the data?
type: Comment

http://stackoverflow.com/comment/86375160
comment on: http://stackoverflow.com/a/49655874
has text: You mean like this: https://cloud.google.com/pubsub/docs/push ? There's two types of subscriptions, that describes the push method, so when you setup the subscription, you setup an endpoint for the messages to be sent. The process is described there. It also has an example of what the response will look like.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49717267
has comment: http://stackoverflow.com/comment/86448167
answers question: http://stackoverflow.com/q/49717224
has comment: http://stackoverflow.com/comment/86447625
has body: You can use this: import sys n = int(sys.argv[1]) for i in range(n): for j in range(n): a,b =i,j while b: a, b = b, a%b GCD = a if GCD == 1: sys.stdout.write("* ") else: sys.stdout.write(" ") print
has comment: http://stackoverflow.com/comment/86447530
type: Answer
has comment: http://stackoverflow.com/comment/86447829
accepted answer of: http://stackoverflow.com/q/49717224
score: 0
has comment: http://stackoverflow.com/comment/86448002
type: AcceptedAnswer

http://stackoverflow.com/a/49626353
type: Answer
has comment: http://stackoverflow.com/comment/86260010
has comment: http://stackoverflow.com/comment/86261166
has comment: http://stackoverflow.com/comment/86260383
score: 2
has body: You can use the str.isdigit method. &gt;&gt;&gt; list_1 = ['50', 'ALA', 'A', '53', '5', 'N', '4'] &gt;&gt;&gt; list_1 = [x for x in list_1 if x.isdigit()] &gt;&gt;&gt; list_1 ['50', '53', '5', '4'] Note that this will not work for floating point representations of numbers. &gt;&gt;&gt; '650.43'.isdigit() False If you want to filter these as well, write a traditional loop. &gt;&gt;&gt; list_1 = ['50', '650.43', 'test'] &gt;&gt;&gt; result = [] &gt;&gt;&gt; for x in list_1: ... try: ... float(x) ... result.append(x) ... except ValueError: ... pass ... &gt;&gt;&gt; result ['50', '650.43']
accepted answer of: http://stackoverflow.com/q/49626310
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86260544
downvote count: 0
answers question: http://stackoverflow.com/q/49626310

http://stackoverflow.com/q/49631404
upvote count: 0
answer count: 2
has title: Training loss doesn't match validation loss when X_train = X_test
downvote count: 1
tagged with: machine-learning
tagged with: keras
possible better answer: http://stackoverflow.com/a/49631485
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49631485
has comment: http://stackoverflow.com/comment/86271161
has comment: http://stackoverflow.com/comment/86273455
has answer: http://stackoverflow.com/a/49631516
accepted answer: http://stackoverflow.com/a/49631516
tagged with: neural-network
tagged with: python
score: -1
has body: I am running: D.fit(X_train, y_train, nb_epoch=12,validation_data=(X_train,y_train)) But I get outputs like: Train on 61936 samples, validate on 61936 samples Epoch 1/12 61936/61936 [==============================] - 10s 166us/step - loss: 0.0021 - val_loss: 1.5650e-04 Epoch 2/12 61936/61936 [==============================] - 10s 165us/step - loss: 0.0014 - val_loss: 6.6482e-04 ... Epoch 10/12 61936/61936 [==============================] - 11s 170us/step - loss: 0.0104 - val_loss: 9.6666e-05
type: AnsweredQuestion

http://stackoverflow.com/comment/138160606
has text: what if your line looks like: `"something", "something, something", "something else", "3,3,3,5,5"` ?? the row.split(",") will not parse properly.
score: 0
comment on: http://stackoverflow.com/a/49693997
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86504414
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49730806
type: Comment
has text: This solution will be quite slow (because it uses apply+lambda). If both formats exist in the same column, there are still vectorized solutions which will be efficient.

http://stackoverflow.com/comment/86303355
type: Comment
has text: This can be used to compare easily for any value. For ex using re.findall('(?<!\S)\d(?!\S)', s) for comparing with values less than 20 or any two digit value may fail.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49643433

http://stackoverflow.com/a/78218489
has body: If you are using pyproject.toml here's the correct syntax to @xtofl solution: [tool.pylint.typecheck] signature-mutators=['click.decorators.option', 'click.decorators.argument', 'click.decorators.version_option', 'click.decorators.help_option', 'click.decorators.pass_context', 'click.decorators.confirmation_option' ]
type: Answer
answers question: http://stackoverflow.com/q/49680191
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49729362
score: 0
tagged with: deep-learning
tagged with: loss-function
answer count: 1
has body: I try to build a model that will identify by data and try to see the LOSS function loss =tf.reduce_mean(-(y_ * tf.log(y)+(1- y_)* tf.log (1-y))) But as of now I only get NAN on the prediction and printing NAN in the LOSS function np_labels = np.array(labels) np_labels = np_labels.reshape([np_labels.shape[0], 1]) features = 910 hidden_layer_nodes = 100 x = tf.placeholder(tf.float32, [None, features]) y_ = tf.placeholder(tf.float32, [None, 1]) W1 = tf.Variable(tf.truncated_normal([features,hidden_layer_nodes], stddev=0.1)) b1 = tf.Variable(tf.constant(0.1, shape=[hidden_layer_nodes])) z1 = tf.add(tf.matmul(x,W1),b1) a1 = tf.nn.relu(z1) W2 = tf.Variable(tf.truncated_normal([hidden_layer_nodes,1], stddev=0.1)) b2 = tf.Variable(0.) z2 = tf.matmul(a1,W2) + b2 y = 1 / (1.0 + tf.exp(-z2)) loss =tf.reduce_mean(-(y_ * tf.log(y)+(1- y_)* tf.log (1-y))) update = tf.train.AdamOptimizer(0.01).minimize(loss) sess = tf.Session() sess.run(tf.global_variables_initializer()) for i in range(0,50): sess.run(update, feed_dict = {x:fvecs, y_:np_labels}) print(sess.run(loss, feed_dict={x: fvecs, y_: np_labels})) # sess.run(update, feed_dict = {x:data_x, y_:data_y}) # print(sess.run(loss, feed_dict={x: data_x, y_: data_y})) print('prediction: ', y.eval(session=sess, feed_dict = {x:[[493.9, 702.6, ..... i want to print the loss Thanks
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49729928
has title: nan on loss function tensorflow
downvote count: 1

http://stackoverflow.com/comment/86261903
comment on: http://stackoverflow.com/a/49626715
type: AnswerComment
score: 0
has text: Hey there, I am trying what you said but I dont know where is the source code for numpy in my computer. Once I feel like I almost found it, the command line said: "This is the wrong setup.py file to run "
type: Comment

http://stackoverflow.com/comment/86502156
score: 0
comment on: http://stackoverflow.com/q/49743629
has text: In case anyone is confused the picture of the current dataset doesn't depict its full width since it is 63 columns wide and may have impacted viewing in the browser.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86283597
type: AnswerComment
comment on: http://stackoverflow.com/a/49636565
score: 0
type: Comment
has text: Hi @MadPhysicist this is the [link](https://stackoverflow.com/questions/49637965/how-do-i-pickle-pyephem-objects-for-multiprocessing) to my other question. Thank you a lot for your help so far!

http://stackoverflow.com/comment/86416951
type: Comment
type: QuestionComment
score: 0
has text: The whole point of `pbkdf2` is to be computationally expensive and take a long time. Is your goal to prevent people from brute-forcing hashes by submitting lots of different inputs? If that's the case, you can use Bear Brown's suggestion and hash the input from the user as it comes in, and then compare it to the hashes in the database.
comment on: http://stackoverflow.com/q/49701383

http://stackoverflow.com/comment/86462886
type: Comment
type: QuestionComment
has text: @RahulBharadwaj, I'm trying to seperate Jill, Allen Golden , Monkey Washington,DC I've successfully done the first and the third, but the whitespace between Golden(space),(space)monkey is tripping me up
comment on: http://stackoverflow.com/q/49724412
score: 0

http://stackoverflow.com/q/49733305
linked to: http://stackoverflow.com/q/16249736
type: Question
upvote count: 4
tagged with: python-3.x
tagged with: mongodb
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 4
has body: I am facing performance problem while reading data from mongodb using pymongo and creating data frame from the results of mongo query. I have below type of documents in a collection and i have totally 5 million documents in a collection with the size of 4.7 Gb of data { "CUST_LEVEL1" : "ALL CHANNELS", "CUST_LEVEL2" : "CUSTOMER CHANNEL", "CUST_LEVEL3" : "Commercial Rebate", "CUST_LEVEL4" : "Express Scripts Inc.", "CUST_LEVEL5" : "UBC ESI MC NON STND", "CUST_LEVEL6" : "BR - 103 OPEN 103-140Price Protection", "PRODUCT_LEVEL1" : "Allergan USA Inc.", "PRODUCT_LEVEL2" : "SPECIALIZE", "PRODUCT_LEVEL3" : "MED DERM", "PRODUCT_LEVEL4" : "TAZORAC", "PRODUCT_LEVEL5" : 46, "PRODUCT_LEVEL6" : "Tazorac .1% Gel 30 G", "METHODOLOGY" : "", "CALCULATION_PERIODS" : "", "FREQ_CAL_START_PERIOD_SID" : "", "FREQ_CAL_END_PERIOD_SID" : "", "PERIOD_DATE" : "2015-01-01 00:00:00", "ACCOUNT_GROWTH" : 2, "PRODUCT_GROWTH" : 3, "CCP_DETAILS_SID" : 563275, "PROJECTION_SALES" : 0, "PROJECTION_UNITS" : 0, "ACTUAL_SALES" : 0, "ACTUAL_UNITS" : 0, "EXFACTORY_ACTUAL_SALES" : 0, "EXFACTORY_ACTUAL_UNITS" : 0, "EXFACTORY_CUST_ACTUAL_SALES" : 0, "EXFACTORY_CUST_ACTUAL_UNITS" : 0, "EXFACTORY_FORECAST_SALES" : 0, "EXFACTORY_FORECAST_UNITS" : 0, "EXFACTORY_CUST_FORECAST_UNITS" : 0, "EXFACTORY_CUST_FORECAST_SALES" : 0, "ITEM_PRICE" : 0 } I have followed this answer to read data from mongodb using Pymongo and below code is used to read data from 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['EVENTSTABLE'].find({},{"PERIOD_DATE":1,"CCP_DETAILS_SID":1,"ACCOUNT_GROWTH":1,"PRODUCT_GROWTH":1,"ACTUAL_SALES":1, "EXFACTORY_FORECAST_SALES":1,"EXFACTORY_FORECAST_UNITS":1,"ITEM_PRICE":1,"PROJECTION_SALES":1}) # Expand the cursor and construct the DataFrame fd = pd.DataFrame(list(cursor)) After reading data from mongodb i wrote below code to derive "PROJECTION_SALES" field. fd['PROJECTION_SALES']=((((fd['ACCOUNT_GROWT…
favorite count: 0
has title: Python pandas and MongoDB performance
has comment: http://stackoverflow.com/comment/128028159
tagged with: pandas

http://stackoverflow.com/q/49641791
type: AnsweredQuestion
tagged with: classification
upvote count: 0
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/49641858
tagged with: scikit-learn
has title: Poor real-time SVM performance
has answer: http://stackoverflow.com/a/49641858
favorite count: 0
type: Question
has body: I'm working on a gesture recognition program. My dataset consist of hands in different poses. Im trying to use an SVM to get a baseline before I jump into neural networks. My dataset has 6 classes I'm trying to classify, with around 1000 examples for each class. I used an 80-20 split. 80% for training and 20% for testing. After running the SVM model on the testing set I'm plotting a confusion-matrix which is showing me that it's getting ~96% Precision , ~96% Recall, and ~96% F1-Score. Here are some examples of my training set images: https://imgur.com/gwRSx3C https://imgur.com/UxUPj5t https://imgur.com/wXcaUq6 Webcam Images https://imgur.com/j97cTnp https://imgur.com/6QDHMAD https://imgur.com/C9DELsr Here are some images from my webcam. I'm stoked naturally. Only downside is that when I hook up my model to a webcam for real-time inference, the model is borderline butt. Anyone have any ideas as to why it might be doing so badly if the precision, recall, f1 are so high?
tagged with: python
tagged with: computer-vision
score: -2
tagged with: svm

http://stackoverflow.com/a/49635660
type: Answer
has comment: http://stackoverflow.com/comment/86279183
answers question: http://stackoverflow.com/q/49635591
has body: You are doing += do the keylist which adds to that list, you need to do it to the val array. for i in zip(list1, list2, list3): val = map(str,i) val += 'X' # you can combine this and the above if you want to look like: #val = map(str, i) + 'X' keylist.append("/".join(val)) print(keylist)
score: 1
has comment: http://stackoverflow.com/comment/86279128
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86279174

http://stackoverflow.com/q/49664631
answer count: 1
has comment: http://stackoverflow.com/comment/86339126
tagged with: checksum
has comment: http://stackoverflow.com/comment/86363037
has comment: http://stackoverflow.com/comment/86363012
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86844876
tagged with: linux
has title: Linux checksum of directory
has answer: http://stackoverflow.com/a/49914221
score: -2
tagged with: python
has body: I need to check if a directory and all its sub-directories and files have had any changes to: file permission file name file contents I'd like to get a checksum out of it. Using tar doesn't seem to work well, because it contains file modify time, and maybe access time too. I'm not sure. Python's checksumdir doesn't contain any metadata at all, not even file name. Anyone know of a way to accomplish this? Thanks.
has comment: http://stackoverflow.com/comment/86355273
upvote count: 0
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/86398373
type: Comment
score: 0
has text: In machine learning , we do lot of pre-processing things, after that only we pass data for training. but while predicting we dont know what was the process used.
type: QuestionComment
comment on: http://stackoverflow.com/q/49692436

http://stackoverflow.com/q/49743742
type: Question
has comment: http://stackoverflow.com/comment/86502911
tagged with: python
tagged with: flask
accepted answer: http://stackoverflow.com/a/49744262
has comment: http://stackoverflow.com/comment/86502889
has title: Flask SQLaclemy AttributeError: 'NoneType' object has no attribute 'all'
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86502578
has answer: http://stackoverflow.com/a/49744262
score: 0
answer count: 1
has body: I'm trying to take request and use that variable and then use that variable in a SELECT * FROM (VARIABLE) for my database, It works in the python command line but not in my file to render template. Here is my code sorry im new to this. app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/bustedin2' SQLALCHEMY_TRACK_MODIFICATIONS = False db = SQLAlchemy(app) class Offender2(db.Model): id = db.Column(db.Integer, primary_key=True) Name = db.Column(db.String(80), unique=False, nullable=False) DOB = db.Column(db.String(120), unique=False, nullable=False) Sex = db.Column(db.String(80), unique=False, nullable=False) Race = db.Column(db.String(120), unique=False, nullable=False) Charge = db.Column(db.String(80), unique=False, nullable=False) ChargeLevel = db.Column(db.String(120), unique=False, nullable=False) ArrestDate = db.Column(db.String(80), unique=False, nullable=False) City = db.Column(db.String(120), unique=False, nullable=False) State = db.Column(db.String(80), unique=False, nullable=False) BookingNumber = db.Column(db.String(120), unique=False, nullable=False) ArrestDate = db.Column(db.String(80), unique=False, nullable=False) AddedToDataBaseDate = db.Column(db.String(120), unique=False, nullable=False) # notice that all models inherit from SQLAlchemy's db.Model # Make the WSGI interface available at the top level so wfastcgi can get it. wsgi_app = app.wsgi_app @app.route('/') def show_all(): return render_template('ShowAll.html', offenders=Offender2.query.all()) @app.route("/Details/&lt;int:id&gt;") def show_one(id): found_Offender = Offender2.query.get(id) return render_template('details.html', offender=found_Offender) # @app.route('/Details/Multi/&lt;int:BookingNumber&gt;') # def get_booking(): # BookingNumber = request.args.get('BookingNumber') # Found_Booking = Offender2.query.filter(Offender2.BookingNumber == "BookingNumber") # return render_template('ShowMultible.html', offenders = Found_Booking) @app.route('/Detai…
tagged with: flask-sqlalchemy

http://stackoverflow.com/a/49817725
answers question: http://stackoverflow.com/q/49719015
has comment: http://stackoverflow.com/comment/104934195
type: Answer
has comment: http://stackoverflow.com/comment/91049014
score: 1
downvote count: 0
upvote count: 1
has body: A solution is to use driver.quit() instead of driver.close() As explained here Another solution is to add a custom profile fp = webdriver.FirefoxProfile('specify location to profile .default') driver = webdriver.Firefox(firefox_profile=fp)

http://stackoverflow.com/comment/86538450
has text: The reason is i wanted to publish my ip to all the clients on my subnet so multicast is not i wanted unfortunately @Ron Maupin
comment on: http://stackoverflow.com/q/49715779
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49724767
type: Question
has title: Use Votes from Hough Transform to Find the Best Fit Line
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/86469578
tagged with: opencv
has body: I am trying to find the silhouette of the object in an image. After applying Canny edge detection, I am using Hough Transform to find the lines (assuming the object has only straight lines). I use a small threshold on purpose, so I can get many line candidates and choose the best fit. For example: Obviously, this is more than enough. Currently, I am using the following code, which preserves the first line detected in every line cluster. n2 = 0 strong_lines = np.zeros([10000,1,2]) for n1 in range(0,len(lines)): for rho,theta in lines[n1]: if n1 == 0: strong_lines[n2] = lines[n1] n2 = n2 + 1 else: closeness_rho = np.isclose(rho,strong_lines[0:n2,0,0], atol = 50) closeness_theta = np.isclose(theta,strong_lines[0:n2,0,1], atol = np.pi/18) closeness = np.all([closeness_rho,closeness_theta], axis=0) if not any(closeness): strong_lines[n2] = lines[n1] n2 = n2 + 1 As you see, the lines preserved are not the best fit lines, because it simply preserves the first line detected and ditch the nearby lines. What I am thinking is, instead of preserving the first line detected, I would like to compare the votes from Hough Transform of every line in this cluster, and preserve the line with the most votes. Sadly, the Hough Transform function in OpenCV does not provide the exact vote of each line. Is there any way to resolve this, or do you have any better insight of this? Thank you very much :)
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86502829
favorite count: 0

http://stackoverflow.com/q/49749940
answer count: 3
has answer: http://stackoverflow.com/a/49750157
accepted answer: http://stackoverflow.com/a/49750062
downvote count: 0
has answer: http://stackoverflow.com/a/49750062
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/39093546
has title: Sort a tuple with many condition
upvote count: 2
has answer: http://stackoverflow.com/a/49750161
tagged with: python
tagged with: sorting
duplicate of: http://stackoverflow.com/q/39093546
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49750157
tagged with: list
has body: For example, I have a tuple: m = [(5,1),(3,7),(5,7),(6,2),(8,2),(3,6),(5,3),(8,2)] I want to sort this tuple to a tuple like this: m_sorted = [(8, 2), (8, 2), (6, 2), (5, 1), (5, 3), (5, 7), (3, 6), (3, 7)] First I do: m = sorted(m,reverse=True) => m = [(8, 2), (8, 2), (6, 2), (5, 7), (5, 3), (5, 1), (3, 7), (3, 6)] But after that i'm stuck, i don't know what to do next.Conditions is sort descending first element in tuple if they duplicate sort ascending second element.

http://stackoverflow.com/a/49741982
downvote count: 1
score: -1
has body: user_1.privileges.is_admin = True
answers question: http://stackoverflow.com/q/49741907
type: Answer
upvote count: 0

http://stackoverflow.com/comment/86304249
has text: @jpp On the other hand - you look for tuples and you get back tuples - looks prettier to me :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49648089
type: Comment

http://stackoverflow.com/q/49659237
linked to: http://stackoverflow.com/q/993984
has body: &gt; a = [1,2,3,4,5] &gt; b = [1,2,3,4,5] &gt; answer = [2,6,9,16,25] &gt;[e for e in a if a in b] #at this point, i'm lost. sorry i'm new What do I do after this? I want to multiply the elem in a if it's the same as the elem in b then check if the answer is in answer.
tagged with: python
has answer: http://stackoverflow.com/a/49659294
has answer: http://stackoverflow.com/a/49659419
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49764932
tagged with: python-2.7
tagged with: list
has answer: http://stackoverflow.com/a/49659404
has title: How do I multiply an element inside a list to another elem inside a list whom are the same and then check if the answer is inside another list?
has answer: http://stackoverflow.com/a/49659378
has comment: http://stackoverflow.com/comment/86328340
downvote count: 0
has answer: http://stackoverflow.com/a/49659642
score: 1
upvote count: 1
answer count: 7
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/49673030
has comment: http://stackoverflow.com/comment/86328003
has answer: http://stackoverflow.com/a/49662240
type: Question

http://stackoverflow.com/a/49715042
answers question: http://stackoverflow.com/q/49714954
has comment: http://stackoverflow.com/comment/86443658
type: AcceptedAnswer
downvote count: 0
has body: You can calculate a matrix of all shortest weighted paths in the graph with: shortest1 = shortest_path_length(G, weight="distance") You can now calculate the eccentricity of the graph with: ecc = eccentricity(G, sp=shortest2) Finally, you can use the eccentricity to calculate the diameter, etc.: diam = diameter(G, e=ecc) Note that the shortest paths returned by shortest_path_length and expected by eccentricity have different structure (a list of tuples of (node, dictionary) vs a dictionary of dictionaries). You can convert one to the other with shortest2 = dict(shortest1).
accepted answer of: http://stackoverflow.com/q/49714954
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/a/78356336
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49648391
has body: To execute talib please use below code. I have executed this successfully in Google Colab. !wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz !ls !tar xvzf ta-lib-0.4.0-src.tar.gz !ls import os os.chdir('/lib/Ta-lib') #This path should exist in your colab folder, copy file path from there after making new folder !./configure --prefix=/usr !make !make install os.chdir('../') !ls !pip install TA-Lib import talib as ta
type: Answer

http://stackoverflow.com/q/49741703
score: 3
has comment: http://stackoverflow.com/comment/86498017
tagged with: pandas
upvote count: 5
tagged with: python
has title: Pandas create a custom groupby aggregation for column
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49742219
type: UnansweredQuestion
downvote count: 2
answer count: 1
has body: Is there a way in Pandas to create a new column that is a function of two column's aggregation, so that for any arbitrary grouping it preserves the function? This would be functionally similar to creating a calculated column in excel and pivoting by labels. df1 = pd.DataFrame({'lab':['lab1','lab2']*5,'A':[1,2]*5,'B':[4,5]*5}) df1['C'] = df1.apply(lambda x: x['A']/x['B'],axis=1) pd.pivot_table(df1,index='lab',{'A':sum,'B':sum,'C':lambda x: x['A']/x['B']}) should return: |lab|A B|C| |----|---|---| |lab1|5 |20|.25| |lab2|10|25 |.4| i'd like to aggregate by 'lab' (or any combination of labels) and have the dataframe return the aggregation without having to re-define the column calculation. I realize this is trivial to manually code, but it's repetitive when you have many columns.

http://stackoverflow.com/comment/86320439
type: QuestionComment
has text: Quick question: who owns event3 and does it need such strict permissions?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49654856

selenium-ide
tags question: http://stackoverflow.com/q/49643646
tag name: selenium-ide
type: Tag

http://stackoverflow.com/q/49666015
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: http://stackoverflow.com/tag/html
has title: Is there any easy approach to compare two pdf or html or xml files and save the differences for the purpose of automation testing?
tagged with: python
has answer: http://stackoverflow.com/a/49666236
has body: XML files are very huge and if I use Jaxb for comparision I have to create 50 to 60 Pojo classes. Is there any easiest way to compare two PDF/HTML/XML files using Java/Python or any language/ open source tool?
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/49666327
answer count: 2
upvote count: 0
tagged with: java
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 2

http://stackoverflow.com/q/49682431
type: Question
tagged with: python-3.x
tagged with: qt-designer
has comment: http://stackoverflow.com/comment/116462381
has answer: http://stackoverflow.com/a/69535105
type: UnansweredQuestion
has body: I want the click of 'OK' to run some code and then NOT close the dialog Ui code is as below. I capture the button click using self.accepted.connect(self.browse_folder) However, what is happening is that as self.browse_folder is called, the main dialog closes. This behaviour seems to be Related to reject / accept connections in a ButtonBox from PyQt5 import QtCore, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(600, 400) self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) self.buttonBox.setGeometry(QtCore.QRect(10, 350, 161, 41)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.verticalLayoutWidget = QtWidgets.QWidget(Dialog) self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 20, 561, 301)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget) self.textEdit.setObjectName("textEdit") self.verticalLayout.addWidget(self.textEdit) self.retranslateUi(Dialog) self.buttonBox.accepted.connect(Dialog.accept) self.buttonBox.rejected.connect(Dialog.reject) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Read A File"))
tagged with: python
upvote count: 2
score: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86378154
has comment: http://stackoverflow.com/comment/86389791
has comment: http://stackoverflow.com/comment/86378141
has title: PyQt5 ButtonBox Cancel OK always closes dialog
favorite count: 0

http://stackoverflow.com/comment/86422631
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49704631
has text: @Kronos - Do you think `flag = ((df['Date'] != '7April2018') & df['Date'].notnull()).sum()` ?
score: 0

http://stackoverflow.com/comment/86433229
score: 0
type: AnswerComment
has text: @camnooten, check the updated answer and see if it works.
comment on: http://stackoverflow.com/a/49709739
type: Comment

http://stackoverflow.com/q/49673345
has comment: http://stackoverflow.com/comment/86357497
accepted answer: http://stackoverflow.com/a/49673613
has comment: http://stackoverflow.com/comment/86357275
has comment: http://stackoverflow.com/comment/86357372
has comment: http://stackoverflow.com/comment/86357413
has comment: http://stackoverflow.com/comment/86357298
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86357352
has body: I'm filtering my DataFrame dropping those rows in which the cell value of a specific column is None. df = df[df['my_col'].isnull() == False] Works fine, but PyCharm tells me: PEP8: comparison to False should be 'if cond is False:' or 'if not cond:' But I wonder how I should apply this to my use-case? Using 'not ...' or ' is False' did not work. My current solution is: df = df[df['my_col'].notnull()]
has comment: http://stackoverflow.com/comment/86357294
upvote count: 23
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86357744
has comment: http://stackoverflow.com/comment/86357218
has comment: http://stackoverflow.com/comment/86357528
type: AnsweredQuestion
has title: Python Pandas: get rows of a DataFrame where a column is not null
linked to: http://stackoverflow.com/q/13413590
tagged with: pandas
has answer: http://stackoverflow.com/a/49673613
tagged with: dataframe
tagged with: python
score: 23

http://stackoverflow.com/a/49666468
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49664980
has body: Don't use form_field() if you don't want its extra functionality. This will render just the input field: {{ form.password(class='form-control', placeholder='Enter Password') }} In your example the field's label is empty, but in case the field has a label, it must be printed as well. Bootstrap rules are: Wrap labels and form controls in &lt;div class="form-group"&gt; (needed for optimum spacing) Add class .form-control to all textual &lt;input&gt;, &lt;textarea&gt;, and &lt;select elements (source: https://www.w3schools.com/bootstrap/bootstrap_forms.asp)
type: Answer
answers question: http://stackoverflow.com/q/49664980
downvote count: 0

http://stackoverflow.com/comment/86247088
has text: Would you mind taking a look at the answers and seeing if they solved your problem? Thanks.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49605319

http://stackoverflow.com/comment/86369895
comment on: http://stackoverflow.com/q/49679128
score: 0
has text: What helps a lot is using an online regex debugging tool and/or python's debug regex flag
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49752388
has comment: http://stackoverflow.com/comment/86611503
tagged with: qsqlquerymodel
has comment: http://stackoverflow.com/comment/86611053
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86613048
has comment: http://stackoverflow.com/comment/86611958
has comment: http://stackoverflow.com/comment/86609888
has title: Editable QTableView of complex SQL query
has comment: http://stackoverflow.com/comment/86607782
tagged with: python
accepted answer: http://stackoverflow.com/a/49812372
type: Question
has answer: http://stackoverflow.com/a/49800234
has answer: http://stackoverflow.com/a/49812372
answer count: 2
linked to: http://stackoverflow.com/q/52166429
has comment: http://stackoverflow.com/comment/86607876
tagged with: qsqltablemodel
tagged with: pyqt
downvote count: 0
tagged with: pyqt5
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86612398
possible better answer: http://stackoverflow.com/a/49800234
has body: How can I make an editable QTableView displaying data from a complex SQLite query? I need to fill a QTableView with data from several SQLite tables. This needs to be editable by the user. As the queries are a bit complex (including JOINs and CASE WHEN etc.), I'm doing this via a QSqlTableModel and a QSqlQuery. I have been told, however, that this is not how QSqlTableModels should be used. So, can someone please show me how to get a result like the one shown here via the proper way? Also, while my QTableViews are editable, the results don't seem to get stored in the SQLite database. (When I comment out fill_tables, I still get the original results after restarting the GUI. Changing the EditStrategy to OnFieldChange doesn't help.) Is that because I'm handling QSqlTableModel wrong? #!/usr/bin/python3 from PyQt5.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlRelationalTableModel, QSqlRelation) from PyQt5.QtWidgets import QTableView, QApplication from PyQt5.Qt import QSortFilterProxyModel import sys db_file = "test.db" def create_connection(db_file): db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(db_file) if not db.open(): print("Cannot establish a database connection to {}!".format(db_file)) return False return db def fill_tables(): q = QSqlQuery() q.exec_("DROP TABLE IF EXISTS Manufacturers;") q.exec_("CREATE TABLE Manufacturers (Company TEXT, Country TEXT);") q.exec_("INSERT INTO Manufacturers VALUES ('VW', 'Germany');") q.exec_("INSERT INTO Manufacturers VALUES ('Honda' , 'Japan');") q.exec_("DROP TABLE IF EXISTS Cars;") q.exec_("CREATE TABLE Cars (Company TEXT, Model TEXT, Year INT);") q.exec_("INSERT INTO Cars VALUES ('Honda', 'Civic', 2009);") q.exec_("INSERT INTO Cars VALUES ('VW', 'Golf', 2013);") q.exec_("INSERT INTO Cars VALUES ('VW', 'Polo', 1999);") class CarTable(QTableView): def __init__(self): super().__init__() self.init_UI() self.create_model() def create_model(self): query = """ SELECT (comp.company || " " || cars.model) as Car…
favorite count: 0
has comment: http://stackoverflow.com/comment/86612676

http://stackoverflow.com/comment/86472129
type: Comment
score: 0
type: AnswerComment
has text: Now this. IOError: [Errno 13] Permission denied: 'C:\\Users\\vnitin\\OneDrive' Not sure, why permission denied, because it works very well with the full path as argument.
comment on: http://stackoverflow.com/a/49729052

http://stackoverflow.com/comment/135271311
score: 2
comment on: http://stackoverflow.com/a/76725710
type: AnswerComment
has text: Answer needs supporting information 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](https://stackoverflow.com/help/how-to-answer).
type: Comment

http://stackoverflow.com/q/49679800
type: UnansweredQuestion
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/49940489
tagged with: passlib
has body: I've got a GAE app built with Flask Security (which is awesome BTW). Everything works great, but I'm getting errors like this in my GAE logs: /.../lib/passlib/crypto/digest.py:414: PasslibRuntimeWarning: inconsistent digest name: 'md5' resolved to &lt;built-in function new&gt;, which reports name as 'MD5' Although the above message says it is a warning, GAE logs report it as an error. I'd like to remove these errors from my GAE logs so I can focus on actual errors. Is there a place where I can change md5 to MD5 to avoid this error?
tagged with: flask-security
tagged with: python
tagged with: flask
score: 0
has title: "Inconsistent digest name" errors with passlib and Flask Security
answer count: 1
type: Question

http://stackoverflow.com/q/49647836
type: Question
tagged with: numpy
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49647997
tagged with: python
upvote count: 1
has title: getting multiple array after performing subtraction operation within array elements
score: 1
has body: import numpy as np m = [] k = [] a = np.array([[1,2,3,4,5,6],[50,51,52,40,20,30],[60,71,82,90,45,35]]) for i in range(len(a)): m.append(a[i, -1:]) for j in range(len(a[i])-1): n = abs(m[i] - a[i,j]) k.append(n) k.append(m[i]) print(k) Expected Output in k: [5,4,3,2,1,6],[20,21,22,10,10,30],[25,36,47,55,10,35] which is also a numpy array. But the output that I am getting is [array([5]), array([4]), array([3]), array([2]), array([1]), array([6]), array([20]), array([21]), array([22]), array([10]), array([10]), array([30]), array([25]), array([36]), array([47]), array([55]), array([10]), array([35])] How can I solve this situation?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/86470764
score: 0
has text: Could you pull this off by storing the answers in a dictionary where the ID is the key and the value is a string? Then you could just append the additional words to the string as they are encountered.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49728401

http://stackoverflow.com/a/70677913
type: Answer
score: -1
has body: maybe do datetime.datetime.utcfromtimestamp(now_utc) - datetime.timedelta(hours=8)
has comment: http://stackoverflow.com/comment/124945348
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49671138

http://stackoverflow.com/comment/86311065
type: QuestionComment
comment on: http://stackoverflow.com/q/49642516
score: 0
has text: Is there any other way to work on jupyter...I am accessing in this way only
type: Comment

http://stackoverflow.com/q/49604410
tagged with: amazon-dynamodb
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: Dynamodb put_item qps
has body: Does dynamodb limit the qps of put_item action? I tried to migrate some records from json files to dynamodb by using aiobotocore which is an asynchronous wrapper of boto3. By using method put_item, it's hard to reach the throughtput. After change methods from put_item to batch_write_item, it's easily up to the write capacity. # Codes like this import aiobotocore import asyncio resources = iter([]) throughput = 1000 loop = asyncio.get_event_loop() dydb = aiobotocore.get_session().create_client('dynamodb') async def put_item(cli, item, table_name): await cli.put_item(TableName=table_name, Item=item) async def batch_write_item(cli, items): await cli.batch_write_item(RequestItems=items) async def test_put_item(resource, table_name): for item in resource: await put_item(dydb, item, table_name) async def test_batch_write_item(resource): batch = [] for item in resource: if len(batch) &gt; 24: await batch_write_item(dydb, batch) batch = [] else: batch.append(item) if __name__ == "__main__": # put item tasks = [test_put_item(resource) for _ in range(throughput)] loop.run_until_complete(asyncio.gather(*tasks)) # batch write # tasks = [test_batch_write_item(resource) for _ in range(throughput // 25)] # loop.run_until_complete(*tasks)
answer count: 0

http://stackoverflow.com/comment/86386813
comment on: http://stackoverflow.com/a/49687256
type: Comment
type: AnswerComment
has text: Actually I want to add a scrollbar and show the picture inside the scrollbar. If there is any way of achieveing the same which will allow me to let the drawing code be in QMainWindow, then please tell. QGraphicsClass is already there. I added scrollbar to it because that was the only way I thought scrollbar can be added.
score: 0

http://stackoverflow.com/q/49696956
has comment: http://stackoverflow.com/comment/86408345
tagged with: sockets
tagged with: python
has title: Writing and reading file in same script
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I am studying sockets in Python 3. I captured data with a socket and saved it to a file. Then using a regex to get something from the same file. I know how to use with open as but prefer the explicit open and close methods to avoid having an additional block spacing. This is a section of the code. Is this the right way? Do I have the open the file in writing mode, close it. Then opening again in reading mode and close it again? fhandle = open('stream_data.txt', 'w') while True: data = mysock.recv(512) if (len(data) &lt; 1): break fhandle = write(data.decode()) mysock.close() fhandle.close() fhandle = open('stream_data.txt', 'r') for line in fhandle: match = re.match(r'...' (some other awesome code here) fhandle.close()
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86408252
has comment: http://stackoverflow.com/comment/86408264

http://stackoverflow.com/a/49729908
accepted answer of: http://stackoverflow.com/q/49729810
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49729810
has body: You should convert your list of arrays into a single numpy array. Also note that numpy array indexing in 2d is performed by arr[row, column]. If you don't filter by a dimension, just use :. from numpy import array u = [array([ 2.06642033, -0.03448756]), array([ 2.03964994, -0.18737285]), array([ 1.99884859, -0.21461016]), array([ 1.95476809, -0.2254584 ]), array([ 1.90875336, -0.23472173]), array([ 1.86082857, -0.24471069])] u = np.array(u) res = u[:, 0] # array([ 2.06642033, 2.03964994, 1.99884859, 1.95476809, 1.90875336, # 1.86082857])
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/49688041
has body: You read the file with readline and it reads line by line, splitting file on newlines. If the file is not very big, you can read it at once, e.g. with open(file_path, 'r') as file: content = file.read() (see this answer) and then apply the regexp.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49687914

http://stackoverflow.com/q/49731163
upvote count: 2
possible better answer: http://stackoverflow.com/a/49732391
downvote count: 0
has answer: http://stackoverflow.com/a/49732391
favorite count: 0
accepted answer: http://stackoverflow.com/a/49735541
has title: Python - Creating dataframes from a cvs file and merging these dataframes together
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49735541
answer count: 3
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/49781330
type: Question
score: 2
has body: I have a problem with merging together serval dataframes. I downloaded some historical trading data and saved it into a csv file. So now I want to read the data from the cvs file into several dataframes and extract some close prices. I created a function, called read_dataset that reads the data into a dataframe and returns that dataframe. In combination with a for loop I stored all Dataframes in a dict. Dict keys are the abbreviations of the currency (see coin_list dataframe). # List of available coins, saved in a DataFrame called coin_list coins = { 'Bitcoin': 'BTC', 'Ethereum': 'ETH', 'Ripple': 'XRP', 'BitcoinCash': 'BCH', 'Litecoin':'LTC', 'EOS': 'EOS', 'Tronix': 'TRX', 'Stellar' : 'XLM', 'Neo' : 'NEO', 'Cardano': 'ADA', 'IOTA' : 'IOT', 'Monero': 'XMR'} # Create a coin list as Dataframe of the dictionary above coin_list = pd.DataFrame(list(coins.items()), index = np.arange(0,12), columns=('Currency', 'Abbreviation'), dtype=str) # Read data into DataFrames def read_dataset (filename): print('Reading data from %s' % filename) file = pd.read_csv(filename) file = file.drop('Unnamed: 0', axis=1) return file # Read all cryptocurrency data into a dictionary of dataframes. currency_data = {} df = pd.DataFrame() for currency in coin_list['Abbreviation']: df = read_dataset(currency + '_historical_data_daily_updated') df = df.set_index('Timestamp') currency_data[currency] = df currency_data Out: {'ADA': close high low open volumefrom volumeto Timestamp 2017-12-30 0.5900 0.6941 0.4200 0.4955 24118261.70 14016860.69 2017-12-31 0.7100 0.7400 0.5900 0.5900 13107255.34 8971147.70 2018-01-01 0.7022 0.7150 0.6320 0.7100 13805601.70 9403559.91 2018-01-02 0.7620 0.8000 0.6750 0.7022 8440669.40 6292466.84 So after the dict currency_data is created I want to access and separate the dataframes contained in currency_data. Therefore I want to create a for loop to merge for example all close prices of the data frames into one dataframe. Has anyone an idea how I can achieve that? I can do …

http://stackoverflow.com/a/49756848
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49755808
has comment: http://stackoverflow.com/comment/86576340
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49755808
has body: Consider iterating elementwise between dataframe names and objects with zip. Right now you are attempting to concatenate an entire dataframe object, df, in the destination path string: for name, df in zip(['A1','A2','A3','A4','A5'], [A1,A2,A3,A4,A5]): for index, row in df.iterrows(): try: shutil.move('source_folder' +'/'+ row['file_name'], 'Destination'+ name +'/'+ row['file_name']) except(FileNotFoundError): pass Alternatively, use a dictionary and iterate through its keys and values. Also, use os.path.join() and avoid concatenating forward/back slashes in directory names: import os df_dict = {'A1': A1, 'A2': A2, 'A3': A3, 'A4': A4, 'A5': A5} for name, df in df_dict.items(): for index, row in df.iterrows(): try: shutil.move(os.path.join('source_folder', row['file_name']), os.path.join('Destination'+ name, row['file_name'])) except(FileNotFoundError): pass By the way, consider saving similar structured dataframe objects in a container like list or dictionary from the start and avoid the many named objects flooding your global environment. Don't do this just for the loop! You can run any dataframe operation accordingly: df_dict['A1'].head(...) df_dict['A1'].describe(...) df_dict['A1'].groupby(...)
downvote count: 0

http://stackoverflow.com/a/49713352
has comment: http://stackoverflow.com/comment/86440327
has comment: http://stackoverflow.com/comment/86440265
type: Answer
has comment: http://stackoverflow.com/comment/86440254
has comment: http://stackoverflow.com/comment/86440245
has comment: http://stackoverflow.com/comment/86440158
has comment: http://stackoverflow.com/comment/86440293
answers question: http://stackoverflow.com/q/49713196
has body: The reason why your code turns "before" into "five" instead of "befive" is this line of code here: userInput = userInput.replace ( i, "five" ) In this context, i is the string "before", so you're replacing the entire word with "five". The correct variable to use instead of i would be e, which is currently the string "for". userInput = userInput.replace ( e, "five" ) Now the output we get is "Befivee I go three bed at 1630". Notice the double "e" in "Befivee". This is because you've ordered the words in dictFour incorrectly: dictFour = [ "four", "for", "fore" ] Because the shorter word "for" is listed before the longer word "fore", the code will always replace the "for" in every occurence of "fore", thus giving us that duplicated "e" in the output. You have to reorder your lists in such a way that longer words are listed before shorter words: dictFour = [ "four", "fore", "for" ] # swap "for" and "fore" dictTwo = [ "two", "too", "to", "tu" ] # swap "to" and "too" The next problem is your handling of numbers in the input: if int(i): i = int(i) + 1 print (i) int(i) will throw a ValueError if the word can't be converted to a number, which crashes the program. Even if the check passes, i = int(i) + 1 only updates the value of the i variable, but doesn't change the number in the input string. The first thing we do to fix the code is to get rid of those numbered lists dictZero, dictOne, etc. Whenever you have more than 3 variables with a number in their name, that's a sign that you should store them in a list or a dict instead. In this case, since it's critical that the values are ordered correctly, we're going to use a list and sort the numbers descendingly: replacements = [('five', [ "four", "fore", "for" ]), ('four', [ "three" ]), ('three', [ "two", "too", "to", "tu" ]), ('two', [ "one", "won", "juan" ]), ('one', [ "zero", "none", "nil", "null" ]), ] The descending order is important so that subsequent replacements don't turn "one" into "two" into "three" into "four" etc…
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49713196

http://stackoverflow.com/comment/86373847
score: 0
type: Comment
type: QuestionComment
has text: It's instructive to define a class with a `__getitem__` method, and look at the `args` tuple that indexing gives it. `numpy` `index_tricks.py` uses this to create a number of pseudo indexing functions, such as `np.r_` and `np.mgrid`.
comment on: http://stackoverflow.com/q/49678660

textblob
tags question: http://stackoverflow.com/q/49743234
tag name: textblob
tags question: http://stackoverflow.com/q/49731478
type: Tag

http://stackoverflow.com/q/49744833
has comment: http://stackoverflow.com/comment/86504895
has comment: http://stackoverflow.com/comment/86504418
has comment: http://stackoverflow.com/comment/86504174
has comment: http://stackoverflow.com/comment/86504637
has comment: http://stackoverflow.com/comment/86504499
tagged with: python
possible better answer: http://stackoverflow.com/a/49745576
tagged with: command-line
type: AnsweredQuestion
tagged with: syntax-error
has title: How can I specify quotes(" ") in my string text in Python?
answer count: 2
score: 0
has body: The command I want to run from my python script is: tool-manager-cli -a "somexml.xml" -c "another.xml" My python code is: command1 = """ tool-manager-cli -a "somexml.xml" -c "another.xml" """ subprocess.Popen(command1) However when I run my py script, I get SyntaxError: invalid syntax as my error for this line. How can I specify quotes(" ") in my string text without closing it or invalid syntax?
has comment: http://stackoverflow.com/comment/86504467
has answer: http://stackoverflow.com/a/49744848
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86504517
type: Question
has answer: http://stackoverflow.com/a/49745576
accepted answer: http://stackoverflow.com/a/49744848
has comment: http://stackoverflow.com/comment/86504184

http://stackoverflow.com/q/49704105
tagged with: subprocess
tagged with: jython
score: -2
has title: What is the best way to run the same java function repeatedly in python?
answer count: 1
has body: I am doing a project that requires me to repeatedly run a java function in python (it's like designing a learning algorithm in python but the value function was provided in java) So what would be the practice for this scenario? Shall I use subprocess.run() to call the java function every time or shall I use the things like Py4J, Jython or JPype? What's the difference between using subprocess.run() and the others? The efficiency should be the top concern since I need to run the same java function repeatedly.
has answer: http://stackoverflow.com/a/49704196
accepted answer: http://stackoverflow.com/a/49704196
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86421598
tagged with: java
has comment: http://stackoverflow.com/comment/86421567
linked to: http://stackoverflow.com/q/7372592
tagged with: python
tagged with: jpype
favorite count: 0
type: Question
upvote count: 0
downvote count: 2

http://stackoverflow.com/comment/86506660
has text: @OluwafemiSule But why does the memory consumption increases when i run .find_one ? approx 6 gb!
comment on: http://stackoverflow.com/q/49731562
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49660249
type: UnansweredQuestion
has title: Moving numbers in a list based on condition
tagged with: python
has answer: http://stackoverflow.com/a/49660319
has comment: http://stackoverflow.com/comment/86330573
has comment: http://stackoverflow.com/comment/86330255
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49660360
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has body: Program is suppose to move numbers around based on a the "pivot" value. All numbers in front of the pivot value on the list need to be less than or equal to the pivot value and all numbers behind the pivot value are greater than the pivot value. (Python 3.x) a = [1,4,3,7,4,7,6,3,7,8,9,9,2,5] print("Original List") print(a) pivot = 4 #or select any number from the list b = list(a) for i in range(len(a)): pivotIndex = b.index(pivot) #gives index of pivot through every iteration if a[i] &gt; pivot: b.insert(pivotIndex+1,a[i]) elif a[i] &lt;= pivot: b.insert(0,a[i]) print("New List") print(b) The problems are that I can't figure out how to remove the original number once it has been moved and in a list like this where there are duplicates of the pivot value, when a number comes up that is equal to the pivot it moves it to the front and treats it as the new pivot. Am I going about this the wrong way?

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/49613045
tags question: http://stackoverflow.com/q/49609811

http://stackoverflow.com/a/49737963
has comment: http://stackoverflow.com/comment/86587207
has comment: http://stackoverflow.com/comment/86492337
accepted answer of: http://stackoverflow.com/q/49736849
type: Answer
answers question: http://stackoverflow.com/q/49736849
has comment: http://stackoverflow.com/comment/86490733
has comment: http://stackoverflow.com/comment/86587347
upvote count: 2
has body: It depends on whether you scale the variance or not. The "other site" uses scale=TRUE. If you want to do this with sklearn, add StandardScaler before fitting the model and fit the model with scaled data, like this: from sklearn.preprocessing import StandardScaler X = StandardScaler().fit_transform(irisdf.iloc[:,0:4]) scores = model.fit_transform(X) Edit: Difference between StandardScaler and normalize Here is an answer which pointed out a key difference (row vs column). Even you use normalize here, you might want to consider X = normalize(X.T).T. The following code shows some differences after transformation: import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, normalize iris = datasets.load_iris() varnames = ['SL', 'SW', 'PL', 'PW'] fig, ax = plt.subplots(2, 2, figsize=(16, 12)) irisdf = pd.DataFrame(data=iris.data, columns=varnames) irisdf.plot(kind='kde', title='Raw data', ax=ax[0][0]) irisdf_std = pd.DataFrame(data=StandardScaler().fit_transform(irisdf), columns=varnames) irisdf_std.plot(kind='kde', title='StandardScaler', ax=ax[0][1]) irisdf_norm = pd.DataFrame(data=normalize(irisdf), columns=varnames) irisdf_norm.plot(kind='kde', title='normalize', ax=ax[1][0]) irisdf_norm = pd.DataFrame(data=normalize(irisdf.T).T, columns=varnames) irisdf_norm.plot(kind='kde', title='normalize', ax=ax[1][1]) plt.show() I'm not sure how deep I can go with the algorithm/math. The point for StandardScaler is to get uniform/consistent mean and variance across features. The assumption is that variables with large measurement units are not necessarily (and should not be) dominant in PCA. In other word, StandardScaler makes features contribute equally to PCA. As you can see, normalize won't give consistent mean or variance.
has comment: http://stackoverflow.com/comment/86588013
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86587929
downvote count: 1

http://stackoverflow.com/a/49686598
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49683200
has body: Approach: All wanted tags are siblings of each other. So, basically, you'll have to use find_next_sibling() function to find them. Explanation: All the names (titles) of bird types are located inside the &lt;h2&gt; tag. But, the first &lt;h2&gt; tag is for Contents (so skip that). Order and Family are located inside the &lt;p&gt; tag which comes after the &lt;h2&gt; tag. You can find that using h2.find_next_sibling('p'). The table with Name, Binomial, and Status can be found using h2.find_next_sibling('table'). Using all this, you can print all the details you want. But, you'll have to break the loop when you reach the &lt;h2&gt; tag which contains References. This can be done using if h2.find('span', class_='mw-headline').text == 'References': break Code: r = requests.get('https://en.wikipedia.org/wiki/List_of_birds_of_Trinidad_and_Tobago') soup = BeautifulSoup(r.text, 'lxml') for bird in soup.find_all('h2')[1:]: title = bird.find('span', class_='mw-headline').text if title == 'References': break print(title) p_tag = bird.find_next_sibling('p') order, family = [x.text for x in p_tag.find_all('a')] table = p_tag.find_next_sibling('table') for row in table.find_all('tr')[1:]: name, binomial, status = [x.text for x in row.find_all('td')] print(order, family, name, binomial, status, sep=' | ') print() Partial output: Tinamous Tinamiformes | Tinamidae | Little tinamou | Crypturellus soui | Trinidad only Screamers Anseriformes | Anhimidae | Horned screamer | Anhima cornuta | Trinidad only - rare/accidental Ducks, geese, and waterfowl Anseriformes | Anatidae | Fulvous whistling-duck | Dendrocygna bicolor | Trinidad only Anseriformes | Anatidae | White-faced whistling-duck | Dendrocygna viduata | Trinidad only - rare/accidental ... ... Waxbills and allies Passeriformes | Estrildidae | Common waxbill | Estrilda astrild | Trinidad, accidental Tobago - introduced species Passeriformes | Estrildidae | Tricolored munia | Lonchura malacca | Trinidad only - introduced species Old…
answers question: http://stackoverflow.com/q/49683200
has comment: http://stackoverflow.com/comment/86419217
upvote count: 1

http://stackoverflow.com/comment/86432616
type: Comment
has text: thank you very so much, Now the code is working ， Good night everyone！ahah
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49708381

http://stackoverflow.com/comment/86254416
score: 0
comment on: http://stackoverflow.com/a/49622545
type: Comment
has text: awesome.. finally got a hold of it. so, you can basically just using the remainder as variant. awesome :) let me implement it and see how it looks in code
type: AnswerComment

http://stackoverflow.com/comment/129354353
has text: Does this answer your question? [Convert "\x" escaped string into readable string in python](https://stackoverflow.com/questions/63218987/convert-x-escaped-string-into-readable-string-in-python)
comment on: http://stackoverflow.com/q/49756071
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49647606
has title: Pipeline and GridSearchCV with a custom regression function - passing parameters?
has comment: http://stackoverflow.com/comment/86303471
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49647841
answer count: 1
has comment: http://stackoverflow.com/comment/86304410
downvote count: 0
upvote count: 1
tagged with: machine-learning
score: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49647841
favorite count: 0
has body: I'm trying to use Pipeline and GridSearchCV with a custom regression function. I've got the approach to work using sklearn.svm.SVR by setting up its class, and then passing the parameters from the dictionary when setting up GridSearchCV. I don't seem to be able to do the same thing when using my own regression function (RegFn). In particular I want to pass the values from the parameter dictionary to the RegFn when setting it up. Grateful for any pointers on how to get this working. from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.base import BaseEstimator,RegressorMixin parameters = dict(regfn__i=i, regfn__j=j, regfn__k=k) regfn = RegFn(numInputs=noinputs, numOutputs=1, i = 100, j = 1, k =0.5) scaler = StandardScaler() steps = [ ('scaler', scaler), ('regfn', regfn ) ] grid = GridSearchCV(Pipeline(steps), param_grid=parameters, cv=splits, refit=True, verbose=3, n_jobs=1) Updated class structure class RBF(BaseEstimator,RegressorMixin): def __init__(self, i,j,k,numInputs=10,numOutputs=1): self.numInputs = numInputs self.numOutputs = numOutputs self.i = i self.j = j self.k = k ..... def fit(self, x, y): .... def predict(self, x): .... I'm still not able to pass the i, j, k values from the dictionary. Am I referring to them in the correct way?
type: Question

http://stackoverflow.com/q/49652206
tagged with: python
has answer: http://stackoverflow.com/a/49654463
has body: Im new here, and i have a problem on a quiz im working with Python Tkinter. So here is the code: b5 = Button(root, text="Next Question",command=question_2_output) b5.configure(command = des) b5.pack(side=BOTTOM) With this button im trying to acess on two functions. --> def question_2_output(): lab7 = Label(root, text="Qestion 2 Qestion 2 Qestion 2 Qestion 2", font="Verdana 11 italic") lab7.pack() lab7.place(x = 350, y = 60) def des(): q1.destroy() With this code i try to put lab7 on the same place the previous Question q1 were and destroy/delete the older Label (Question). But i get this error NameError: name 'q1' is not defined. I cant destroy q1. q1 is in this function. def question_1_output(): q1 = Label(root, text="This is a very very very very very long question?", font="Verdana 11 italic") q1.pack() q1.place(x = 350, y = 60) Any help?? Thanks!
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49652446
score: 0
tagged with: tkinter
answer count: 3
has answer: http://stackoverflow.com/a/49652446
has title: Python GUI tkinter NameError
tagged with: user-interface
has comment: http://stackoverflow.com/comment/86316657
type: Question
accepted answer: http://stackoverflow.com/a/49654463
has comment: http://stackoverflow.com/comment/86313639
has answer: http://stackoverflow.com/a/49652539

http://stackoverflow.com/q/49676047
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49676086
has comment: http://stackoverflow.com/comment/86363330
favorite count: 0
accepted answer: http://stackoverflow.com/a/49676086
type: Question
tagged with: numpy
has body: Data ID Field1 Field2 1 A '1' 2 A ' ' 3 B '2' 4 B '3' Want ID Field1 Field2 1 A '1' 4 B '3' I have multiple duplicate rows which only differ on Field2 (character field). For each distinct Field1 I want to only keep the row which has the max character value for Field2 (i.e. '3'>'2'>'1'>'(blank space)')
tagged with: python
has answer: http://stackoverflow.com/a/49676160
has title: removing duplicate rows pandas with condition
possible better answer: http://stackoverflow.com/a/49676160
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/119236917
type: Comment
has text: None of these answers work for B= [4, 3], which as the OP said, should not remove anything. Thanks for the answers though, as they would help those seeking for removing values from lists in a simple and straightforward manner.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49737705

http://stackoverflow.com/q/49681820
has answer: http://stackoverflow.com/a/49681905
tagged with: python
score: -1
tagged with: eclipse
has body: I'm brand new to Python and Eclipse and am in the process of trying to setup my Windows 10 system with a proper dev environment. I've been searching everywhere for a straight answer on which install of Eclipse to use for Python development but to no avail. I've installed the Java JDK and Python but when I went to install Eclipse, I was met with over 20 options for Eclipse and none of them mention Python. I know I have to install the Python libraries (PyDev /LiClipse) once Eclipse is setup but which option is the best to use?
has comment: http://stackoverflow.com/comment/86375706
type: AnsweredQuestion
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49681905
downvote count: 1
favorite count: 0
type: Question
has title: Which install of eclipse should I use for python development?

http://stackoverflow.com/q/49747499
has body: How to find the word after a match, if word in list? For example, I want to find the word after match1 if this word is in list: r = ["word1", "word2", "word3"] If found, then return the word(i). If not, then return Unknown. Toy example: Text1 = "This is a match1 for example match1 random text match1 anotherword" Text2 = "This is a match1 word1 example" Text3 = "This is an example without word of interest" I want to look the word after match1 if this word is in list r = ["word1", "word2", "word3"] Expected result: For Text1 I expect to get Unknown, for Text2 word1, and for Text3 Unknown. I have managed so far to extract "word1" only if it's among the first two occurences, but if for example we have Text4 (below) I can'textract it because I'm only going until the second time I see the match, and just keep going further and deeper with if-else statements I dont think its the way to go, because the word1 can even not be present at all. Text4 = "example match1 example match1 example match1 word1" def get_labels(text): q = ["match1"] #Here the idea is to have several, but its the same logic r = ["word1", "word2", "word3"] labels = [] for i,item in enumerate(q): label = text[text.find(q[i])+len(q[i]):].split()[0] if label in r: labels.append(label) else: texto_temp = text[text.find(q[i])+len(q[i]):] label2 = texto_temp[texto_temp.find(q[i])+len(q[i]):].split()[0] labels.append(label2) return labels Any ideas will be appreciated.
possible better answer: http://stackoverflow.com/a/49747736
tagged with: python
has answer: http://stackoverflow.com/a/49747736
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49748534
has title: Find word after a match if word in list in python
has answer: http://stackoverflow.com/a/49750608
tagged with: string
type: Question
accepted answer: http://stackoverflow.com/a/49748534
has comment: http://stackoverflow.com/comment/86509458

http://stackoverflow.com/comment/86366011
score: 0
comment on: http://stackoverflow.com/q/49677313
type: Comment
type: QuestionComment
has text: @Aran-Fey It is possible but the list of columns to use would be significantly large compared with the unused columns list (160 vs 30)

http://stackoverflow.com/comment/86409771
has text: The `setlocale` doesn't recognize the second argument.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49698247
score: 1

http://stackoverflow.com/comment/86430709
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49699973
has text: What do you mean by why, @DebanjanB? I really didn't understand your question. However, do you think it is impossible to achieve?

http://stackoverflow.com/comment/86216726
has text: why this encoding .. what are you attempting to model. Why not use the same encoding as the author of the notebook?
comment on: http://stackoverflow.com/q/49604079
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/99245091
type: Comment
score: 2
has text: Confirming that increasing the RAM on my Droplet instance from 1GB to 2GB also solved this.
type: AnswerComment
comment on: http://stackoverflow.com/a/49800671

http://stackoverflow.com/comment/86390388
has text: Thank you. This is exactly what I was looking for!
comment on: http://stackoverflow.com/a/49689414
type: Comment
score: 0
type: AnswerComment

wait
tags question: http://stackoverflow.com/q/49674084
type: Tag
tag name: wait

http://stackoverflow.com/comment/86464173
comment on: http://stackoverflow.com/a/49725068
has text: Holy, this is so neat and perfect! Thank you so much! Really appreciate it!!! Thanks!!!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49678405
score: 0
has body: What you are looking at is likely a CSRF token The linked answer is very good, but a summary is, these tokens used to make sure that you can't send malicious requests to a site from another page in your web browser. In this case it is a bit silly, because logging in has no consequences. It was likely added automatically by the framework your university website uses. You will have to extract this token from the login page before doing your login POST and then include it with your data. The full steps would be the following: Fetch the login page extract the token with e.g. BeautifulSoup or requests-html Send the login request: payload = {"username" : user, "password" : passw, "execution": token}
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86372782
accepted answer of: http://stackoverflow.com/q/49678261
type: Answer
has comment: http://stackoverflow.com/comment/86372741
answers question: http://stackoverflow.com/q/49678261

http://stackoverflow.com/comment/86246910
comment on: http://stackoverflow.com/a/49619830
type: Comment
score: 0
type: AnswerComment
has text: thanks for the quick reply. Getting an invalid syntax on the print line. If its better/easier to have the data in 2 .csvs that can be easily done.

http://stackoverflow.com/comment/86518881
comment on: http://stackoverflow.com/a/49752164
has text: No any file to be downloaded.<Response [200]> <Response [200]>
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86257855
type: Comment
type: QuestionComment
score: 0
has text: From the looks of it you're saving new objects only, so why do you expect to see UPDATEs?
comment on: http://stackoverflow.com/q/49625415

http://stackoverflow.com/comment/86207689
has text: Ascii Char 24 is equivalent to CANCEL character.
comment on: http://stackoverflow.com/a/49600284
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49684663
has comment: http://stackoverflow.com/comment/86380681
score: -2
has title: I cannot print the variable with my text
has comment: http://stackoverflow.com/comment/86380694
has comment: http://stackoverflow.com/comment/86380685
upvote count: 0
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/49684743
tagged with: python
tagged with: variables
tagged with: string
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49684702
favorite count: 0
tagged with: printing
has answer: http://stackoverflow.com/a/49684748
has body: I'm trying just to create a simple line of code but I can not seem to figure out how to print a string and a variable at the same time. If someone could plz help me that would be great. day = 1 print ("Day Number: ("+day+")")
type: Question

http://stackoverflow.com/q/49741998
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49742161
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49742221
has answer: http://stackoverflow.com/a/49742161
has answer: http://stackoverflow.com/a/49742221
score: 1
has body: I have a moderately long Python list that looks like the following (showing first 5 rows): In [4]: dfdist_list[:5] Out[4]: [[10255, 10256, (-89.572, 41.235), (-89.025, 41.431000000000004), 37.963909], [10255, 937, (-89.572, 41.235), (-101.209, 36.184), 11622.426262], [10255, 3392, (-89.572, 41.235), (-101.221, 36.008), 11621.601622], [10255, 306, (-89.572, 41.235), (-101.53399999999999, 36.241), 11599.87664], [10255, 7313, (-89.572, 41.235), (-103.331, 35.109), 11475.272909]] The first two columns of the list are ID numbers for start and end nodes (order not important). The next two columns are the nodes' geographic coordinates. And the last column is the calculated distance in miles between the nodes. I'm looping through a CSV file to create this list. But for each loop, before I perform the calculation, I want to check to see if there is already a row in the list with the same nodes but in reverse order. (If so, then I'll skip adding the new row, because that data is already in there.) What is the clearest/simplest way to check if a row exists in a list, where you know the first two elements of that row? Update: In particular, I tried the following which seems like it should work, but I can't get it to spit out a True/False. It just spits out that generator object line: In [18]: any([indexY,indexX] in subl[:2] for subl in dfdist_list) Out[18]: &lt;generator object &lt;genexpr&gt; at 0x000000000A902FC0&gt;
tagged with: python
upvote count: 1
has title: Check for row in Python list based on first two elements
answer count: 2
has comment: http://stackoverflow.com/comment/86498690

http://stackoverflow.com/q/49644482
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/49646099
score: 0
has comment: http://stackoverflow.com/comment/86296968
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49646380
has body: In [56]: df Out[56]: array([[3, 133, nan, ..., 202, 109, 1427], [3, 133, nan, ..., 183, 120, 1448], [3, 133, nan, ..., 205, 22, 417], ..., [8, 43, nan, ..., 88, 11, 11], [64, 173, nan, ..., 2774, 2029, 1210], [12, 85, nan, ..., 19, 10, 25]], dtype=object) collections.Counter(df[:,[0,1]]) df is the numpy array and I want to get the count of both the first and second columns, just like count(*) from df group by col-0, col-1 But is returns the error TypeError: unhashable type: 'numpy.ndarray' How can I realize it ? Pandas is very slow and I don't tend to use it.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86296724
tagged with: numpy
has title: How to count the frequency of two columns in numpy array?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49645853
tagged with: arrays

http://stackoverflow.com/comment/86258229
has text: I did this, as you can see in the code, yet it still doesn't work.
comment on: http://stackoverflow.com/a/49620037
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/138482307
type: AnswerComment
comment on: http://stackoverflow.com/a/49884125
has text: I would add to your class smth for hypothesis - like `def predict(self, params, exog=None):` *if exog is None: exog = self.exog; return np.dot(exog, params[:self.exog.shape[1]])*
type: Comment
score: 0

http://stackoverflow.com/q/49721813
has comment: http://stackoverflow.com/comment/86461434
tagged with: python
has body: I wrote a simple script that can send notifications via Pushbullet using the pushbullet module, which I installed using pip. I'm using Python 2.7.14. Now, the script works but I want to trigger it from a bash script and here starts the pain. When I use the bash script the IMPORT command fails when loading the PUSHBULLET module. I found out that also running the .py script using the syntax: python pushbullet_test.py fails. Can someone help me see what I'm doing wrong? here's the bash script: #!/bin/bash STRING="Launching script..." PYTHON="/usr/bin/python" SCRIPT_ROOT="/home/ale/Documenti/" SCRIPT="pushbullet_test.py" echo "Using $PYTHON" pushd . cd $SCRIPT_ROOT echo $STRING $PYTHON "$SCRIPT" popd This is the python code: import requests from pushbullet import Pushbullet #THIS IS WHERE IT BREAKS import sys batt = "30%" pb = Pushbullet(api_key="o.blaeudeusadushdufhsfs") push = pb.push_note("ALERT", "Battery charge lower than {}".format(batt)) I found that the script only works when copied into the python terminal, AND when the working directory is my home. Tried to fix it using pushd but it didn't work. Thank you for any support! Ale
has comment: http://stackoverflow.com/comment/86461404
tagged with: python-import
tagged with: bash
tagged with: cwd
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86498520
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86457149
has comment: http://stackoverflow.com/comment/86456886
favorite count: 0
type: Question
tagged with: linux
has title: Python - ImportError: cannot import name
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86465712

http://stackoverflow.com/q/49609473
answer count: 4
has comment: http://stackoverflow.com/comment/86226144
has comment: http://stackoverflow.com/comment/86229067
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49609551
score: 1
has answer: http://stackoverflow.com/a/49609551
downvote count: 0
has title: pip3 Crashing with Import Error
tagged with: pip
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: linux
accepted answer: http://stackoverflow.com/a/49610309
has answer: http://stackoverflow.com/a/53695975
has body: Python 3.5.2 Ubuntu 16.04 LTS Trying to use pip3 to install some packages and it returns the following regardless of argument: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 33, in vendored __import__(vendored_name, globals(), locals(), level=0) ImportError: No module named 'pip._vendor.pkg_resources' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; from pip import main File "/usr/lib/python3/dist-packages/pip/__init__.py", line 13, in &lt;module&gt; from pip.exceptions import InstallationError, CommandError, PipError File "/usr/lib/python3/dist-packages/pip/exceptions.py", line 6, in &lt;module&gt; from pip._vendor.six import iteritems File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 75, in &lt;module&gt; vendored("pkg_resources") File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored __import__(modulename, globals(), locals(), level=0) File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 664, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 634, in _load_backward_compatible File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2927, in &lt;module&gt; File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2913, in _call_aside File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in _initialize_master_working_set File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 956, in subscribe File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in…
has answer: http://stackoverflow.com/a/53888530
tagged with: python
has answer: http://stackoverflow.com/a/49610309
linked to: http://stackoverflow.com/q/42184792

http://stackoverflow.com/q/49707863
has body: When plotting several lines in 3D the last line allways covers previeously plotted lines even if it is behind it. import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D def sinus(t,a,n): y = [1.0*a*np.sin(2.0*np.pi*t*n+0),1.0*a*np.sin(2.0*np.pi*t*n+2.0*np.pi/3),1.0*a*np.sin(2.0*np.pi*t*n+4.0*np.pi/3)] z = [1.0*a*np.cos(2.0*np.pi*t*n+0),1.0*a*np.cos(2.0*np.pi*t*n+2.0*np.pi/3),1.0*a*np.cos(2.0*np.pi*t*n+4.0*np.pi/3)] return y,z t = np.linspace(0,1,1e6) Y,Z = sinus(t,2,2) fig = plt.figure() ax = Axes3D(fig) for i in range(0,len(Y)): print(i,len(Y)) ax.plot(t, Y[i],zs=Z[i],linewidth=4.0) plt.show() In the resulting plot the red line allways covers the blue or green line even though it should pass behind it. The expected behaviour would be like this. How can this be achieved with python?
tagged with: matplotlib
tagged with: python
has title: python matplotlib axes3d lines cross neglecting depth
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86503203
has comment: http://stackoverflow.com/comment/86593400
has comment: http://stackoverflow.com/comment/86452381
score: 2
has comment: http://stackoverflow.com/comment/86429214

http://stackoverflow.com/comment/86440558
type: QuestionComment
has text: I'm sorry that I don't explain this problem clearly. 'work_element_count > 0' occur in the tensorflow source code file 'python3.6/site-packages/tensorflow/include/tensorflow/core/util/cuda_launch_config.h'
score: 0
comment on: http://stackoverflow.com/q/49705477
type: Comment

http://stackoverflow.com/q/49733624
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49733933
accepted answer: http://stackoverflow.com/a/49733933
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has body: I'm relatively new to databases, so this question may have a simple answer (I've been searching for hours). I want to write a Python script that pulls the SQL Code stored in SQL Server Management Studio. I can successfully connect to the database using pyodbc and run queries against the database tables, but I would like to be able to pull, for example, the SQL code stored in a procedure, function, view, etc. without running it. This seems like something that would be relatively simple. I know it can be done in Powershell, but I would prefer to use Python. Is there some sort of module or pyodbc hack that will do this?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: ssms
has title: Pulling SQL Script from Database Using pyodbc
tagged with: python
tagged with: pyodbc

http://stackoverflow.com/a/49758009
has comment: http://stackoverflow.com/comment/87118335
has body: If I understand you well, you want to have a column per genre, indicating T/F. I would advice you to look at the get_dummies function import pandas as pd s = pd.Series(list('abca')) pd.get_dummies(s) Update - if you have columns with double values, you can split them before or after. Example of splitting after (would guess its quickest, but one should test). Code could be prettier, but hope its clear. import pandas as pd import numpy as np s = pd.Series(['a', 'b', 'c', 'a|b', 'a|d']) d = pd.get_dummies(s) columns = list(d) for col in columns: if '|' in col: for l in col.split('|'): if l in columns: d[l] = np.maximum(d[l].values, d[col].values) else: d[l] = d[col]
accepted answer of: http://stackoverflow.com/q/49757970
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87215907
has comment: http://stackoverflow.com/comment/87120267
answers question: http://stackoverflow.com/q/49757970
type: AcceptedAnswer
score: 1

http://stackoverflow.com/a/74656705
has body: You can try this variant: def square_digits(num): return int(''.join(str(int(i)**2) for i in str(num)))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49604549

http://stackoverflow.com/comment/86236205
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49614467
has text: @user4343502 Okay, Thanks! Will keep in mind the next time.
type: Comment

pdf-parsing
type: Tag
tags question: http://stackoverflow.com/q/49623051
tag name: pdf-parsing

http://stackoverflow.com/q/49626378
type: Question
tagged with: python-3.x
has body: There's a few posts like this already, but after following them I still encounter some issues. trade = client.get_my_trades(symbol=ticker) # fetching all trades made on the ticker IOSTBTC print(trade) json_trade = json.dumps(trade, indent=4) # converting and indenting for easier readability. print(json_trade+"\n") json_normalised = json_normalize(trade) # normalising with pandas for spreadsheet use print("Normalised JSON\n", json_normalised) json_normalised = DataFrame(pandas.read_json("logs.xlsx")) json_normalised_str = str(json_normalised) logs = open("logs.xlsx", "w") # creating file to write to logs.write(json_normalised_str) # writing data to file, oldest first This code runs fine, with no erros. However, when I check the logs.xlsx, all the data is in a single column, with spaces in between where they should be separated by columns. For example, here's some of the JSON data: [{'id': 3084149, 'orderId': 7071890, 'price': '0.00000312', 'qty': '400.00000000', 'commission': '0.00041327', 'commissionAsset': 'BNB', 'time': 1522223234240, 'isBuyer': True, 'isMaker': True, 'isBestMatch': True}, {'id': 3084468, 'orderId': 7073272, 'price': '0.00000314', 'qty': '400.00000000', 'commission': '0.00041694', 'commissionAsset': 'BNB', 'time': 1522223910252, 'isBuyer': False, 'isMaker': True, 'isBestMatch': True}] What I want is for 'id' and 'orderId' and 'price' (et cetera) to have it's own column. With the above data I would have two rows of information. But instead, this is what I recieve when I use this data: What can I do?
accepted answer: http://stackoverflow.com/a/49626658
has answer: http://stackoverflow.com/a/49626658
answer count: 1
downvote count: 0
upvote count: 1
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has title: Making a spreadsheet out of JSON data using DataFrame from pandas
favorite count: 0

http://stackoverflow.com/comment/86301006
type: AnswerComment
score: 1
has text: python3 does not have `xrange` generator
type: Comment
comment on: http://stackoverflow.com/a/49646470

http://stackoverflow.com/comment/86376784
comment on: http://stackoverflow.com/a/49682493
type: Comment
has text: you're a hero. I have just read the documentation on re_first as i wasn't aware of that. But could you explain what r"\d+\.\d+" is doing? Thanks a ton!
score: 0
type: AnswerComment

http://stackoverflow.com/a/49752020
score: 4
upvote count: 4
has body: No, there is nothing like that in C#. Due to the statically-typed nature of C#, a feature like that couldn't work with arbitrary expressions for the slice points. I think that the closest you can get is to create a bunch of extension methods that have the slice points embedded in their names. E.g.: public static (T1, T2) Take2&lt;T1, T2, T3&gt;(this (T1, T2, T3) tuple) =&gt; (tuple.Item1, tuple.Item2); var tuple = (1,2,3); var subtuple = tuple.Take2(); Note that if the tuple members have names, this will strip them off.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49748514
accepted answer of: http://stackoverflow.com/q/49748514
type: Answer

http://stackoverflow.com/q/49685092
score: 5
linked to: http://stackoverflow.com/q/3411771
has answer: http://stackoverflow.com/a/49685146
type: UnansweredQuestion
has title: Replace multiple strings at the same time
upvote count: 5
has comment: http://stackoverflow.com/comment/86381521
has answer: http://stackoverflow.com/a/49685114
tagged with: python
has answer: http://stackoverflow.com/a/49687890
answer count: 3
has body: Lets say I have this string "abcd" Now I want to replace all 'a's with a 'd' and I want to replace all 'd's with an 'a'. The problem is that string.replace does not work in this situation. "abcd".replace('a','d').replace('d','a') abca Expected output is "dbca" How would I acheive this?
downvote count: 0
linked to: http://stackoverflow.com/q/37782066
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86381571

http://stackoverflow.com/comment/97001476
score: 0
has text: fwiw I'm still looking for a solution to this problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49640489

http://stackoverflow.com/comment/86316379
type: Comment
score: 0
type: QuestionComment
has text: Your `TEXT` function doesn't do anything other than setting global variables.
comment on: http://stackoverflow.com/q/49653573

http://stackoverflow.com/comment/86441053
score: 0
comment on: http://stackoverflow.com/q/49713857
has text: @Ry All values are in a larger list. For example, I'm trying to compare myArray[0], myArray[3], and myArray[9] to see if any 2 of those 3 values are equal to one another.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49744733
answers question: http://stackoverflow.com/q/49739769
type: Answer
has body: Create a function that will return a string in the correct format then use matplotlib.ticker.FuncFormatter to designate your function as the y axis formatter. Assuming you want the y-axis labels to look like this: 1000.00, 100.00, 10.00, 1.00, 0.1, 0.01, 0.001, 0.0001 and adapting from a matplotlib example: import math from matplotlib.ticker import FuncFormatter y_s = [1000, 100, 10, 1, 0.1000, 0.01000, 0.001000, 0.0001000] x_s = [pow(10,y) for y in range(8)] def my_format(y, pos): # y &lt;= 0 formats not needed for log scale axis # use the log of the label to determine width and precision decades = int(math.log10(y)) if decades &gt;= 0: decimal_places = 2 width = 1 + decades + decimal_places else: decimal_places = abs(decades) width = 1 + decimal_places # construct a format spec fmt = '{{:{}.{}f}}%'.format(width,decimal_places) return fmt.format(y) fig, ax = plt.subplots() ax.set_xscale('log') ax.set_yscale('log') ##ax.set_ylim(min(y_s)/10,max(y_s)*10) ax.set_ylim(0.00001,1000) ax.yaxis.set_major_formatter(formatter) plt.plot(x_s,y_s) plt.show() plt.close()
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/49622962
has comment: http://stackoverflow.com/comment/86252945
has answer: http://stackoverflow.com/a/49623035
score: 5
downvote count: 0
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86252902
has body: for example, I want to define a function: def add_value(dic, path, value): # dict is a Dictionary to be modified # path is a list, like ['A', 'B', 'C', ...] # value is a list or tuple ... ... return dic d = {} d = add_value(d, ['A', 'B'], ('log.txt', '12KB')) print(d) d = add_value(d, ['X', 'Y', 'Z'], ('backup.bin', '17MB')) print(d) d = add_value(d, ['X', 'Y', 'Z'], ('file.lst', '5KB')) print(d) output should like next: {'A': {'B': {'log.txt': '12KB'}}} {'A': {'B': {'log.txt': '12KB'}}, 'X': {'Y': {'Z': {'backup.bin': '17MB'}}}} {'A': {'B': {'log.txt':'12KB'}}, 'X': {'Y': {'Z': {'backup.bin': '17MB', 'file.lst': '5KB'}}}} I have tried like this: import json def add_value(dic, path, value): # dic is a dict to be modified # path is a list # value is a tumple like ('file1.txt': '20kb') length = len(path) if length == 1: if path[0] not in dic: dic[path[0]] = {} else: dic[path[0]].append(value) return dic elif length == 2: if path[0] not in dic: dic[path[0]] = {} if path[1] not in dic[path[0]]: dic[path[0]][path[1]] = {} dic[path[0]][path[1]][value[0]] = value[1] return dic elif length == 3: if path[0] not in dic: dic[path[0]] = {} if path[1] not in dic[path[0]]: dic[path[0]][path[1]] = {} if path[2] not in dic[path[0]][path[1]]: dic[path[0]][path[1]][path[2]] = {} dic[path[0]][path[1]][path[2]][value[0]] = value[1] return dic elif length == 4: if path[0] not in dic: dic[path[0]] = {} if path[1] not in dic[path[0]]: dic[path[0]][path[1]] = {} if path[2] not in dic[path[0]][path[1]]: dic[path[0]][path[1]][path[2]] = {} if path[3] not in dic[path[0]][path[1]][path[2]]: dic[path[0]][path[1]][path[2]][path[3]] = {} dic[path[0]][path[1]][path[2]][path[3]][value[0]] = value[1] return dic else: return d = {} d = add_value(d, ['A', 'B'], ('log.txt', '12KB')) d = add_value(d, ['A', 'B', 'C',], ('log2.txt', '34kb')) d = add_value(d, ['A', 'G'], ('log2.txt', '2kb')) d = add_value(d, ['X', 'Y', 'Z'], ('log2.txt', '3kb')) print(json.dumps(d, indent=2)) and output is : { "X": { "Y": …
has title: How to add some data to specific 'path' in python dict?
type: AnsweredQuestion
tagged with: algorithm
upvote count: 5
answer count: 1
has comment: http://stackoverflow.com/comment/86253538
favorite count: 0
has comment: http://stackoverflow.com/comment/86252903
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49623035
has comment: http://stackoverflow.com/comment/86253103

http://stackoverflow.com/comment/86272612
score: 0
type: Comment
type: QuestionComment
has text: You should post the data in line 13, that would give more clue
comment on: http://stackoverflow.com/q/49632641

http://stackoverflow.com/comment/86330317
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49649606
has text: @user2357112: the main reason is speed. For simple languages, using a well defined FSM with regexes is several orders of magnitudes faster than any generic recursive descent parser. In my current implementation, I can parse streamed lines faster that I get them from the network, with almost no memory footprint.

http://stackoverflow.com/a/49664125
answers question: http://stackoverflow.com/q/49664085
downvote count: 0
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
has body: You can use built-in function zip for that: for studread, studentname in zip(student_result_reading, student_name): print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread)) Also, if you are using Python 2, you, probably, encountering problem, with this two lines: student_name_enter = input("Please enter student name: ") and continueask = input("Would you like to enter someone else? ") I.e., if you enter something like student name as input for student name, you will get SyntaxError or NameError. Reason is, in Python 2, input function expects valid Python expression, in you case, string, like "student name", not simply student name. For later expression to be valid input, you can use function raw_input.
has comment: http://stackoverflow.com/comment/86338156
accepted answer of: http://stackoverflow.com/q/49664085

http://stackoverflow.com/q/49680416
favorite count: 0
tagged with: fuzzywuzzy
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49680515
has answer: http://stackoverflow.com/a/49680515
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have a list of words: lst = ['dog', 'cat', 'mate', 'mouse', 'zebra', 'lion'] I also have a pandas dataframe: df = pd.DataFrame({'input': ['dog', 'kat', 'leon', 'moues'], 'suggested_class': ['a', 'a', 'a', 'a']}) input suggested_class dog a kat a leon a moues a I would like to populate the suggested_class column with the value from lst that has the highest levenshtein distance to a word in the input column. I am using the fuzzywuzzy package to calculate that. The expected output would be: input suggested_class dog dog kat cat leon lion moues mouse I'm aware that one could implement something with the autocorrect package like df.suggested_class = [autocorrect.spell(w) for w in df.input] but this would not work for my situation. I've tried something like this (using from fuzzywuzzy import fuzz): for word in lst: for n in range(0, len(df.input)): if fuzz.ratio(df.input.iloc[n], word) &gt;= 70: df.suggested_class.iloc[n] = word else: df.suggested_class.iloc[n] = "unknown" which only works for a set distance. I've been able to capture the max distance with: max([fuzz.ratio(df.input.iloc[0], word) for word in lst]) but am having trouble relating that to a word from lst, and subsequently populating suggested_class with that word.
has title: Most Likely Word Based on Max Levenshtien Distance
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0
tagged with: levenshtein-distance

optimization
tags question: http://stackoverflow.com/q/49698432
tags question: http://stackoverflow.com/q/49610050
tags question: http://stackoverflow.com/q/49690720
tags question: http://stackoverflow.com/q/49643423
tag name: optimization
tags question: http://stackoverflow.com/q/49690450
tags question: http://stackoverflow.com/q/49731383
tags question: http://stackoverflow.com/q/49628200
tags question: http://stackoverflow.com/q/49720934
tags question: http://stackoverflow.com/q/49708476
tags question: http://stackoverflow.com/q/49633188
tags question: http://stackoverflow.com/q/49677505
tags question: http://stackoverflow.com/q/49719076
tags question: http://stackoverflow.com/q/49735841
tags question: http://stackoverflow.com/q/49681267
tags question: http://stackoverflow.com/q/49630143
tags question: http://stackoverflow.com/q/49625236
type: Tag
tags question: http://stackoverflow.com/q/49658698

http://stackoverflow.com/comment/86475447
score: 0
has text: Python is an interpreted language you can not run .py file within python console. You have to run it line by line within console.
type: AnswerComment
comment on: http://stackoverflow.com/a/49730489
type: Comment

http://stackoverflow.com/q/49652084
upvote count: 1
has answer: http://stackoverflow.com/a/49652480
favorite count: 0
type: Question
tagged with: python-3.x
has body: i try to install flask on my windows cmd and i got UnicodeDecodeError when installing MarkupSafe module Exception: Traceback (most recent call last): File "c:\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str return s.decode(sys.__stdout__.encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 5: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\python36\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\python36\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\python36\lib\site-packages\pip\req\req_install.py", line 878, in install spinner=spinner, File "c:\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess line = console_to_str(proc.stdout.readline()) File "c:\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str return s.decode('utf_8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 5: invalid continuation byte
tagged with: python
tagged with: flask
type: AnsweredQuestion
has title: i try to install flask on my windows cmd and i got UnicodeDecodeError when installing MarkupSafe module
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49652480
answer count: 1
tagged with: pip

http://stackoverflow.com/q/49599917
tagged with: python
tagged with: css
tagged with: python-2.7
score: 0
tagged with: django-templates
answer count: 0
has body: Below shown extended html of an app for a class based view is not taking css from static file as mentioned in html. Please help in how to implement css for this extended block. HTML File: {% extends "base_template.html" %} {%block css%} {% load static %} {%endblock%} {% block content %} Dynamic content You have visited this page {{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}. {% endblock %} Custom.css h1, h2, h3, h4, h5, h6 { color: black; } .btnlayout li form{ display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; width: 80px; } .btnlayout li { float: left; border-right:1px solid #bbb; border-left:1px solid #bbb; } base_template.html EKMMSC {% load static %} {% block css %}{% endblock %} I need the form elements to be displayed inline where as they are getting displayed as list. **Custom.css is present inside /static/css/* ** And static files are getting loaded as i have cross checked by putting image but css file isnt loading.
has comment: http://stackoverflow.com/comment/86212873
has comment: http://stackoverflow.com/comment/86295415
type: Question
has title: Extended template block not taking css from static
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86217231
tagged with: django

http://stackoverflow.com/comment/86482924
type: Comment
type: QuestionComment
has text: as timgeb said, you should re-structure your code to use OOP, what you are trying to do becomes easier with that.
score: 0
comment on: http://stackoverflow.com/q/49734332

http://stackoverflow.com/comment/86370846
type: AnswerComment
score: 0
type: Comment
has text: @Rokas98765 Hmm that's difficult. There's noone other than you who'll know whether or not code will be ''correct'' once written, certainly nothing inside `gym` itself that could check. A custom environment is precisely that: custom, it can be basically anything you want. The most important thing is to get an intuitive understanding of what the different functions are supposed to do. Then you can try putting `print()`s here and there, see if what you expect to happen happens. If you can get visualization running, that'll obviously help too, then you can look at the screen to see whats happening
comment on: http://stackoverflow.com/a/49678668

http://stackoverflow.com/comment/86426612
has text: @Itay4 i didnt know that actually...i tried to figure it out but i don't know yet how to set it up...
type: QuestionComment
comment on: http://stackoverflow.com/q/49704679
score: 0
type: Comment

http://stackoverflow.com/comment/86354707
type: QuestionComment
has text: Seems to work. Thanks!
type: Comment
comment on: http://stackoverflow.com/q/49671464
score: 0

http://stackoverflow.com/comment/86399515
type: QuestionComment
comment on: http://stackoverflow.com/q/49693558
score: 0
has text: give an example
type: Comment

http://stackoverflow.com/a/65854788
type: Answer
has body: I had this problem and ended up using simple tuples with text
answers question: http://stackoverflow.com/q/49705082
score: 0

http://stackoverflow.com/q/49682016
favorite count: 0
type: Question
tagged with: filtering
upvote count: 2
tagged with: odoo
downvote count: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 2
accepted answer: http://stackoverflow.com/a/49683272
type: AnsweredQuestion
has title: Add default filter in view - Odoo
tagged with: view
has body: I have created a view and defined my filter as follows: employee.search.view employee Then i created the one to display the employee details: employee.tree employee {"search_default_dept_search":1} Even though i upgrade my application, the filter i specified as {"search_default_dept_search":1} is not applied on the view. I want that default filter to be applied and I want that this filter can never be removed in the view.
has answer: http://stackoverflow.com/a/49683272
answer count: 1

http://stackoverflow.com/comment/86493625
type: AnswerComment
score: 0
has text: range(1, number_of_pages) will get number_of_pages - 1. So, if there are 61 pages, it will get 60 pages. I am using Python 3.5.
type: Comment
comment on: http://stackoverflow.com/a/49736102

http://stackoverflow.com/a/49620168
has body: I'm not certain that I understand your question, but I if I do then something like the following should work: # Create your input set. my_set = [[1, 3, 4, 10], [2, 4, 7, 1], [1, 4, 4, 8]] # Define a generic function. It sounds like you might use draw_square here. def do_something(): print("Doing something!") # Loop through each list in your input. for input_list in my_set: # Use the third element of the list to determine how many times # to do something (draw squares in your case). num_actions = input_list[2] for _ in range(num_actions): # This could be a function or any other logic you want. do_something() This code will loop through each list in my_set and for each list will call the function do_something x times, where x is the third element of the list.
answers question: http://stackoverflow.com/q/49620004
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/86257219
comment on: http://stackoverflow.com/a/49625104
type: AnswerComment
has text: Works perfectly, thanks :)
score: 0
type: Comment

http://stackoverflow.com/q/49750550
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49750962
has title: How to run python script with python from virtual environment without cmd
answer count: 1
downvote count: 0
tagged with: virtualenv
favorite count: 0
type: Question
has body: Does anyone know how to run python script with python from virtual environment without cmd. In Linux it is easy with shebang. Problem is that I have installed Python2 and on MyProject I have created virtual environment in Python3. Now when I click on main.py in MyProject I get syntax error and that is normal because it calls Python2 and in main.py I use async def that in Python2 doesn't exist. What I must add in main.py so that it automatically recognises that it should be executed by python3 located in virtual environment and not with windows assigned default python2. I don’t want to use cmd and I want all in main.py that is needed to run that py on click. Any ideas?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9079036
tagged with: python

http://stackoverflow.com/comment/86408500
comment on: http://stackoverflow.com/a/49697764
type: Comment
score: 0
type: AnswerComment
has text: Nice, I forgot about this one. One question, though. Does calling `groupby` automatically mean it's O(n log n) as in the background it creates groups by sorting? I seem to remember this was the case.

http://stackoverflow.com/a/49660486
downvote count: 0
has body: Given the DataFrame, df = pd.DataFrame({'Name': ['ABC'], 'Address': ['Line1, Line2, LineN, PostCode']}) Address Name 0 Line1, Line2, LineN, PostCode ABC If you need only post code, you can extract that using rsplit and re-assign it to the column Address. It will save you the step of concat. df['Address'] = df['Address'].str.rsplit(',').str[-1] You get Address Name 0 PostCode ABC Edit: Give that you have dataframe with address values in list df = pd.DataFrame({'Name': ['FAUCET INN LIMITED'], 'Address': 'Union, 88-90 George Street, London, W1U 8PA'}) Address Name 0 [Union, 88-90 George Street, London, W1U 8PA] FAUCET INN LIMITED You can get last element using df['Address'] = df['Address'].apply(lambda x: x[0].split(',')[-1]) You get Address Name 0 W1U 8PA FAUCET INN LIMITED
answers question: http://stackoverflow.com/q/49660209
has comment: http://stackoverflow.com/comment/86331073
upvote count: 8
has comment: http://stackoverflow.com/comment/86331092
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/49660209
type: AcceptedAnswer

anaconda
tags question: http://stackoverflow.com/q/49630609
tags question: http://stackoverflow.com/q/49645806
tags question: http://stackoverflow.com/q/49602688
tags question: http://stackoverflow.com/q/49635129
tags question: http://stackoverflow.com/q/49627859
type: Tag
tags question: http://stackoverflow.com/q/49739651
tags question: http://stackoverflow.com/q/49668760
tags question: http://stackoverflow.com/q/49646211
tag name: anaconda
tags question: http://stackoverflow.com/q/49733380
tags question: http://stackoverflow.com/q/49642516
tags question: http://stackoverflow.com/q/49751989
tags question: http://stackoverflow.com/q/49714910
tags question: http://stackoverflow.com/q/49659099
tags question: http://stackoverflow.com/q/49756618
tags question: http://stackoverflow.com/q/49722779
tags question: http://stackoverflow.com/q/49657742
tags question: http://stackoverflow.com/q/49741469
tags question: http://stackoverflow.com/q/49710553
tags question: http://stackoverflow.com/q/49736915
tags question: http://stackoverflow.com/q/49722143
tags question: http://stackoverflow.com/q/49755099
tags question: http://stackoverflow.com/q/49684669
tags question: http://stackoverflow.com/q/49731747
tags question: http://stackoverflow.com/q/49615395
tags question: http://stackoverflow.com/q/49601292
tags question: http://stackoverflow.com/q/49640452
tags question: http://stackoverflow.com/q/49678246
tags question: http://stackoverflow.com/q/49616399
tags question: http://stackoverflow.com/q/49600611
tags question: http://stackoverflow.com/q/49738702
tags question: http://stackoverflow.com/q/49735311
tags question: http://stackoverflow.com/q/49735569
tags question: http://stackoverflow.com/q/49681424
tags question: http://stackoverflow.com/q/49603097
tags question: http://stackoverflow.com/q/49647452
tags question: http://stackoverflow.com/q/49717462
tags question: http://stackoverflow.com/q/49714322

http://stackoverflow.com/comment/86410639
score: 0
comment on: http://stackoverflow.com/q/49698613
type: Comment
has text: Is that exactly how the sample answer appears on the page? Because when I run it, I get `SyntaxError: 'return' outside function`
type: QuestionComment

http://stackoverflow.com/comment/86371913
score: 0
comment on: http://stackoverflow.com/q/49679872
has text: Is it allowed to remap multiple characters to the same character? In other words, are `ab` and `cc` isomorphic? What about `ab` and `bb`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87253575
has text: When you set up a new virtual environment, you have to install django with `python -m pip install django` inside it. If it's not installed in your virtual env, it won't find django - even if you installed system-wide outside virtual environment. You can look here for a nice explanation: https://realpython.com/python-virtual-environments-a-primer/#how-does-a-virtual-environment-work
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50032168
score: 1

http://stackoverflow.com/q/49613268
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: I am running an optimization problem in torch. My torch installation is GPU compatible but for some odd reason it does not use the GPU at all when running. Everything seems to be done by the CPU and my local RAM. import numpy as np import scipy.sparse.csgraph as csg import torch from torch.autograd import Variable import torch.autograd as autograd import matplotlib.pyplot as plt %matplotlib inline def cmdscale(D): # Number of points n = len(D) # Centering matrix H = np.eye(n) - np.ones((n, n))/n # YY^T B = -H.dot(D**2).dot(H)/2 # Diagonalize evals, evecs = np.linalg.eigh(B) # Sort by eigenvalue in descending order idx = np.argsort(evals)[::-1] evals = evals[idx] evecs = evecs[:,idx] # Compute the coordinates using positive-eigenvalued components only w, = np.where(evals &gt; 0) L = np.diag(np.sqrt(evals[w])) V = evecs[:,w] Y = V.dot(L) return Y, evals Y = np.array([[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 1., 1., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 1., 0.], [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0.], [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 1., 0., 1., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0.]]) temp = Y[~np.all(Y == 0, axis=1)] temp = temp[:,~np.all(Y == 0, axis=1)] Y = np.asarray(temp, dtype='uint8') n = np.shape(Y)[0] k = 2 D = csg.shortest_path(Y, directed=True) Z = cmdscale(D)[0…
has comment: http://stackoverflow.com/comment/86270465
favorite count: 0
tagged with: gpu
score: 1
answer count: 1
tagged with: torch
type: Question
tagged with: pytorch
has answer: http://stackoverflow.com/a/49614777
has title: Torch code not running on GPU

http://stackoverflow.com/q/49696135
has title: How to add a column value into dataframe dictionary using a for loop so that each dataframe gets a unique column?
linked to: http://stackoverflow.com/q/13704860
favorite count: 0
score: 4
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49696368
answer count: 2
has comment: http://stackoverflow.com/comment/86405102
accepted answer: http://stackoverflow.com/a/49696443
downvote count: 0
has answer: http://stackoverflow.com/a/49696443
has comment: http://stackoverflow.com/comment/86405117
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
has body: I want to add the codes to the dataframe dictionary. codes = [['01', '02', '03', '05', '06', '08', '10', '11', '13', '15', '17', '19', '21', '23', '25', '27', '29', '31', '33', '35', '37', '39', '43', '45', '4.55', '48', '52'] #27Codes df = pd.read_excel(sales,sheet_name=None,ignore_index = True, skiprows=7) #27 Sheets for i in codes: for key in df.keys(): df['Sheet1']['Code'] = i I can't figure out why I seem to have the i in every dataframe. I think I understand why I can't figure out how to correct it. I am a beginner at coding. Expected output: df['Sheet1'] Date Particulars Inwards Code 1 2017-04-01 EFG 12800 01 2 2017-07-22 ABC 100 01 3 2017-09-05 BCD 10000 01 4 2018-03-13 ABC 2000 01 Code column should be 02 in the next dataframe and so on. After this I want to concat the dataframes and group_by particulars and then write to Excel.
has comment: http://stackoverflow.com/comment/86405322
tagged with: dataframe
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/49696368

http://stackoverflow.com/q/49609259
type: AnsweredQuestion
score: 1
answer count: 1
tagged with: python
has body: Aim is to see the scrollbars in the window: The function of drawing scrollbars has been taken from here: https://www.programcreek.com/python/example/52415/PyQt4.QtGui.QGraphicsScene What does the error mean and what am I supposed to do to solve it? import sys from PyQt4 import QtGui from PyQt4 import QtCore from PyQt4.QtGui import QMainWindow, QSizePolicy, QWidget, QVBoxLayout, QAction,\ QKeySequence, QLabel, QItemSelectionModel, QMessageBox, QFileDialog, QFrame, \ QDockWidget, QProgressBar, QProgressDialog from PyQt4.QtCore import SIGNAL, QSettings, QSize, QPoint, QVariant, QFileInfo, QTimer, pyqtSignal, QObject class Window(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QGraphicsView.__init__(self, parent) self.scene = QtGui.QGraphicsScene(self) self.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.darkGray, QtCore.Qt.SolidPattern)) self.setScene(self.scene) self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.viewport().setCursor(QtCore.Qt.CrossCursor) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self._pan = False self._draw = False self._moved = False self._sel = False self.pen = None self.penid = None self.cmap = None self.penwidth = 4 self._redoStack = [] self._histStates = [] self._baseRects = [] app = QtGui.QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) Error: Traceback (most recent call last): File "temp.py", line 42, in &lt;module&gt; GUI = Window() File "temp.py", line 21, in __init__ self.setScene(self.scene) AttributeError: 'Window' object has no attribute 'setScene'
has title: PyQt: self.setScene(self.scene) AttributeError: 'Window' object has no attribute 'setScene'
has answer: http://stackoverflow.com/a/49609366
type: Question
tagged with: pyqt
tagged with: pyqt4
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49609366

http://stackoverflow.com/comment/86303319
score: 0
type: Comment
type: AnswerComment
has text: def appender(a,b): a.sort(key = lambda l: l.score) a.append(b) return a[:10] -- Would it be like this?
comment on: http://stackoverflow.com/a/49647034

http://stackoverflow.com/comment/86242937
score: 1
type: QuestionComment
has text: @blue_note - If it's in the same app it depends how your 'message broker' is operating - if the communicator is in a separate thread, there are several options from `threading.Semaphore` to `threading.Event`. If it's operating as a separate process, check the `multiprocessing.Queue` and `multiprocessing.Manager` structures. If completely external, again, IPC/RPC can be easily achieved through sockets (there are even cute wrappers in the `multiprocessing.connection` package). Your question is way too broad for a simple/decisive answer.
type: Comment
comment on: http://stackoverflow.com/q/49617651

http://stackoverflow.com/comment/86310619
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49651202
has text: Where did 1519653600 come from?
score: 0

http://stackoverflow.com/q/49688972
has comment: http://stackoverflow.com/comment/86390102
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86389300
has comment: http://stackoverflow.com/comment/86390182
has comment: http://stackoverflow.com/comment/86389803
tagged with: django
tagged with: django-models
tagged with: python
has body: I am able to upload the files in django. I have also managed to register different users. But when the users log in , they all see the set of files that were uploaded by anyone. instead I want the user views only those set of files which he/she has uploaded. models.py from django.contrib.auth.models import User class Document(models.Model): user = models.ForeignKey(User) description = models.CharField(max_length=255, blank=True) document = models.CharField(max_length=255, ) uploaded_at = models.DateTimeField(auto_now_add=True) views.py def fileupload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() document = Document( description=request.POST['description'], document=myfile.name, uploaded_at=datetime.datetime.now(),) document.save() messages.success(request, 'Member was created successfully!') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return redirect('fileupload') else: documents = Document.objects.order_by('-uploaded_at')[:3] context = {'documents': documents} return render(request, 'fileupload.html', context)
score: 0
has comment: http://stackoverflow.com/comment/86390337
tagged with: django-views
has title: Django uploading files history for user
answer count: 0
has comment: http://stackoverflow.com/comment/86390219
has comment: http://stackoverflow.com/comment/86389477
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/86390042
has comment: http://stackoverflow.com/comment/86389528
has comment: http://stackoverflow.com/comment/86389954
has comment: http://stackoverflow.com/comment/86390302
has comment: http://stackoverflow.com/comment/86389450

gunicorn
tags question: http://stackoverflow.com/q/49632652
tags question: http://stackoverflow.com/q/49630981
tags question: http://stackoverflow.com/q/49706746
type: Tag
tags question: http://stackoverflow.com/q/49616505
tag name: gunicorn
tags question: http://stackoverflow.com/q/49712468
tags question: http://stackoverflow.com/q/49678805
tags question: http://stackoverflow.com/q/49754413
tags question: http://stackoverflow.com/q/49737354

http://stackoverflow.com/q/49710546
has comment: http://stackoverflow.com/comment/86442516
score: 0
answer count: 0
tagged with: pyqtgraph
has title: Display 3D Matrix using pyqtgraph
has comment: http://stackoverflow.com/comment/86436255
type: Question
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20839329
has comment: http://stackoverflow.com/comment/86434610
has body: I am trying to display a 3D matrix (distance matrix) using python programming and pyqtgraph (the plot is similar to this example in Matlab: MatLab - Euclidean Distance Plot 3D.) I have the list of points that I want to display on plot as x and y coordinates and the distance is already calculated and I have the related matrix. I have tried the examples related to Mesh and Surface Plot from the pyqtgraph.examples but the final plot is not what I am looking for. I am new to pyqtgraph. Can you help me with the method and the parameters that I can use for drawing this plot? EDIT: I have tried several codes and examples so far . In the following code I used this example https://gist.github.com/markjay4k/da2f55e28514be7160a7c5fbf95bd243 for the grids and Surface plot form pyqtgraph.examples but it doesn't show the plot. I am not sure if I should use Mesh or Surface plot. w = gl.GLViewWidget() w.opts['distance'] = 40 w.setWindowTitle('graph') w.setGeometry(0, 110, 1920, 1080) w.show() gx = gl.GLGridItem() gx.rotate(90, 0, 1, 0) gx.translate(-10, 0, 0) w.addItem(gx) gy = gl.GLGridItem() gy.rotate(90, 1, 0, 0) gy.translate(0, -10, 0) w.addItem(gy) gz = gl.GLGridItem() gz.translate(0, 0, -10) w.addItem(gz) x1 = [0,1,2,3] y1 = [0,1,2,3] x1=np.array(x1) y1=np.array(y1) z1 = [[22,33,44,55],[44,55,66,77],[11,22,33,44],[66,44,99,89]] z1=np.matrix(z1) p2 = gl.GLSurfacePlotItem(x=x1, y=y1, z=z1,shader='normalColor') p2.translate(-10,-10,0) w.addItem(p2)

http://stackoverflow.com/q/49681424
favorite count: 0
has comment: http://stackoverflow.com/comment/86377526
has comment: http://stackoverflow.com/comment/86375491
tagged with: pycharm
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86377536
has title: Using Conda Environment from PyCharm
has body: I've looked at all the responses in the search and specifically Use Conda environment in pycharm without resolving my problem. I'm on Win10 using the latest Anaconda and PyCharm for Python 3.6. The situation is that I've created a new environment using Conda which uses the Python version available in the base environment. Therefore, there is no python.exe in the newly created environment. In PyCharm, when I try to select the Conda environment, the dialog apparently does not see a Python there and refuses to set that as the environment. In PyCharm, I create a new Project (pure Python) and set the location for the project in my PyCharmProjects directory. I then try to select existing interpreter and navigate to the appropriate Conda environment which I'm unable to select. I'm not sure if there is something I don't understand or there is actually a problem here, but I'm getting a bit frustrated trying to find the proper approach. Any help appreciated. --Don
has comment: http://stackoverflow.com/comment/86375052
tagged with: python
type: UnansweredQuestion
tagged with: conda
has answer: http://stackoverflow.com/a/50011402
tagged with: anaconda
score: 2
linked to: http://stackoverflow.com/q/42746732
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/86247708
type: Comment
has text: I dont understand what you mean by entire exception. I am sorry. If run the code in current state, we can recreate the error. What I wanted to achieve was there are rows, for this case, 4th row, under PA column, data is with comma, I would like to split them into next row as well as respective columns "var2" and "var3".
type: QuestionComment
comment on: http://stackoverflow.com/q/49607549
score: 0

http://stackoverflow.com/q/49608540
has comment: http://stackoverflow.com/comment/86223984
favorite count: 0
type: Question
tagged with: django-timezone
has title: How do I get 1 day before timezone.now()
tagged with: timezone
has answer: http://stackoverflow.com/a/61086258
accepted answer: http://stackoverflow.com/a/49608674
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86223670
has comment: http://stackoverflow.com/comment/86224671
has answer: http://stackoverflow.com/a/49608674
upvote count: 6
has comment: http://stackoverflow.com/comment/86223921
has body: I have a button that should appear 1 day before the model object's start_date. In my view I have a functions that tells me if the object's start_date or end_date is now. def has_engagement(self): from rental.models import Inquiry inquiries = Inquiry.objects.filter(inquiryequipment__equipment=self).filter(start_date__lte= timezone.now()).\ filter(end_date__gte=timezone.now()).filter(status="CO") if not inquiries: return False # no current confirmed engagement else: return True # there is a current confirmed engagement instead of this, i need to check if today is a day before the start or end dates. Any ideas? Thanks
has comment: http://stackoverflow.com/comment/86223858
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/61086258
answer count: 2
has comment: http://stackoverflow.com/comment/86223699
score: 6
downvote count: 0

http://stackoverflow.com/q/49708101
type: Question
has comment: http://stackoverflow.com/comment/86432138
tagged with: rate-limiting
answer count: 2
has comment: http://stackoverflow.com/comment/86434043
type: UnansweredQuestion
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/86430867
tagged with: python
linked to: http://stackoverflow.com/q/35196974
favorite count: 0
has answer: http://stackoverflow.com/a/70510944
tagged with: aiohttp
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/86431205
has comment: http://stackoverflow.com/comment/86443727
linked to: http://stackoverflow.com/q/48682147
upvote count: 5
has comment: http://stackoverflow.com/comment/86431831
has title: aiohttp: rate limiting requests-per-second by domain
tagged with: asynchronous
has body: I am writing a web crawler that is running parallel fetches for many different domains. I want to limit the number of requests-per-second that are made to each individual domain, but I do not care about the total number of connections that are open, or the total requests per second that are made across all domains. I want to maximize the number of open connections and requests-per-second overall, while limiting the number of requests-per-second made to individual domains. All of the currently existing examples I can find either (1) limit the number of open connections or (2) limit the total number of requests-per-second made in the fetch loop. Examples include: aiohttp: rate limiting parallel requests aiohttp: set maximum number of requests per second Neither of them do what I am requesting which is to limit requests-per-second on a per domain basis. The first question only answers how to limit requests-per-second overall. The second one doesn't even have answers to the actual question (the OP asks about requests per second and the answers all talk about limiting # of connections). Here is the code that I tried, using a simple rate limiter I made for a synchronous version, which doesn't work when the DomainTimer code is run in an async event loop: from collections import defaultdict from datetime import datetime, timedelta import asyncio import async_timeout import aiohttp from urllib.parse import urlparse from queue import Queue, Empty from HTMLProcessing import processHTML import URLFilters SEED_URLS = ['http://www.bbc.co.uk', 'http://www.news.google.com'] url_queue = Queue() for u in SEED_URLS: url_queue.put(u) # number of pages to download per run of crawlConcurrent() BATCH_SIZE = 100 DELAY = timedelta(seconds = 1.0) # delay between requests from single domain, in seconds HTTP_HEADERS = {'Referer': 'http://www.google.com', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0'} class DomainTimer(): def __init__(self): self.timer = N…
has answer: http://stackoverflow.com/a/49717630

http://stackoverflow.com/a/53254860
type: Answer
has body: class SimpleExample(BaseWidget): def __init__(self): super().__init__('Simple example') self._scatter_plot = ControlMatplotlib() self._scatter_plot.value = plot_data def plot_data(figure): axes = figure.add_subplot(111) X = [i for i in range(0, 100, 2)] Y = [i for i in range(0, 150, 3)] axes.scatter(X, Y) if __name__ == '__main__': start_app(SimpleExample)
answers question: http://stackoverflow.com/q/49718416
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49735789
type: AcceptedAnswer
downvote count: 0
score: 16
upvote count: 16
has body: For a one liner simply run on Windows: set CUDA_VISIBLE_DEVICES=2,3 &amp; python my_script.py
answers question: http://stackoverflow.com/q/49735693
type: Answer
accepted answer of: http://stackoverflow.com/q/49735693

http://stackoverflow.com/comment/113756776
comment on: http://stackoverflow.com/a/49637877
has text: I have the same question, would be very helpful to know!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86490500
score: 0
type: AnswerComment
type: Comment
has text: Sorry, just call df.groupby(variable) not string ‘variable’
comment on: http://stackoverflow.com/a/49699769

http://stackoverflow.com/a/49684004
answers question: http://stackoverflow.com/q/49683944
score: 0
has body: In [1]: long_string = 'asdfsadfCosta Ricaasdkj asdfsd asdjas USA alsj' In [2]: 'Costa Rica' in long_string Out[2]: True You don't have your code properly shown and I'm a little too lazy to parse it. Hope this helps.
type: Answer

http://stackoverflow.com/a/49723482
type: Answer
has comment: http://stackoverflow.com/comment/86462026
score: 0
has body: The route you have configured would match only on a string literal [list]. Routes cannot match on Python objects, only strings and replacement markers. From Route Pattern Syntax under URL Dispatch: A pattern segment (an individual item between / characters in the pattern) may either be a literal string (e.g., foo) or it may be a replacement marker (e.g., {foo}), or a certain combination of both. Nonetheless you can extract a multidict from the request object. # Conjugation of English verbs is horrible config.add_route('show_chosen_categories', '/categories/') Assuming you have a list of checkboxes named the same or a select multiple input in a form, with either input being named category, then your request parameters would be generated to look like this: category=1&amp;category=2 Then any URL that begins with categories would be matched, and request parameters would be usable in your view, depending on your form action: # form action="POST" request.POST.getall('category') # form action="GET" request.GET.getall('category') &gt;&gt;&gt; [1, 2] See Multidict under Request and Response Objects for further information.
has comment: http://stackoverflow.com/comment/86472907
has comment: http://stackoverflow.com/comment/86516350
answers question: http://stackoverflow.com/q/49723179

http://stackoverflow.com/comment/86346624
type: AnswerComment
score: 0
has text: As the data shape is already a problem for a while, may I redirect you to another post I created where I explain the data with a nice image. That might make more sense than the actual data. The data amount is simplified but the principle is the same (just compare the first line of this post to the other post). : https://stackoverflow.com/questions/49577361/time-series-translation-into-keras-input
comment on: http://stackoverflow.com/a/49668012
type: Comment

http://stackoverflow.com/a/49624268
has body: 1) Add a menu function, I only did the first three so that you can get the idea (you can do the rest of them), for example. def menu(): print '1) Create a dictionary' print '2) Update the dictionary' print '3) Sort the dictionary' task = raw_input('Enter the number to perform the corresponding task: ') if task == '1': user_dict = creating_dictionary() elif task == '2': try: updating_dictionary(user_dict) except UnboundLocalError: print "A dictionary doesn't exist, you'll have to create one\n" creating_dictionary() elif task == '3': try: sorting_dictionary(user_dict) except UnboundLocalError: print "A dictionary doesn't exist, you'll have to create one\n" creating_dictionary() 2) add menu() as your first statement in main() 3) at the end of every function add a call to menu() 4) If you set it up correctly then the only call you'll need in main() is menu(). You'll be able to delete all of the other function calls since at the end of every function you'll be calling menu().
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49623390
has comment: http://stackoverflow.com/comment/86285363
downvote count: 0

http://stackoverflow.com/comment/86526366
type: QuestionComment
comment on: http://stackoverflow.com/q/49755239
type: Comment
score: 0
has text: I added data[i]=numpy.choice... is it clearer? I need that data[i,0]!=data[i,1] and the drawn couple data[i] in a list without replacement

http://stackoverflow.com/comment/86261440
type: Comment
comment on: http://stackoverflow.com/a/49620268
type: AnswerComment
has text: Literally written in the code.. thanks for your help, I'll double check better next time.
score: 1

http://stackoverflow.com/comment/86387084
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49687823
has text: A better explanation maybe: https://stackoverflow.com/a/40983245/3727050
score: 1

http://stackoverflow.com/a/49728426
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49728277
has comment: http://stackoverflow.com/comment/86471978
answers question: http://stackoverflow.com/q/49728277
has body: Consider having a look at the permissions defined for /usr/local/lib/python2.7/pip. Probably this directory is not readable, and consequently, Python cannot find pip distribution.
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/86431688
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49672570
has text: was the issue solved in the end? I am asking because in the other question you have wrote that it was a issue with the path, but here you say it is unreadable.
type: Comment

http://stackoverflow.com/a/49694778
type: Answer
has body: You could use str.count in a comprehension. Then wrap that in a data frame constructor. from pandas.io.common import StringIO as sio pd.read_csv(sio( ''.join(l for l in open('test.csv') if l.count(',') &gt; 2) ), header=None) 0 1 2 3 0 5 5 5 5 1 6 6 6 6 2 7 7 7 7
downvote count: 0
answers question: http://stackoverflow.com/q/49691983
upvote count: 1
score: 1

http://stackoverflow.com/comment/86424426
type: QuestionComment
has text: What version of Django are you using?
type: Comment
comment on: http://stackoverflow.com/q/49705082
score: 0

machine-translation
type: Tag
tags question: http://stackoverflow.com/q/49701826
tag name: machine-translation

http://stackoverflow.com/a/49731630
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49731494
answers question: http://stackoverflow.com/q/49731494
type: Answer
has body: IIUC, I think you need to transpose the dataframe to get index ['A','B','C','D']as x-axis and then plot. Also use plt.show() to display the histogram. The latest version of pandas will display directly the plot with axes object displaying. But, for the older versions need to explicitly write the plt.show() code to display. import matplotlib.pyplot as plt df.T.plot(kind='hist') plt.show()

http://stackoverflow.com/comment/86335925
has text: Could you elaborate I'm not sure I understand. You want the resultant array to be of shape (None,) correct?
type: Comment
comment on: http://stackoverflow.com/a/49662938
type: AnswerComment
score: 0

http://stackoverflow.com/a/51187997
has body: For NLTK Confusion Matrix you need a list classifier = NaiveBayesClassifier.train(trainfeats) refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) lsum = [] tsum = [] for i, (feats, label) in enumerate(testfeats): refsets[label].add(i) observed = classifier.classify(feats) testsets[observed].add(i) lsum.append(label) tsum.append(observed print (nltk.ConfusionMatrix(lsum,tsum))
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49713164
score: 1
type: Answer

http://stackoverflow.com/comment/86459321
has text: thanks, saw it. However i am still not able to run it. the same row five me the error KeyError: 'temp_id'. Does the python/pandas version may affect this? I am trying step by step..
comment on: http://stackoverflow.com/a/49714265
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49716559
type: Answer
answers question: http://stackoverflow.com/q/49716462
score: 0
has body: &gt;&gt;&gt; n = 2 &gt;&gt;&gt; seq = [2, 2, 1, 3] &gt;&gt;&gt; res = [] &gt;&gt;&gt; for i in range(len(seq) - n + 1): ... res.append(sum(seq[i:i+n])) ... &gt;&gt;&gt; res [4, 3, 4] This does the work - just loop through the elements upto len(seq) - n + 1 - this is because you don't want python to sum the last numbers which are less than n in length.

http://stackoverflow.com/a/49733160
type: Answer
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86948708
answers question: http://stackoverflow.com/q/49731937
has comment: http://stackoverflow.com/comment/86515954
has body: It will make is much easier you you will share a small dataset that illustrate the problem. However, I will state some of the issues with non-standards datasets and how to overcome them. Possible solutions Regularization and validation-based optimization - are methods that are always good to try when looking for some extra-accuracy. See dropout methods here (original paper), and some overview here. Unbalanced data - Sometimes of the time series categories/events behave like anomalies, or just in unbalanced ways. If you read a book, words like the or it will appear much more times than warehouse or such. This can become a problem if your main task is to detect the word warehouse and you train your network (even lstms) in traditional ways. A way to overcome this problem is by balancing the samples (creating balanced datasets) or to give more weight to low-frequent categories. Model structure - sometimes fully connected layers are not enough. See computer vision problems for instance, where we train using convolution layers. The convolution and pooling layers enforce structure on the model, which is suitable for images. This is also some sort of regulation, since we have less parameters in those layers. In time-series problems, convolutions are also possible and turns out that works just fine. See example in Conditional Time Series Forecasting with Convolution Neural Networks. The above suggestions are presented in the order I would suggest to try. Good luck!

http://stackoverflow.com/q/49664413
has comment: http://stackoverflow.com/comment/86339356
tagged with: python
has body: I have client_id something like this 'xxxx.apps.googleusercontent.com' I have a python dict like this { "name" : "M.S.Dhoni", "job" : "Wicket keeper" } Is there any way encrypt this dictionary based on the client_id to make it use as a token for each and every server call. plz give me hint how to do it. Thanks.
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has title: encrypting a python dictionary using client_id for using it as a token
has comment: http://stackoverflow.com/comment/86338556
tagged with: django
tagged with: django-rest-framework

http://stackoverflow.com/q/49675629
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49675839
tagged with: button
has comment: http://stackoverflow.com/comment/86363320
type: Question
has comment: http://stackoverflow.com/comment/86371908
has comment: http://stackoverflow.com/comment/86366105
linked to: http://stackoverflow.com/q/16424091
has comment: http://stackoverflow.com/comment/86363290
score: 0
has comment: http://stackoverflow.com/comment/86365151
tagged with: python
duplicate of: http://stackoverflow.com/q/16424091
has comment: http://stackoverflow.com/comment/86364672
tagged with: image
has body: I'm trying to create a loop of buttons in Tk while each of the buttons have image embedded to it, when I first tried the loop without images it worked but now when I add images it doesn't def menu_window(self, box): """Specific function for opening the menu window""" window = Toplevel() self.activate_window(window, 420, 380) # window default activation at size 400x400 menu = self.waiter.full_menu() SoupMaker(self.main_url+FOOD_IMAGES).get_images() # Download menu images. counter, rowc = 0, 0 for item in menu: # Create a button for every item in the website menu - on click, insert item to order list. food_img = ImageTk.PhotoImage(Image.open(item+'.png')) bt = Button(window, image=food_img) # on click if counter &gt;= 3 and counter % 3 == 0: counter = 0 rowc += 1 bt.configure(command=lambda i=item + ' ' + menu[item]: box.insert(END, i)) bt.grid(sticky='W', row=counter, column=rowc) # increase row number for every button counter += 1 print 'done buttons' window.mainloop() While the buttons do show in the window, they are empty and not usable(Configured commands don't work)... This is an image of the screen with the empty images: IMG LINK
has title: Tkinter Button Images not working in a loop
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86365012

http://stackoverflow.com/comment/86411528
has text: i still got an error after adding a wait statement saying Message: unknown error: Element ... is not clickable at point (900, 577). Other element would receive the click: ...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49698733
type: Comment

http://stackoverflow.com/q/49736915
has answer: http://stackoverflow.com/a/49737410
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86488563
downvote count: 0
has body: I am trying to run (from Spyder) a python script that contains the following code: if __name__ == "__main__": parser = argparse.ArgumentParser(description='Project description') parser.add_argument( 'nbr_workers', type=int, help='Number of workers e.g. 1, 2, 4, 8') parser.add_argument( '--nbr_samples_in_total', type=int, default=1e4, help='Number of samples in total e.g. 100000000') parser.add_argument( '--processes', action="store_true", default=True, help='True if using Processes, absent (False) for Threads') I know that I can use control + F6 in Spyder to submit command line options. However, I am not able to make it work. Entering generate the error runfile('C:/Users/john/.spyder/temp.py', args='3 1000 1', wdir='C:/Users/john/.spyder') usage: temp.py [-h] [--nbr_samples_in_total NBR_SAMPLES_IN_TOTAL] [--processes] nbr_workers temp.py: error: unrecognized arguments: 1000 1 An exception has occurred, use %tb to see the full traceback. SystemExit: 2 What am I doing wrong here? Thanks!
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86488549
tagged with: anaconda
type: Question
has title: how to pass boolean arguments in spyder?
tagged with: spyder
tagged with: python
accepted answer: http://stackoverflow.com/a/49737410
has comment: http://stackoverflow.com/comment/86488361
score: 1

http://stackoverflow.com/a/49661076
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49660813
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/86332073
score: 2
has comment: http://stackoverflow.com/comment/86332049
downvote count: 0
has body: Instead of using string operations, it's faster to convert the input to a number and use bit operations: parts = line.split(maxsplit=4) # remove spaces in the number and convert it to int from base 16 num = int(parts[4].replace(' ', ''), 16) # create a bit mask with exactly `length` 1s mask = (1 &lt;&lt; length) - 1 # calculate the offset from the right shift = 40 - start - length # shift the value to the right and apply the binary mask to get our value val = (num &gt;&gt; shift) &amp; mask According to my timings, the bit operations are faster by about 20%. Timing results with 1 million iterations: string_ops 2.735653492003621 seconds bit_ops 2.190693126998667 seconds
answers question: http://stackoverflow.com/q/49660813

http://stackoverflow.com/q/49660966
has comment: http://stackoverflow.com/comment/86331654
has answer: http://stackoverflow.com/a/49661008
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49661038
has answer: http://stackoverflow.com/a/49661007
tagged with: duplicates
tagged with: python
answer count: 6
has title: Removing duplicates from a list of tuples in python
has answer: http://stackoverflow.com/a/49661054
has comment: http://stackoverflow.com/comment/86331878
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/49661010
tagged with: set
has answer: http://stackoverflow.com/a/49665865
type: Question
has body: I have a list of tuples, and I want to remove duplicate tuples. Something like this. x = [['aaron','jeng'],['sdf','wqd'],['aaron','jeng']] I want the output something like this : y = [['aaron','jeng'],['sdf','wqd']] How can I do that in an easy way? I can write code to do that, but is there any inbuilt function for this? Edit 1 : As everyone has suggested, I'm sorry to call them tuples. I meant a list of lists. Thank You.

http://stackoverflow.com/a/49730746
score: 1
upvote count: 1
has body: It looks like you are using outdated Spark version and experience SPARK-21523 - Fix bug of strong wolfe linesearch init parameter lose effectiveness. If you use Spark 2.2 make sure to update to 2.2.1 release, where the bug is already fixed.
answers question: http://stackoverflow.com/q/49725614
type: Answer
downvote count: 0

http://stackoverflow.com/q/49711149
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86435875
has comment: http://stackoverflow.com/comment/86435923
upvote count: 1
tagged with: python
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/86436112
type: Question
has comment: http://stackoverflow.com/comment/86436089
score: 1
has body: Is there any smart way in Python to make bidirectional connections between objects? It's many-to-many type of connection. Take a look at this sample picture: All of the objects visible on the picture are also objects in my program. What I would like to achieve is that whenever I do something like print(object.connetions) I get a list of all connected objects. So looking at the sample picture when I do print(N2.connections) it lists R6,Jolie etc. Similarly print(AB.connections) prints P1...3, P8..0. What I currently implemented is one-way connection using list(), so that I am only able to print connections of AB object - it stores all connected objects(P1...3, P8..0) in a list. I know that one of the possible solutions is to add such a connection lists to all objects, but it would require two lists and two append() operations for every single connection. Do you now any other smart method to implement such functionality?
has answer: http://stackoverflow.com/a/49711971
has comment: http://stackoverflow.com/comment/86436238
has answer: http://stackoverflow.com/a/49711730
has title: Bidirectional connection between objects in Python

http://stackoverflow.com/q/49636021
type: AnsweredQuestion
tagged with: pandas
has body: I have the following dictionary: dct = { (1/1 , 2/1, 'AAPL') : pd.DataFrame({'aapl' : [1,2,3]}), (1/1, 2/1 , 'XOM') : pd.DataFrame({'xom' : [4,5,6]}) } and what I would like to do is concat the dataframes based on the first 2 values of the key (for eg. if 1/1 and 2/1 are a match among keys, then concat those frames). Results should look like: dct = { (1/1 , 2/1) : pd.DataFrame({'aapl' : [1,2,3], 'xom' : [4,5,6] })
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86279531
has comment: http://stackoverflow.com/comment/86279613
downvote count: 0
has comment: http://stackoverflow.com/comment/86279510
has comment: http://stackoverflow.com/comment/86279666
possible better answer: http://stackoverflow.com/a/49636092
has title: Concat python values based on similar keys in python dict
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49636187
has answer: http://stackoverflow.com/a/49636092
has answer: http://stackoverflow.com/a/49636187
has answer: http://stackoverflow.com/a/49636286
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86279571
has comment: http://stackoverflow.com/comment/86279559
answer count: 4
has answer: http://stackoverflow.com/a/49636137

http://stackoverflow.com/q/49675331
upvote count: 1
favorite count: 0
type: Question
has body: I am wondering if there is an efficient way to perform the following. I have two (numpy) arrays, and I would like to count the number of instances of a value occurring in one based on the criteria of another another array. For example: a = np.array([1,-1,1,1,-1,-1]) b = np.array([.75,.35,.7,.8,.2,.6]) I would like to calculate c as the number of 1's in a that occur when b > .5, so in this case `c = 3'. My current solution is ugly and would appreciate any suggestions.
accepted answer: http://stackoverflow.com/a/49675525
has answer: http://stackoverflow.com/a/49675525
tagged with: python
has answer: http://stackoverflow.com/a/49675408
has title: Count Instances in One Array Based on Another Array
type: AnsweredQuestion
tagged with: numpy
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/49675408
downvote count: 0

http://stackoverflow.com/a/49673956
has body: The batch size is automatically computed and added to the tensors shapes by Tensorflow, so it doesn't have to be done manually. Your generator should also be defined to output single samples. Assuming the 4 in position 0 of your shapes are for the batch size, then: import tensorflow as tf import numpy def _generator(): for i in range(100): feats = numpy.random.rand(2) labels = numpy.random.rand(1) yield feats, labels def input_func_gen(): shapes = ((2),(1)) dataset = tf.data.Dataset.from_generator(generator=_generator, output_types=(tf.float32, tf.float32), output_shapes=shapes) dataset = dataset.batch(4) # dataset = dataset.repeat(20) iterator = dataset.make_one_shot_iterator() features_tensors, labels = iterator.get_next() features = {'x': features_tensors} return features, labels x_col = tf.feature_column.numeric_column(key='x', shape=(2)) es = tf.estimator.LinearRegressor(feature_columns=[x_col]) es = es.train(input_fn=input_func_gen,steps = None)
has comment: http://stackoverflow.com/comment/90800603
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/90802878
accepted answer of: http://stackoverflow.com/q/49673602
type: Answer
answers question: http://stackoverflow.com/q/49673602
has comment: http://stackoverflow.com/comment/90959950
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49746957
upvote count: 2
answers question: http://stackoverflow.com/q/49746822
type: Answer
accepted answer of: http://stackoverflow.com/q/49746822
score: 2
type: AcceptedAnswer
downvote count: 0
has body: It is allowed, your problem is, that is is a reserved keyword, e.g. foo is None Rename your variable ;)

http://stackoverflow.com/a/49651316
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49651170
has body: Here is one way using pandas and numpy. import pandas as pd from io import StringIO str1 = StringIO(""" stat,a_a,b_a,c_a,d_a std,1,2,3,4""") str2 = StringIO(""" stat,a_b,b_b,c_b,d_b std,2,3,4,5""") # replace str1 &amp; str2 with 'file1.csv' and 'file2.csv' df1 = pd.read_csv(str1) df2 = pd.read_csv(str2) df = pd.DataFrame(np.median([df1.iloc[:, 1:].values, df2.iloc[:, 1:].values], axis=0), columns=list('abcd')).assign(stat=df1['stat']) df = df'stat', 'a', 'b', 'c', 'd' df.to_csv('file.csv', index=False) # stat a b c d # 0 std 1.5 2.5 3.5 4.5
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49696238
answer count: 2
linked to: http://stackoverflow.com/q/49018413
has answer: http://stackoverflow.com/a/49696337
upvote count: 1
tagged with: python
type: UnansweredQuestion
has title: subprocess.call() in windows 10 returns an error that it can't find the file
has answer: http://stackoverflow.com/a/75953499
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86405261
downvote count: 0
score: 1
has body: I am working on a unix script that needs some adaptations to work under windows 10. The script uses subprocess to perform file operations using DOS commands. Specifically, a statement that uses subprocess to copy a file from a directory to the current directory returns an error message. The correct DOS command is copy "D:\tess\catalog files\TIC55234031.fts" . However, ref_fits_filename="D:\TESS\catalog files\TIC55234031.fts" and subprocess.call(['copy ', ref_fits_filename,' .']) # copy the ref fits file to here which aims to perform exactly the same operation, goes wrong: Traceback (most recent call last): File "EBcheck.py", line 390, in subprocess.call(['copy ', ref_fits_filename,' .']) # copy the ref fits file to here File "C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 267, in call with Popen(*popenargs, **kwargs) as p: File "C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Users\FD-Computers\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified Obviously, there must be a subtle syntax error or an issue I haven't though of that causes the problem. Are there experts in Python programmming under windows 10 to clarify the issue on this forum ? The Python version used here is the recent Python 3.6.4.
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/87797163
type: QuestionComment
comment on: http://stackoverflow.com/q/49726598
has text: A bit late, but still: Checkout [TkinterTreeCtrl](http://tkintertreectrl.sourceforge.net/)
score: 0
type: Comment

http://stackoverflow.com/a/49737775
has comment: http://stackoverflow.com/comment/86498352
score: 0
has body: i = 1 while i &lt;= 6: print(n * i, '\t',) i += 1 print()
type: Answer
answers question: http://stackoverflow.com/q/49737648

http://stackoverflow.com/q/49663980
has comment: http://stackoverflow.com/comment/86337788
accepted answer: http://stackoverflow.com/a/49664149
tagged with: pyqt
has answer: http://stackoverflow.com/a/49664149
tagged with: pythonqt
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: unable to select rows in table widget In PyQGIS
has comment: http://stackoverflow.com/comment/86338017
upvote count: 0
has comment: http://stackoverflow.com/comment/86337890
tagged with: qgis
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86337932
has body: In PyQGIS design tablewidget, I have set table widget to be read-only and when I select particular,it is didn't read that row? self.dlg.ui.tableWidget.item(row, 1).setFlags(Qt.NoItemFlags) unable to select rows in table widget,to read datas.
type: AnsweredQuestion

http://stackoverflow.com/comment/86552244
type: Comment
has text: @bigT rather use `parser.error`, they don't need to see a traceback.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49706078

http://stackoverflow.com/a/49631260
answers question: http://stackoverflow.com/q/49631178
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/127067918
downvote count: 1
score: 8
has body: Use functools.partial combined with a dictionary in this situation. I assume what you really want to do is more complex, since multiple functions are not necessary for this specific task. from functools import partial def add(x, i): return x + i d = {f'add{k}': partial(add, i=k) for k in range(1, 10)} d['add3'](5) # 8 Explanation It is good practice to store a variable number of related objects in a specially defined dictionary. functools.partial is a higher order function which returns an input function with selected argument(s) fixed. Polluting the namespace From the comments, a commonly asked question goes: OP seems to be asking if there's a better way of just doing def add1:... def add2:... While I agree with your solution, I don't agree with the fact that it's the solution to the current question. - MooingRawr Why is using an iterator to define functions a bad idea? It seemed like a good way to shorten code to me. Is it generally better to define them one by one? – jessica My short answer: Using globals().update to pollute the namespace is a bad idea.. Hold related variables in specially made collections. It makes sense from any viewpoint (maintainability, calling, modifying, etc). – jpp @BoarGules's extend answer: It's not a good idea because it creates functions dynamically, but they can only be called by static code (otherwise the code wouldn't know what to call), so what's the point of them being dynamic? Creating them dynamically makes the code hard to read (you can't easily search for the function definition) and gives IDEs unnecessary trouble in their efforts to help you. You save tedious, repetitive coding, but programming sometimes entails tedious and careful repetition. The effort and skill would be better spent speeding up the coding (clever search/replace, macros, whatever). – BoarGules
upvote count: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/49631178

http://stackoverflow.com/a/49692616
type: Answer
has comment: http://stackoverflow.com/comment/86403358
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49691763
has body: Rather than closing and opening new sockets repeatedly, I would suggest maintaining multiple open socket connections server side and handling each socket using the select() method. https://docs.python.org/2/library/select.html https://pymotw.com/2/select/ Can a server handle multiple sockets in a single thread?
answers question: http://stackoverflow.com/q/49691763
has comment: http://stackoverflow.com/comment/86403708

http://stackoverflow.com/comment/86414130
comment on: http://stackoverflow.com/q/49699242
type: Comment
type: QuestionComment
has text: Did you make sure that `window_length` and `timesteps` are equal?
score: 0

http://stackoverflow.com/comment/86614524
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49767210
has text: Alright I think I found the solution that worked for me. You need to build your app with Incremental included as a dependency first without twisted. After incremental is built into your .buildozer build then go back and build with twisted included in your dependencies.

python-3.6
tags question: http://stackoverflow.com/q/49672351
tags question: http://stackoverflow.com/q/49677625
tags question: http://stackoverflow.com/q/49639242
tags question: http://stackoverflow.com/q/49735639
tags question: http://stackoverflow.com/q/49727872
tags question: http://stackoverflow.com/q/49603867
tags question: http://stackoverflow.com/q/49602620
tags question: http://stackoverflow.com/q/49719333
tags question: http://stackoverflow.com/q/49736023
tags question: http://stackoverflow.com/q/49640637
tags question: http://stackoverflow.com/q/49626150
tags question: http://stackoverflow.com/q/49711843
type: Tag
tag name: python-3.6
tags question: http://stackoverflow.com/q/49691601
tags question: http://stackoverflow.com/q/49639072
tags question: http://stackoverflow.com/q/49706228
tags question: http://stackoverflow.com/q/49757889
tags question: http://stackoverflow.com/q/49610255
tags question: http://stackoverflow.com/q/49741175
tags question: http://stackoverflow.com/q/49637441
tags question: http://stackoverflow.com/q/49631163
tags question: http://stackoverflow.com/q/49733506
tags question: http://stackoverflow.com/q/49648180
tags question: http://stackoverflow.com/q/49753612
tags question: http://stackoverflow.com/q/49638700

http://stackoverflow.com/comment/86264347
type: Comment
has text: Thanks! That works fine, too (upvoted), but seems slower than the other solution and then also requires to create temporary files which I would like to avoid...
score: 0
comment on: http://stackoverflow.com/a/49628720
type: AnswerComment

http://stackoverflow.com/a/49641967
has body: You could try: with open('file.csv') as fin: reader = csv.reader(fin) [fout.write(r[0],r[1]) for r in reader] If you need further help, leave a comment.
answers question: http://stackoverflow.com/q/49641899
score: 0
type: Answer

http://stackoverflow.com/comment/86240149
has text: do you have any other python version installed on your computer? also see if you have django in pip installed list you can see all of them by typing `pip freeze` alternatively try to install django inside a virtualenv with `virtualenv env` and `env\Scripts\activate` and then `pip install django` - it'll only install it for that local env
score: 0
comment on: http://stackoverflow.com/q/49616506
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49698919
has body: Pandas would probably be a good option import pandas as pd pd.DataFrame(cust_rec).T Otherwise try this: for key, vals in cust_rec.iteritems(): to_print = '\t'.join(str(val) for val in vals) print key + '\t' + to_print
score: 0
has comment: http://stackoverflow.com/comment/86411125
type: Answer
has comment: http://stackoverflow.com/comment/86411232
answers question: http://stackoverflow.com/q/49698809

http://stackoverflow.com/comment/86441189
comment on: http://stackoverflow.com/a/49713914
score: 0
has text: @Primusa This statement results in True against a small list of [1, 2, 3] when I should see False.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49723167
answers question: http://stackoverflow.com/q/49722928
has body: As BoarGules commented, I was using the wrong environment. The package was installed on another environment. I switched to Anaconda 5, where the package is installed, and now it works. I leave a screen capture on how to change to Anaconda. https://i.sstatic.net/2WSAi.png
score: 0
type: Answer

http://stackoverflow.com/comment/86357681
comment on: http://stackoverflow.com/a/49673276
has text: What does type(data) print after json.loads(data)?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86395653
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49691737
has text: @Noxeus for example, inside 'xxx.tar.gz' there is an unique folder ('folder'), inside folder 'folder' there are files like: image.jpg, text.txt,text2.txt... If I run the code, I get my_path/extracted/folder/, and inside: text.txt,text2.txt
type: Comment

http://stackoverflow.com/comment/86590133
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49735509
score: 0
has text: i gave two strings in k and s so wrote like that,it can be anything

http://stackoverflow.com/q/49635129
type: Question
tagged with: python-3.x
tagged with: vtk
has comment: http://stackoverflow.com/comment/86279019
tagged with: anaconda
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70523931
tagged with: python
has comment: http://stackoverflow.com/comment/88675634
has comment: http://stackoverflow.com/comment/88659521
score: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86278405
answer count: 2
upvote count: 2
downvote count: 0
has body: Win 10, x64, Python 3.6.6 &amp; Python 2.7.12 (I tried the code in both), IPython 6.1.0 So far I am only able to run VTK projects using Visual Studio in C++ but would like the ease of using an interpreted language for development. So I installed the latest VTK via the Anaconda command prompt, conda install -c anaconda vtk No problems everything updated &amp; superseded as necessary. So I tried out a trial program from the Python examples only to get... ModuleNotFoundError: No module named 'vtk' I added C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\pkgs\vtk-8.1.0-py36he6bbf13_201\Lib\site-packages\vtk to my PYTHONPATH in Spyder but I still get the same error. Any idea why IPython cant see the vtk library? EDIT: VTK shows up as an installed library when I type conda list at the command line
has title: Anaconda VTK install missing VTK module?
has answer: http://stackoverflow.com/a/51358650
favorite count: 0

http://stackoverflow.com/a/49972795
type: Answer
has body: example.robot file * Settings * Library example.py Documentation A test suite with a single test for valid login. ... ... This test has a workflow that is created using keywords in ... the imported resource file. * Variables * ${Host} 0.0.0.0 ${Port} 45141 * Test Cases * Test_1 [Tags] example [Documentation] Sample Test smoke 4 1 Test_2 [Tags] example [Documentation] Sample Test smoke 3 Test_3 [Tags] example [Documentation] Sample Test smoke 6 1
score: 0
answers question: http://stackoverflow.com/q/49739628

freeze
tags question: http://stackoverflow.com/q/49756273
type: Tag
tag name: freeze

http://stackoverflow.com/a/49675526
type: AcceptedAnswer
downvote count: 0
has body: from PyQt5 import QtWidgets class ResultView(QtWidgets.QGraphicsView): def __init__(self, parent): super(ResultView, self).__init__(parent) or from PyQt5 import QtWidgets class ResultView(QtWidgets.QGraphicsView): def __init__(self): super(ResultView, self).__init__(self.parent) the correct syntax is: super(AnotherDialog, self).__init__(parent, **kwargs)
has comment: http://stackoverflow.com/comment/86363454
type: Answer
has comment: http://stackoverflow.com/comment/86362037
accepted answer of: http://stackoverflow.com/q/49675279
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49675279

http://stackoverflow.com/comment/86347900
type: AnswerComment
has text: @nerak99 Have you tried the code that I have proposed?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49668757

http://stackoverflow.com/comment/86391191
comment on: http://stackoverflow.com/q/49689807
type: Comment
type: QuestionComment
score: 0
has text: What is the error?

http://stackoverflow.com/comment/87041224
score: 0
has text: Thank you so much for the detailed explanation. I learned so much reading your answer.
type: Comment
comment on: http://stackoverflow.com/a/49738373
type: AnswerComment

http://stackoverflow.com/comment/86413060
type: Comment
type: QuestionComment
has text: all data1 items are like: {'cty': 'United Kingdom', 'hse': 'House of Blois', 'nm': 'Stephen', 'yrs': '1135-1154'}
comment on: http://stackoverflow.com/q/49699779
score: 0

http://stackoverflow.com/q/49608461
has comment: http://stackoverflow.com/comment/86223775
tagged with: indexing
has answer: http://stackoverflow.com/a/49608760
accepted answer: http://stackoverflow.com/a/49608760
type: AnsweredQuestion
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86223475
tagged with: loops
has body: I have a pandas data-frame with axes like Time[s], Time[s].1, Time[s].2 ans so on up to Time[s].30. I want to find out the column with the maximum resolution. For that I need to put those all in a for loop I think. As the name 'Time[s].x' is a string, I don't know how to iterate it from 0 to 30. for i in df['Time[s]."Something to write here"]: Sample Input dataframe: (The columns are till Time[s].30) Time[s] v1 Time[s].1 v2 160.84621 0 160.84808 7 161.14613 0 161.14802 7 Sample Output: 'Time[s]' As the interval i.e (df['Time[s]'][1] - df['Time[s]][0]) is less than (df['Time[s].1'][1] - df['Time[s].1][0]). I need to check with all 30 columns.
has comment: http://stackoverflow.com/comment/86224082
favorite count: 0
has title: Iterate a for loop with an integer which is a part of a string
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/86224211
answer count: 1
tagged with: python

http://stackoverflow.com/comment/86365554
comment on: http://stackoverflow.com/q/49676954
type: Comment
type: QuestionComment
score: 0
has text: @CharlesDuffy, maybe I'm missing something here, but, XPath can't be used with BeautifulSoup.

http://stackoverflow.com/a/49667730
has body: First point: instead of blindly assuming there will be a "sport_events" key in the response data, just check what you really have. Your resp variable is a plain python dict, which api is very extensively documented. Also you should wrap the request in a try/except (HTTP requests can very easily fail...) and check the response status code before the response.json() call (and wrap this call in another try/except - it's not garanteed to succeed even with a 200 status code and an application/json content type in the response). Second point: don't build your dates from integers and string formatting, use the stdlib's datetime module instead (or some 3rd part wrapper around it like dateutil) and a strftime() call to format the date object to string. As a side note, this: for i in range(len(a)): s.append(a[i]['competitors']) is the uselessly complicated way to write: for item in a: s.append(item['competitors']) which itself can be rewritten as: s = [item["competitor"] for item in a] but I wonder why you bother building this list since you only use it's first item, so you could as well replace this: s = [] #looping through json output received for i in range(len(a)): s.append(a[i]['competitors']) gm = s[0] with: gm = a[0]["competitor"]
type: Answer
answers question: http://stackoverflow.com/q/49665969
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49695305
answers question: http://stackoverflow.com/q/49694818
has body: You're using a POST method, which is not allowed in this url: &gt;&gt; request.get_method() 'POST' Google search expects a GET. Every time you include the data in the request, it will automatically be a POST. But instead, you can do this directly: response = urllib.request.urlopen('{0}?{1}'.format(url, data))
type: Answer
score: 0

http://stackoverflow.com/comment/119032771
type: Comment
comment on: http://stackoverflow.com/a/55620248
has text: Worked fine on windows
type: AnswerComment
score: 0

http://stackoverflow.com/a/49726341
has comment: http://stackoverflow.com/comment/86466449
has comment: http://stackoverflow.com/comment/86470201
has comment: http://stackoverflow.com/comment/86470195
score: 0
has body: try to add below method to your form from django import forms from .models import User class RegistrationForm(forms.Form): # .............. # .............. def clean(self): mail = form.cleaned_data['email'] if User.objects.filter(email=mail).exists(): raise forms.ValidationError('Looks like email already exists') return self.cleaned_data change the code in views.py if User.objects.filter(email=mail).exists(): raise new_form.ValidationError('Looks like email already exists') else: new_form.save() to new_form.save()
type: Answer
answers question: http://stackoverflow.com/q/49726193

http://stackoverflow.com/a/49623839
type: Answer
answers question: http://stackoverflow.com/q/49623436
score: 5
downvote count: 0
upvote count: 5
has body: Since you have a binary_classification task your last layer should look something like this model.add(Dense(1, activation='sigmoid')) Right now you model is out puting 3D array which don't match the shape of your target (2D)

http://stackoverflow.com/comment/127392636
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).
score: 1
type: Comment
comment on: http://stackoverflow.com/a/72098885
type: AnswerComment

http://stackoverflow.com/q/49682567
has title: How can I slice the beginning and end of a pandas dataframe?
score: 0
has body: I have 100 values in a dataframe and I want to print a nice table using tabulate. This works for me: print(tabulate(dat], headers='keys', tablefmt='psql')) Now, this prints out the entire dataframe. I couldn't get the relevant slicing info here: Understanding Python&#39;s slice notation But I want to print out the first 5 values and then a few ... and then the last 5 values. Example: 4 2 1 5 1 . . 4 1 2 4 5 How can I do it?
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/49682638
tagged with: slice
has comment: http://stackoverflow.com/comment/86376860
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49682638
answer count: 1
linked to: http://stackoverflow.com/q/509211
type: Question

http://stackoverflow.com/q/49632327
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49636477
accepted answer: http://stackoverflow.com/a/49636477
has body: Suppose I have a speak function: def speak(): print("moo") I can disassemble it as one usually does, with dis.dis: &gt;&gt;&gt; dis.dis(speak) 2 0 LOAD_GLOBAL 0 (print) 3 LOAD_CONST 1 ('moo') 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 9 POP_TOP 10 LOAD_CONST 0 (None) 13 RETURN_VALUE But I want to destruct the code object associated with the speak function into a sequence of instructions, and then compile these back. With the help of dis.Bytecode, I can get a sequence of dis.Instructions that represents the code object: &gt;&gt;&gt; bytecode = dis.Bytecode(speak) &gt;&gt;&gt; for instruction in bytecode: ... print(instruction) ... Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=0, starts_line=2, is_jump_target=False) Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval='moo', argrepr="'moo'", offset=3, starts_line=None, is_jump_target=False) Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='1 positional, 0 keyword pair', offset=6, starts_line=None, is_jump_target=False) Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=9, starts_line=None, is_jump_target=False) Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=10, starts_line=None, is_jump_target=False) Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=13, starts_line=None, is_jump_target=False) Is there a straightforward way to compile these Instruction objects into the original code object? For instance, I'm looking for a compile_back function that would take a sequence of instructions and output an executable code object: &gt;&gt;&gt; code_object = compile_back(dis.get_instructions(speak)) &gt;&gt;&gt; exec(code_object) moo
tagged with: bytecode-manipulation
type: Question
upvote count: 2
tagged with: python-3.x
tagged with: bytecode
downvote count: 0
answer count: 1
tagged with: python
has title: Recompile Python bytecode instructions
favorite count: 0
score: 2

http://stackoverflow.com/q/49634506
favorite count: 0
type: Question
has title: Error installing scipy package on Windows
has body: I was trying to install some specific packages for python2.7 on Windows using pip and got the following error while trying to install scipy 0.16.1: (env) C:\Users\Asus\Documents\LEI\Algo-Rhythm&gt;pip install --no-use-wheel scipy==0.16.1 DEPRECATION: --no-use-wheel is deprecated and will be removed in the future. Please use --no-binary :all: instead. Collecting scipy==0.16.1 Using cached scipy-0.16.1.tar.gz Skipping bdist_wheel for scipy, due to binaries being disabled for it. Installing collected packages: scipy Running setup.py install for scipy ... error Complete output from command c:\users\asus\documents\lei\algo-rhythm\env\scripts\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\asus\\appdata\\local\\temp\\pip-build-itlx8i\\scipy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\asus\appdata\local\temp\pip-uzs8w6-record\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\asus\documents\lei\algo-rhythm\env\include\site\python2.7\scipy: lapack_opt_info: openblas_lapack_info: libraries openblas not found in ['c:\\users\\asus\\documents\\lei\\algo-rhythm\\env\\lib', 'C:\\'] NOT AVAILABLE lapack_mkl_info: mkl_info: libraries mkl,vml,guide not found in ['c:\\users\\asus\\documents\\lei\\algo-rhythm\\env\\lib', 'C:\\'] NOT AVAILABLE NOT AVAILABLE atlas_3_10_threads_info: Setting PTATLAS=ATLAS c:\users\asus\documents\lei\algo-rhythm\env\lib\site-packages\numpy\distutils\system_info.py:635: UserWarning: Specified path C:\projects\np-wheel-builder\atlas-builds\atlas-3.11.38-sse2-64\lib is invalid. warnings.warn('Specified path %s is invalid.' % d) &lt;class 'numpy.distutils.system_info.atlas_3_10_threads_info'&gt; NOT AVAILABLE atlas_3_10_info: &lt;class 'numpy.distutils.system_info.atlas_3_10_info'&gt; NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS &lt;class 'numpy.distutils.system_info.at…
tagged with: windows
accepted answer: http://stackoverflow.com/a/49635467
tagged with: pip
tagged with: python
type: AnsweredQuestion
tagged with: installation
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49635467
tagged with: scipy

http://stackoverflow.com/q/49651353
tagged with: wtforms
tagged with: python
has answer: http://stackoverflow.com/a/49790537
tagged with: flask
tagged with: flask-sqlalchemy
downvote count: 1
has body: i am new in codding and flask and i want to know how to retrieve the combo box value based on the previous combo box. i followed the tutorial and successfully to retrieve the first combo box value from the database. https://www.youtube.com/watch?v=b9W2ul2VRRc&amp;t=761s now based on that value i want to retrieve the second value. could you please check my code and advice how i need to put the filter condition suppose i have to combo box first customer_name and second instance_name. if i choose customer =tcs then corresponding instance_name must be showin in the next combo box like instance_name = tcs_test_33i class custdetail(db.Model): cust_id = db.Column(db.Integer, primary_key=True) customer = db.Column(db.String(50)) instance_name = db.Column(db.String(50)) def Customer_query(): return custdetail.query def Customer_query_env(): return custdetail.query#.filter(custdetail.customer == customer) class CustomerForm(FlaskForm): opts = QuerySelectField(query_factory=Customer_query, allow_blank=False, get_label='customer') class CustomerEnv(FlaskForm): opts1 = QuerySelectField(query_factory=Customer_query_env, allow_blank=False, get_label='instance_name') @app.route('/runpage/', methods=['GET', 'POST']) def index(): form = CustomerForm() form1 = CustomerEnv() form.opts.query = custdetail.query.filter(custdetail.cust_id &gt; 0) #form1.opts1.query = custdetail.query.filter(custdetail.customer == format(form.opts.data)) if form.validate_on_submit(): return '&lt;html&gt;&lt;h1&gt;{}&lt;/h1&gt;&lt;/html&gt;'.format(form.opts.data) if form1.validate_on_submit(): return '&lt;html&gt;&lt;h1&gt;{}&lt;/h1&gt;&lt;/html&gt;'.format(form1.opts1.data) return render_template('runpage.html', form=form, form1=form1) if __name__ == '__main__': app.run(debug=True)
type: AnsweredQuestion
score: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/49790537
answer count: 1
favorite count: 0
type: Question
tagged with: flask-wtforms
has title: how to retrieve second value based on previous value in flask

http://stackoverflow.com/comment/86396605
type: Comment
type: QuestionComment
has text: @Foki My previous comment solves your issue: just create a link pointing to the file. And that's what [the answer I was referring to](https://stackoverflow.com/a/1696905/1081569) suggests. If you can't figure it out you can open a new question with your attempt and why it fails.
comment on: http://stackoverflow.com/q/49691443
score: 0

http://stackoverflow.com/q/49725588
tagged with: python
score: -1
has body: I want to get class instance into function as argument, like code below. I know it doesn`t work. class coordinate: x = 1 y = 2 inst = coordinate() def get_class(instance): return instance.x + instance.y get_class(inst) Just getting instance`s inner variable is one of the solution, but the class that I want to use contains pretty diverse things. It makes code confusing x = inst.x y = inst.y def get_class(x, y): return x + y get_class(x, y) Is there any possible way?
tagged with: class
upvote count: 0
tagged with: arguments
has title: getting instance as argument python
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49725644
answer count: 1
has comment: http://stackoverflow.com/comment/86494029

http://stackoverflow.com/q/49601263
favorite count: 0
type: Question
answer count: 2
tagged with: pytorch
type: UnansweredQuestion
downvote count: 0
tagged with: machine-learning
has title: Loss doesn't decrease in training the pytorch RNN
tagged with: python
has body: Here is the RNN network I designed for a sentiment. class rnn(nn.Module): def __init__(self, input_size, hidden_size, output_size): super().__init__() self.hidden_size = hidden_size self.i2h = nn.Linear(input_size, hidden_size) self.h2o = nn.Linear(hidden_size, output_size) self.h2h = nn.Linear(hidden_size , hidden_size) self.relu = nn.Tanh() self.sigmoid = nn.LogSigmoid() def forward(self, input, hidden): hidden_new = self.relu(self.i2h(input)+self.h2h(hidden)) output = self.h2o(hidden) output = self.sigmoid(output) return output, hidden_new def init_hidden(self): return Variable(torch.zeros(1, self.hidden_size)) Then, I create and train the network as : RNN = rnn(50, 50, 1) learning_rate = 0.0005 criteria = nn.MSELoss() optimizer = optim.Adam(RNN.parameters(), lr=learning_rate) hidden = RNN.init_hidden() epochs = 2 for epoch in range(epochs): for i in range(len(train['Phrase'])): input = convert_to_vectors(train['Phrase'][i]) for j in range(len(input)): temp_input = Variable(torch.FloatTensor(input[j])) output, hidden = RNN(temp_input, hidden) temp_output = torch.FloatTensor([np.float64(train['Sentiment'][i])/4]) loss = criteria( output, Variable(temp_output)) loss.backward(retain_graph = True) if (i%20 == 0): print('Current loss is ', loss) The problem is that the loss of the network isn't decreasing. It increases, then decreases and so on. It isn't stable at all. I tried using a smaller learning rate but it doesn't seem to help. Why is this happening and how can I rectify this?
has comment: http://stackoverflow.com/comment/86218174
has comment: http://stackoverflow.com/comment/86216093
has comment: http://stackoverflow.com/comment/86220803
has answer: http://stackoverflow.com/a/51021966
has answer: http://stackoverflow.com/a/49607636
upvote count: 1
score: 1
tagged with: recurrent-neural-network

http://stackoverflow.com/comment/86518938
type: Comment
has text: "I want to create another file and class to continue first file and class" => I'm not sure to understand what you __really__ mean by this but one thing is sure: "continuing a file and class" just doesn't make sense (it's a syntactically correct sentence, but about as sensible as "I want my rhodoid to grow a tractor and squash the sea").
score: 0
comment on: http://stackoverflow.com/q/49751425
type: QuestionComment

http://stackoverflow.com/comment/86406465
score: 0
has text: Thanks @pault the explanation really helps with remembering and learning. If possible could you add how to `groupby` ['Particulars'], it returns an object and I can't seem to figure out(even though there are a lot of answers to it) why I can't get a `Dataframe` from it. Basically want to get all the rows with the same `Particulars` into a new dataframe. I have a way of doing it but it seemed `groupby` and `sort` should have been used.
type: Comment
comment on: http://stackoverflow.com/a/49696443
type: AnswerComment

http://stackoverflow.com/q/49650569
has comment: http://stackoverflow.com/comment/86321730
duplicate of: http://stackoverflow.com/q/1132941
tagged with: class
has comment: http://stackoverflow.com/comment/86309290
has comment: http://stackoverflow.com/comment/86309797
linked to: http://stackoverflow.com/q/1680528
score: 1
favorite count: 0
tagged with: static
has body: Below is the documented way to create a mutable non-static class variable in python. class Cla: def __init__(self): self.arr = [] def showIds(self): print(str(id(self.arr))) def show(self): print(self.arr) a = Cla() b = Cla() a.showIds() b.showIds() a.arr.append(10) b.arr.append(20) a.show() b.show() And it works (Sample output ...) 140174126200712 140174126185032 [10] [20] However, to accept some arguments while creating, I modified the __init__ to below. (Only change is in the __init__ function. class Cla: def __init__(self, arr=[]): self.arr = arr def showIds(self): print(str(id(self.arr))) def show(self): print(self.arr) a = Cla() b = Cla() a.showIds() b.showIds() a.arr.append(10) b.arr.append(20) a.show() b.show() And suddenly the list becomes shared. 140711339502152 140711339502152 [10, 20] [10, 20] My question is why? What is wrong with above approach. PS: I have gone through below already. Static class variables in Python -- Lists &amp; Objects How to avoid having class data shared among instances?
has title: What is wrong with the following code in Python?
linked to: http://stackoverflow.com/q/1132941
type: Question
answer count: 0
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/30809431

http://stackoverflow.com/q/49665316
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49669790
tagged with: python
has answer: http://stackoverflow.com/a/49665816
has title: getting data from HTML code using loop
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: selenium
tagged with: web-scraping
type: Question
answer count: 2
has body: I'm trying to scrape data from a simple website and save it into a CSV file using python 2.7 with selenium but I'm stuck with one little problem. As you can see below in the HTML, there are 2 classes company and person. Under the company class sometimes there are 3 person classes and sometimes there's only 1 or 4 hence it means that there is no sequence. what should I do that every time I could get only the persons who are under the specified company class? .. .. .. .. .. .. .. .. .. .. and data should be save in csv like this: company1 person1 company1 person2 company1 person3 company2 person1 company3 person1 company3 person2 anybody help me out? which kind of loop should i use here? what will be logic?
tagged with: automation

http://stackoverflow.com/a/49732929
downvote count: 0
score: 1
upvote count: 1
has body: That's because in the first two cases you're essentially converting a list into a set i.e. individual elements of the list become elements of the set. Since those are strings, and strings are hashable, they are allowed in the set. In the third case the elements of the list you're trying to convert into a set are lists themselves and a list is not hashable, hence the error. It's equivalent as if you've tried to do: your_set = set() your_set.add("Frankfurt") # OK your_set.add(["Frankfurt", "Basel"]) # Err
answers question: http://stackoverflow.com/q/49732748
type: Answer

http://stackoverflow.com/q/49747048
accepted answer: http://stackoverflow.com/a/49747219
tagged with: multithreading
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has title: Python multithreading service
has answer: http://stackoverflow.com/a/49747219
tagged with: winapi
answer count: 1
tagged with: python
score: -1
has body: I'm trying to create windows service on python with several threads. I wrote the code that works as I need, but I can't understand how it breaks the threads! Why break in while loop break the threads which are not in the while loop? import win32serviceutil import win32service import win32event import servicemanager import threading from classifier import clf, refit class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "MyService" _svc_display_name_ = "My Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): t1 = threading.Thread(target=clf) t2 = threading.Thread(target=refit) t1.start() t2.start() while True: rc = win32event.WaitForSingleObject(self.hWaitStop, 100) if rc == win32event.WAIT_OBJECT_0: break if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc)
tagged with: service
type: Question
upvote count: 0

http://stackoverflow.com/q/49750037
tagged with: firefox
tagged with: geckodriver
tagged with: python
has title: Geckodriver 0.18.0 random nonresponsiveness. Caused by several geckodrivers interfering with each other?
type: AnsweredQuestion
has body: Short version I am running Selenium 3.11.0 + Geckodriver 0.18.0 + Firefox 59.0.2 on Ubuntu 14.04.5. When trying to open an URL, Selenium sometimes throws the following error [Errno 111] Connection refused https://www.example.com Geckodriver.log shows 1523165125053 geckodriver INFO geckodriver 0.18.0 1523165125060 geckodriver INFO Listening on 127.0.0.1:37893 1523165126313 geckodriver::marionette INFO Starting browser /usr/bin/firefox with args ["-marionette"] 1523165127142 Marionette INFO Enabled via --marionette (firefox:28158): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox:28158): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox:28158): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox:28158): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox:28158): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox:28158): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed (/usr/lib/firefox/firefox:28235): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (/usr/lib/firefox/firefox:28235): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed (/usr/lib/firefox/firefox:28235): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (/usr/lib/firefox/firefox:28235): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed (/usr/lib/firefox/firefox:28235): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (/usr/lib/firefox/firefox:28235): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed 1523165129816 Marionette INFO Listening on port 41316 1523165129876 Marionette WARN TLS certificate errors will be igno…
tagged with: xvfb
score: 2
downvote count: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/86561057
accepted answer: http://stackoverflow.com/a/49798323
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49798323
upvote count: 2

http://stackoverflow.com/comment/93614811
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49617670
has text: Were you able to solve it?
score: 0

http://stackoverflow.com/q/49637979
has title: Python Celery workflow error handling stop execution
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a work flow that looks like this: I would like to check the status of each chain during the Combine task and stop if there are any errors, stop execution. But if no errors, go head to Format Results task. I'm having trouble getting the errors in Task 1, 2, etc to propogate to the Combine Task. Is there a method to do this in Celery? I can do on_error callback / link_error in each Tasks but how to propogate that to the Combine Task?
tagged with: celery
has comment: http://stackoverflow.com/comment/86616896
tagged with: celery-task
upvote count: 1
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49683473
score: 0
tagged with: rospy
has comment: http://stackoverflow.com/comment/86381177
answer count: 1
has comment: http://stackoverflow.com/comment/86379798
has comment: http://stackoverflow.com/comment/86378649
has comment: http://stackoverflow.com/comment/86380558
has answer: http://stackoverflow.com/a/49724403
has body: I had a python script that would: Loop through rosbags in a given directory Each non image message is directly copied to the new bag and each image message would be compressed and added to the new bag I decided to make a new version of this script to speed things up. My new script does: Loop through the rosbags in a given directory Each non image message is directly copied to the new bag Each image message is added to a queue Once all messages in the bags are processed I create processes that are reading from the queue, compressing images and adding it to the finished list. Loop through the finished list to add the compressed images to the new bag I have some issues with the code that I have created. Only one CPU seems to be at 100% usage. When it moves on to the next rosbag the ram usage is still high. Seems like something is not being deleted. I don't believe ROS knowledge is needed to solve this question. Am I using the multiprocessing library correctly? import glob import os import argparse from datetime import datetime import numpy as np import cv2 import sys import copy import rosbag import rospy from sensor_msgs.msg import CompressedImage from cv_bridge import CvBridge from multiprocessing import Process, Manager, Queue, cpu_count, queues # Image constants IMG_W = 1280 IMG_H = 1024 NUM_CHANNEL = 3 bridge = CvBridge() parser = argparse.ArgumentParser( description='Creates a bag containing the image data') parser.add_argument( 'input_dirs', nargs='+', help='Input and Output directory for bag files.') args = parser.parse_args() queue = Queue() manager = Manager() converted_imgs = manager.list() bag_path='' out_path='' if len(args.input_dirs) == 2: bag_path = args.input_dirs[0] out_path = args.input_dirs[1] os.chdir(bag_path) else: print('Please enter the input and output bag path.') exit() bag_names = [] # Add all bags in bag_path to bag_names for file in sorted(os.listdir(bag_path)): if file.endswith(".bag"): bag_names.append(file) camera_image_topics = { '/cam…
has title: Python multiprocessing image compression - only one CPU at 100%
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/86379035
has comment: http://stackoverflow.com/comment/86381197
type: Question
has comment: http://stackoverflow.com/comment/86405778
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86380467
has comment: http://stackoverflow.com/comment/86378730
has comment: http://stackoverflow.com/comment/86403331
has comment: http://stackoverflow.com/comment/86378747
tagged with: python
has comment: http://stackoverflow.com/comment/86462363
linked to: http://stackoverflow.com/q/1294382
tagged with: opencv
has comment: http://stackoverflow.com/comment/86378778

http://stackoverflow.com/a/49728849
has body: Add the path to PYTHONPATH environment variable.
has comment: http://stackoverflow.com/comment/86472010
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/49728799
downvote count: 1
has comment: http://stackoverflow.com/comment/86472240
has comment: http://stackoverflow.com/comment/86472367

http://stackoverflow.com/q/49635465
accepted answer: http://stackoverflow.com/a/49658922
has comment: http://stackoverflow.com/comment/86296836
possible better answer: http://stackoverflow.com/a/49644981
tagged with: opencv
has answer: http://stackoverflow.com/a/49644981
has comment: http://stackoverflow.com/comment/86280530
type: Question
type: AnsweredQuestion
has title: Error in ellipses using Opencv python
score: 1
has comment: http://stackoverflow.com/comment/86293127
favorite count: 0
has body: I have an input image and would like to draw ellipses on all contours that are found. I'm using python-opencv and getting the following error. Can anyone help me with this? I do know to draw the ellipse, but unsure about how to draw over every detected objects in a image. I am new to this area, hence please excuse me for silly question. OpenCV Error: Incorrect size of input array (There should be at least 5 points to fit the ellipse) in cv::fitEllipse, file C:\bld\opencv_1498171314629\work\opencv-3.2.0\modules\imgproc\src\shapedescr.cpp, line 358 Traceback (most recent call last): File "D:/project/test.py", line 41, in &lt;module&gt; ellipse = cv2.fitEllipse(contours[0]) cv2.error: C:\bld\opencv_1498171314629\work\opencv- 3.2.0\modules\imgproc\src\shapedescr.cpp:358: error: (-201) There should be at least 5 points to fit the ellipse in function cv::fitEllipse
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49658922
has comment: http://stackoverflow.com/comment/86278478
tagged with: contour
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/q/49711332
type: Question
has comment: http://stackoverflow.com/comment/86461924
linked to: http://stackoverflow.com/q/36570460
linked to: http://stackoverflow.com/q/22493724
type: UnansweredQuestion
has body: I have a XML file "definitions.xml" with below content. OLD_A OLD_B I want to modify the file as below: NEW_A NEW_B I have tried below code: from lxml import etree def Definations_Parser(): global Definations_tree global Definations_root parser = etree.XMLParser(remove_blank_text = True) Definations_tree = etree.parse('C:\\Users\\dell\\Desktop\\definitions.xml', parser) Definations_root = Definations_tree.getroot() def Definations_File_Modify(): Process_1 = Definations_root.find('Process') property_1 = Process_1.find('property[@name="am"]') print ('Current value is:', property_1.get('name')) def Definations_File_Write(): Definations_tree.write('C:\\Users\\dell\\Desktop\\definitions.xml', pretty_print = True) Definations_Parser() Definations_File_Modify() Definations_File_Write() How can I get current present values "OLD_A" and "OLD_B" and change it to "NEW_A" and "NEW_B" ?
tagged with: python
has comment: http://stackoverflow.com/comment/86461926
has title: Changing XML using LXML and Python
score: 0
tagged with: lxml
has answer: http://stackoverflow.com/a/49734891
answer count: 1
has comment: http://stackoverflow.com/comment/86461925

http://stackoverflow.com/comment/86440219
has text: I am trying to sum the column open_price 300+200+100
comment on: http://stackoverflow.com/q/49710133
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86336776
score: 0
type: AnswerComment
has text: Strictly speaking, this is not currying, but partial application, [I believe](https://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application), but I frequently get the two confused anyway...
type: Comment
comment on: http://stackoverflow.com/a/49663377

http://stackoverflow.com/comment/86241863
type: AnswerComment
has text: oh..ok..I used `print` and call function both gave `False` I thought that was `"False"`
comment on: http://stackoverflow.com/a/49616721
type: Comment
score: 0

http://stackoverflow.com/q/49650531
has title: Python - product of two field with a foreign key
type: Question
tagged with: django-queryset
has body: I would like to know how to calculate the product of two field : score in FeatureInfo and ratio in Feature. When I'm saving my FeatureInfo in my admin panel, it's not updating my field total. How can the field total be updated? models.py class Feature(models.Model): name = models.CharField(max_length=255, unique=True, null=True) ratio = models.IntegerField(null=True) class FeatureInfo(models.Model): name = models.CharField(max_length=255, unique=True, null=True) score = models.IntegerField(null=True) feature = models.ForeignKey(Feature, on_delete="CASCADE") _total = models.IntegerField(db_column='total') @property def total(self): return self.score * self.feature.score admin.py @admin.register(FeatureInfo) class FeatureInfoAdmin(admin.ModelAdmin): fields = ('id', 'feature', 'score', 'name', 'total') readonly_fields = ('id', 'total') list_filter = ('feature',) list_display = list_filter
type: UnansweredQuestion
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49650663
score: 0
tagged with: django-models
tagged with: python

http://stackoverflow.com/q/49645768
upvote count: 1
tagged with: git
favorite count: 0
type: Question
has body: I have a GUI application that uses the pythongit library to perform updates. When a user is authenticating with a SSH key to the repository the updates works smoothly, but when a username/password authentication is used, then a prompt will appear on the terminal where the application was started (leaving the user with the GUI interface open thinking it's frozen). Is there a way to determine if the repo is using SSH or password authentication and then possibly manually prompt for a username/password first and passing it to the fetch call? Here is the basic functionality: def repo_pull(self, git_path): try: repo = Repo(git_path) except InvalidGitRepositoryError as igre: raise ValueError('Get the project as a Git repository (no archives)') commits_ahead = repo.iter_commits('origin/master..master') if sum(1 for c in commits_ahead) &gt; 0: raise ValueError("Can't pull from git; local repository has unpushed commits!") origin = repo.remote() try: origin.fetch() except GitCommandError as gce: ,,,
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49649879
has title: Python git determine if project has SSH or PWD authentication
score: 1
answer count: 1
downvote count: 0
tagged with: authentication

http://stackoverflow.com/a/49702624
has body: I think you need to call interpolate. For your example dataframe: # This is the same as what you had index = pd.date_range(ts1.index.min(),ts1.index.max(), freq="H") # Here, reindex as you had done before, but chain an 'interpolate' on top of that ts1 = ts1.reindex(index).interpolate(method='time') If you print the first 10 columns, you'll see that the NaNs for 2018-01-27 have been interpolated: &gt;&gt;&gt; ts1.head(10) temp rh snow wind gust \ 2018-01-26 21:00:00 -10.120000 63.930000 207.100000 4.018000 9.806000 2018-01-26 22:00:00 -9.750000 58.540000 207.000000 3.856000 11.149000 2018-01-26 23:00:00 -9.710000 60.920000 206.900000 6.505000 13.759000 2018-01-27 00:00:00 -10.110000 57.450000 206.700000 6.602000 12.488000 2018-01-27 01:00:00 -10.041459 58.191892 206.854054 6.574757 12.575784 2018-01-27 02:00:00 -9.972919 58.933784 207.008108 6.547514 12.663568 2018-01-27 03:00:00 -9.904378 59.675676 207.162162 6.520270 12.751351 2018-01-27 04:00:00 -9.835838 60.417568 207.316216 6.493027 12.839135 2018-01-27 05:00:00 -9.767297 61.159459 207.470270 6.465784 12.926919 2018-01-27 06:00:00 -9.698757 61.901351 207.624324 6.438541 13.014703 wind_dir 2018-01-26 21:00:00 173.900000 2018-01-26 22:00:00 158.500000 2018-01-26 23:00:00 159.100000 2018-01-27 00:00:00 167.700000 2018-01-27 01:00:00 166.791892 2018-01-27 02:00:00 165.883784 2018-01-27 03:00:00 164.975676 2018-01-27 04:00:00 164.067568 2018-01-27 05:00:00 163.159459 2018-01-27 06:00:00 162.251351
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49702465
accepted answer of: http://stackoverflow.com/q/49702465
type: Answer

http://stackoverflow.com/comment/86300249
comment on: http://stackoverflow.com/a/49642042
has text: `SET SESSION` is always considered DDL, but each request in a Teradata mode session is automatically commited (unless you use `BEGIN/END TRANSACTION`). You might consider setting the session mode explicitly (`TMODE=ANSI`) to avoid problmens when you connect to a system with a different default.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/49695960
tagged with: python
has comment: http://stackoverflow.com/comment/86405828
has comment: http://stackoverflow.com/comment/86405031
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49696726
has comment: http://stackoverflow.com/comment/86405888
has title: Mix Django and DRF urls
tagged with: django
has comment: http://stackoverflow.com/comment/86405007
has comment: http://stackoverflow.com/comment/86405347
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/86405455
has body: So far, I have built a REST API with Django Rest Framework (DRF) which can be consumed by any front-end. Let call this API backend. I am trying to add another Django app (a regular one this time i.e. no DRF) which shares the same models. Let call this app webapp However, it seems that the URLs linked to webapp are not available. Here is my urls.py: from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from rest_framework.authtoken import views as token_views from backend import views from webapp import views as webapp_views router = routers.SimpleRouter() router.register(r'users', views.UserViewSet, 'User') router.register(r'games', views.GameViewSet, 'Game') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^connect/', views.CustomObtainAuthToken.as_view()), url(r'membership_create/', views.MembershipCreate.as_view()), url(r'auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()), url(r'auth/connect_with_credentials/', views.TokenViewWithData.as_view()), url(r'debug/', views.UserLoginAndIdView.as_view()), url(r'^auth/', include('rest_framework_social_oauth2.urls'), url(r'^test/', webapp_views.home, name='test'), # the new view ) ] urlpatterns += router.urls And the single view (from webapp.views): from django.http import HttpResponse from django.shortcuts import render def home(request): return HttpResponse(""" WEBAPP ! test webapp """) I am thus wondering if DRF and regular Django views can be mixed so easily or if it is not the right way of doing it. EDIT: Using the URLconf defined in WMC.urls, Django tried these URL patterns, in this order: ^admin/ ^connect/ membership_create/ auth/connect_with_fb/ auth/connect_with_credentials/ debug/ ^auth/ ^users/$ [name='User-list'] ^users/(?P<pk>[^/.]+)/$ [name='User-detail'] ^users/(?P<pk>[^/.]+)/games/$ [name='User-games'] ^games/$ [name='Game-list'] ^games/(?P<pk>[^/.]+)/$ [name='Game-detail'] The current URL, test/, didn't match any of these.
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49696726
upvote count: 1
has comment: http://stackoverflow.com/comment/86405222
has comment: http://stackoverflow.com/comment/86405771
answer count: 1
downvote count: 1

http://stackoverflow.com/q/49693464
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49693721
has body: d={'a':'Apple','b':'ball','c':'cat'} The above dictionary I have and I want my Output like the below-mentioned result res="a=Apple,b=ball,c=cat" Is it possible in a pythonic way then please answer it I have tried various method but did not get desired output?
has title: Converting dictionary into string
has answer: http://stackoverflow.com/a/49693721
has answer: http://stackoverflow.com/a/70555903
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86399306
answer count: 4
has answer: http://stackoverflow.com/a/49693722
type: AnsweredQuestion
downvote count: 4
upvote count: 3
has answer: http://stackoverflow.com/a/49694114
accepted answer: http://stackoverflow.com/a/49693722
favorite count: 0
type: Question

http://stackoverflow.com/comment/86504675
type: QuestionComment
has text: You're modifying the session objects directly with `setValues`, so there's no reason to create both `xy1` and `xy2` as references. Try running `xy1.setValues(s + xy1)`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49743363

http://stackoverflow.com/comment/86463689
score: 0
has text: `db.collection.insert_one('obj')` You are passing string `obj` to be inserted. Insert argument must be a `dict`. Remove the quotes around `obj`.
comment on: http://stackoverflow.com/q/49724882
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49717183
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm having some issues with a query I wrote in Python (have to use it for TensorFlow), which works just fine but is way too slow, since the input dataset is quite big. It can take over 5 minutes for the query to complete, and checking the Task Manager I can confirm it's indeed running on a single core. Here's the code: # Assume words is a list of strings for i, pair in enumerate(sorted( ((word, words.count(word)) # Map each word to itself and its count for word in set(words)), # Set of unique words (remove duplicates) key=lambda p: p[1], # Order by the frequency of each word reverse=True)): # Descending order - less frequent words last # Do stuff with each sorted pair What I'm doing here is just to take the input list words, get rid of the duplicates, then sort the words in descending order based on their frequency in the input text. If I were to write this in C# using PLINQ, I'd do something like this: var query = words.AsParallel().Distinct() .OrderByDescending(w =&gt; words.Count(s =&gt; s.Equals(w))) .Select((w, i) =&gt; (w, i)); I couldn't find an easy way to rewrite the paralell implementation in Python using possibly built-in libraries. I saw some guides about the Pool extension, but that looks like it's just an equivalent of the parallel Select operation, so I'd still miss how to implement the Distinct and OrderByDescending operations in Python, in parallel. Is it possible to do this with built-in libraries, or are there commonly used 3rd party libraries to do this? Thanks!
tagged with: multithreading
answer count: 1
has answer: http://stackoverflow.com/a/49719120
upvote count: 1
linked to: http://stackoverflow.com/q/15479928
downvote count: 1
favorite count: 0
type: Question
tagged with: c#
tagged with: plinq
tagged with: python-multithreading
accepted answer: http://stackoverflow.com/a/49719120
has title: How to parallelize this query in Python (just like PLINQ)?

http://stackoverflow.com/a/49671266
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49670868
type: Answer
upvote count: 1
has body: To get rid of the empty set, just start your loop with 1 instead of 0, then ''.join: def powerset(s): x = len(s) masks = [1 &lt;&lt; i for i in range(x)] for i in range(1, 1 &lt;&lt; x): yield ''.join(ss for mask, ss in zip(masks, s) if i &amp; mask) If you want to repeat this, i.e. get the powerset of the powerset of the original list, just feed the result back into the function in a loop: lst = ["A", "B"] for _ in range(5): lst = list(powerset(lst)) print(lst) Having said that, it might make more sense to do this filtering and joining as a post-processing step, as in @L3viathan's answer, as a true powerset function should neither omit nor modify results.
accepted answer of: http://stackoverflow.com/q/49670868

http://stackoverflow.com/comment/86461017
type: Comment
has text: Really thanks. I'll update this if I find a faster solution. Going to benchmark on some GB dataset.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49714265

http://stackoverflow.com/comment/86456592
comment on: http://stackoverflow.com/q/49721677
type: Comment
score: 0
type: QuestionComment
has text: You don't realize that this matches question marks. There are no "optionals" in a character class. You mean `\d+(\.\d+)?`.

http://stackoverflow.com/comment/86475939
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49727668
has text: ya its working..i have given wrong mapping name..tq

http://stackoverflow.com/q/49692440
type: Question
has body: I have all the packages required to run the ipynb file on my computer, but while I run the notebook file, I get the error message 'No module named 'plotly'' (for example). 'plotly' has actually been installed on the system, and even if I install it in a previous step in the notebook file, I get the same error message. I am not really sure if it is a problem with sync between the system and notebook file or I'm missing something really obvious here. The same holds true many other packages and libraries. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/86402346
has comment: http://stackoverflow.com/comment/86402412
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86407726
has title: Installed required packages on the host system but facing missing packages issue in Jupyter Notebook
favorite count: 0
has answer: http://stackoverflow.com/a/49817252
has comment: http://stackoverflow.com/comment/86402485
tagged with: matplotlib
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86397697
has comment: http://stackoverflow.com/comment/86397997
tagged with: jupyter-notebook

http://stackoverflow.com/comment/86293938
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49643141
has text: `pbounds` is just a dictionary where `'x'` and `'y'` are mapped to the tuple `(-20, 20)`. The values of `'x'` or `'y'` could be changed to anything.

http://stackoverflow.com/comment/86294183
comment on: http://stackoverflow.com/q/49643187
has text: The _real_ answer is that the committee was full of electrical engineers who don't understand how programming works. Most languages in 1985 had comparison operators that define a total ordering—possibly as a partial function that's a total ordering where it's defined (in Python terms, that means they either order things sensibly or raise an exception)—but definitely not a total function that's a partial ordering. So "signaling NaN" makes some sense, but "quiet NaN' comparisons do not. Unfortunately, in 2018, the general rule is even more widespread than in 1985, but a violation for NaN is too.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86454687
type: QuestionComment
score: 0
has text: Unrelated to your problem, but `Divisors` _really_ shouldn't be a class. It'd make more sense as a function.
comment on: http://stackoverflow.com/q/49720780
type: Comment

http://stackoverflow.com/q/49754797
score: 7
has comment: http://stackoverflow.com/comment/86524956
tagged with: python
has answer: http://stackoverflow.com/a/49755226
accepted answer: http://stackoverflow.com/a/49755226
has title: How to draw 2D random uniform samples from two ranges
has comment: http://stackoverflow.com/comment/86524539
has comment: http://stackoverflow.com/comment/86524894
tagged with: numpy
has answer: http://stackoverflow.com/a/49754895
possible better answer: http://stackoverflow.com/a/49754895
has comment: http://stackoverflow.com/comment/86524567
answer count: 2
downvote count: 0
upvote count: 7
has body: I have two pairs of min and max values for two variables. I want to draw n random samples from a uniform distribution of these two variables, lying between their min and max values. For example: min_x = 0 max_x = 10 min_y = 0 max_y = 20 Let's say I draw three samples. These could be: [(4, 15), (8, 9), (0, 19)] # First value is drawn randomly with uniform probability between min_x and max_x, second value is drawn similarly between min_y and max_y How can I achieve this with numpy in a simple way? I've come up with this: &gt;&gt;&gt; min_x = 0 &gt;&gt;&gt; max_x = 10 &gt;&gt;&gt; min_y = 0 &gt;&gt;&gt; max_y = 20 &gt;&gt;&gt; sample = np.random.random_sample(2) &gt;&gt;&gt; sample[0] = (sample[0]) * max_x - min_x &gt;&gt;&gt; sample[1] = (sample[1]) * max_y - min_y &gt;&gt;&gt; sample array([ 1.81221794, 18.0091034 ]) but I feel like there should be a simpler solution. EDIT: Not a duplicate. The answers of the suggested duplicate question deals with integers.
linked to: http://stackoverflow.com/q/46984635
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86524715
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86524578

http://stackoverflow.com/q/49683822
has comment: http://stackoverflow.com/comment/86381169
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86379227
linked to: http://stackoverflow.com/q/19960077
has body: I am new to Python Data Science. Did work in R and exploring Python for ML. I used pass vector in R where condions but I am not sure how I do that in Python. raw_data1 = {'age1': [23,45,21],'age2': [10,20,50], 'age3':[44,55,77]} df1 = pd.DataFrame(raw_data1, columns = ['age1','age2','age3']) raw_data2 = {'age1': [23,45]} df2 = pd.DataFrame(raw_data2, columns = ['age1']) Here I like to query df1 based on df2-age1 vector. I tried below but didn't work df3 = df1.iloc[np.where(df1.age1 == df2['age1'])] Thanks for your help
has title: Python - How I pass a vector in where condition
type: Question
duplicate of: http://stackoverflow.com/q/19960077
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86379725
has comment: http://stackoverflow.com/comment/86379269
score: 0

http://stackoverflow.com/comment/86404418
type: QuestionComment
has text: You should check what `key` is
comment on: http://stackoverflow.com/q/49695836
score: 0
type: Comment

http://stackoverflow.com/a/49601213
answers question: http://stackoverflow.com/q/49601091
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86211035
has comment: http://stackoverflow.com/comment/86210187
score: 0
has body: Quick and dirty, but works. import csv def filter_csv(start_date, end_date, csvfile): spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') total_temp = 0 for row in spamreader: values = row[0].split(',') if start_date &lt;= int(values[0]) &lt;= end_date: total_temp += int(values[1]) return total_temp with open('d.csv', newline='') as csvfile: total_temp = filter_csv(20160101, 20160102, csvfile) print(total_temp)
type: Answer
accepted answer of: http://stackoverflow.com/q/49601091

http://stackoverflow.com/comment/86339779
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49642516
has text: One more question - from my understanding, binder is used for accessing notebooks in your github repo. Therefore it seems like you'll only be able to access files within your repo, starting from the top level directory. Can you tell me the path of the file you're trying to access?
score: 0

http://stackoverflow.com/comment/86379403
score: 0
type: AnswerComment
has text: https://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented; https://www.laurentluce.com/posts/python-list-implementation/ For more, search SO for `[python] list implementation` or web for `python list implementation`, which is what I did.
type: Comment
comment on: http://stackoverflow.com/a/49660040

http://stackoverflow.com/comment/86465047
comment on: http://stackoverflow.com/q/49725522
has text: Magic 8-ball says `code_num` is a string.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49646184
has body: I have an rdd: a,1,2,3,4 b,4,6 c,8,9,10,11 I want to convert this into Spark Data Frame with index: df: Index Name Number 0 a 1,2,3,4 1 b 4,6 2 c 8,9,10,11 I tried splitting the RDD: parts = rdd.flatMap(lambda x: x.split(",")) But that resulted in : a, 1, 2, 3,... How do I split and convert the RDD to Dataframe in pyspark such that, the first element is taken as first column, and the rest elements combined to a single column ? As mentioned in the solution: rd = rd1.map(lambda x: x.split("," , 1) ).zipWithIndex() rd.take(3) Output: [(['a', '1,2,3,4'], 0), (['b', '4,6'], 1), (['c', '8,9,10,11'], 2)] Next Step: rd2=rd2=rd.map(lambda x,y: (y, x[0] , x[1]) ).toDF(["index", "name" ,"number"]) rd2.collect() I am getting the following error: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 55.0 failed 1 times, most recent failure: Lost task 0.0 in stage 55.0 (TID 85, localhost, executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last): Is it an issue with the version?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86300765
tagged with: pyspark
downvote count: 0
tagged with: dataframe
tagged with: python
tagged with: rdd
answer count: 1
has title: Splitting an Pyspark RDD into Different columns and convert to Dataframe
accepted answer: http://stackoverflow.com/a/49646384
has comment: http://stackoverflow.com/comment/86342614
has answer: http://stackoverflow.com/a/49646384
tagged with: apache-spark
score: 2
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/comment/86327012
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49658760
has text: How to output should look like?

http://stackoverflow.com/a/58589469
answers question: http://stackoverflow.com/q/49691410
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: This code should do what you want: my_list=['one', 'two', 'one', 'one', 'two'] for i, item in enumerate(my_list): if i != 0: if item == my_list[i-1]: print(my_list[i+1])

http://stackoverflow.com/a/49695437
has comment: http://stackoverflow.com/comment/86403998
score: 0
has comment: http://stackoverflow.com/comment/86404329
answers question: http://stackoverflow.com/q/49695292
type: Answer
has comment: http://stackoverflow.com/comment/86403591
has body: Just add and drop a merge column and you are done: df_seg['merge_col'] = df_seg.Country.apply(lambda x: x.split('-')[0]) df_g['merge_col'] = df_g.Country.apply(lambda x: x.split('-')[0]) then do: df = pd.merge(df_g, df_seg'merge_col', 'Precio', on='merge_col', how='left').drop('merge_col', 1) returns Sitio Country Precio 0 Los Andes Online HN - Honduras 0.5 1 Guarda14 US - Estados Unidos 2.1 2 Guarda14 PE - Peru NaN

http://stackoverflow.com/a/49679801
has comment: http://stackoverflow.com/comment/86371452
accepted answer of: http://stackoverflow.com/q/49679633
type: Answer
has body: You have to loop through .degree tags and extract the required information from it in pairs. Here's how to do it the normal way: education = driver.find_element_by_id("education") for degree in education.find_element_by_class_name("degree"): school = degree.find_element_by_class_name("school") year = degree.find_element_by_class_name("year") print(school.text, year.text) And here's how to do it using CSS selector: for degree in driver.find_elements_by_css_selector("#education .degree"): school = degree.find_element_by_css_selector(".school") year = degree.find_element_by_css_selector(".year") print(school.text, year.text) Note: as @Andersson commented, you should check if elements (.year and .school) exist if it's possible to be missing using one of the methods mentioned in this answer. Otherwise, this code might throw a NoSuchElementException.
answers question: http://stackoverflow.com/q/49679633
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86371476
score: 3

http://stackoverflow.com/comment/86488000
type: AnswerComment
has text: @HoudaF If you are working with csv-files there is really no other option than pandas (today).
type: Comment
comment on: http://stackoverflow.com/a/49736714
score: 0

http://stackoverflow.com/comment/86559092
has text: It is absolutely normal and expected that a model in CPLEX or any of the other solvers will have only a small proportion of the variables in the objective function. In most models there will be many variables and constraints defining e.g. the structure of the problem, but which do not appear in the objective.
type: QuestionComment
comment on: http://stackoverflow.com/q/49751406
score: 2
type: Comment

http://stackoverflow.com/comment/86609367
has text: The comments by Steeve and Michael Peter on the first link you posted suggest that it no longer works. Presumably, it worked in an earlier version.
comment on: http://stackoverflow.com/a/49763069
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49700133
type: UnansweredQuestion
tagged with: python
tagged with: rgb
linked to: http://stackoverflow.com/q/34913005
has comment: http://stackoverflow.com/comment/86415803
score: 3
tagged with: colors
has comment: http://stackoverflow.com/comment/86418421
has body: I have some problems converting a rgb photo to ycbcbr, modifying the y channel and converting back to rgb, generally it works perfect but for some edge cases it returns negative values or values greater than 255 so when i convert it back to uint8 for matplotlib it shows bright spots. RGB to YCbCr def rgb2ycbcr(data): res = np.empty(data.shape) res[...,0] = (data[...,0] * 0.299 + data[...,1] * 0.587 + data[...,2] * 0.114) res[...,1] = 128 + (data[...,0] * -0.169 + data[...,1] * -0.331 + data[...,2] * 0.5) res[...,2] = 128 + (data[...,0] * 0.5 + data[...,1] * -0.419 + data[...,2] * -0.081) return res and YCbCr to RGB: def ycbcr2rgb(data): res = np.empty(data.shape) data[...,1] = data[...,1] - 128 data[...,2] = data[...,2] - 128 res[...,0] = data[...,0] * 1 + data[...,2] * 1.4 res[...,1] = data[...,0] * 1 + data[...,1] * -0.343 + data[...,2] * -0.711 res[...,2] = data[...,0] * 1 + data[...,1] * 1.765 return res The strange thing is that when i dont touch the Y channel the photo converts ok (i know that when i modify the Y channel i keep the values in range)
upvote count: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49705851
favorite count: 0
type: Question
has title: ycbcr to rgb color conversion error on edge cases

http://stackoverflow.com/q/49601800
duplicate of: http://stackoverflow.com/q/48423236
tagged with: python
has comment: http://stackoverflow.com/comment/86210896
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/48423236
answer count: 0
has body: I have a numpy array which I plot with plt.imshow(img_right, cmap = plt.cm.gray,picker=True) I then attache an on-pick handler to it win.canvas.mpl_connect('pick_event',onclick) I then click on the image location. My reuirment is to get the array index of the numpy 2-D array which was used to plot the data originally I tried the following the the onpick even handler print dir(event_pick) event=event_pick.mouseevent print dir(temp) I see that none of these contain a ind attribute. How do I get the array index from the clicked location?(I dont need the xydata, I need the closest array index)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86211581
has title: matplotlib get numpy array index location on click
has comment: http://stackoverflow.com/comment/86213338
score: 0
has comment: http://stackoverflow.com/comment/86240161
tagged with: matplotlib

http://stackoverflow.com/comment/86399622
type: Comment
has text: So what are the arguments accepted by patch.object: class, method, returnval?
comment on: http://stackoverflow.com/a/49683090
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86301762
score: 0
type: Comment
has text: Thank you, Tobias, that does sound as something i would need for my system. Unfortunately, i have never worked with JavaScript, do u have any suggesting where to start with jquery to make it work as you described?
type: AnswerComment
comment on: http://stackoverflow.com/a/49646144

http://stackoverflow.com/a/49702920
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49702766
has comment: http://stackoverflow.com/comment/86419499
has body: General NumPy indexing is complicated, but this is still the easy case. I've always felt that it helps to think in terms of how indexing the result corresponds to indexing the original array. The result of x[:, :, 0] is an array such that for any indices i and j, result[i, j] == x[i, j, 0] Similarly, if you index a 5D array a as a[:, 1, :, 2, :], the result is such that result[i, j, k] == a[i, 1, j, 2, k]
has comment: http://stackoverflow.com/comment/86419610
accepted answer of: http://stackoverflow.com/q/49702766
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86419615
has comment: http://stackoverflow.com/comment/86419664

php
tags question: http://stackoverflow.com/q/49679035
tags question: http://stackoverflow.com/q/49723366
tags question: http://stackoverflow.com/q/49652911
tags question: http://stackoverflow.com/q/49629508
tags question: http://stackoverflow.com/q/49661446
tag name: php
tags question: http://stackoverflow.com/q/49610673
tags question: http://stackoverflow.com/q/49623927
tags question: http://stackoverflow.com/q/49726689
type: Tag

http://stackoverflow.com/q/49617233
has comment: http://stackoverflow.com/comment/86241640
answer count: 1
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/35257738
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/35257738
has title: How do I store the printed result of a generator in a variable for further use?
tagged with: python
has answer: http://stackoverflow.com/a/49617361
tagged with: generator
has body: I used a generator to create a 10 by 10 of 'O's: board = [] for x in range(0, 10): board.append(["O"] * 10) def board_generator(layout): for y in layout: yield (" ".join(y)) my_board = board_generator(board) Then I set imputed the result into a variable, but when I tried outputting it to another source, I got this: &lt;generator object board_generator at 0x0135AAF0&gt; I tried to get the printed result I wanted by doing this: def print_board(boards): for i in boards: print(i) However, I could not place impute this into a variable because it does not return anything, therefore I could not output it to a text file. How do I fix this?
linked to: http://stackoverflow.com/q/231767
type: UnansweredQuestion

http://stackoverflow.com/comment/86227174
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49610336
type: Comment
has text: Is this a loss reference?

http://stackoverflow.com/comment/86490475
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49736688
has text: The good news is that thanks to your question it will be fixed in the next Django release 2.0.5.

http://stackoverflow.com/a/49683605
type: Answer
has body: The strings will be isomorphic if the number of unique characters in each string is the same as the number of unique pairs of corresponding characters between them (they also have to be the same length). So this function will do it concisely and much faster: def isIsomorphic(w1,w2) : if len(w1) != len(w2): return False return len(set(w1)) == len(set(w2)) == len(set(zip(w1,w2))) [EDIT] 3.3 seconds on my computer for 1 million iterations of a pair of 25 character strings (vs 12 seconds for Aran-Fey's updated code).
downvote count: 0
answers question: http://stackoverflow.com/q/49679872
upvote count: 5
score: 5

http://stackoverflow.com/comment/86528101
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49755410
has text: Thank you, I mean there are 200000 samples

http://stackoverflow.com/comment/86555825
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49757899
has text: Yes this works when both 'Strain' and 'Species' are used, thanks!
type: Comment

http://stackoverflow.com/comment/86505175
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49745344
has text: Gee one has to be quick on stack overflow ! :)

http://stackoverflow.com/q/49607111
accepted answer: http://stackoverflow.com/a/49619218
has comment: http://stackoverflow.com/comment/86221349
tagged with: django-celery
has answer: http://stackoverflow.com/a/49619218
type: Question
has comment: http://stackoverflow.com/comment/86227958
answer count: 2
has comment: http://stackoverflow.com/comment/86222777
has comment: http://stackoverflow.com/comment/86224470
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/49609363
has title: Can't call Celery in Django
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86224135
has comment: http://stackoverflow.com/comment/86223550
has answer: http://stackoverflow.com/a/49609363
has body: So the problem is that when I try to call main task from Django lpr.views.py page shows that loading icon and thats it, nothin else happens. There is no output in Django or Celery console. When I try and run the task from python shell it runs without a problem and saves result in db. I added add task for test purposes and when I run add task it returns an error because of missing 'y' argument which is normal. But what is up with that main task? There is my code just in case. Project structure: Project ├── acpvs │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── lpr │ ├── __init__.py │ ├── tasks.py │ ├── urls.py │ └── views.py └── manage.py settings.py import djcelery INSTALLED_APPS = [ ... 'djcelery', 'django_celery_results', ] CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_ALWAYS_EAGER = False djcelery.setup_loader() init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from acpvs.celery import app as celery_app __all__ = ['celery_app'] acpvs.celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'acpvs.settings') app = Celery('acpvs') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) lpr.tasks.py from __f…
has comment: http://stackoverflow.com/comment/86221232
has comment: http://stackoverflow.com/comment/86221112
has comment: http://stackoverflow.com/comment/86221184

http://stackoverflow.com/comment/86303295
has text: I did same and i can import nn now . Try installing both `neat` and than `near-python==0.8`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49628450

http://stackoverflow.com/comment/86390771
type: AnswerComment
has text: If there is the risk that `.` appears in the file name, simply make a recursive function that takes the right part of a string splitted at the `.` until there is no more `.` in the right part. You'll get the file's extension everytime ;)
comment on: http://stackoverflow.com/a/49689642
type: Comment
score: 0

http://stackoverflow.com/comment/86522098
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49753411
has text: Optimisation with respect to less loops and condition.
type: Comment

http://stackoverflow.com/comment/86307612
type: Comment
has text: This cannot be answered without seeing the code for averaging gradients. You can fetch the gradients using TF and then do averaging (This can cause some memcpys) . You can use NCCL, ... This all depends on *your* actual implementations. Other open questions are DMA available or not?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49643622

http://stackoverflow.com/a/49674310
answers question: http://stackoverflow.com/q/49674219
has comment: http://stackoverflow.com/comment/86359504
type: Answer
has comment: http://stackoverflow.com/comment/86360135
has comment: http://stackoverflow.com/comment/86359439
has comment: http://stackoverflow.com/comment/86359469
upvote count: 2
has body: I am using repeat and reindex s=df.iloc[[4],] # pick the row you want to do repeat s=s.reindex(s.index.repeat(45))# repeat the row by the giving number #s=pd.DataFrame([df.iloc[4,].tolist()]*25) if need enhance the speed , using this line replace the above s.loc[:,'C']=1 # change the value pd.concat([df,s]) #append to the original df
downvote count: 0
has comment: http://stackoverflow.com/comment/86359366
has comment: http://stackoverflow.com/comment/86360046
score: 2

http://stackoverflow.com/q/49755144
has title: Reading CSV with comma at last line
accepted answer: http://stackoverflow.com/a/49755666
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86567253
has answer: http://stackoverflow.com/a/49755666
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
type: Question
has body: i'm using Python to read in a series of CSVs that were obtained via a web scraper (there's thousands so editing by hand is a no go). The data looks like this: "Client: Secret Client" "G/L Account: (#-#-#) Secret Type of Account" "Process Date: MM/DD/YYYY" "Export Date: MM/DD/YYYY" "Unit Name ","Description","Pay. Type ","Amount","Tran. Date " "last, first","some note (dates with commas like 17 Aug, 2018 could be here)","Credit Card ","$AMNT.CHANGE","Date and Timestamp" "Total","","","$AMNT.CHANGE"," If you count carefully you'll see a final comma followed by a rogue ". The code I'm trying to use is here: import os import pandas as pd import csv def read_temp(file): tmp = pd.read_csv(file, header=None, error_bad_lines=False, quotechar='"', skiprows=5, quoting=csv.QUOTE_ALL,skipinitialspace=True, skipfooter=1) gl = pd.read_csv(file, header=None, error_bad_lines=False, quotechar='"', skiprows=1, nrows=1, quoting=csv.QUOTE_ALL,skipinitialspace=True) proc_date = pd.read_csv(file, header=None, error_bad_lines=False, quotechar='"', skiprows=2, nrows=1, quoting=csv.QUOTE_ALL,skipinitialspace=True) cols = ['NAME', 'DESCRIPTION', 'PAY_TYP', 'AMOUNT', 'TRAN_DATE'] tmp.columns = cols # print(tmp.columns) # print(file) tmp['G/L_ACCOUNT'] = gl[0][0].split(':')[1] tmp['PROCESS_DATE'] = proc_date[0][0].split(':')[1] for col in tmp.columns: tmp[col] = tmp[col].str.strip('"') return tmp master = "C:\\path\\to\\master\\" want=[] flag = 0 for direc in os.listdir(master): for file in os.listdir(master+direc): temp = read_temp(master+direc+'\\'+file) want.append(temp) df = pd.concat(want) the error is: ',' expected after '"' I think if I could use a CSV Reader and regular expressions (which I have zero experience with) to read each line before hand and find everything that's surrounded by " " then I could change it somehow or posisbly delete that ending comma and double quote. Any ideas would be appreciated!
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/117838734
comment on: http://stackoverflow.com/a/51486322
has text: I don't get it ? please explain your solution ?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86251636
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49622084
score: 0
has text: I thunk you should create a deep copy of dataframe instead of `df=df_raw` using copy module `import copy` `df=copy.deepcopy(df_raw)`

http://stackoverflow.com/a/49699363
has body: parse_args() does not depopulate sys.argv. Therefore, len(sys.argv) == 1 is a good proxy for a no-argument check (since sys.argv still has a length of 1 when no arguments are passed).
answers question: http://stackoverflow.com/q/49699290
type: Answer
accepted answer of: http://stackoverflow.com/q/49699290
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86440513
type: Comment
type: AnswerComment
score: 1
has text: @buhtz: you are correct. I should have mentioned that. You just need to check the `widget` attribute of the event object to only run your task on the root window.
comment on: http://stackoverflow.com/a/49682181

http://stackoverflow.com/comment/86229082
comment on: http://stackoverflow.com/q/49610409
score: 0
has text: Also i forgot to mention that i'm working on a virtualenv that might make a difference too?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49623102
answers question: http://stackoverflow.com/q/49623007
has body: The reason to use for…else or while…else is when you have code that needs to be run if you fell off the end of the loop without a break statement. Usually this means you were testing each value for some condition, with a break on success, but never succeeded: for idx, val in enumerate(lst): if val in good_vals: break else: print("Couldn't find a good value") return None print(f"Found good value {val} at position {idx}") return do_something_with(idx) But in simple cases, like the one above—and like yours—you can always rewrite things to make the else unnecessary: for idx, val in enumerate(lst): if val in good_vals: print(f"Found good value {val} at position {idx}") return do_something_with(idx) print("Couldn't find a good value")
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49680515
type: Answer
accepted answer of: http://stackoverflow.com/q/49680416
has comment: http://stackoverflow.com/comment/86373058
answers question: http://stackoverflow.com/q/49680416
type: AcceptedAnswer
downvote count: 0
has body: Since you mention fuzzywuzzy from fuzzywuzzy import process df['suggested_class']=df.input.apply(lambda x : [process.extract(x, lst, limit=1)][0][0][0]) df Out[1365]: input suggested_class 0 dog dog 1 kat cat 2 leon lion 3 moues mouse
has comment: http://stackoverflow.com/comment/86373168
score: 3
upvote count: 3

http://stackoverflow.com/comment/86408682
comment on: http://stackoverflow.com/q/49697477
score: 0
has text: @BilltheLizard it's the relative contributions to luminance of red green blue.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49738373
upvote count: 17
has body: Note: with "axis" I refer to image coordinates, not to NumPy's array dimensions. The issue is with the interpretation of ndarray's dimensions ("The N-dimensional array"), or the definition of a coordinate system in that context. For Pillow, it's clear: Coordinate System The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5). Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600). That would look like this (image -> public domain): Your code, modified to create a 2x2 pixel image: import numpy as np from PIL import Image # Pillow w, h, d = 2,2,3 x,y = 0,1 grid = np.zeros((w, h, d), dtype=np.uint8) # NumPyarray for image data #test = np.zeros(w*h*d, dtype=np.uint8).reshape(w, h, d) #print(np.array_equal(grid,test)) # =&gt; True # red pixel with NumPy grid[x, y] = [255, 0, 0] print(grid[::]) # green pixel with Pillow img = Image.fromarray(grid, 'RGB') pixels = img.load() pixels[x,y] = (0, 255, 0) # display temporary image file with default application scale = 100 img.resize((w*scale,h*scale)).show() shows the issue (draw pixel at (0,1), green: Pillow, red: ndarray): X and Y indeed are swapped: Is it because of NumPy or Pillow? The ndarray prints as [[[ 0 0 0] [255 0 0]] [[ 0 0 0] [ 0 0 0]]] which is easily reformatted to visually correspond to the image pixels [ [ [ 0 0 0] [255 0 0] ] [ [ 0 0 0] [ 0 0 0] ] ] which shows that Pillow interprets the array as one would expect. But why does NumPy's ndarray seem to swap the axes? Let's take this apart a bit further [ # grid [ # grid[0] [ 0 0 0] #grid[0,0] [255 0 0] #grid[0,1] ] [ #grid[1] [ 0 0 0] #grid[1,0] [ 0 0 0] #grid[1,1] ] ] Let's test this (-i has Python r…
has comment: http://stackoverflow.com/comment/126535381
accepted answer of: http://stackoverflow.com/q/49720605
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87041224
downvote count: 0
score: 17
answers question: http://stackoverflow.com/q/49720605

http://stackoverflow.com/comment/86334604
has text: If you are running on the current build of Chrome `65`, if you are not running **at least** chromedriver version `2.36`, please update your chromedriver and execute your test again. Update from [HERE](https://sites.google.com/a/chromium.org/chromedriver/downloads). I have been seeing a lot of issue regarding the new stable build of chrome, and older versions of the chromedriver.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49658070

http://stackoverflow.com/a/49812372
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49752388
downvote count: 0
has body: Based on the great specific solution by @eyllanesc, I have made a generalized version of a QSqlQueryModel where it's possible to specify which columns should be editable. It might need adjustments for other people's queries, but I hope it's helpful to someone out there struggling with similar problems: import sys from PyQt5.QtCore import Qt from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel from PyQt5.QtWidgets import QApplication, QTableView db_file = "test.db" def create_connection(file_path): db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(file_path) if not db.open(): print("Cannot establish a database connection to {}!".format(file_path)) return False return True def fill_tables(): q = QSqlQuery() q.exec_("DROP TABLE IF EXISTS Manufacturers;") q.exec_("CREATE TABLE Manufacturers (Company TEXT, Country TEXT);") q.exec_("INSERT INTO Manufacturers VALUES ('VW', 'Germany');") q.exec_("INSERT INTO Manufacturers VALUES ('Honda' , 'Japan');") q.exec_("DROP TABLE IF EXISTS Cars;") q.exec_("CREATE TABLE Cars (Company TEXT, Model TEXT, Year INT);") q.exec_("INSERT INTO Cars VALUES ('Honda', 'Civic', 2009);") q.exec_("INSERT INTO Cars VALUES ('VW', 'Golf', 2013);") q.exec_("INSERT INTO Cars VALUES ('VW', 'Polo', 1999);") class SqlQueryModel_editable(QSqlQueryModel): """a subclass of QSqlQueryModel where individual columns can be defined as editable """ def __init__(self, editables): """editables should be a dict of format: {INT editable_column_nr : (STR update query to be performed when changes are made on this column INT model's column number for the filter-column (used in the where-clause), )} """ super().__init__() self.editables = editables def flags(self, index): fl = QSqlQueryModel.flags(self, index) if index.column() in self.editables: fl |= Qt.ItemIsEditable return fl def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole: mycolumn = index.column() if mycolumn in self.editables: (query, filter_col) = self.editables[mycolu…
has comment: http://stackoverflow.com/comment/86645718
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49752388

http://stackoverflow.com/comment/86536755
type: Comment
comment on: http://stackoverflow.com/q/49743649
type: QuestionComment
has text: @zipzit The problem is that there is no "area away from the joint" on the xray-image, at least it's not far enough to approximate the image of the bone as a rectangle with two parallel sides. This is a reasonable approximation for small angles of the bones, but if it is exactly the small angle that we are after, I don't think that this would give a particularly good approximation.
score: 0

http://stackoverflow.com/a/49643258
has comment: http://stackoverflow.com/comment/86381003
has comment: http://stackoverflow.com/comment/86350131
answers question: http://stackoverflow.com/q/49629011
has comment: http://stackoverflow.com/comment/86350054
has comment: http://stackoverflow.com/comment/86301414
accepted answer of: http://stackoverflow.com/q/49629011
score: 1
has comment: http://stackoverflow.com/comment/86300897
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86399224
upvote count: 1
type: Answer
has body: Update the redact stage for your aggregation pipeline. if, then and else are a part of the $cond operator and they're not operators in themselves. Also, $in operator is passed an array where its first item is checked for presence in the second item. The second item is usually an iterable. Mongo 3.6 messenger_pipeline_status = ( messenger_active_status['data']['pending'] + messenger_active_status['data']['processing'] ) assigned_status = ['DEL_ASSIGNED','PU_ASSIGNED'] subpipeline = [ { '$match': { '$expr': { '$and': [ {'$eq': ['$fk_shipment_id', '$$pkey']}, {'$eq': ['$fk_messenger_id', fk_user_id]}, {'$in': ['$status_value', assigned_status]} ] } } }, { '$sort': { 'rec_timestamp': -1 } }, { '$limit': 1 }, { '$project': { 'fk_shipment_id': 1 } } ] pipeline = [ { '$match': { 'status_value': {'$in': messenger_pipeline_status} 'is_deleted': False, 'is_postponed': False, 'is_active': True, } }, { '$lookup': { 'from': 'db_shipment_status_history', 'let': {'pkey': '$pkey'}, 'pipeline': subpipeline, 'as': 'shipment_status_history' } }, { '$match': { 'shipment_status_history': { '$ne': [] } } }, { '$unwind': '$shipment_status_history' }, { '$project': { '_id': 1, 'pkey': 1, '_code': 1, 'date_created': 1, 'sender_full_name': '$sender.full_name', 'sender_raw_address': '$sender.raw_address', 'sender_formatted_address': '$sender.formatted_address', 'receiver_full_name': '$receiver.full_name', 'receiver_raw_address': '$receiver.raw_address', 'receiver_formatted_address': '$receiver.formatted_address', 'status_name': 1, 'team_value': 1, 'cs_name': 1, 'fk_messenger_id': '$shipment_status_history.fk_shipment_id' } } ] result = db.db_shipment.aggregate(pipeline) print(list(result)) [Edit] Mongo 3.2 The following aggregation pipeline produces similar results as the above and is valid query for Mongo 3.2. messenger_pipeline_status = ['MISSFLT', 'OFFLOAD'] pipeline = [ { '$match': { 'status_value': { '$in': messenger_pipeline_status} 'is_deleted': False, 'is_postponed': False, 'is_active…

http://stackoverflow.com/comment/86524353
type: QuestionComment
comment on: http://stackoverflow.com/q/49751550
has text: @Chris_Rands your code is the answer to my problem, thank you. Can you explain me why in my #b code the loop "for word in words" does not actually loop through the list and always returns the first element of the list?
score: 0
type: Comment

http://stackoverflow.com/comment/86285776
type: Comment
comment on: http://stackoverflow.com/q/49638857
type: QuestionComment
has text: Please add your code and the full error traceback.
score: 1

http://stackoverflow.com/a/49695372
has body: You need additional key for help the merge , I am using cumcount to distinguish the repeat value df1.assign(key=df1.groupby('Sitio').cumcount()).\ merge(df2.assign(key=df2.groupby('Sitio').cumcount()). drop('Country',1), how='left', on=['Sitio','key']) Out[1491]: Sitio Country key Precio 0 Los Andes Online HN - Honduras 0 0.5 1 Guarda14 US - Estados Unidos 0 2.1 2 Guarda14 PE - Peru 1 NaN
type: Answer
answers question: http://stackoverflow.com/q/49695292
score: 0

http://stackoverflow.com/a/49756627
score: 1
downvote count: 0
has body: You will want to loop each row. This can be achieved by using the itertuple method as follows. Example data: sales = [{'values': [1,2,3,4], 'title': 'title 1'}, {'values': [2,3,5,7], 'title': 'title 2'}, {'values': [4,5,5,7], 'title': 'title 3'}] df = pd.DataFrame(sales) Produce a plot for the values in each row with the title specified in each row for row in df.itertuples(): plt.plot(row.values,marker='o') plt.title(row.title) plt.savefig(row.title + '.png') plt.clf() The output of this is 3 separate plots (one for each row in the dataframe).
answers question: http://stackoverflow.com/q/49755687
type: Answer
upvote count: 1

http://stackoverflow.com/q/49607700
has comment: http://stackoverflow.com/comment/86221977
has comment: http://stackoverflow.com/comment/86222114
upvote count: 1
has comment: http://stackoverflow.com/comment/86222322
tagged with: autopep8
downvote count: 1
has comment: http://stackoverflow.com/comment/86221965
has comment: http://stackoverflow.com/comment/86235490
favorite count: 0
type: Question
has body: I have code without correct indentations if age &gt; 18: if salary &gt; 100000: print('success') elif salary &lt; 50000: print('fail') else: print('get_more_info') else: print('fail') I need to get if age &gt; 18: if salary &gt; 100000: print('success') elif salary &lt; 50000: print('fail') else: print('get_more_info') else: print('fail') I try to use exec(autopep8.fix_code(str)) but I get an error File "&lt;string&gt;", line 3 print('success') elif salary &lt; 50000: print('fail') else: print('get_more_info') else: print('fail') ^ SyntaxError: invalid syntax Also I try to use reindent.py But it return File "code_file.py", line 1 if age &gt; 18: if salary &gt; 100000: print('success') elif salary &lt; 50000: print('fail') else: print('get_more_info') else: print('fail') ^ SyntaxError: invalid syntax How can I fix that and do it automatically?
has comment: http://stackoverflow.com/comment/86222364
has title: Automatically fixing python indentations
has comment: http://stackoverflow.com/comment/86221941
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86222033
score: 0
answer count: 0
tagged with: auto-indent
has comment: http://stackoverflow.com/comment/86222752

http://stackoverflow.com/comment/86384903
score: 0
has text: @manandearth I have tried to add picture instead of text but I couldn't and I tried to merge the pdf file that I create with this and another pdf file that I created and added picture in it but unsuccssfully it did not worked and I tried to add extra option in this source that Mr. Didier Stevens did but I couldn't. The extra option that I want to add is instead of text I want to add picture in to pdf. I can share a demo video what does this tool does and what I want to do thanks. I also tried to add this but it did not worked. pastebin.com/nvttwe6z
type: QuestionComment
comment on: http://stackoverflow.com/q/49685677
type: Comment

http://stackoverflow.com/a/49693722
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/49693464
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/120558135
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49693464
has body: Read your dictionary as key/value pairs (dict.items()) and then just format them in a string you like: d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'} res = &quot;,&quot;.join(&quot;{}={}&quot;.format(*i) for i in d.items()) # a=Apple,c=cat,b=ball The order, tho, cannot be guaranteed for a dict, use collections.OrderedDict() if order is important.
has comment: http://stackoverflow.com/comment/86400767
type: Answer

http://stackoverflow.com/q/49744330
has comment: http://stackoverflow.com/comment/86503852
type: AnsweredQuestion
upvote count: 3
tagged with: gdal
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86519518
favorite count: 0
has comment: http://stackoverflow.com/comment/86519218
type: Question
tagged with: tiff
has answer: http://stackoverflow.com/a/49787235
accepted answer: http://stackoverflow.com/a/49787235
score: 3
has title: Why GDAL can't open big geo Tiff?
has body: python with anaconda .gdal version =2.2.2 libtiff version =4.09 ,Win 7 ,RAM =8G: After update packages, I find my program doesn't work. In Anaconda prompt ,It shows ‘not definite GDAL_DATA’, So I add env variable with ‘%~dp0......\Library\share\gdal’ .Ok,It doesn't tell me ‘not definite GDAL_DATA’.But the program does not work ~~ :( from osgeo import gdal import numpy as np ds = gdal.Open('G:\Soil_GridV2\Sand\SNDPPT_M_sl1_250m_ll.tif') channel = np.array(ds.GetRasterBand(1).ReadAsArray()) and then : from osgeo import gdal import numpy as np ds = gdal.Open('G:\Soil_GridV2\Sand\SNDPPT_M_sl1_250m_ll.tif') channel = np.array(ds.GetRasterBand(1).ReadAsArray()) Traceback (most recent call last): File "&lt;ipython-input-18-343e96de9e31&gt;", line 4, in &lt;module&gt; channel = np.array(ds.GetRasterBand(1).ReadAsArray()) AttributeError: 'NoneType' object has no attribute 'GetRasterBand'** So I check the Variable in spyder ，and find ds is None value.SO I guess the GDAL now broken can't open tiff? SO i try it again with a small tiff file(about 67.8 M) .successed! SO I find my GDAL can't open big Geo tiff file such as first file (about 2.15G) So ,should I do to fix it or repalce it with other libs? :)
has comment: http://stackoverflow.com/comment/86517717
tagged with: python

http://stackoverflow.com/q/49661678
upvote count: 1
has comment: http://stackoverflow.com/comment/86333251
has comment: http://stackoverflow.com/comment/86333340
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/37743940
tagged with: python
has answer: http://stackoverflow.com/a/49661725
accepted answer: http://stackoverflow.com/a/49661725
has comment: http://stackoverflow.com/comment/86333215
type: AnsweredQuestion
has body: I have a Julian date: 736257, I need help converting it from Julian date to Gregorian date in Python.
score: 1
has title: converting form Julian date to gregorian date in python
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86333305

http://stackoverflow.com/a/49713966
has comment: http://stackoverflow.com/comment/86441403
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49713918
has comment: http://stackoverflow.com/comment/86441396
answers question: http://stackoverflow.com/q/49713918
upvote count: 3
score: 3
has body: You can use the Python feature called "Inspect". It returns a list of frame records. The third element in each record is the caller name. Refer docs here: https://docs.python.org/3/library/inspect.html import inspect def x(): print inspect.stack()[1][3] def y(): x()
type: Answer
has comment: http://stackoverflow.com/comment/86441180
downvote count: 0

http://stackoverflow.com/q/49625694
has comment: http://stackoverflow.com/comment/86258412
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/86258376
tagged with: tree
score: 2
has comment: http://stackoverflow.com/comment/86259074
tagged with: code-formatting
has comment: http://stackoverflow.com/comment/88147743
tagged with: python
has comment: http://stackoverflow.com/comment/86259122
has comment: http://stackoverflow.com/comment/86260028
tagged with: lark-parser
type: Question
has comment: http://stackoverflow.com/comment/86258465
has comment: http://stackoverflow.com/comment/86258536
answer count: 0
has body: I've build syntax tree using lark Tree(if, [Tree(condition, [Token(VARIABLE, 'x'), Token(ACTION_OPERATOR, '&gt;'), Token(SIGNED_NUMBER, '18')]), Tree(result, [Tree(if, [Tree(condition, [Token(VARIABLE, 'y'), Token(ACTION_OPERATOR, '&gt;'), Token(SIGNED_NUMBER, '500000')]), Tree(result, [Token(STRING, 'switch_credit_type')]), Tree(condition, [Token(VARIABLE, 'y'), Token(ACTION_OPERATOR, '&lt;'), Token(SIGNED_NUMBER, '50000')]), Tree(result, [Tree(if, [Tree(condition, [Token(VARIABLE, 'z'), Token(ACTION_OPERATOR, '&gt;'), Token(SIGNED_NUMBER, '2')]), Tree(result, [Token(STRING, 'success')]), Tree(condition, [Token(VARIABLE, 'z'), Token(ACTION_OPERATOR, '&lt;'), Token(SIGNED_NUMBER, '1')]), Tree(result, [Tree(if, [Tree(condition, [Token(VARIABLE, 'a'), Token(ACTION_OPERATOR, '&gt;'), Token(VARIABLE, 'y')]), Tree(result, [Token(STRING, 'refused')]), Tree(else, [Token(STRING, 'get_more_info')])])]), Tree(else, [Token(STRING, 'get_more_info')])])]), Tree(else, [Token(STRING, 'fail')])])])]) I need to generate python code from it (condition) But I have problem with indents and try to build code generator automatically code = [] add_indent = '' def py_cond_gen(t, level=0): global code, add_indent if t.data == 'if': code.append('if') for i, child in enumerate(t.children): if child.data == 'condition': if code[-1] != 'if': code.append('elif') condition_expr = ' '.join([str(children) for children in child.children]) + ':\n\t' + add_indent code.append(condition_expr) if child.data == 'result': if type(child.children[0]).__name__ == 'Tree' and child.children[0].data == 'if': add_indent = '\t' * (level+1) py_cond_gen(child.children[0], level=level+1) add_indent = add_indent[:level-2] else: code.append("print('%s')" % child.children[0] + '\n' + add_indent[:level-2]) if child.data == 'else': code.append('else:\n\t' + add_indent[:level-2]) code.append("print('%s')" % child.children[0] + '\n' + add_indent[:level-2]) But there is extra indentation and I have no idea no how can I fix t…
upvote count: 2
type: UnansweredQuestion
has title: Python: generate python code from tree

http://stackoverflow.com/comment/86293451
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49641858
score: 0
has text: Thanks for the feedback. What do you mean use your testing set as the last possible moment? And wouldn't incorporating webcam data into my dataset give me false results? (Model learn to recognize me.)

http://stackoverflow.com/comment/86310099
has text: you might need to use the show_record_id flag which is by default set to False
score: 0
comment on: http://stackoverflow.com/q/49650320
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49715995
downvote count: 1
answer count: 1
tagged with: cython
linked to: http://stackoverflow.com/q/49058949
favorite count: 0
type: Question
tagged with: numpy
has title: Optimize away PyFloat_FromDouble, Pyx_GetItemInt and PyObject_RichCompare in Cython generated C code
tagged with: python
has body: I am trying to write a run length encoding arithmetic library for Python in Cython. Below you see how the declaration and the important parts of the hot loop of the algorithm looks. It has two places with much and moderate Python interaction, line 73-74 and 77. The C code generated for the heavy Python interaction part is shown in a picture at the end. I will only inquire about how to solve 73-74 here as I imagine the fix for 77 will be similar. As you can see, there is 1) a lot of type casting in the generated C code, 2) it uses richcompare and 3) getitemint. I do not understand why: 1) The types should be that same, 2) the comparison should be possible at a C level as they are just comparing the same types of numbers and 3) getitem should be superfluous as you are just looking up an index in C array. How can fix this to optimize my code? Is the problem that the numpy array declarations create Python objects and that I need to give a pointer to them in some way? Here you see the C code Cython generated for the two dark and light yellow places in my hot loop:
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49716047
accepted answer: http://stackoverflow.com/a/49716047
upvote count: 1
tagged with: types

http://stackoverflow.com/comment/86372055
type: Comment
comment on: http://stackoverflow.com/a/49679950
type: AnswerComment
score: 0
has text: thank you that worked, I had to flatten x into a 1d array and then reshape it as 2,-1 as I was using two samples.

http://stackoverflow.com/comment/86579939
type: Comment
has text: Ah rats. Yeah I'm behind a corporate firewall. I was kind of hoping it was something else but they probably just changed firewall settings. thanks for your prompt response
comment on: http://stackoverflow.com/q/49756437
type: QuestionComment
score: 0

http://stackoverflow.com/a/49620984
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/86297037
accepted answer of: http://stackoverflow.com/q/49620889
has body: There are 2 reasons why your solutions are inefficient for your task: Using your for loop, you search from first to last, instead of last to first. In addition, you are unnecessarily building a list. For numpy.where, you retrieve all the indices, before you select the final one. You can resolve these 2 issues via a custom function which searches from last to first. In addition, you can improve performance via JIT-compiling. from numba import jit import numpy as np arr = np.random.randint(0, 9, 100000) @jit(nopython=True) def indexer(arr, item): for idx, val in enumerate(arr[::-1]): if val == item: return len(arr) - idx - 1 %timeit indexer(arr, 5) # 2.52 µs %timeit np.where(arr==5)[0][-1] # 454 µs
type: Answer
has comment: http://stackoverflow.com/comment/86289447
answers question: http://stackoverflow.com/q/49620889
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86263973
type: Comment
type: QuestionComment
has text: You can also attach an IAM role to the EC2 instance with `ec2:StopInstances` permissions. Steps: Start instances using CloudWatch events, Run your scripts. Once script execution is done, get the instance id from the meta-data (`curl http://169.254.169.254/latest/meta-data/instance-id`) and issue `aws ec2 stop-instances --instance-ids i-XXXX`
score: 0
comment on: http://stackoverflow.com/q/49622575

detection
tags question: http://stackoverflow.com/q/49636813
type: Tag
tag name: detection

http://stackoverflow.com/q/49623781
tagged with: django-rest-framework
has body: i have poll app following is my root urls urlpatterns = [ path('poll/', include('myproject.poll.urls')), ] and I have app url router = DefaultRouter() router.register(r'', PollViewSet) urlpatterns = [ path('', include(router.urls)) ] i used ViewSet so I can use reverse('poll-list'), reverse('poll-detail')... and i can access xxx.xxx.xxx.xxx/poll and xxx.xxx.xxx.xxx/poll/1/ .... but I want to redirect(mapping?) url when i access xxx.xxx.xxx.xxx/api/v1/poll/ to xxx.xxx.xxx.xxx/poll I don't want to change existing urls. because I want to bundle the views of several apps into one api url file. How can i do that? and what is the best way?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49624347
tagged with: django
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
has title: how to redirect? mapping? url in django
has comment: http://stackoverflow.com/comment/86255594
accepted answer: http://stackoverflow.com/a/49624347
downvote count: 0
has comment: http://stackoverflow.com/comment/86254739
answer count: 1

http://stackoverflow.com/comment/86471572
type: QuestionComment
comment on: http://stackoverflow.com/q/49723499
score: 0
has text: I missed that you were using `getValue()` instead of `read()` so the rewind probably wasn't required.
type: Comment

http://stackoverflow.com/comment/86343937
type: AnswerComment
comment on: http://stackoverflow.com/a/49667042
has text: Which solution is better yours or coldspeed, can you please explain.
score: 0
type: Comment

http://stackoverflow.com/q/49700936
tagged with: decision-tree
has answer: http://stackoverflow.com/a/49701049
favorite count: 0
type: Question
answer count: 2
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86415473
type: UnansweredQuestion
tagged with: group-by
has answer: http://stackoverflow.com/a/49710716
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86418385
has body: I was trying to find the best variable to split a decision tree on and it required grouping and counting the occurrence of some values. A dummy data set is zipped=[(‘a’, ‘None’), (‘b’, ‘Premium’), (‘c’, ‘Basic’), (‘d’, ‘Basic’), (‘b’, ‘Premium’), (‘e’, ‘None’), (‘e’, ‘Basic’), (‘b’, ‘Premium’), (‘a’, ‘None’), (‘c’, ‘None’), (‘b’, ‘None’), (‘d’, ‘None’), (‘c’, ‘Basic’), (‘a’, ‘None’), (‘b’, ‘Basic’), (‘e’, ‘Basic’)] So, I would like to find how many None, Basic and Premium are there in each of the a,b,c,d,e I need it to look like {‘a’:[‘None’:3,‘Basic’:0,‘Premium’:0], ‘b’:[‘None’:1,‘Basic’:1,‘Premium’:3],…} . I am also open to a better way of aggregation or data structure. Here is what I tried to do temp=Counter( x[1] for x in zipped if x[0]=='b') print(temp) and I got Counter({'Premium': 3, 'None': 1, 'Basic': 1})
tagged with: list
has title: group a list of lists and count occurence of the second element for a unique first element
tagged with: machine-learning

http://stackoverflow.com/a/49717913
downvote count: 0
has comment: http://stackoverflow.com/comment/86536532
type: AcceptedAnswer
has body: You can use tf.while_loop to execute an arbitrary TensorFlow operation repeatedly, until some stopping condition occurs. The stopping condition is itself specified as an op. Note that tf.while_loop should be used with care, as its iterations will run in parallel by default. For example, if the loop body increments a tf.Variable, then you must use control dependencies to ensure that the iterations run in sequence. However, you mentioned that you have a working implementation with a Python loop. When possible, using Python for the loop is usually the most efficient solution. When you build the loop in Python, you create separate ops for each iteration in the loop. This lets TensorFlow decide at graph-building how to assign computing resources to each op. For example, memory requirements and parallelization possibilities are easier to predict if the number of iterations is known in advance. For this reason, tf.while_loop and tf.map_fn are most commonly used when the stopping condition is not known at graph-building time. You might still want to use tf.while_loop instead of a Python loop if there is a fixed but very large number of iterations, because there is a nontrivial memory cost per op.
accepted answer of: http://stackoverflow.com/q/49714839
type: Answer
answers question: http://stackoverflow.com/q/49714839
has comment: http://stackoverflow.com/comment/86490682
upvote count: 3
score: 3

http://stackoverflow.com/a/51768849
has body: The following packages are required for a brand new installation of jupyter notebook (version 5.6) with conda, so the working version of tornado is 5.1. ipykernel: 4.8.2-py36_0 conda-forge ipywidgets: 7.4.0-py_0 conda-forge jupyter: 1.0.0-py_1 conda-forge jupyter_client: 5.2.3-py_1 conda-forge jupyter_console: 5.2.0-py36_0 conda-forge nbconvert: 5.3.1-py_1 conda-forge notebook: 5.6.0-py36_0 conda-forge qtconsole: 4.3.1-py36_0 conda-forge terminado: 0.8.1-py36_0 conda-forge tornado: 5.1-py36h470a237_1 conda-forge widgetsnbextension: 3.4.0-py36_0 conda-forge To fix this problem, one can manually install the newest version of tornado: conda install tornado --update or re-install jupyter notebook from scratch: conda uninstall jupyter tornado conda install jupyter
answers question: http://stackoverflow.com/q/49603097
score: 10
upvote count: 10
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86285262
comment on: http://stackoverflow.com/q/49638807
type: QuestionComment
has text: Yes, I need to log in and then view the page source code in chrome. Then parse the code in python...
type: Comment
score: 0

http://stackoverflow.com/q/49621613
has comment: http://stackoverflow.com/comment/86250093
type: AnsweredQuestion
answer count: 2
tagged with: raspberry-pi
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/49621642
has body: When ever i try to run this script through the terminal on my raspberry pi: input = 5 num = int(input) for i in range(2,num): if (num % i) == 0: print(num, "is divisible by", i) break else: print(num, "is a prime number") break its output is: (5, 'is a prime number') i cannot find any reason that this would be happening and it only happens through the terminal, but for some reason if i take away the ()'s it still works, which it shouldn't i am very new at python and may have made a silly mistake but i can't find anything about it online
tagged with: raspberry-pi3
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: terminal
has title: python showing ()'s around print command
score: -2
has comment: http://stackoverflow.com/comment/86250112
has comment: http://stackoverflow.com/comment/86250075
has answer: http://stackoverflow.com/a/49621642
has answer: http://stackoverflow.com/a/49621636
possible better answer: http://stackoverflow.com/a/49621636
tagged with: python

http://stackoverflow.com/comment/86495157
has text: You have to be more specific about *when* they should be shown. Are you working in a Python shell, IDLE, IPython, Jupyter, Visual Studio code, something else? Do you want them to show in the IDE at all or is this about `help()` or documentation builds?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49740290
type: Comment

http://stackoverflow.com/comment/86363198
has text: @JamesZ, I'll look into OLTP, seems promising actually.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49675751

http://stackoverflow.com/comment/86346997
comment on: http://stackoverflow.com/a/49666443
type: AnswerComment
score: 0
has text: So, if use only `pq.index = pd.to_timedelta(pq.index, unit='d')` it working?
type: Comment

http://stackoverflow.com/a/49738863
score: 1
upvote count: 1
has body: You didn't iterate through all the names in first_name (should probably be called first_names because it's a list of multiple first names). You forgot : after the if Other than that seems good. Working solution: first_names = ['john', 'robert'] for first_name in first_names: if len(first_name) &gt;= 4: print(first_name)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49738790
downvote count: 0
answers question: http://stackoverflow.com/q/49738790

http://stackoverflow.com/q/49618760
tagged with: amazon-web-services
favorite count: 0
tagged with: aws-lambda
type: Question
has title: AWS Lambda error (module initialization error: name 'dynamodb' is not defined) with dynamodb
accepted answer: http://stackoverflow.com/a/49683022
tagged with: python
has body: I'm trying to run a lambda function that takes an attribute about the AWS IoT Dash button, its serialNumber, and queries it in DynamoDB. Consequently, it is supposed to print the entire row. Here is the code ---> from __future__ import print_function import boto3 import json import decimal from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): print ('Init 1Push_Care_DATAprint') print (event) serialNumber = event['serialNumber'] class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 &gt; 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) dynamodb = boto3.resource('dynamodb',region_name='us-east-1') table = dynamodb.Table('1Push_Care_USERinfo') response = table.query( KeyConditionExpression=Key('Device_ID').eq('serialNumber') ) items = response['Items'] print(items) Here is the error message I keep receiving ---> module initialization error: name 'dynamodb' is not defined
type: AnsweredQuestion
tagged with: aws-iot
tagged with: amazon-cloudwatchlogs
score: 1
has answer: http://stackoverflow.com/a/49683022
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49711876
downvote count: 0
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49710321
upvote count: 3
answers question: http://stackoverflow.com/q/49710321
type: AcceptedAnswer
has body: After much tinkering, and comparing against some of the examples from the project page I finally discovered what the bug was. It boils down to a naming convention that isn't easy to find if you don't know to look for it or what you're looking for. This is an incorrect file: Numbers.jsgf #JSGF V1.0; grammar Values; &lt;Zero&gt; = ( zero ); And this is a correct file: Numbers.jsgf #JSGF V1.0; grammar Numbers; &lt;Numbers&gt; = ( zero ); To explain it simply: The file name MUST be the same as the grammar name There MUST be one grammar rule (e.g. &lt;Numbers&gt;) with the same name as the file / grammar name If either of those conditions isn't met, then the program won't be able to understand the file and will crash. As a side note, .jsgf and .gram files are referencing the same coding standards, and the extension seems to come down to personal taste.

http://stackoverflow.com/q/49728799
has answer: http://stackoverflow.com/a/49732560
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/6908143
has answer: http://stackoverflow.com/a/49728849
favorite count: 0
type: Question
has title: set path for command line of python (mac)
type: UnansweredQuestion
tagged with: path
tagged with: python
tagged with: command-line
has body: I defined some command line tools of python (take mycmd.py as an example), and saved them in the folder ~/Scripts. Hence, I have to type (for example) python /Scripts/mycmd.py -o v. It is tedious to repeat the name of the folder /Scripts. I want to run the command only inputting python mycmd.py -o v, even without cd. How should I do? Add a path to the original one? PS: in mac
answer count: 2

http://stackoverflow.com/comment/86452258
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49719686
has text: @roganjosh - I think compare solution with `isin`, but I have to test it for 100% sure :)
type: Comment

http://stackoverflow.com/q/49696107
has answer: http://stackoverflow.com/a/49696227
tagged with: python
score: 0
has title: How could I cover the output in Python 3.6
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I try to rewrite a line in an output with this code. import time print('Hello, world!', end='', flush=True) time.sleep(1) print('\rHi.') I prefer to get this at last: Hi. But actually, I got this: Hi.lo, world! So, how could I do?

http://stackoverflow.com/comment/86238908
type: QuestionComment
has text: After making the string formatting update, have you tried printing `response.json()` (or `json.dumps(resp_json)`) to see what the response looks like? Maybe it will show an error.
comment on: http://stackoverflow.com/q/49613600
score: 0
type: Comment

reddit
tags question: http://stackoverflow.com/q/49705937
tags question: http://stackoverflow.com/q/49743797
tags question: http://stackoverflow.com/q/49670922
type: Tag
tag name: reddit

http://stackoverflow.com/q/49661487
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86333908
answer count: 1
favorite count: 0
has title: Array Value Must Start with "{" or dimension information
has comment: http://stackoverflow.com/comment/86333617
has body: Here's my create table code: cur.execute('CREATE TABLE IF NOT EXISTS Customers (id INTEGER PRIMARY KEY, firstName Varchar(30), lastName Varchar(30), street TEXT, city Varchar(50), state Varchar(2), zip INTEGER);') And here's my Upsert Function: def upsert_customer(customer): cur=conn.cursor() if 'id' in customer: cur.execute('UPDATE Customers SET firstName= %s, lastName = %s, street=%s, city=%s, state=%s, zip=%s WHERE id =%s;' , (customer['firstName'], customer['lastName'], customer['street'], customer['city'], customer['state'], customer['zip'])) else: cur.execute('INSERT INTO Customers( firstName, lastName, street,city,state,zip) VALUES ( %s, %s, %s, %s, %s, %s);' , (customer['firstName'], customer['lastName'], customer['street'], customer['city'], customer['state'], customer['zip'])) conn.commit() When I add a customer from a webpage, I get the error message, and in the web page it displays the following error: " Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application." The program is to complete implementation of functions that connects a web page to our PostgreSQL in ElephantSQL. I'm not sure how to fix this.
tagged with: postgresql
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86333017
has answer: http://stackoverflow.com/a/49666479
has comment: http://stackoverflow.com/comment/86332918
tagged with: sql

http://stackoverflow.com/q/49683944
has comment: http://stackoverflow.com/comment/86379542
has comment: http://stackoverflow.com/comment/86379609
type: Question
has comment: http://stackoverflow.com/comment/86379755
has body: I’m trying to search a long string of characters for a country name. The country name is sometimes more than one word, such as Costa Rica. Here is my code: eol = len(CountryList) for c in range(0, eol): country = str(CountryList[c]) countrymatch = re.search(country, fullsampledata) if countrymatch: ... fullsampledata is a long string with all the data in one line. I’m trying to parse out the country by cycling thru a list of valid country names. If country is only one word, such as ‘Holland’, it finds it. However, if country is two or more words, ‘Costa Rica’, it doesn’t find it. Why?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86441471
has title: Need to search a string for a "two word" pattern in python
linked to: http://stackoverflow.com/q/3437059
has comment: http://stackoverflow.com/comment/86380989
tagged with: python
has comment: http://stackoverflow.com/comment/86379829
has answer: http://stackoverflow.com/a/49684004
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49684039

http://stackoverflow.com/q/49753655
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has body: I've looked around and discovered Tkinter, however learning everything for Tk for my current needs (just a simple text input, textbox and an image) doesn't seem worth it. Any better alternative?
accepted answer: http://stackoverflow.com/a/49753706
answer count: 1
has comment: http://stackoverflow.com/comment/86521834
has answer: http://stackoverflow.com/a/49753706
type: AnsweredQuestion
downvote count: 3
score: -2
upvote count: 1
has title: Quick & Simple GUI Lib for Windows?

http://stackoverflow.com/comment/86441818
type: Comment
has text: ...and those 14 consecutive digits with commas, brackets, and quotes are? I can't duplicate your problem if you don't provide all of the essentials. And please take the time to read: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
score: 1
comment on: http://stackoverflow.com/q/49714331
type: QuestionComment

http://stackoverflow.com/comment/86323982
type: Comment
type: AnswerComment
score: 0
has text: How can it be dynamic for all the files
comment on: http://stackoverflow.com/a/49657458

http://stackoverflow.com/comment/86432023
comment on: http://stackoverflow.com/a/49708564
type: Comment
score: 0
type: AnswerComment
has text: This example code, as shown, doesn't run as it has unbalanced parentheses.

http://stackoverflow.com/comment/86481053
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49733506
has text: Are you deliberately not killing d1 after d finishes?

http://stackoverflow.com/q/49645478
has answer: http://stackoverflow.com/a/49645742
type: AnsweredQuestion
tagged with: python-2.7
has body: I am starting asynchronous tasks using python's concurrent.futures ThreadPoolExecutor. Following this approach, I monitor the progress of the async calls using the tqdm progress bar. My code looks like this: with concurrent.futures.ThreadPoolExecutor(max_workers = n_jobs) as executor: future_to_url = {executor.submit(target_function, URL): URL for URL in URL_list} kwargs = {'total': len(future_to_url), # For tqdm 'unit': 'URL', # For tqdm 'unit_scale': True, # For tqdm 'leave': False, # For tqdm 'miniters': 50, # For tqdm 'desc': 'Scraping Progress'} for future in tqdm(concurrent.futures.as_completed(future_to_url), **kwargs): URL = future_to_url[future] try: data = future.result() # Concurrent calls except Exception as exc: error_handling() # Handle errors else: result_handling() # Handle non-errors The console output looks like this: Scraping Progress: 9%|▉ | 3.35k/36.2k [08:18&lt;1:21:22, 6.72URL/s] # I want &lt; 6/s Scraping Progress: 9%|▉ | 3.40k/36.2k [08:26&lt;1:21:16, 6.72URL/s] # I want &lt; 6/s Scraping Progress: 10%|▉ | 3.45k/36.2k [08:30&lt;1:20:40, 6.76URL/s] # I want &lt; 6/s Scraping Progress: 10%|▉ | 3.50k/36.2k [08:40&lt;1:20:51, 6.73URL/s] # I want &lt; 6/s Scraping Progress: 10%|▉ | 3.55k/36.2k [08:46&lt;1:20:36, 6.74URL/s] # I want &lt; 6/s Scraping Progress: 10%|▉ | 3.60k/36.2k [08:52&lt;1:20:17, 6.76URL/s] # I want &lt; 6/s I know I can set up a URL queue and control its size, as described here. However, I don't know how to control throughput speed itself. Lets say I want not more than 6 URLs/sec. Can this be archived by something else than throwing in time.sleep(n) to target_function() in the above example? How to effectively control throughput speed of ThreadPoolExecutor in python's concurrent.futures?
answer count: 1
has comment: http://stackoverflow.com/comment/86299235
has comment: http://stackoverflow.com/comment/86299075
tagged with: concurrent.futures
linked to: http://stackoverflow.com/q/16914665
favorite count: 0
has comment: http://stackoverflow.com/comment/86299334
type: Question
has comment: http://stackoverflow.com/comment/86299140
score: 2
upvote count: 2
tagged with: python-multithreading
has title: How to control throughput speed of python's ThreadPoolExecutor?
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86299194
accepted answer: http://stackoverflow.com/a/49645742

http://stackoverflow.com/comment/127647874
comment on: http://stackoverflow.com/a/64549704
type: Comment
score: 2
has text: Thank you! I was loading JSON file with the following code: import json with open('movie.json', encoding='utf8') as JSONFile: data = json.load(JSONFile) print(len(data['movie'][0])) and it was throwing the above-mentioned error, by adding "encoding='utf8'" to the "with open()", it is solved.
type: AnswerComment

http://stackoverflow.com/a/49709678
answers question: http://stackoverflow.com/q/49709598
has body: I think need assign: df = df.loc[:, dict_lup.values()].rename(columns={v: k for k, v in dict_lup.items()}) .assign(cover = df['cover'] * 100., id = df['condition'].map(constants.dict_c), temperature = (df['min_t'] + df['max_t'])/2.)
has comment: http://stackoverflow.com/comment/86436520
accepted answer of: http://stackoverflow.com/q/49709598
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/49722094
has comment: http://stackoverflow.com/comment/86457766
has comment: http://stackoverflow.com/comment/86457912
tagged with: telegram
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/86457788
has title: Bot can't send channel photo by file_id
upvote count: 1
tagged with: python
answer count: 1
tagged with: telegram-bot
has comment: http://stackoverflow.com/comment/86458024
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49723303
score: 1
has body: I use python and here is a problem. First I use method get_chat to get file_id of photo chat as example. import telebot bot = telebot.TeleBot("xxxxxxxxxxxxxxxxxxxxxxxx") s = bot.get_chat('@codygarbrandt_best') print(s.photo.big_file_id) Then I want to send this photo to myself. bot.send_photo(my_chat_id , s.photo.big_file_id ) But I get the following error. Bad Request: type of file mismatch I remember it worked before, how can I achieve this now?
has answer: http://stackoverflow.com/a/49723303
favorite count: 0

http://stackoverflow.com/comment/100919586
type: Comment
type: AnswerComment
has text: See this link: https://github.com/conda/conda/issues/7980. These two lines of code at the beginning of your bash script will allow you to use `conda activate` in a script: `CONDA_BASE=$(conda info --base) ; source $CONDA_BASE/etc/profile.d/conda.sh`
score: 9
comment on: http://stackoverflow.com/a/56973810

http://stackoverflow.com/a/51021966
has body: You just need to call optimizer.step() after you do loss.backward(). Which, by the way, illustrates a common misconception: Backpropagation is not a learning algorithm, it's just a cool way of computing the gradient of the loss w.r.t. your parameters. You then use some variant of Gradient Descent (eg. plain SGD, AdaGrad, etc., in your case Adam) to update the weights given the gradients.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49601263
score: 1
upvote count: 1

qgraphicsview
tags question: http://stackoverflow.com/q/49644530
tags question: http://stackoverflow.com/q/49664603
type: Tag
tags question: http://stackoverflow.com/q/49665870
tags question: http://stackoverflow.com/q/49686907
tags question: http://stackoverflow.com/q/49747858
tag name: qgraphicsview

http://stackoverflow.com/comment/86388772
type: Comment
score: 0
has text: Ok, thanks, will check it out
type: QuestionComment
comment on: http://stackoverflow.com/q/49688208

http://stackoverflow.com/comment/86535521
has text: The 0.25 problem is a side-effect of sgd and random weight initialization, sometimes you'll get stuck there and sometimes you won't. The way around it would be to boost your learning rate whenever your errors are the same as the last epoch errors.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49758402
type: Comment

http://stackoverflow.com/q/49602671
has answer: http://stackoverflow.com/a/49602709
answer count: 3
has comment: http://stackoverflow.com/comment/86212584
tagged with: pandas
tagged with: dataframe
tagged with: naming
possible better answer: http://stackoverflow.com/a/49602996
has body: I'm unable to construct a dataframe from 3 individual numbers. I want to do this in order for a function to return the dataframe, which I then append to other existing results. Desired result is a dataframe with columns named "a", "b" and "C", each containing the value of a, b, and c. Try one: a=1 b=2 c=3 dat=pd.DataFrame([a,b,c], columns=list('abc')) #fails with size error Try two: dat=pd.DataFrame() dat['a']=pd.np.nan dat['b']=pd.np.nan dat['c']=pd.np.nan dat['c']=c # no numbers are added to the column; still has 0 rows What am I missing here? Desired result is: a | b | c ------------- 1 | 2 | 3
favorite count: 0
type: Question
downvote count: 0
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/49602996
upvote count: 11
has answer: http://stackoverflow.com/a/49602723
accepted answer: http://stackoverflow.com/a/49602709
has title: Make One-Row Dataframe
type: AnsweredQuestion

http://stackoverflow.com/comment/86434656
type: QuestionComment
comment on: http://stackoverflow.com/q/49710454
score: 0
type: Comment
has text: @abarnert well, it's a comment, not an answer ;-)

http://stackoverflow.com/comment/86522295
comment on: http://stackoverflow.com/q/49738455
type: Comment
type: QuestionComment
has text: And there are still no errors? I have had flaky issues in the past with AD cmdlets, but there have always been errors. I would try doing some explicit error checking around the command. Also perhaps a try{} catch{} block.
score: 0

http://stackoverflow.com/a/49675781
type: Answer
score: 0
has body: The output(value) of the html = driver.page_source will help, but I assume this will work as well: from urllib.request import urlopen from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException url ='http://marketdata.krx.co.kr/mdi#document=080120&amp;547c5e15ef32e37dc099b89d69ac8970-[object%20HTMLDivElement]=1&amp;547c5e15ef32e37dc099b89d69ac8970-[object%20HTMLDivElement]=2&amp;547c5e15ef32e37dc099b89d69ac8970-[object%20HTMLDivElement]=1&amp;547c5e15ef32e37dc099b89d69ac8970-object%20HTMLDivElement]=1' driver = webdriver.Chrome() driver.get(url) element = driver.find_element_by_xpath('//select[@name="upclss"]') all_options = element.find_elements_by_tag_name("option") for option in all_options : if option.text == "원자재": option.click() driver.implicitly_wait(5) another = driver.find_element_by_xpath('//li[@class="active"]') another.click() driver.implicitly_wait(5) tds = driver.find_element_by_xpath("//table/tr/td") for td in tds : print(td.text)
answers question: http://stackoverflow.com/q/49674105
has comment: http://stackoverflow.com/comment/86381168

http://stackoverflow.com/comment/86338834
type: QuestionComment
has text: i figured it out after i posted my question on SO. its serving my purpose now.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49623423

http://stackoverflow.com/comment/86438032
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49707042
type: Comment
has text: You can also use the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/): `aws iam list-users --query Users[*].UserName`

http://stackoverflow.com/a/49640596
downvote count: 0
has comment: http://stackoverflow.com/comment/86289929
has body: The simplest way is to just pass it an object that acts enough like a sequence to get array to treat it as one, but then throw it off the trail once it starts. I can't remember the exact rules for what array considers a sequence, but it's still pretty easy to find things that break. For example, confuse it into building a size-2 array before realizing that (by the old-style sequence iterator protocol) the object actually has length 0: class BadSeq: def __len__(self): return 2 def __getitem__(self, idx): raise IndexError() Now np.array(BadSeq()) will raise: ValueError: cannot copy sequence with size 2 to array axis with dimension 0 By contrast, list(BadSeq()) will return an empty list. Or just violate the sequence protocol entirely: class BadSeq: def __len__(self): return 2 def __getitem__(self, idx): raise TypeError(f"Take your {type(idx).__name__} and shove it") Now np.array(BadSeq()) will just pass the TypeError through: TypeError: Take your int and shove it Of course here, list has the same behavior. I believe you can play similar tricks with the buffer protocol, but that requires building a C extension, which is more work than I want to put into this. (Actually, I did try hacking up a memoryview from an array.array via ctypes.pythonapi, but it turns out that segfaults are easier to get than exceptions that way, and if that's what you want, there are better ways to do it…) As a side note, the following code does not raise an exception, but probably doesn't do what you want: x = [] x.append(x) arr = np.array(x, copy=False, subok=False) The original x is an infinite-dimensional nested list, but arr is a 32D array whose single element (arr[(1,)*32])) is a reference to x, as an object. Although you get effectively the same result with finite nesting: y = [] for _ in range(33): y = [y[:]] arr = np.array(y, copy=False, subok=False) This gives you a 32D array whose single element is a 3D nested list.
has comment: http://stackoverflow.com/comment/86289914
score: 3
has comment: http://stackoverflow.com/comment/86291474
type: Answer
answers question: http://stackoverflow.com/q/49639414
upvote count: 3

http://stackoverflow.com/q/49713656
has comment: http://stackoverflow.com/comment/86440688
tagged with: pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49713800
favorite count: 0
has answer: http://stackoverflow.com/a/49713800
has body: Let's say there is a Panadas DataFrame that contains movie rating data. 1) Is there a way to assign user_id and movie_id with one liner? 2) Other than visual help, is there a benefit/usage of name property? For example, accessing index by user_id etc..? import pandas as pd ratings = pd.DataFrame({0: [3, 1, 5], 1: [2, 2, 4]}) ratings.index.name = 'user_id' ratings.columns.name = 'movie_id'
has title: Pandas usage of df.index.name and df.columns.name
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/49713693
answer count: 2
downvote count: 2
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/49713693

http://stackoverflow.com/q/49600583
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49639160
tagged with: python
has comment: http://stackoverflow.com/comment/86247768
tagged with: pymunk
has answer: http://stackoverflow.com/a/49639160
favorite count: 0
has title: How to fix unbalanced falling kinematics in Pymunk
tagged with: game-physics
score: 2
type: AnsweredQuestion
answer count: 1
has body: Why is the physics wrong in the following Pymunk example? from __future__ import print_function import sys from math import pi import pygame from pygame.locals import USEREVENT, QUIT, KEYDOWN, KEYUP, K_s, K_r, K_q, K_ESCAPE, K_UP, K_DOWN, K_LEFT, K_RIGHT from pygame.color import THECOLORS import pymunk from pymunk import Vec2d import pymunk.pygame_util LEG_GROUP = 1 class Simulator(object): def __init__(self): self.display_flags = 0 self.display_size = (600, 600) self.space = pymunk.Space() self.space.gravity = (0.0, -1900.0) self.space.damping = 0.999 # to prevent it from blowing up. # Pymunk physics coordinates start from the lower right-hand corner of the screen. self.ground_y = 100 ground = pymunk.Segment(self.space.static_body, (5, self.ground_y), (595, self.ground_y), 1.0) ground.friction = 1.0 self.space.add(ground) self.screen = None self.draw_options = None def reset_bodies(self): for body in self.space.bodies: if not hasattr(body, 'start_position'): continue body.position = Vec2d(body.start_position) body.force = 0, 0 body.torque = 0 body.velocity = 0, 0 body.angular_velocity = 0 body.angle = body.start_angle def draw(self): ### Clear the screen self.screen.fill(THECOLORS["white"]) ### Draw space self.space.debug_draw(self.draw_options) ### All done, lets flip the display pygame.display.flip() def main(self): pygame.init() self.screen = pygame.display.set_mode(self.display_size, self.display_flags) width, height = self.screen.get_size() self.draw_options = pymunk.pygame_util.DrawOptions(self.screen) def to_pygame(p): """Small hack to convert pymunk to pygame coordinates""" return int(p.x), int(-p.y+height) def from_pygame(p): return to_pygame(p) clock = pygame.time.Clock() running = True font = pygame.font.Font(None, 16) # Create the torso box. box_width = 50 box_height = 100 # leg_length = 100 leg_length = 125 leg_thickness = 2 leg_shape_filter = pymunk.ShapeFilter(group=LEG_GROUP) # Create torso. mass = 200 points = [(-box_width/2, -box_height/2), (-box_…
has comment: http://stackoverflow.com/comment/86244181
type: Question

http://stackoverflow.com/comment/86333363
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49661206
has text: I'm downvoting this question because despite numerous requests you refuse to describe the pattern of your version numbers clearly. Of course, if you knew what the pattern was you probably could write the regexp yourself.

http://stackoverflow.com/comment/86419113
has text: here is the link to download the SP500 csv file https://fred.stlouisfed.org/series/SP500 use the download button then choose csv file. I have tried 4 other feb files, they all give the same error when trying to load price data as float fields. the decimal point in the fields throws the error.
score: 0
comment on: http://stackoverflow.com/q/49702529
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49724789
has title: How to convert a key string back into a pycrypto key object? (Python)
tagged with: python
has comment: http://stackoverflow.com/comment/86520621
upvote count: 2
score: 2
has body: I am replicating a TCP client-server secure handshake in python using the pycrypto module. When the "server" sends the public key over the socket, I am forced to convert the public key to a string. The "client" then receives the public key as a string, which cannot be encrypted according the pycrypto module. I get the error: AttributeError: 'str' object has no attribute 'encrypt' in reference to enc_data = public_key.encrypt(secret_piece, 12) on the client side. How do convert the string public_key back to its original value when it was first generated by the RSA module? Server Code: def main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.bind((host,port)) s.listen(1) c, addr = s.accept() print "Connection from: "+str(addr) while True: data = c.recv(1024) if not data: break print "from connected user: "+str(data) print "Start the SSL Handshake..." a = raw_input('Press enter to generate the key pair. ') key = RSA.generate(1024, random_generator) public_key = key.publickey() print "Key pair generated" a = raw_input('Press enter to send public key to client ') print "Sending key..." if c.send(str(public_key)): print "Public Key Sent" print "Waiting for secret list..." if c.recv(1024): print "List received." secret_list = c.recv(1024) a = raw_input('Press enter to check the information from the list. ') decrypted_info = key.decrypt(secret_list.enc_data) match_or_not = SHA256.new(decrypted_info).digest() == secret_list.hash_value if match_or_not: print "Info Matches. Sending the ciphertext..." info_to_be_encrypted = "It seems all secure. Let's talk!" aes = AES.new(Random.get_random_bytes(16), AES.MODE_ECB) cipher_text = aes.encrypt(info_to_be_encrypted) if c.send(cipher_text): print "Ciphertext sent." Client Code def main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.connect((host,port)) message = raw_input("-&gt; ") while message != 'q': s.send(message) public_key = s.recv(1024) print 'Received from server: '+str(public_key) message = raw_input("-&gt;…
answer count: 2
has comment: http://stackoverflow.com/comment/86465206
tagged with: client-server
downvote count: 0
tagged with: pycrypto
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86465141
has answer: http://stackoverflow.com/a/49787202
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49786230

sqlalchemy
tags question: http://stackoverflow.com/q/49737777
tags question: http://stackoverflow.com/q/49628474
tags question: http://stackoverflow.com/q/49712362
tags question: http://stackoverflow.com/q/49629431
tags question: http://stackoverflow.com/q/49675751
tags question: http://stackoverflow.com/q/49730763
tags question: http://stackoverflow.com/q/49727254
tags question: http://stackoverflow.com/q/49743183
tags question: http://stackoverflow.com/q/49726033
tags question: http://stackoverflow.com/q/49646848
tags question: http://stackoverflow.com/q/49657732
tags question: http://stackoverflow.com/q/49730133
tags question: http://stackoverflow.com/q/49673471
tags question: http://stackoverflow.com/q/49621202
tags question: http://stackoverflow.com/q/49607031
tags question: http://stackoverflow.com/q/49695723
tags question: http://stackoverflow.com/q/49689214
tags question: http://stackoverflow.com/q/49713177
tags question: http://stackoverflow.com/q/49676760
tags question: http://stackoverflow.com/q/49657120
tags question: http://stackoverflow.com/q/49654885
tags question: http://stackoverflow.com/q/49686876
tags question: http://stackoverflow.com/q/49627534
tags question: http://stackoverflow.com/q/49628329
tags question: http://stackoverflow.com/q/49694574
tags question: http://stackoverflow.com/q/49723540
tags question: http://stackoverflow.com/q/49727453
tags question: http://stackoverflow.com/q/49652698
tags question: http://stackoverflow.com/q/49732898
tags question: http://stackoverflow.com/q/49717961
tags question: http://stackoverflow.com/q/49610780
tags question: http://stackoverflow.com/q/49689581
tags question: http://stackoverflow.com/q/49676307
tags question: http://stackoverflow.com/q/49605159
tags question: http://stackoverflow.com/q/49755300
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/49625415
tags question: http://stackoverflow.com/q/49654351
type: Tag

http://stackoverflow.com/q/49705462
tagged with: python
has body: I have a nested list in the following format: [['john'],['jack','john','mary'],['howard','john'],['jude']...] I want to find the first 3 or 5 indices of john that occurs in the nested list(since the list is really long) and return the indices like: (0,0),(1,1),(2,1) or in any format which is advisable. I'm fairly new to nested list. Any help would be much appreciated.
linked to: http://stackoverflow.com/q/6294179
has title: find all occurences of a string and its indices in nested list python
linked to: http://stackoverflow.com/q/33938488
has answer: http://stackoverflow.com/a/49705551
score: 2
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/86424215
answer count: 1
accepted answer: http://stackoverflow.com/a/49705551
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/5234090

http://stackoverflow.com/a/49612588
type: Answer
score: 0
has body: You can do this with numpy already with your function. For example, the code below will do what you want: x = numpy.linspace(0, 0.2, 100) y = x*10 If you defined x as above and passed it to your function it would perform exactly as you want.
answers question: http://stackoverflow.com/q/49611116

http://stackoverflow.com/comment/86428658
comment on: http://stackoverflow.com/q/49707269
type: Comment
type: QuestionComment
has text: in exercise 31 of LPTHW there is a code that you type out, at the end of the exercise zed asks you to create a game using the code he has just had you write out to test your understanding... my game has gotten a little too complicated for my knowledge, but its all a learning curve
score: 0

http://stackoverflow.com/q/49728732
downvote count: 0
tagged with: django
has body: I am trying to use django-channels in my django-project and getting this error while trying to run the server. I am following this tutorial to build chatting application. https://gearheart.io/blog/creating-a-chat-with-django-channels/ Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7fb7aa2b1e18&gt; Traceback (most recent call last): File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) 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 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2226, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 1200, in _l…
tagged with: python
has title: Getting error when trying to run server having django -channels
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49729141
type: UnansweredQuestion
tagged with: django-channels

http://stackoverflow.com/a/49736221
score: 0
has body: Instead of storing your objects in a list, you should convert that list into a dict: objects_by_name = {obj._name: obj for obj in list_a} This lets you look up the object associated with a name in O(1) time. Updating all objects is now as easy as iterating over list_b, grabbing the corresponding object from the dict, and calling its update method: for dic in list_b: obj = objects_by_name[dic['name']] obj.update(dic) Overall this has a time complexity of O(n), whereas your code is O(n log n) because of the sort.
type: Answer
answers question: http://stackoverflow.com/q/49735841

http://stackoverflow.com/comment/86498938
type: QuestionComment
has text: I added an image of a MNIST test image, it is white digits on black backgrounds for sure. I thought maybe the code took the five.jpg image and converted it to grayscale but maybe it needs to be inverted as well? Thanks for the feedback!
score: 0
comment on: http://stackoverflow.com/q/49741671
type: Comment

http://stackoverflow.com/a/49702809
score: 1
downvote count: 0
upvote count: 1
has body: You can't use copytree this way. Once it gets an error along some subtree, it bails out of that subtree. After it returns you the error, there's no way to resume where it left off But notice that the shutil docs have a link to the source code. Much of the standard library is deliberately written to be useful not just as a library, but also as sample code. It's not that complicated—in fact, the only really tricky part is the way it collects up errors so it can fail the way it does, which is the one part you don't want. So, fork that function into your own code and modify it to handle errors the way you want.
type: Answer
answers question: http://stackoverflow.com/q/49702776

http://stackoverflow.com/comment/86346256
comment on: http://stackoverflow.com/q/49667924
type: Comment
score: 0
type: QuestionComment
has text: Exercise: does speaking the word *"France"* take you to the country by that name? (Don't try this at home!)

http://stackoverflow.com/q/49696870
tagged with: django
tagged with: python
tagged with: request
has title: python|django how to post file, change it, and send it back?
has comment: http://stackoverflow.com/comment/86421847
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has body: I am writing a small test project with python\django. I'm sending an image to server (with request post), resizing it and want it back to the client. So far it seems that everything working properly beside that i dont know how to send the file back to the client. CLIENT: testFile = "&lt;location&gt;" api_url = 'http://localhost:9999/upload' files = {'file': open(testFile, 'rb')} r = requests.post(api_url,files=files,data={"m":10,"n":15}) files["file"].close() print r -&gt; status 200 SERVER: @csrf_exempt def post(request): if request.method == 'POST': logger.info("New post request") #logger.info(request.FILES) file = request.FILES['file'] resized_frame = job_manager.add_job(file,request.POST.get("m"),request.POST.get("n")) logger.info("returning new resized frame ") response = HttpResponse(content_type='image/png') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(resized_frame) return response #return HttpResponse(resized_frame) else: return HttpResponse('500') can I even send response with files while getting a post request?
favorite count: 0
has comment: http://stackoverflow.com/comment/86407051
type: Question
has comment: http://stackoverflow.com/comment/86406751
type: UnansweredQuestion

http://stackoverflow.com/comment/86543303
has text: @RezaCivil I appreciate. By the way, could you accept the answer if it answers the question clear enough?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49638970
score: 0

http://stackoverflow.com/q/49625891
has answer: http://stackoverflow.com/a/49627149
downvote count: 0
has answer: http://stackoverflow.com/a/49625980
has comment: http://stackoverflow.com/comment/86259525
answer count: 4
possible better answer: http://stackoverflow.com/a/49625980
favorite count: 0
has answer: http://stackoverflow.com/a/78518114
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49627149
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/86259356
has body: How can I sort a path that it contains integer as well as strings? My file names are : tmp_1483228800-1485907200_0, tmp_1483228800-1485907200_1, tmp_1483228800-1485907200_2, .... I need to sort them according to the integers after the last underline. That’s how my code looks like: act = "." + "/*/raw_results.csv" files = glob.glob(act) sorted_list = sorted(files, key = lambda x:int(os.path.splitext(os.path.dirname(x))[0])) I know the problem is there are lot of integers and some strings in between so it can not convert everything to integer,but I do not know how to solve it. Thanks in advance.
has title: Sort a list that contains path in python
has answer: http://stackoverflow.com/a/49626190
score: 2
has comment: http://stackoverflow.com/comment/86260675
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86260210
has comment: http://stackoverflow.com/comment/86260437

http://stackoverflow.com/comment/86290458
comment on: http://stackoverflow.com/q/49641382
type: QuestionComment
score: 0
type: Comment
has text: Could you clarify better the last two bolded points? They appear to be asking to do the same thing

http://stackoverflow.com/a/49640665
downvote count: 0
has comment: http://stackoverflow.com/comment/86289433
answers question: http://stackoverflow.com/q/49640641
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86289497
has comment: http://stackoverflow.com/comment/86289761
has comment: http://stackoverflow.com/comment/86289604
accepted answer of: http://stackoverflow.com/q/49640641
has comment: http://stackoverflow.com/comment/86289125
has body: Use subprocesses instead. import subprocess # Start proc = subprocess.Popen(["name.py"]) # Stop proc.terminate()
has comment: http://stackoverflow.com/comment/86289964
has comment: http://stackoverflow.com/comment/86289204
type: Answer
has comment: http://stackoverflow.com/comment/86289159
has comment: http://stackoverflow.com/comment/86289129
score: 2
upvote count: 2

http://stackoverflow.com/comment/86207114
has text: @JonClements thank you. it works. but really is there difference between create "DiGraph" then using "numpy" convert and numpy convert with create_using attribute ?!!.
comment on: http://stackoverflow.com/q/49599905
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/116824197
has text: thank you for the answer. can you think of a reason why this works but not the property method
type: Comment
comment on: http://stackoverflow.com/a/49750517
score: 0
type: AnswerComment

pyopenssl
tag name: pyopenssl
tags question: http://stackoverflow.com/q/49728265
type: Tag
tags question: http://stackoverflow.com/q/49664036

http://stackoverflow.com/q/49625958
tagged with: nltk
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86259263
has body: I am trying to get precision, recall and F-measure of positive and negative predictions for sentiment analysis. I used python 3.6 as follow: import nltk from nltk.tokenize import word_tokenize # Trainng data train = [('I love this sandwich.', 'pos'), ('This is an amazing place!', 'pos'), ('I feel very good about these beers.', 'pos'), ('This is my best work.', 'pos'), ("What an awesome view", 'pos'), ('I do not like this restaurant', 'neg'), ('I am tired of this stuff.', 'neg'), ("I can't deal with this", 'neg'), ('He is my sworn enemy!', 'neg'), ('My boss is horrible.', 'neg') ] # Test data test = [('The beer was good.', 'pos'), ('I do not enjoy my job', 'neg'), ("I ain't feeling dandy today.", 'neg'), ("I feel amazing!", 'pos'), ('Gary is a friend of mine.', 'pos'), ("I can't believe I'm doing this.", 'neg') ] # Tokenize Training words Training_words = set(word.lower() for passage in train for word in word_tokenize(passage[0])) # Training feature sets training_set = [({word: (word in word_tokenize(x[0])) for word in Training_words}, x[1]) for x in train] # Tokenize Test words Test_words = set(word.lower() for passage in test for word in word_tokenize(passage[0])) # Test feature sets test_set= [({word: (word in word_tokenize(x[0])) for word in Test_words}, x[1]) for x in test] # Naive Bayes classifier classifier = nltk.NaiveBayesClassifier.train(training_set) # Informative Features classifier.show_most_informative_features() # print the accuracy print("accuracy %",(nltk.classify.accuracy(classifier, test_set))*100) The above code display the Informative Features and the accuracy of the Naive Bayes classifier. I tried the code below to get its precision , recall and F-measure of positive and negative predictions. from nltk.metrics.scores import (precision, recall) import collections import nltk.metrics refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) for i, (feats, label) in enumerate(test_set): refsets[label].add(i) observed = classifi…
tagged with: python-3.x
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has title: How I can get precision, recall and F-measure of positive and negative predictions from a nltk classifier?
favorite count: 0
type: Question

http://stackoverflow.com/comment/86292343
type: Comment
comment on: http://stackoverflow.com/a/49642375
type: AnswerComment
has text: This does not create an `OrderedDict` that is in the reverse order. It doesn't created a `dict` at all...
score: 1

http://stackoverflow.com/comment/86424074
type: Comment
type: QuestionComment
has text: @zwer, I can rename `main1.py` modules, but as I wrote in P.S., I am not able to predict if there is any collisions. For example, I can rename it to `new_local_module`, but `main3.py` (which is new cause I import them dynamically) may have that `new_local_module` too.
score: 0
comment on: http://stackoverflow.com/q/49705245

http://stackoverflow.com/q/49728132
tagged with: python
has answer: http://stackoverflow.com/a/49728252
tagged with: string
linked to: http://stackoverflow.com/q/2594810
has title: Python 3: Reading string from file and define the same string in code working differently
score: 0
has comment: http://stackoverflow.com/comment/86471113
has comment: http://stackoverflow.com/comment/86470286
has comment: http://stackoverflow.com/comment/86470928
duplicate of: http://stackoverflow.com/q/4020539
type: Question
tagged with: python-3.x
tagged with: encoding
has body: I have a text file like below # 1.txt who is the\u00a0winners\u00a0where\u00a0season result\u00a0is 7th If I read a file and print it, it shows &gt;&gt;&gt; s = open("1.txt").read() &gt;&gt;&gt; print(s) who is the\u00a0winners\u00a0where\u00a0season result\u00a0is 7th However, If I do like below with the same string, &gt;&gt; s = "who is the\u00a0winners\u00a0where\u00a0season result\u00a0is 7th" &gt;&gt; print(s) who is the winners where season result is 7th I want to read a text file like "1.txt" and print it like the below one. I can not find how to do it. Please help me. Thanks.
type: UnansweredQuestion
answer count: 1
tagged with: file

http://stackoverflow.com/a/49609595
has body: You can use collections.defaultdict to create a dictionary with lists as the values to which you can append items. from collections import defaultdict my_dict = defaultdict(list) with open('text.txt') as f: key = '' for line in f: if not line.startswith('#'): key = line # key = function(line.split()) continue my_dict[key].append(line.strip('#').split()) print(my_dict) Output: defaultdict(&lt;class 'list'&gt;, {'text1 text2\n': [['text2', 'text3', 'text4'], ['text5', 'text4', 'text6']], 'text3 text4\n': [['text21', 'text31', 'text41'], ['text51', 'text41', 'text61']]}) Just change the key = line line to whatever function you're passing the key to. My text.txt file contains: text1 text2 # text2 text3 text4 # text5 text4 text6 text3 text4 # text21 text31 text41 # text51 text41 text61
type: Answer
has comment: http://stackoverflow.com/comment/86225876
has comment: http://stackoverflow.com/comment/86226029
answers question: http://stackoverflow.com/q/49609501
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49609501
score: 0

http://stackoverflow.com/a/49681743
score: 0
has comment: http://stackoverflow.com/comment/86404646
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49681501
answers question: http://stackoverflow.com/q/49681501
has body: The token is in the html source: input type="hidden" name="X-XSRF-TOKEN" value="26660efc-6d90-4ef6-a717-fb9cfed99bad" id="X-XSRF-TOKEN" You can use BeautifulSoup to parse the html and get the token: import requests from bs4 import BeautifulSoup as BS url = 'https://accounts.epicgames.com/register/doCustomRegister?productName=fortnite' resp = requests.get(url) soup = BS(resp.text, 'lxml') token = soup.select_one('input[id="X-XSRF-TOKEN"]')['value'] print(token)
type: Answer
has comment: http://stackoverflow.com/comment/86379080

http://stackoverflow.com/q/49670906
has answer: http://stackoverflow.com/a/49671172
has answer: http://stackoverflow.com/a/49671481
has title: Merging different dictionary in python without updating the value stored
score: -1
has body: I have a tree structure where at every node idf values are stored for a large number of words. Dictionary has two fields i.e. word and idf. I want to store all the idf values in a dictionary. I want all the value of idf which are stored in the tree to get stored in the dictionary, but when I am doing so it is storing only one value of each word. For example: A has two childs B and C. A,B,C all has idf values stored at them. I want to make a dictionary which will combine all the idf values and store it together. A = {'a':10, 'b': 11} B = {'a':5, 'c': 8} C = {'b':21, 'd': 20}, I want to store it as dic = {'a':10,'a':5,'b':11,'b':21,'c':8,'d':20} Below is the code that I am using: def idf_total(node): dic={} next_node=[] for child in node.children: next_node.append(child) idf = child.idf dic.update(idf) if next_node: for i in next_node: idf_total(i) return dic Kindly help how this can be done. Latest code: def idf_total_updated(node): dic=defaultdict(list) next_node=[] for child in node.children: next_node.append(child) for k,v in child.idf.items(): dic[k].append(v) if next_node: for i in next_node: idf_total_updated(i) return dic The above latest code is storing multiple values for a key but it is repeating the same value again and again. Where I am going wrong. Please help.
tagged with: pandas
has comment: http://stackoverflow.com/comment/86352072
has comment: http://stackoverflow.com/comment/86351953
answer count: 2
has comment: http://stackoverflow.com/comment/86351979
has comment: http://stackoverflow.com/comment/86352087
downvote count: 1
favorite count: 0
tagged with: tf-idf
tagged with: binary-search-tree
has comment: http://stackoverflow.com/comment/86352177
has comment: http://stackoverflow.com/comment/86351845
type: Question
tagged with: function
upvote count: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/86498733
has text: Does this differ between using PC and Mac? Because in the course I'm watching, the instructor doesn't have any event code to get the game started and he's using a PC.
score: 0
comment on: http://stackoverflow.com/a/49726329
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49735639
linked to: http://stackoverflow.com/q/49009870
has comment: http://stackoverflow.com/comment/86485238
tagged with: performance
score: 1
has comment: http://stackoverflow.com/comment/86486872
has answer: http://stackoverflow.com/a/49735865
possible better answer: http://stackoverflow.com/a/49735959
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86492287
linked to: http://stackoverflow.com/q/53513
answer count: 2
has answer: http://stackoverflow.com/a/49735959
has comment: http://stackoverflow.com/comment/86485192
has comment: http://stackoverflow.com/comment/86485568
upvote count: 2
accepted answer: http://stackoverflow.com/a/49735865
has title: In python why is explicit bool much slower than implicit
has body: Given the following three functions def v1(a): c = 0 for a_ in a: if a_ is not None: c += 1 return c def v2(a): c = 0 for a_ in a: if a_: c += 1 return c def v3(a): c = 0 for a_ in a: if bool(a_): c += 1 return c I get the following performance (I'm using python 3.6 on ubuntu 18.04) values = [random.choice([1, None]) for _ in range(100000)] %timeit v1(values) 3.35 ms ± 28 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit v2(values) 2.83 ms ± 36.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit v3(values) 12.3 ms ± 59.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) The similar performance between v1 and v2 makes sense, but why is v3 so much slower given that v2 is presumably implicitly calling bool(a_) too? Is it simply calling bool() from python rather than from c (as I assume if does) that's causing the difference in performance?
has comment: http://stackoverflow.com/comment/86485276
tagged with: python
tagged with: python-3.6
downvote count: 1
has comment: http://stackoverflow.com/comment/86485250
has comment: http://stackoverflow.com/comment/86489761
type: AnsweredQuestion

http://stackoverflow.com/comment/86493577
has text: I don't understand the question. You have a bunch of x values. How do they relate to the Gaussian distribution function, you create and for which you want to determine mu and sigma? You know, function x and f(x). What is your y value in this question? P.S.: And please delete your other question, which does in essence not differ.
type: Comment
comment on: http://stackoverflow.com/q/49738284
type: QuestionComment
score: 0

http://stackoverflow.com/a/62591463
score: -2
type: Answer
has body: Refer This Link- https://medium.com/@sandeepsinh/multiple-file-download-form-google-cloud-storage-using-python-and-gcs-api-1dbcab23c44 1 - Add Your Credential Json 2 - List Bucket Items 3 - Download import logging import os from google.cloud import storage global table_id global bucket_name logging.basicConfig(format=’%(levelname)s:%(message)s’, level=logging.DEBUG) bucket_name = ‘mybucket’ table_id = ‘shakespeare’ storage_client = storage.Client.from_service_account_json(‘/google-cloud/keyfile/service_account.json’) # The “folder” where the files you want to download are folder=’/google-cloud/download/{}’.format(table_id) delimiter=’/’ bucket=storage_client.get_bucket(bucket_name) blobs=bucket.list_blobs(prefix=table_id, delimiter=delimiter) #List all objects that satisfy the filter. # Download the file to a destination def download_to_local(): logging.info(‘File download Started…. Wait for the job to complete.’) # Create this folder locally if not exists if not os.path.exists(folder): os.makedirs(folder) # Iterating through for loop one by one using API call for blob in blobs: logging.info(‘Blobs: {}’.format(blob.name)) destination_uri = ‘{}/{}’.format(folder, blob.name) blob.download_to_filename(destination_uri) logging.info(‘Exported {} to {}’.format( blob.name, destination_uri)) if __name__ == ‘__main__’: download_to_local()
answers question: http://stackoverflow.com/q/49748910
upvote count: 0
downvote count: 2

http://stackoverflow.com/q/49756071
has body: There are many questions about utf-8 > unicode conversion, but I still haven't found answer for my issue. Lets have strings like this: a = "Je-li pro za\\xc5\\x99azov\\xc3\\xa1n\\xc3\\xad" Python 3.6 understands this string like Je-li pro za\xc5\x99azov\xc3\xa1n\xc3\xad. I need to convert this utf-8-like string to unicode representation. The final result should be Je-li pro zařazování. With a.decode("utf-8") I get AttributeError: 'str' object has no attribute 'decode', because Python means the object is already decoded. If I convert it to bytes first with bytes(a, "utf-8"), the backslashes are doubled only and .decode("utf-8") returns it to my current a again. How to get unicode string Je-li pro zařazování from this a?
has comment: http://stackoverflow.com/comment/86527258
has comment: http://stackoverflow.com/comment/86527288
linked to: http://stackoverflow.com/q/1864701
tagged with: python
tagged with: unicode
has comment: http://stackoverflow.com/comment/86536677
linked to: http://stackoverflow.com/q/63218987
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/129354353
linked to: http://stackoverflow.com/q/1885181
has answer: http://stackoverflow.com/a/49756591
accepted answer: http://stackoverflow.com/a/49756591
answer count: 1
tagged with: python-unicode
tagged with: utf-8
has comment: http://stackoverflow.com/comment/86527168
favorite count: 0
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/7048745
has title: Python 3.6, utf-8 to unicode conversion, string with double backslashes

http://stackoverflow.com/q/49718980
has answer: http://stackoverflow.com/a/50144701
linked to: http://stackoverflow.com/q/27114470
tagged with: urlfetch
score: 1
has body: I'm using linux with google-cloud-sdk-app-engine-python package installed version 196.0.0-0. I try to create local unit test, following reference from [1]. class ViewsTestCase(unittest.TestCase): def setUp(self): self.client = application.test_client() self.client.testing = True self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_urlfetch_stub() def tearDown(self): self.testbed.deactivate() add PYTHONPATH environment variable: export PYTHONPATH="$PYTHONPATH:/usr/lib/google-cloud-sdk/platform/google_appengine:/usr/lib/google-cloud-sdk/platform/google_appengine/lib:/usr/lib/google-cloud-sdk/platform/google_appengine/lib/yaml/lib" then I try to run it. $ python test_views.py Traceback (most recent call last): File "test_views.py", line 6, in &lt;module&gt; from google.appengine.ext import testbed File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/ext/testbed/__init__.py", line 130, in &lt;module&gt; from google.appengine.api import urlfetch_stub File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/api/urlfetch_stub.py", line 32, in &lt;module&gt; _fancy_urllib_InvalidCertException = fancy_urllib.InvalidCertificateException AttributeError: 'module' object has no attribute 'InvalidCertificateException' I have read this similar thread [2]. But I checked, the path of fancy_lib has been fixed. $ find /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/ /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/ /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/__init__.pyc /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/fancy_urllib /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/fancy_urllib/__init__.pyc /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/fancy_urllib/__init__.py /usr/lib/google-cloud-sdk/platform/google_appengine/lib/fancy_urllib/__init__.py I have tried to add fancy_urllib to PYTHONP…
answer count: 1
upvote count: 1
has title: App Engine python local unit test urlfetch_stub.py fancy_urllib module has no attribute 'InvalidCertificateException'
has comment: http://stackoverflow.com/comment/92235562
favorite count: 0
type: Question
tagged with: testing
type: UnansweredQuestion
downvote count: 0
tagged with: google-app-engine-python
tagged with: python

http://stackoverflow.com/q/49730257
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49730548
has comment: http://stackoverflow.com/comment/86474491
has title: Renaming categories
has answer: http://stackoverflow.com/a/49730548
upvote count: 0
tagged with: python
tagged with: string
downvote count: 1
has body: text category ----------------------------------------------- nike shoes from nike brought by ankit flour grocery rice grocery adidas shoes from adidas are cool The above is my data-set format. How exactly do I generalize the category while categorising. Example I want the output as:- text category ----------------------------------------------- nike shoes from brand flour grocery rice grocery adidas shoes from brand
type: AnsweredQuestion
tagged with: pandas
answer count: 1
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/86474246
tagged with: text-classification

http://stackoverflow.com/q/49751509
has comment: http://stackoverflow.com/comment/86517461
type: AnsweredQuestion
has body: This working function will receive a dictionary that will proceed with uploading or download files based on the transfer_type value. But currently my IDE is displaying the warningLocal variable might be referenced before assignment when i'm using it to execute the subprocess.run stage. My question is, should i accept the sugestion of declating as a global variable inside the function ( global cmd ) or should I ignore this suggestion? def scp_transfer(data): host = data['host'] remote = data['remote'] local = data['local'] transfer_type = data['transfer_type'] if transfer_type == 'download': cmd = 'scp -qr %s:%s %s' % (host, remote, local) if transfer_type == 'upload': cmd = 'scp -qr %s %s:%s' % (local, host, remote) run = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE) try: run.check_returncode() except subprocess.CalledProcessError as e: print(e.output) else: print(run.stdout.decode('utf-8'))
has comment: http://stackoverflow.com/comment/86517507
accepted answer: http://stackoverflow.com/a/49751548
has comment: http://stackoverflow.com/comment/86517431
score: -1
has answer: http://stackoverflow.com/a/49751548
type: Question
upvote count: 0
answer count: 1
tagged with: python
downvote count: 1
has title: Local variable might be referenced before assignment
favorite count: 0

http://stackoverflow.com/q/49709242
score: 3
has comment: http://stackoverflow.com/comment/86433289
has answer: http://stackoverflow.com/a/49711713
type: Question
upvote count: 3
type: UnansweredQuestion
has body: I am trying to find a best xgboost model through GridSearchCV and as a cross_validation I want to use an April target data. Here is the code: x_train.head() x_train y_train.head() y_train from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.metrics import make_scorer from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import TimeSeriesSplit import xgboost as xg xgb_parameters={'max_depth':[3,5,7,9],'min_child_weight':[1,3,5]} xgb=xg.XGBRegressor(learning_rate=0.1, n_estimators=100,max_depth=5, min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8) model=GridSearchCV(n_jobs=2,estimator=xgb,param_grid=xgb_parameters,cv=train_test_split(x_train,y_train,test_size=len(y_train['2016-04':'2016-04']), random_state=42, shuffle=False),scoring=my_func) model.fit(x_train,y_train) model.grid_scores_ model.best_params_ But I have this error while I am training my model. Error Can anybody help me with this please? Or could someone suggest how can I split nonshuffled data to train/test to validate model on the last month? Thanks for helping
answer count: 1
tagged with: cross-validation
downvote count: 0
tagged with: machine-learning
tagged with: grid-search
tagged with: python
tagged with: train-test-split
has title: Python: ValueError too many values to unpack (expected 2)
favorite count: 0
has comment: http://stackoverflow.com/comment/86432172

http://stackoverflow.com/comment/86315493
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49653430
has text: The statement that every time `mainActivity.showFrame(self, loginScreen)` is run it creates a new instance of `mainActivity` is false. This does not create instances of `mainActivity`.
score: 0

http://stackoverflow.com/a/49638687
upvote count: 1
score: 0
has body: You could use a set: &gt;&gt;&gt; seen=set(['one', 'two', 'three', 'one']) &gt;&gt;&gt; seen {'one', 'two', 'three'}
downvote count: 1
answers question: http://stackoverflow.com/q/49638617
type: Answer

http://stackoverflow.com/comment/86265628
comment on: http://stackoverflow.com/q/49616151
has text: You say the file uploads successfully—just without the extension. Where exactly did you see the file? Is the rest of the name correct? That is, is it only the extension that is missing? Are there any other differences? E.g., is it in the same folder as other files uploaded manually (i.e., not with Selenium)?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49671070
upvote count: 2
has comment: http://stackoverflow.com/comment/86353120
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86357297
has answer: http://stackoverflow.com/a/49712666
has comment: http://stackoverflow.com/comment/86355146
type: Question
has comment: http://stackoverflow.com/comment/86352906
tagged with: statsmodels
has comment: http://stackoverflow.com/comment/86368735
has comment: http://stackoverflow.com/comment/86368445
has body: I'm currently trying to fit an ARMA model to some data, using the statsmodels module in Python. The problem is, however, that it fails to load the package, and just returns an AttributeError which states: File "C:\Projects\Python\KalmanFilteringDataFusion\armaTest.py", line 5, in &lt;module&gt; from statsmodels.tsa.arima_model import ARIMA File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\statsmodels\tsa\arima_model.py", line 30, in &lt;module&gt; from statsmodels.tsa.ar_model import AR File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\statsmodels\tsa\ar_model.py", line 608, in &lt;module&gt; class ARResults(tsbase.TimeSeriesModelResults): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\statsmodels\tsa\ar_model.py", line 811, in ARResults preddoc = AR.predict.__doc__.split('\n') AttributeError: 'NoneType' object has no attribute 'split' The only thing i'm doing, is trying to import the ARIMA module as: from statsmodels.tsa.arima_model import ARIMA If i try to import another statmodels sub-module (ex. import statsmodels.formula.api as smf) it returns: File "C:\Projects\Python\KalmanFilteringDataFusion\armaTest.py", line 5, in &lt;module&gt; import statsmodels.formula.api as smf File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\statsmodels\formula\api.py", line 15, in &lt;module&gt; from statsmodels.discrete.discrete_model import MNLogit File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\statsmodels\discrete\discrete_model.py", line 146, in &lt;module&gt; class DiscreteModel(base.LikelihoodModel): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\statsmodels\discrete\discrete_model.py", line 208, in DiscreteModel fit.__doc__ += base.LikelihoodModel.fit.__doc__ TypeError: unsupported operand type(s) for +=: 'NoneType' and 'NoneType'…
has title: Error when Importing Statsmodels in Python
has comment: http://stackoverflow.com/comment/86368868
accepted answer: http://stackoverflow.com/a/49712666
has comment: http://stackoverflow.com/comment/86360671
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: python-3.x
tagged with: python-import

http://stackoverflow.com/q/49698922
has comment: http://stackoverflow.com/comment/86411555
has comment: http://stackoverflow.com/comment/86411273
tagged with: python
has body: In my current code I need a function into which I can put (l,m,theta,phi) or in scipy's notation (n,m,theta,phi) and it will output the value of a spherical harmonic for those parameters. scipy's sph_harm function worked perfectly for this until trying for higher l and m. For example if I use l=88, m=85, theta=0, phi=pi/2 (i.e. sph_harm(85,88,0,np.pi/2)) then the outputted value is nan+nanj. Any ideas how to avoid this problem? I need to be able to put in any reasonable (|m|
has comment: http://stackoverflow.com/comment/86411403
has comment: http://stackoverflow.com/comment/86411597
answer count: 0
has title: scipy spherical harmonics giving nan+nanj
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question

http://stackoverflow.com/a/49602325
has comment: http://stackoverflow.com/comment/86216614
has body: I think what you're looking for is a static function. import smtplib class MailUtils: @staticmethod def sendmail(argument): TO = 'yourmail@gmail.com' if argument=='PIR': SUBJECT = 'PIR' TEXT = 'Motion is detected' gmail_sender = 'mymail@gmail.com' gmail_passwd = 'mypwd' server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo server.login(gmail_sender, gmail_passwd) BODY = '\r\n'.join([ 'TO: %s' % TO, 'From: %s' % gmail_sender , 'Subject: %s' % SUBJECT , '', TEXT ]) try: server.sendmail(gmail_sender, [TO], BODY) print 'email sent' except: print 'error' server.quit() You would use it by doing this: import MailUtils MailUtils.sendmail(argument) Note: As mentioned in the comments below, this approach works best if the class contains multiple related functions, not just a single one.
has comment: http://stackoverflow.com/comment/86219215
score: 1
has comment: http://stackoverflow.com/comment/86235767
has comment: http://stackoverflow.com/comment/86242767
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49601149
answers question: http://stackoverflow.com/q/49601149
has comment: http://stackoverflow.com/comment/86231682
has comment: http://stackoverflow.com/comment/86230806
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86231254
has comment: http://stackoverflow.com/comment/86231456

http://stackoverflow.com/comment/86462025
type: Comment
comment on: http://stackoverflow.com/a/49699284
has text: I've edited my original answer, let me know if it works for you, it was kinda weird/fun issue.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86481721
has text: If event isn't in process_model, index won't have a value, since index indicates the location of event in process_model, which it then doesn't have. That's why it's assigned None. It's like asking for the house number of a house that isn't in a street. It simply doesn't have one. Probably you know what you want, but unfortunately I do not understand what exactly it is...
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49719491

http://stackoverflow.com/comment/86239442
has text: @paulo but how does it know which CoinData matches up to which Coin? I have a list of 900+ coins in Coin and 63,000 CoinData entries. Doing it manually isn't an option. In admin I want users to click on a coin (Coin) then be presented with a number of ways to request the CoinData, along with a default view.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49614682

http://stackoverflow.com/comment/86508139
type: Comment
has text: @user3157132 Just have it pass either `self` or `self.logon_session` to each instance's constructor. Not only do you not need inheritance just to share a value, it doesn't even _help_ you share a value
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49745474

http://stackoverflow.com/comment/86556615
type: QuestionComment
comment on: http://stackoverflow.com/q/49748390
type: Comment
has text: Thanks, it works if you convert `parts` to list (tuple being immutable) `path_parts = list(path.parts)`.
score: 1

http://stackoverflow.com/comment/86284603
comment on: http://stackoverflow.com/q/49617350
score: 0
type: Comment
type: QuestionComment
has text: @soupault How would I do it with OpenCV?

http://stackoverflow.com/q/49697514
downvote count: 0
tagged with: scikit-learn
tagged with: xgboost
favorite count: 0
accepted answer: http://stackoverflow.com/a/49728714
type: AnsweredQuestion
has title: XGBoost get predict_contrib using sklearn API?
upvote count: 7
score: 7
has body: In Python, XGBoost allows you to train/predict using their Booster class or using their sklearn API (http://xgboost.readthedocs.io/en/latest/python/python_api.html). I'm using the sklearn API, and want to use the pred_contribs capabilities of XGBoost. I would expect this to work, but it doesn't: model = xgb.XGBClassifier().fit(X_train, y_train) pred = model.predict_proba(X_test, pred_contribs=True) It looks like pred_contribs is only a parameter for the Booster class predict function. How do I use this parameter through the sklearn API? Or is there an easy workaround to get the prediction contributors after training using the sklearn API?
tagged with: python
has answer: http://stackoverflow.com/a/49728714
type: Question
answer count: 1

http://stackoverflow.com/q/49636643
has comment: http://stackoverflow.com/comment/86343224
has answer: http://stackoverflow.com/a/49636882
has answer: http://stackoverflow.com/a/49644072
tagged with: point-clouds
tagged with: python
has body: I have a cloud of points with the form of a cylinder(x, y, z) like the picture:. I want to divide it into 3D segments within a specific angle. It looks like I have a pie and I need to cut it into pieces. What is the best way to do this?
has comment: http://stackoverflow.com/comment/86313534
favorite count: 0
type: Question
tagged with: geometry
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86342629
tagged with: angle
type: UnansweredQuestion
has title: Geometry - Divide 3D points into segments with specific angle
tagged with: computational-geometry
downvote count: 0
score: 2

http://stackoverflow.com/comment/86490756
comment on: http://stackoverflow.com/a/49701067
type: AnswerComment
score: 0
type: Comment
has text: Updated the answer for partial read. Glad you asked the question.

http://stackoverflow.com/a/50956100
answers question: http://stackoverflow.com/q/49659825
has body: I've stumbled across the same function and project you're working on. You have to change: stat = html.find("div", class_="parsys mainParsys section").find('h3').text to stat = html.find("div", class_="parsys mainParsys").find('h3').text Also, if you're working in 3.6, you have to update: import urllib.request urllib.request.urlretrieve(url, filename)
type: Answer
score: 0

http://stackoverflow.com/a/49710527
type: Answer
score: 0
has body: Don't use stateful transformations. Just reduceByKey: from operator import add tags_totals = (dataStream .flatMap(lambda line: line.split(" ")) .map(lambda x: (x, 1)) .reduceByKey(add))
answers question: http://stackoverflow.com/q/49703022

http://stackoverflow.com/q/49671990
tagged with: python
has comment: http://stackoverflow.com/comment/87967014
tagged with: sorting
tagged with: lambda
score: 15
has comment: http://stackoverflow.com/comment/86355328
has answer: http://stackoverflow.com/a/50537922
upvote count: 16
accepted answer: http://stackoverflow.com/a/51217757
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16857204
has comment: http://stackoverflow.com/comment/87966985
tagged with: list
has answer: http://stackoverflow.com/a/51217757
possible better answer: http://stackoverflow.com/a/49671991
has comment: http://stackoverflow.com/comment/86355299
linked to: http://stackoverflow.com/q/50297704
has body: I wish to sort the below list first by the number, then by the text. lst = ['b-3', 'a-2', 'c-4', 'd-2'] # result: # ['a-2', 'd-2', 'b-3', 'c-4'] Attempt 1 res = sorted(lst, key=lambda x: (int(x.split('-')[1]), x.split('-')[0])) I was not happy with this since it required splitting a string twice, to extract the relevant components. Attempt 2 I came up with the below solution. But I am hoping there is a more succinct solution via Pythonic lambda statements. def sorter_func(x): text, num = x.split('-') return int(num), text res = sorted(lst, key=sorter_func) I looked at Understanding nested lambda function behaviour in python but couldn't adapt this solution directly. Is there a more succinct way to rewrite the above code?
downvote count: 1
has title: Nested lambda statements when sorting lists
favorite count: 0
has answer: http://stackoverflow.com/a/50542225
type: Question
tagged with: python-3.x
answer count: 8
has answer: http://stackoverflow.com/a/50225608
has answer: http://stackoverflow.com/a/49672246
linked to: http://stackoverflow.com/q/36391807
has comment: http://stackoverflow.com/comment/87967087
has comment: http://stackoverflow.com/comment/86355068
has answer: http://stackoverflow.com/a/50546551
has answer: http://stackoverflow.com/a/50570537
has comment: http://stackoverflow.com/comment/87967027
has answer: http://stackoverflow.com/a/49671991

http://stackoverflow.com/a/49672509
type: Answer
has comment: http://stackoverflow.com/comment/86356457
has comment: http://stackoverflow.com/comment/86356894
has comment: http://stackoverflow.com/comment/86364189
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49671754
has body: This can be done via integer linear programming. library(lpSolve) # inputs nr &lt;- 3 # no of rows nc &lt;- 3 # no of cols r &lt;- 2 # sum of each row equals r c &lt;- 2 # sum of each col equals c obj &lt;- rep(1, nr * nc) const.mat &lt;- rbind( t(rep(1, nc) %x% diag(nr)), # this matrix multiplied by c(m) is row sums (diag(nc) %x% t(rep(1, nr))) # this matrix multiplied by c(m) is col sums ) const.rhs &lt;- c(rep(r, nr), rep(c, nc)) out &lt;- lp(obj = obj, const.mat = const.mat, const.dir = "=", const.rhs = const.rhs, all.bin = TRUE) out ## Success: the objective function is 6 matrix(out$solution, nr, nc) ## [,1] [,2] [,3] ## [1,] 0 1 1 ## [2,] 1 0 1 ## [3,] 1 1 0
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86355598
accepted answer of: http://stackoverflow.com/q/49671754

http://stackoverflow.com/comment/86533605
has text: Glad to help and congrats on your code, it's very easy to follow. I'm editing the original answer.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49758402

http://stackoverflow.com/a/49723303
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49722094
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49722094
has body: The big_file_id which can be read from the get_chat method can only be used for downloading the photo. You will have to store the file locally yourself and then resend it. Unique file identifier of big (640x640) chat photo. This file_id can be used only for photo download. [doc]

http://stackoverflow.com/a/49687317
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49686993
has body: I don't believe there is x++ inpython. I know how it is used, and how it adds one to a number, but python does not support this. So instead you should use x+=1. That's fixing your syntax error. But for your question about doing it in one step, do this: a = 90 z = a + 1 This works, but using x++ is not supported in python and is not more effective tha simply adding one to a and assigning it to z.

http://stackoverflow.com/comment/86436803
comment on: http://stackoverflow.com/q/49661591
type: QuestionComment
score: 0
has text: `ensemble_test` is just another method of voting as I mentioned in the question. I I am trying to predict the rock type based on the log data I get. I tried to train the classifiers on individual rock type and my `X_train` remains the same while `y_trains` are a series of rocks as you can see. I did the same with Automatic voting, `RandomForestClassifier`, `SVM` & `KNearestNeighbor`, but my ROC plots work perfectly as I expected them to after getting good prediction scores of `f1` and `roc_auc` from them, but when I do this on `ensemble_test`, it looks awfully bad as you can see.
type: Comment

http://stackoverflow.com/a/49755442
accepted answer of: http://stackoverflow.com/q/49755180
upvote count: 3
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49755180
has comment: http://stackoverflow.com/comment/86526682
downvote count: 0
type: AcceptedAnswer
has body: By default, Django will do HTML escaping of template arguments, which (among other things) changes &amp; to &amp;amp;. Use the safe template filter in your template to avoid that: &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="refresh" content="5; url=" /&gt; &lt;script&gt; window.top.location.href = ''; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;api_status1: {{ redirect_url }}&lt;/p&gt; &lt;p&gt;api_command1: {{ api_command1 }}&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;
has comment: http://stackoverflow.com/comment/86527589

http://stackoverflow.com/a/49657049
upvote count: 2
answers question: http://stackoverflow.com/q/49656326
type: Answer
accepted answer of: http://stackoverflow.com/q/49656326
score: 2
type: AcceptedAnswer
has body: The traceback suggests you are importing a model in your settings.py: from apps.frontend.ad_akumuliatoriai.models import Language You shouldn't do this. Remove the import.
downvote count: 0

http://stackoverflow.com/a/49677760
type: AcceptedAnswer
has body: TCP sockets are streams of bytes, not streams of messages.. If you want a stream of messages, you have to define a protocol on top of that, and code to handle sending and receiving data in that protocol. If your messages are all strings, and never include newline characters, probably the simplest protocol is just separating the messages with newlines. I think you’ve already worked that out, you just need to know how to implement it. If the way you’re handling the network is a blocking recv (whether in the main loop of your program, or in the loop of a thread dedicated to reading off the socket), there’s built in support for this protocol: call sock.makefile with an appropriate mode (r plus an encoding if you want Unicode strings for your messages, rb if you want raw bytes), and you can use it like a file—e.g., a for msg in file: loop, or a while loop over file.readline() until you get an exception (meaning socket error) or empty string (meaning EOF—a clean socket close). If your messages can have newlines in them, you may still be able to use this. Just escape the messages (maybe using full backslash-escape so they’re always readable, for easy debugging, or maybe just msg.replace('\\', '\\\\').replace('\n', '\\n')) before sending, and unescape on receiving. Under the covers, this works the same way a normal file object does with disk files: when you ask for the next line, if it already has a complete line in the buffer, it just splits it off and returns it; if not, it reads buffers and appends them onto what it has until it finally gets a newline, then splits off the first complete line and returns it to you. So, it will never block waiting for two packets if the first packet contained a newline. But it will also never give you a “no complete message yet” to deal with; it’ll just keep blocking until it reads enough packets to get the next newline. It is worth learning how to build something like this from scratch at some point—but meanwhile, you can just use what’s …
downvote count: 0
answers question: http://stackoverflow.com/q/49677331
type: Answer
accepted answer of: http://stackoverflow.com/q/49677331
score: 2
upvote count: 2

http://stackoverflow.com/comment/88734386
has text: Could you help me with an example?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49727982

nltk
tags question: http://stackoverflow.com/q/49726068
tags question: http://stackoverflow.com/q/49637529
tags question: http://stackoverflow.com/q/49689789
tags question: http://stackoverflow.com/q/49600319
tag name: nltk
tags question: http://stackoverflow.com/q/49755153
tags question: http://stackoverflow.com/q/49724554
tags question: http://stackoverflow.com/q/49678251
tags question: http://stackoverflow.com/q/49625958
type: Tag
tags question: http://stackoverflow.com/q/49658383
tags question: http://stackoverflow.com/q/49715600
tags question: http://stackoverflow.com/q/49624767
tags question: http://stackoverflow.com/q/49612437

http://stackoverflow.com/q/49718246
tagged with: gdcm
answer count: 1
has body: I install gdcm in windows ,then I "import gdcm" in python, I got this error, My environment is python2.7.9, gdcm is GDCM-2.8.4-Windows-x86_64,
type: Question
linked to: http://stackoverflow.com/q/49297078
has answer: http://stackoverflow.com/a/49772698
has title: I install gdcm in windows ,then i "import gdcm" in python, I got anerror
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: pydicom
score: 0

http://stackoverflow.com/comment/86444855
type: Comment
has text: Possible duplicate of [How do I put a variable inside a String in Python?](https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-inside-a-string-in-python)
comment on: http://stackoverflow.com/q/49715886
score: 1
type: QuestionComment

http://stackoverflow.com/a/77105443
answers question: http://stackoverflow.com/q/49622924
downvote count: 0
upvote count: 1
score: 1
has body: You can inherit the Event class and add this functionality class AsynEventWithTimeout(asyncio.Event): async def wait(self, timeout: float | None = None) -> bool: try: await asyncio.wait_for(super().wait(), timeout=timeout) except asyncio.TimeoutError: return False return True async def event_setter(event: AsynEventWithTimeout) -> None: await asyncio.sleep(11) event.set() async def main() -> None: event = AsynEventWithTimeout() asyncio.create_task(event_setter(event)) counter = 0 while not await event.wait(timeout=2): print(f"Hello {counter}") counter += 1 asyncio.run(main())
type: Answer

http://stackoverflow.com/comment/86281271
type: Comment
score: 0
type: AnswerComment
has text: I see. Still, from what I understood the name of the file will be its name as it is in the FTP server (file), so you'd be able to retrieve its name whatever it is, save it with that name, and read it into a dataframe referencing path + file.csv.
comment on: http://stackoverflow.com/a/49618434

http://stackoverflow.com/q/49602337
type: Question
has answer: http://stackoverflow.com/a/49602679
accepted answer: http://stackoverflow.com/a/49602679
tagged with: qml
tagged with: python
tagged with: listview
type: AnsweredQuestion
upvote count: 3
has title: ListView with CheckDelegate items not keeping Checked Checkboxes when scrolling
score: 3
downvote count: 0
tagged with: pyqt
answer count: 1
tagged with: pyqt5
has body: Holla, so I have this simple script that displays 100 elements in a GUI and each element has a checkbox, I can check the boxes and they do remain checked for a while, but if I scroll up or down until they get out of view they will reseted(sometimes only the first element will be checked). Now I know that in ListView the elements are displayed once they come into view, and I've tried multiple things like Increasing the ListView Height , the ContentHeight, but nothing works. This issues is the same for example RadioDelegate Main.py file: from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtGui import QGuiApplication from PyQt5.QtCore import QObject, QUrl,QTimer import sys app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine('main.qml') sys.exit(app.exec_()) main.qml : import QtQuick 2.0 import QtQuick.Controls 2.3 import QtQuick.Layouts 1.3 ApplicationWindow { visible: true width: 400 height: 550 title: qsTr("Ttile") ColumnLayout { anchors.fill: parent ListView { id: listView objectName : "lvob" model: 100 delegate: CheckDelegate { text: modelData } Layout.fillWidth: true Layout.fillHeight: true ScrollBar.vertical: ScrollBar {} } } } Video Explanation : Click Me What am I doing wrong? Update: after some more researching I found that I have to Store the checked items in an array,since I'm very new to python/qml how could I do that? Thank you.
favorite count: 0

http://stackoverflow.com/q/49615355
accepted answer: http://stackoverflow.com/a/49617434
tagged with: json-schema-validator
type: AnsweredQuestion
score: 0
tagged with: pycharm
has title: Python MongoDB JSON schema validator "unresolved reference"
answer count: 1
tagged with: jsonschema
type: Question
has answer: http://stackoverflow.com/a/49617434
tagged with: mongodb
has body: I am relatively new to both Python and MongoDB, I am using python to set up a MongoDB database and create a collection with schema validation. However, when I create the collection as specified in the MongoDB documentation like so: db.create_collection("collection", { validator: { "$schema": "schema_stuff", "property1":"..." } Pycharm throws an error saying: "Unresolved reference 'validator' " I suspect it may have something to do with my import but I'm not sure. from pymongo import MongoClient Any ideas why this might be happening?
tagged with: python

http://stackoverflow.com/q/49752905
has comment: http://stackoverflow.com/comment/86524334
tagged with: class
has answer: http://stackoverflow.com/a/49753357
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86520529
score: 0
linked to: http://stackoverflow.com/q/17330160
answer count: 3
has comment: http://stackoverflow.com/comment/86524410
linked to: http://stackoverflow.com/q/3387691
has title: Python - Transform class attributes at call time
upvote count: 1
has answer: http://stackoverflow.com/a/49753561
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has body: Suppose I have the following class class Headings: standard_heading = { 'height': 3.72, 'width': 25.68, 'left': 1.65, 'top': 0.28 } As an example, I want the following results where all values have been multiplied by 10: Headings.standard_heading &gt;&gt;&gt; { 'height': 37.2, 'width': 256.8, 'left': 16.5, 'top': 2.8 } Is there no way to override the calling of a class attribute by adding a method similar to this to the class: def __getattribute__(cls, attr): return {k:v*10 for k,v in attr.items() I won't ever be creating instances of this class. I just use it for grouping purposes. Thanks
has answer: http://stackoverflow.com/a/49753036
possible better answer: http://stackoverflow.com/a/49753036
tagged with: class-attributes
tagged with: python
accepted answer: http://stackoverflow.com/a/49753561
tagged with: getattr

http://stackoverflow.com/a/49711318
answers question: http://stackoverflow.com/q/49705831
has body: "Pythonic" answer: import tensorflow as tf import string tf.reset_default_graph() iterSession = tf.InteractiveSession() coef = tf.constant([1., 2, 3]) # shape = (3,) LL_grads = { 'a': tf.constant([[1.], [2], [3]]), # shape = (3, 1) 'b': tf.constant([[1., 2], [3, 4], [5, 6]]), # shape = (3, 2) 'c': tf.constant([[[1.], [2]], [[3], [4]], [[5], [6]]]) # shape = (3, 2, 1) } avg_grad_stacked = {x: tf.transpose(tf.transpose(LL_grad) * coef) for x, LL_grad in LL_grads.items()} Explanation: You only need to do the tiling manually in your case because you are doing the multiplication along the 1st dimension. Tensorflow takes care itself of the broadcasting when multiplying tensors along the last dimension. A solution is thus simply to transpose your tensors before multiplication, then transpose the result back. Previous answer with tf.einsum(): It may not directly answer your question, as it isn't much more pythonic, and doesn't use tiling, but tf.einsum() is a powerful tool to multiply tensors of different dimensions (among other things). In your case, it could be used somehow like this: import tensorflow as tf import string tf.reset_default_graph() iterSession = tf.InteractiveSession() coef = tf.constant([1., 2, 3]) # shape = (3,) LL_grads = { 'a': tf.constant([[1.], [2], [3]]), # shape = (3, 1) 'b': tf.constant([[1., 2], [3, 4], [5, 6]]), # shape = (3, 2) 'c': tf.constant([[[1.], [2]], [[3], [4]], [[5], [6]]]) # shape = (3, 2, 1) } avg_grad_stacked = {} for x, LL_grad in LL_grads.items(): dim = len(LL_grad.get_shape()) coef_axis = string.ascii_lowercase[0] # "a" LL_grads_axes = "".join( [string.ascii_lowercase[i] for i in range(dim)]) # e.g. "abc" for dim==3 ein_equation = "{0},{1}-&gt;{0}".format( LL_grads_axes, coef_axis) # e.g. "abc,a-&gt;abc" avg_grad_stacked[x] = tf.einsum(ein_equation, LL_grad, coef)
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86438904
type: AcceptedAnswer
score: 2
accepted answer of: http://stackoverflow.com/q/49705831
type: Answer

http://stackoverflow.com/q/49728462
favorite count: 0
type: Question
has body: So, the basic gist is, I have javascript resources like https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js that I use in the QWebEngine. The intention is, that the program also works offline, so I made a QWebEngineUrlRequestInterceptor that changes those addresses to my own local handler, in this case the target would be conapp://webresource/jquery.min.js However, this results in this log message: js: Redirect from 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js' has been blocked by CORS policy: Redirect location 'conapp://webresource/jquery.min.js' has a disallowed scheme for cross- origin requests. Is there a way to allow redirects to conapp:// specifically? Some Relevant Code Snippets, if it helps (PyQt5) class Interceptor(QWebEngineUrlRequestInterceptor): def __init__(self): super(Interceptor, self).__init__() QWebEngineProfile.defaultProfile().setRequestInterceptor(self) def interceptRequest(self, info): url = info.requestUrl().toString() item = url.split("/")[-1] if item in LazyLoader: target = QUrl(r"conapp://webresource/{}".format(item)) info.redirect(target) class SchemeHandler(QWebEngineUrlSchemeHandler): def __init__(self): super(SchemeHandler, self).__init__() QWebEngineProfile.defaultProfile().settings().setAttribute(6, True) QWebEngineProfile.defaultProfile().installUrlSchemeHandler(b'conapp', self) self._handlers = {} def requestStarted(self, job): url = job.requestUrl() print("Got request for {}".format(url.toDisplayString())) request = url.toString().split("//")[1] buf = QBuffer(parent=self) buf.open(QIODevice.WriteOnly) buf.write(self._handlers[request]().encode("utf-8")) buf.seek(0) buf.close() job.reply(b"text/html", buf) def register(self, contentgenerator, contentname): self._handlers[contentname] = contentgenerator return contentname
upvote count: 2
type: UnansweredQuestion
tagged with: qwebengineview
tagged with: python
has answer: http://stackoverflow.com/a/50063177
has comment: http://stackoverflow.com/comment/87119214
has title: Qt5 - QWebEngine CORS for own uri type
score: 2
linked to: http://stackoverflow.com/q/49362212
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/87128537

http://stackoverflow.com/q/49635819
downvote count: 3
has body: I'm trying to send data from a server made with Flask in Python, to the client and collect this data with AJAX. Many of the examples I have seen does this with jQuery, but I'd like to do it without jQuery. Is it possible to do this with just ordinary Javascript without jQuery, and how would I build this functionality?
tagged with: javascript
duplicate of: http://stackoverflow.com/q/13081532
tagged with: flask
favorite count: 0
tagged with: ajax
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49636076
has title: Sending JSON to AJAX from Python Flask
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/1973140
tagged with: python
score: -3
accepted answer: http://stackoverflow.com/a/49636100
type: Question
possible better answer: http://stackoverflow.com/a/49636076
has answer: http://stackoverflow.com/a/49636100
answer count: 2
duplicate of: http://stackoverflow.com/q/1973140
upvote count: 0

http://stackoverflow.com/comment/86330945
comment on: http://stackoverflow.com/q/49660637
score: 6
type: QuestionComment
has text: Why use regex at all? Just use `word.startswith('th')`.
type: Comment

http://stackoverflow.com/q/49731562
has answer: http://stackoverflow.com/a/49733617
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86498953
has comment: http://stackoverflow.com/comment/86506660
has title: Query from mongoDB table using pymongo taking lot of memory
score: 0
answer count: 1
tagged with: pymongo
has body: i'm new to mongo db. I have a database set up and a table which has around 20 million rows. id source dest value 1 12 123 abc 2 10 435 mmn and so on. I tried to connect it using pymongo package in python. from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client['test'] #name of db stos_table = db['stos'] #stos is table_name which has 20 million rows when i ran the query: result = stos_table.find_one({'source':10,'dest':435}) My memory usage increased by 37 % ( it took approximately 6gb of my ram) Please tell why??? (I guess it loaded entire table in memory) Also the query execution took 10 seconds to run. I actually wanted something like my load should be on database not on memory. Is there any way where i can run similary query without loading entire data in memory and also get the result in milliseconds? Is it possible with mongodb?
tagged with: python
type: Question
tagged with: mongodb

http://stackoverflow.com/a/49714840
score: 1
answers question: http://stackoverflow.com/q/49714601
downvote count: 0
has body: You define a bunch of tuples, then an empty dict then try to access a value in said empty dict. What you want to do is to load those tuples into that dict (or a list) to start. d={obj_1 : ('John', 'Doe', 4, 5), obj_2 : ('Jane', 'Doe', 6, 8), ... obj_106 : ('Johnathan', 'Doe', 9, 1)} for x in range(1, 107): row = (d["obj_{0}".format(x)]) insert_item(row) Or, even better d = [('John', 'Doe', 4, 5), ('Jane', 'Doe', 6, 8), ... ('Johnathan', 'Doe', 9, 1)] for row in d: insert_item(row) You really should read up on how to use a dict
upvote count: 1
type: Answer

http://stackoverflow.com/comment/120475386
has text: @ThomasE.Duursma I told you I'd update the answer if I **ever** found the answer to your question. Two years later here we are :)
comment on: http://stackoverflow.com/a/56139173
score: 2
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86246061
comment on: http://stackoverflow.com/q/49619443
score: 0
has text: This will involved Nltk
type: Comment
type: QuestionComment

metaclass
tags question: http://stackoverflow.com/q/49690930
type: Tag
tags question: http://stackoverflow.com/q/49655566
tag name: metaclass
tags question: http://stackoverflow.com/q/49705827
tags question: http://stackoverflow.com/q/49740290

http://stackoverflow.com/comment/86434542
type: AnswerComment
comment on: http://stackoverflow.com/a/49710497
score: 1
has text: He will obviously need to change his `__str__` and `__repr__` methods to not add an extra `$` on top of `format(self)` then.
type: Comment

http://stackoverflow.com/q/49657966
tagged with: virtual-machine
has comment: http://stackoverflow.com/comment/86326491
type: Question
tagged with: python-3.x
has title: How to automate RDO or VMware workstation?
has body: My requirement is to automate remote desktop, VMWare, and NoMachine. I am not getting which module I can use in python, How to automate these? I got to know about pywinauto but with that, I guess I can just launch any app but not automate it, then how to do that? Thanks in advance. If it is confusing, Please tell me how can I automate the GUI of a remote PC using RDO?
tagged with: automation
has comment: http://stackoverflow.com/comment/86371249
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86325876
tagged with: python
has comment: http://stackoverflow.com/comment/86341130
has comment: http://stackoverflow.com/comment/86371211
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86325177

http://stackoverflow.com/comment/86471095
comment on: http://stackoverflow.com/q/49728421
score: 0
type: Comment
type: QuestionComment
has text: ?? I don't get what you're trying to say. I'm loading data, starting to filter and convert and apply some logic. For this specific warning, adding the copy() solved it.

http://stackoverflow.com/q/49728067
has answer: http://stackoverflow.com/a/49728121
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49729940
score: 0
possible better answer: http://stackoverflow.com/a/49728146
tagged with: django
has answer: http://stackoverflow.com/a/49728146
has body: I tried get the id from my database and make something like /article/1/. 1 is the id of my article but it didn't work. views.py def article(request, article_id): return render_to_response('article.html', {{'article': Articles.objects.get(id=article_id)}}) my urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('showall/', views.articles, name='articles'), path('&lt;int:article_id&gt;/', views.articles, name='article'), ] I get the error: TypeError at /article/1/ articles() got an unexpected keyword argument 'article_id' I also include image of my datebase Datebase
type: Question
answer count: 3
has title: Django view gets unexpected keyword argument
accepted answer: http://stackoverflow.com/a/49728121

pyfcm
tag name: pyfcm
tags question: http://stackoverflow.com/q/49715237
type: Tag

http://stackoverflow.com/q/49672100
has answer: http://stackoverflow.com/a/49672152
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/1207406
has comment: http://stackoverflow.com/comment/86354608
tagged with: python
has comment: http://stackoverflow.com/comment/86354559
type: Question
tagged with: python-3.x
score: 2
has comment: http://stackoverflow.com/comment/86355063
has title: Removing lists within a nested list based on condition
upvote count: 2
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86354848
downvote count: 0
has body: I am have a nested list with the following: [['X', 0], ['X', 0], ['X', ''], ['X', '']] for i in myList: if i[1] == 0: myList.remove(i) This will only remove the first list. Output would be: [['X', 0], ['X', ''], ['X', '']] How can I get it for both?
favorite count: 0
linked to: http://stackoverflow.com/q/10305762

cmder
type: Tag
tag name: cmder
tags question: http://stackoverflow.com/q/49615928

http://stackoverflow.com/a/49714404
downvote count: 1
has body: Assuming by "title", you mean the title of a resource: take a URL like https://www.foo.com/bar/baz/resource.jpg. You need to split it into a list along the /s, then take the last item in that list. The code url = "https://www.foo.com/bar/baz/resource.jpg" print(url.split('/')[-1]) gives the output resource.jpg
type: Answer
answers question: http://stackoverflow.com/q/49714340
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86442035

http://stackoverflow.com/comment/86453704
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49720219
has text: @Njx probably more like `for _ in range(5): stdio.writeln(deck.pop())` - after that your `deck` will be 5 cards shorter - the first 5 being removed by pop() ing them when printing.

http://stackoverflow.com/q/49709616
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49710967
has title: Create a matrix with dimension [N,D] from tensor with dimension [N]
upvote count: 3
has body: I have a tensor with dimension N and I would like to replicate it to create a tensor with dimension NxD being each column the initial vector. Thank you
tagged with: tensorflow
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49710967

http://stackoverflow.com/a/49636565
has comment: http://stackoverflow.com/comment/86282684
has comment: http://stackoverflow.com/comment/86282915
has comment: http://stackoverflow.com/comment/86281472
has comment: http://stackoverflow.com/comment/86281905
has comment: http://stackoverflow.com/comment/86282706
has comment: http://stackoverflow.com/comment/86282098
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86281358
has comment: http://stackoverflow.com/comment/86281383
has comment: http://stackoverflow.com/comment/86281520
accepted answer of: http://stackoverflow.com/q/49636078
has comment: http://stackoverflow.com/comment/86283597
score: 3
has comment: http://stackoverflow.com/comment/86281878
answers question: http://stackoverflow.com/q/49636078
has comment: http://stackoverflow.com/comment/86281974
type: Answer
has body: There are two conceptual issues that @abarnert has pointed out, beyond the syntactic and usage problems in your "pseudocode". The first is that map works with a function that is applied to the elements of your input. The second is that each sub-process gets a copy of you object, so changes to attributes are not automatically seen in the originals. Both issues can be worked around. To answer your immediate question, here is how you would apply a method to your list: with mp.Pool() as pool: pool.map(Example.compute, listofobjects) Example.compute is an unbound method. That means that it is just a regular function that accepts self as a first argument, making it a perfect fit for map. I also use the pool as a context manager, which is recommended to ensure that cleanup is done properly whether or not an error occurs. The code above would not work because the effects of compute would be local to the subprocess. The only way to pass them back to the original process would be to return them from the function you passed to map. If you don't want to modify compute, you could do something like this: def get_val3(x): x.compute() return x.val3 with mp.Pool() as pool: for value, obj in zip(pool.map(get_val3, listofobjects), listofobjects): obj.val3 = value If you were willing to modify compute to return the object it is operating on (self), you could use it to replace the original objects much more efficiently: class Example: ... def compute(): ... return self with mp.Pool() as pool: listofobjects = list(pool.map(Example.compute, listofobjects)) Update If your object or some part of its reference tree does not support pickling (which is the form of serialization normally used to pass objects between processes), you can at least get rid of the wrapper function by returning the updated value directly from compute: class Example: ... def compute(): self.val3 = ... return self.val3 with mp.Pool() as pool: for value, obj in zip(pool.map(Example.compute, listofobjects), listofobjects…
has comment: http://stackoverflow.com/comment/86282016
has comment: http://stackoverflow.com/comment/86281996

http://stackoverflow.com/a/49701723
has comment: http://stackoverflow.com/comment/86422968
has body: Synchronous programming can only do one thing at a time. So while a database query is running, everyone else (say pulling up a webpage via a web framework) has to wait for that to finish. Gevent makes it Asynchronous by using context switching and events. What does this mean? Think of it like this. You have a queue with stuff waiting for things to happen, meanwhile gevent says, ok you can wait, I am going to move to the next task and start doing stuff while I am waiting for you to finish (like a database read, or waiting for user input) and when you are done, when I go back through my queue and you say you're ready for the next step, I focus on that for you. In this way, though still single threaded, the application can be switching between jobs super fast, constantly checking the status to see if it deserves focus or not, meanwhile, other things can get done while it waits for you. As opposed to multiple threads, that are handled by the OS and heavy, they require their own resources and are expensive to switch between. Gevent makes converting stuff that would normally use threading to greenlets easy.
type: Answer
has comment: http://stackoverflow.com/comment/86485549
score: 17
accepted answer of: http://stackoverflow.com/q/49669212
answers question: http://stackoverflow.com/q/49669212
type: AcceptedAnswer
downvote count: 0
upvote count: 17

http://stackoverflow.com/comment/86386256
comment on: http://stackoverflow.com/q/49685775
type: Comment
type: QuestionComment
score: 0
has text: `cvutils` certainly doesn't have any `cvdetector`. Where from have you got that import? I cannot find any suitable `cvdetector` in the Internet.

http://stackoverflow.com/a/49675717
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49675390
has body: A better idea is to store your dataframes in a dictionary, with names as keys: d= {i: pd.DataFrame() for i in company_id} Then you can refer to individual dataframes via dictionary keys, e.g. d['BBG000QFYJ26']. You can iterate the dictionary via dict.items(): for k, v in d.items(): # perform operation
answers question: http://stackoverflow.com/q/49675390
type: Answer
score: 1

http://stackoverflow.com/comment/87028957
comment on: http://stackoverflow.com/a/49651752
score: 0
type: AnswerComment
has text: It'll be great if you would go in more detail, I think I didn't fully understand the documentation.
type: Comment

http://stackoverflow.com/comment/86408123
type: QuestionComment
has text: I think this new question is different enough that you should have considered writing and accepting an answer to the original question, then posting a new one, instead of editing. (And you should still consider reverting and doing that.) It depends on whether you think other people are likely to run into your original issue (and whether you want a bit of rep points from having a good question and a good answer…).
type: Comment
comment on: http://stackoverflow.com/q/49694832
score: 0

http://stackoverflow.com/q/49684951
tagged with: pandas
downvote count: 0
score: 132
upvote count: 132
has answer: http://stackoverflow.com/a/49685031
has answer: http://stackoverflow.com/a/65401791
linked to: http://stackoverflow.com/q/37515896
possible better answer: http://stackoverflow.com/a/65401791
has title: Pandas read_csv dtype read all columns but few as string
favorite count: 0
type: Question
has body: I'm using Pandas to read a bunch of CSVs. Passing an options json to dtype parameter to tell pandas which columns to read as string instead of the default: dtype_dic= { 'service_id':str, 'end_date':str, ... } feedArray = pd.read_csv(feedfile , dtype = dtype_dic) In my scenario, all the columns except a few specific ones are to be read as strings. So instead of defining several columns as str in dtype_dic, I'd like to set just my chosen few as int or float. Is there a way to do that? It's a loop cycling through various CSVs with differing columns, so a direct column conversion after having read the whole csv as string (dtype=str), would not be easy as I would not immediately know which columns that csv is having. (I'd rather spend that effort in defining all the columns in the dtype json!) Edit: But if there's a way to process the list of column names to be converted to number without erroring out if that column isn't present in that csv, then yes that'll be a valid solution, if there's no other way to do this at csv reading stage itself. Note: this sounds like a previously asked question but the answers there went down a very different path (bool related) which doesn't apply to this question. Pls don't mark as duplicate!
has answer: http://stackoverflow.com/a/77905736
answer count: 5
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/69184683
tagged with: python
accepted answer: http://stackoverflow.com/a/49685031
linked to: http://stackoverflow.com/q/10867028
has answer: http://stackoverflow.com/a/73914250
type: AnsweredQuestion

http://stackoverflow.com/a/49709664
has comment: http://stackoverflow.com/comment/86432857
has body: l1=[1,5,6,72,3,4,9,11,3,8] l2=sorted(l1) ln=round(len(l1)*0.25) [i for i in l1 if i not in l2[ln+1:]] Output: [5, 6, 72, 4, 9, 11, 8]
has comment: http://stackoverflow.com/comment/86432775
type: Answer
answers question: http://stackoverflow.com/q/49709522
score: 0

http://stackoverflow.com/a/49617838
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49617712
answers question: http://stackoverflow.com/q/49617712
upvote count: 2
has body: More or less what you have but using groupby.apply, also from your desired output it doesn't seem you prioritize the first condition, in which case, you need to combine the two conditions with or |: def first_last(g): # this is used at multiple places, cache the condition cond = g.D.ge(g.C.mul(0.5)) | g.D.le(g.C.mul(-1)) if cond.any(): return g[cond].iloc[0] else: return g.iloc[-1] df.groupby('B', as_index=False).apply(first_last) # A B C D #0 01:30:00 2002-01-16 10 -12 #1 01:00:00 2002-01-17 20 33 Or a shorter version: def first_last(g): cond = g.D.ge(g.C.mul(0.5)) | g.D.le(g.C.mul(-1)) return g[cond].iloc[0] if cond.any() else g.iloc[-1] df.groupby('B', as_index=False).apply(first_last)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50874554
type: Answer
answers question: http://stackoverflow.com/q/49606484
score: 0
has body: This works for me: list1 = ["VW SPL", 0] print(ocx.dynamicCall('ReadVariable(QVariant, QVariant&amp;)', list1)) print(list1) In your case try this: data = [rqID, proc, 0, 0] item_length = ocx_module.dynamicCall("ReceiveProcDataArr(QVariant, QVariant, QVariant, QVariant&amp;)", data) print(data[3]) Beware that the reference only updates the list: int foo = 0 data = [rqID, proc, 0, foo] item_length = ocx_module.dynamicCall("ReceiveProcDataArr(QVariant, QVariant, QVariant, QVariant&amp;)", data) print(data[3])//It prints the result print(foo)//It prints 0
has comment: http://stackoverflow.com/comment/91775513

http://stackoverflow.com/comment/86485341
type: QuestionComment
type: Comment
has text: @chepner I haven't encountered a problem yet, but that doesn't mean there isn't one. Python 2 certainly has a lot of problems converting between str and unicode. Hence my question about the implications.
score: 0
comment on: http://stackoverflow.com/q/49735426

http://stackoverflow.com/q/49634471
has answer: http://stackoverflow.com/a/49634552
tagged with: jython
type: UnansweredQuestion
answer count: 1
tagged with: docker
score: 0
tagged with: path
has title: Python - how to see and modify Import Path (FileUtil module can not be found)
tagged with: python
tagged with: import
has body: I have a script in jython (basically Python code) that has a module 'FileUtil' all wrapped into a docker.. On some machines - it works fine and on other machines (with same exact docker images) - it is complaining that FileUtil module can not be found. How to check paths and imports during a run in Python? (or how to force preparing environment for docker so that it always has FileUtil module?)
type: Question

http://stackoverflow.com/a/49687931
answers question: http://stackoverflow.com/q/49682296
has body: First, you've got a major problem that will prevent you from even seeing the problem you've asked for help with: Your Thing class defines an __iter__ method that doesn't super, and doesn't yield or return anything. Hopefully that part is just some typo and you know how to fix it to do whatever you actually wanted there. No, onto the problem you're asking about: class IterMixin(): def __iter__(self): for attr, value in self.__dict__.items(): yield attr, value Try printing out the __dict__ of your instances. Or, better, instances of a minimal example like this: class Thing: @property def foo(self): return self._foo @foo.setter def foo(self, data): self._foo = data t = Thing() t.foo = 2 print(t.__dict__) The output is {'_foo': 2}. You've tried to hide the attributes by giving them private names and putting them behind properties, but then you've gone around behind the properties' backs and looked directly into the __dict__ where the real attributes are. And what else could be there? Your actual _foo has to be stored somewhere on each instance. That foo, on the other hand, isn't really a value, it's a getter/setter that uses that private attribute, so it isn't stored anywhere. If you really want to use reflection to find all of the "public values" on an instance, you can do something like this: for attr, value in inspect.getmembers(self): if not attr.startswith('_') and not callable(value): yield attr, value However, I think it would be much better to not do this reflectively. Simpler and cleaner options include: Add a _fields = 'foo', 'bar', 'baz' and have the base class iterate _fields_. Write a decorator that registers a property, and have the base class iterate that registry. Build something that lets you specify the attributes more declaratively and writes the boilerplate for you. See namedtuple, dataclass, and attrs for some inspiration. Just use attrs (or, if you're not the OP but someone reading this from the future who can rely on 3.7+, dataclass) to do that wo…
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86483310
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49682296
type: AcceptedAnswer

http://stackoverflow.com/q/49740628
has comment: http://stackoverflow.com/comment/86495981
has comment: http://stackoverflow.com/comment/86496533
has comment: http://stackoverflow.com/comment/86495838
has title: Cant find django module . import error
type: Question
has comment: http://stackoverflow.com/comment/86496636
has comment: http://stackoverflow.com/comment/86496057
has comment: http://stackoverflow.com/comment/86495793
has comment: http://stackoverflow.com/comment/86497219
has comment: http://stackoverflow.com/comment/86497030
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86496136
linked to: http://stackoverflow.com/q/29934032
has body: I have installed Django and it is already in the package. But when i run python manage.py runserver.I am getting this error Traceback (most recent call last): File "manage.py", line 8, in &lt;module&gt; from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
tagged with: pip
tagged with: django
has comment: http://stackoverflow.com/comment/86496760
tagged with: python
has comment: http://stackoverflow.com/comment/86496869
has comment: http://stackoverflow.com/comment/86496577
has comment: http://stackoverflow.com/comment/86496820
has comment: http://stackoverflow.com/comment/86496860
has comment: http://stackoverflow.com/comment/86496174
has comment: http://stackoverflow.com/comment/86496162
score: 0
answer count: 0

http://stackoverflow.com/comment/86374508
comment on: http://stackoverflow.com/a/49681136
type: Comment
type: AnswerComment
has text: Thanks, reading and processing in chunks might be a possibility. I'm looking into it as well. It'll be great If you can throw some insights on how this can be achieved.
score: 0

http://stackoverflow.com/comment/138311630
comment on: http://stackoverflow.com/a/49620921
type: Comment
score: 0
type: AnswerComment
has text: @ErykSun This works great. The only thing is the lock file doesn't get removed in case of a system crash.

http://stackoverflow.com/comment/86326627
type: QuestionComment
comment on: http://stackoverflow.com/q/49658383
has text: Hey @AlexNikitin, no problem. Are the bigrams/trigrams strings, or lists themselves? Does a trigram look like `['Hello', 'there', 'sir']` or `['hello there sir']`?
type: Comment
score: 0

http://stackoverflow.com/comment/86433056
type: QuestionComment
comment on: http://stackoverflow.com/q/49696790
has text: It is not, I am still having issues writing each field name to a separate file.
score: 0
type: Comment

http://stackoverflow.com/q/49702300
tagged with: python
duplicate of: http://stackoverflow.com/q/477096
has body: I am maintaining a few Python packages, and on systems where dependencies are not fully satisfied, functions which may otherwise work, fail due to global scope imports: import numpy as np def lala(in): out = max(in) return out def fufu(in): out = np.mean(in) return out So for instance here I cannot use lala() if I do not have numpy, ven if lala does not use numpy. Of course, ideally dependencies would be managed correctly, still, it would make for a more robust package if functions failed only when they had to fail. Is there any reason why imports are almost never done in function scope? Is this reason just reducing the number of lines?
tagged with: conventions
accepted answer: http://stackoverflow.com/a/49702364
has comment: http://stackoverflow.com/comment/86418353
type: AnsweredQuestion
score: 3
upvote count: 3
duplicate of: http://stackoverflow.com/q/128478
answer count: 1
favorite count: 0
has title: Why is it uncommon for import statements to be placed inside functions?
has comment: http://stackoverflow.com/comment/86418295
type: Question
tagged with: python-import
has answer: http://stackoverflow.com/a/49702364
linked to: http://stackoverflow.com/q/477096
has comment: http://stackoverflow.com/comment/86418328
downvote count: 0

bash
tags question: http://stackoverflow.com/q/49707469
tags question: http://stackoverflow.com/q/49746006
tags question: http://stackoverflow.com/q/49730803
tags question: http://stackoverflow.com/q/49735956
type: Tag
tags question: http://stackoverflow.com/q/49726243
tags question: http://stackoverflow.com/q/49605276
tags question: http://stackoverflow.com/q/49675087
tags question: http://stackoverflow.com/q/49721813
tags question: http://stackoverflow.com/q/49627914
tags question: http://stackoverflow.com/q/49603157
tags question: http://stackoverflow.com/q/49705758
tags question: http://stackoverflow.com/q/49729099
tags question: http://stackoverflow.com/q/49755433
tags question: http://stackoverflow.com/q/49728878
tag name: bash
tags question: http://stackoverflow.com/q/49660091
tags question: http://stackoverflow.com/q/49622184

http://stackoverflow.com/q/49604318
has body: I have a function that defines a variable inside of it called animal. I also have a decorator for that function, but it needs the variable that's defined in the original function. Either I need the animal variable from the original function, or I need to somehow pass the model_data variable from the decorator into the original function. Any input? Here is the code: @csrf_exempt @require_http_methods(["GET", "PUT", "DELETE"]) @parse_model_data def base_animal(request, model_id): try: animal = Animal.objects.get(pk=model_id) except ObjectDoesNotExist: return json_error(error="No animal found for id: %s" % model_id) if request.method == "GET": return json_success(model=animal) if request.method == "DELETE": animal.delete() return json_success("Animal deleted.") if request.method == "PUT": animal.save() return json_success() Here is the decorator function: def parse_model_data(originalFunction): def parse(*args, **kwargs): request = args[0] model_data = request.get_json_body() if not model_data: return json_error("no json body detected") model_data = Animal.parse_model_data(model_data) for attr, value in model_data.items(): setattr(animal, attr, value) return originalFunction(*args, **kwargs) return parse
has comment: http://stackoverflow.com/comment/86215766
tagged with: python
has comment: http://stackoverflow.com/comment/86216121
has title: How do i pass a variable in a function to a decorator
has comment: http://stackoverflow.com/comment/86216354
linked to: http://stackoverflow.com/q/1965607
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86216435
upvote count: 1
tagged with: decorator
downvote count: 1
has answer: http://stackoverflow.com/a/49604732
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86216297
score: 0

http://stackoverflow.com/a/49685430
has comment: http://stackoverflow.com/comment/86388514
accepted answer of: http://stackoverflow.com/q/49685215
type: Answer
has body: Changing the order in which you are approaching the problem in this case will help. If you first sort and then use groupby, you will get the desired output and you can use the groupby.nth function. Here is a code snippet to demonstrate the idea: df = pd.DataFrame({'id':['a','a','a','b','b','b'], 'var1':[3,2,1,8,7,6], 'var2':['g','h','i','j','k','l']}) n = 2 # replace with required row from each group df.sort_values(['id','var1']).groupby('id').nth(n).reset_index() Assuming id is your sessionid and var1 is the timestamp, this sorts your dataframe by id and then var1. Then picks up the nth row from each of these sorted groups. The reset_index() is there just to avoid the resulting multi-index. If you want to get the last n rows of each group, you can use .tail(n) instead of .nth(n).
answers question: http://stackoverflow.com/q/49685215
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86392476
score: 3

http://stackoverflow.com/comment/86231254
type: Comment
comment on: http://stackoverflow.com/a/49602325
score: 0
type: AnswerComment
has text: @OlivierMelançon The way I've understood it is that it's a way of putting functions into a class because it belongs there logically, but it doesn't need access to the class itself. So, in this case, if you have a "Mail" class (or a "MailUtils" class), the sendmail static method belongs there, just for the sake of making the program more readable. I do understand that they are not needed most of the time, but I still like how it organizes things. (I'm of course open to being wrong, just trying to understand what you mean). :)

http://stackoverflow.com/comment/86440158
comment on: http://stackoverflow.com/a/49713352
score: 0
type: AnswerComment
has text: I will give this stuff a go and see where I end up. I appreciate your time and efforts!
type: Comment

http://stackoverflow.com/comment/86487979
has text: thank you, It seems interesting so I will start using it.
comment on: http://stackoverflow.com/a/49736714
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49626962
favorite count: 0
score: 1
has comment: http://stackoverflow.com/comment/86261161
has body: I am currently constructing a dict comprehension from an itertools groupby object, to construct a lookup dictionary for some strings. #groupby iterable arranged by first 3 chars of each element of 'Titles' list. lookup= groupby(sorted(Titles), key=itemgetter(0,1,2)) #key=concatenate the elements of the tuple, val=list of grouper iterable lookdict={''.join(i):list(j) for i,j in lookup} This second line gives me IndexError: string index out of range. I cannot tell whether it is a problem with j, the grouper iterable, or the join call in the dict comp. The following: for i,j in lookup: print(''.join(i),j) Is, as expected, not problematic. It is necessary to have the values as list and the keys as strings to avoid some kind of transformation upon each lookup. Can anyone point out where I am going wrong here?
tagged with: python
tagged with: dictionary
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86261175
downvote count: 0
tagged with: python-itertools
upvote count: 1
has answer: http://stackoverflow.com/a/49627172
type: UnansweredQuestion
tagged with: dictionary-comprehension
has title: Dict Comprehension Index Error
has answer: http://stackoverflow.com/a/49627275
has comment: http://stackoverflow.com/comment/86261052

http://stackoverflow.com/comment/86528324
score: 2
comment on: http://stackoverflow.com/q/49756598
type: Comment
type: QuestionComment
has text: What if the string is '605260'?

http://stackoverflow.com/a/49708379
has comment: http://stackoverflow.com/comment/86432605
upvote count: 2
has body: You don't include post_id in the template context: def post_detail(request, post_id): context = {'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text} return render(request, 'blogs/post_detail.html', context) Therefore the following url tag is not going to work. Edit post You could fix it by adding post_id to the context: def post_detail(request, post_id): ... post_id = p_id.id context = {'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text, 'post_id': post_id} return render(request, 'blogs/post_detail.html', context) However there's no need to include all of the fields individually. Just include the post in the template. def post_detail(request, post_id): post = BlogPost.objects.get(id=post_id) context = {'post': post} return render(request, 'blogs/post_detail.html', context) Note that I've changed the variable name from p_id to post, because it's a model instance, not an id. Then in the template you can access the fields from post: Title:{{ post.title }} Edit post Edit post Time: Post:
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49708166
downvote count: 0
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49708166

http://stackoverflow.com/q/49732941
tagged with: pandas
answer count: 1
tagged with: dataset
linked to: http://stackoverflow.com/q/29919306
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/29919306
has title: Selecting max confidence category using pandas and numpy
has answer: http://stackoverflow.com/a/49733131
accepted answer: http://stackoverflow.com/a/49733131
tagged with: python
has body: I am stuck in caluculating the highest of the 3 columns and respctive category as per the dataset: &lt;Dataset Image> I want to calculate the max confidence category with confidence level and create a dataset with 4 columns like: TC_Name Failure MaxErrCategory MaxConfidence I have tried capturing the max confidence level for each row but unable to figure out the category: max_conf=data.max(axis=1) Kindly help..
tagged with: numpy
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49637095
has comment: http://stackoverflow.com/comment/86302507
answers question: http://stackoverflow.com/q/49631464
upvote count: 4
has comment: http://stackoverflow.com/comment/86292198
downvote count: 0
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/86292484
accepted answer of: http://stackoverflow.com/q/49631464
has comment: http://stackoverflow.com/comment/86292278
type: AcceptedAnswer
has body: The blocking tasks are not friendly with the event loop where the GUI is executed as they prevent the normal tasks that the GUI performs such as ticket checking, redrawing, etc. from being executed. The solution in these cases is to use thread to execute the blocking task and use the signals to send the information. import sys from PyQt5 import QtCore, QtWidgets from selenium import webdriver class SeleniumWorker(QtCore.QObject): progressChanged = QtCore.pyqtSignal(int) def doWork(self): progress = 0 browser = webdriver.Firefox() links = ['http://www.somesite.com/', 'http://www.somesite.com/page2', 'http://www.somesite.com/page3'] for link in links: browser.get(link) progress += 100 / len(links) self.progressChanged.emit(progress) browser.close() class Widget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) lay = QtWidgets.QHBoxLayout(self) progressBar = QtWidgets.QProgressBar() progressBar.setRange(0, 100) button = QtWidgets.QPushButton("Start") lay.addWidget(progressBar) lay.addWidget(button) self.thread = QtCore.QThread() self.worker = SeleniumWorker() self.worker.moveToThread(self.thread) self.thread.started.connect(self.worker.doWork) button.clicked.connect(self.thread.start) self.worker.progressChanged.connect(progressBar.setValue, QtCore.Qt.QueuedConnection) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())

http://stackoverflow.com/q/49719139
possible better answer: http://stackoverflow.com/a/49719801
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49719276
tagged with: python
has title: Extract number from string and replace?
has answer: http://stackoverflow.com/a/49719801
has answer: http://stackoverflow.com/a/49719276
upvote count: 2
type: AnsweredQuestion
has body: So right now, my code is working as intended from what I know. But, I am incapable of putting together either a small module or another few lines to extract an integer number from users Input and inflate it by 1. dictZero = [ "zero", "none", "null", "nil" ] dictOne = [ "juan", "one", "won" ] dictTwo = [ "two", "to", "too", "tu" ] dictThree = [ "three" ] dictFour = [ "four", "fore", "for" ] userInput = input ( "Enter your sentence to inflate: " ) for i in userInput.split(): for e in dictFour: if e in i: userInput = userInput.replace ( e, "five" ) for d in dictThree: if d in i: userInput = userInput.replace ( d, "four" ) for c in dictTwo: if c in i: userInput = userInput.replace ( c, "three" ) for b in dictOne: if b in i: userInput = userInput.replace ( b, "two" ) for a in dictZero: if a in i: userInput = userInput.replace ( a, "one" ) print ( userInput ) Sample Input: Before we begin to do anything at 1630. Sample Output: Befive we begin three do anything at 1631. Without over-complicating and changing my code significantly, what can I do to simply +1 any number in the input string?
answer count: 2
score: 1
downvote count: 1

image
tags question: http://stackoverflow.com/q/49743051
tags question: http://stackoverflow.com/q/49705675
tags question: http://stackoverflow.com/q/49652082
tags question: http://stackoverflow.com/q/49636870
tags question: http://stackoverflow.com/q/49693406
tags question: http://stackoverflow.com/q/49667248
tags question: http://stackoverflow.com/q/49669049
tags question: http://stackoverflow.com/q/49636813
tags question: http://stackoverflow.com/q/49675629
tags question: http://stackoverflow.com/q/49691696
tags question: http://stackoverflow.com/q/49731759
tags question: http://stackoverflow.com/q/49688722
tags question: http://stackoverflow.com/q/49680181
tags question: http://stackoverflow.com/q/49632200
tags question: http://stackoverflow.com/q/49638305
tags question: http://stackoverflow.com/q/49601934
tags question: http://stackoverflow.com/q/49640666
tags question: http://stackoverflow.com/q/49754923
tag name: image
tags question: http://stackoverflow.com/q/49685370
tags question: http://stackoverflow.com/q/49732290
tags question: http://stackoverflow.com/q/49743649
tags question: http://stackoverflow.com/q/49649215
tags question: http://stackoverflow.com/q/49683500
tags question: http://stackoverflow.com/q/49732726
type: Tag
tags question: http://stackoverflow.com/q/49616151
tags question: http://stackoverflow.com/q/49749294

http://stackoverflow.com/q/49722779
has comment: http://stackoverflow.com/comment/86459325
has title: Running bash commands in two terminals (client/server sides) via python in an anaconda environment
downvote count: 0
has comment: http://stackoverflow.com/comment/86459225
tagged with: jupyter
upvote count: 1
favorite count: 0
type: Question
tagged with: terminal
tagged with: anaconda
type: UnansweredQuestion
tagged with: ubuntu-16.04
tagged with: python
has comment: http://stackoverflow.com/comment/86459053
has comment: http://stackoverflow.com/comment/86459262
has comment: http://stackoverflow.com/comment/86459385
answer count: 0
has comment: http://stackoverflow.com/comment/86459161
has body: I am having a problem in running a bash command via python and a anaconda environment that the required packages have been installed in the environment. One command acts as server side and start a database and another command should be run in client side in another terminal which has been activated for the same anaconda environment. How can I run these bash commands separately in a separate terminals in Python? Is it possible I open client side terminal and activate the anaconda environment, and send the command through os.system() to that specific terminal? If yes, how? As you can see, in one terminal the following command starts the database: (my_env) esara@esara-XPS-8920:~/workspace/$ ./command_ -start ./home/db/ and in another terminal I am running the following command: (my_env) esara@esara-XPS-8920:~/workspace/$ ./command_ -query ./path/to/a file/ How to run these scenario in Python?
has comment: http://stackoverflow.com/comment/86459414
score: 1

http://stackoverflow.com/comment/86333890
score: 0
comment on: http://stackoverflow.com/q/49661827
type: Comment
type: QuestionComment
has text: @abarnert I want the value in the cell. Obscure cpython objects like closure cells aren't of much use to me :)

http://stackoverflow.com/a/49744509
type: Answer
answers question: http://stackoverflow.com/q/49744007
has body: This is a one-liner that will accomplish what you are describing through the use of iterable comprehension, assuming that special characters have a score of 0 similar to whitespace. This function will create an array containing a score for each character in the string, then the sum of these scored is calculated and returned. def str_score(s): return sum([int(x) if x.isdigit() else 1 if x.isalpha() else 0 for x in s]) print(str_score('Cows 16')) &gt;&gt;&gt; 11 If you want special characters to have a value of 1, such as letters then the following function would achieve this functionality. def str_score(s): return sum([int(x) if x.isdigit() else 1 for x in s.replace(' ', '')]) In the second function I have removed all spaces from the string since they have no value.
score: 0

http://stackoverflow.com/comment/86390900
type: QuestionComment
comment on: http://stackoverflow.com/q/49689581
has text: @IljaEverilä I was so close, just needed the correct syntax. Thank you very much, it works. If you answer the question I'll accept it. Also good to know that lazyload is default.
score: 0
type: Comment

http://stackoverflow.com/comment/86373854
type: QuestionComment
has text: Because tuples and lists are **sequences**, so can be indexed at random. Iterators are not sequences, and you can create iterators for many more things than just sequences. Like an [infinite counter](https://docs.python.org/3/library/itertools.html#itertools.count). Sequences are *iterable*, meaning that you can create (new) iterators for them.
comment on: http://stackoverflow.com/q/49680934
score: 0
type: Comment

http://stackoverflow.com/comment/86384830
type: QuestionComment
comment on: http://stackoverflow.com/q/49643616
type: Comment
score: 0
has text: @A.Klim If the comment was helpful, please upvote it!

http://stackoverflow.com/comment/86480839
comment on: http://stackoverflow.com/a/49733526
type: Comment
score: 0
type: AnswerComment
has text: I guess this is for windows.. I am using MAC/Ubuntu

http://stackoverflow.com/q/49672708
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86356171
has answer: http://stackoverflow.com/a/49672823
accepted answer: http://stackoverflow.com/a/49672823
has body: Is there a way to make a nested dictionary such that I can say mydict[x][y][z] += 1, where mydict[x][y][z] did not previously exist, and defaults to 0 (and would be 1 after incrementing)? I looked into answers to a similar question in which you can say mydict[x][y][z] = 1 using defaultdict from the collections class (Declaring a multi dimensional dictionary in python), but this does not allow you to assume a default value and then increment.
tagged with: counter
tagged with: python
tagged with: dictionary
tagged with: defaultdict
has title: Nested dictionary with defaults
score: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/29348345

mouse
tags question: http://stackoverflow.com/q/49688722
type: Tag
tags question: http://stackoverflow.com/q/49735547
tag name: mouse

http://stackoverflow.com/comment/86281714
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49606484
score: 0
has text: The in and out parameters clearly ***must*** be `QVariant&`, so your only possiblilities are the [types specified here](https://doc.qt.io/qt-5/qvariant-obsolete.html#Type-enum). If none of those work, I don't think there is anything else you can do. I suppose `QVariant(QVariant.StringList)` is the best bet if `VARIANT*` is an array of `BSTR`. If it's not, you really need to find out the *precise* type of data that the function is supposed to return through that last parameter.

http://stackoverflow.com/comment/86209289
type: QuestionComment
comment on: http://stackoverflow.com/q/49600319
has text: @KonstantinosKokos Would decision trees work for this kind of problem? The total number of possible uni, bi, tri and quadrigrams in a language is massive. I can't imagine a decision tree being constructed with all of these.
score: 0
type: Comment

http://stackoverflow.com/comment/86401034
has text: you're right, updated my answer. this can probably be made shorter, but it works
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49693903
score: 0

http://stackoverflow.com/comment/86351266
type: AnswerComment
has text: I solved the Problem with pd.date_range. It seems to work with pd 0.18 . Anyways, thanks alot!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49666443

http://stackoverflow.com/comment/86379122
has text: type(config['SEQUENCE'][0]) = str
score: 0
comment on: http://stackoverflow.com/a/49683375
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49734915
linked to: http://stackoverflow.com/q/49996626
downvote count: 0
has comment: http://stackoverflow.com/comment/86488788
linked to: http://stackoverflow.com/q/48079120
tagged with: web-scraping
tagged with: python
has title: "Failed to decode response from marionette" message in Python/Firefox headless scraping script
has answer: http://stackoverflow.com/a/70414316
accepted answer: http://stackoverflow.com/a/49800671
possible better answer: http://stackoverflow.com/a/55206440
has answer: http://stackoverflow.com/a/55260657
has answer: http://stackoverflow.com/a/56405092
linked to: http://stackoverflow.com/q/49831841
score: 42
linked to: http://stackoverflow.com/q/55072731
has answer: http://stackoverflow.com/a/49800671
has answer: http://stackoverflow.com/a/57097031
has answer: http://stackoverflow.com/a/73282478
type: AnsweredQuestion
answer count: 9
tagged with: selenium
has body: Good Day, I've done a number of searches on here and google and yet to find a solution that address this problem. The scenario is: I have a Python script (2.7) that loops through an number of URLs (e.g. think Amazon pages, scraping reviews). Each page has the same HTML layout, just scraping different information. I use Selenium with a headless browser as these pages have javascript that needs to execute to grab the information. I run this script on my local machine (OSX 10.10). Firefox is the latest v59. Selenium is version at 3.11.0 and using geckodriver v0.20. This script locally has no issues, it can run through all the URLs and scrape the pages with no issue. Now when I put the script on my server, the only difference is it is Ubuntu 16.04 (32 bit). I use the appropriate geckodriver (still v0.20) but everything else is the same (Python 2.7, Selenium 3.11). It appears to randomly crash the headless browser and then all of the browserObjt.get('url...') no longer work. The error messages say: Message: failed to decode response from marionette Any further selenium requests for pages return the error: Message: tried to run command without establishing a connection To show some code: When I create the driver: options = Options() options.set_headless(headless=True) driver = webdriver.Firefox( firefox_options=options, executable_path=config.GECKODRIVER ) driver is passed to the script's function as a parameter browserObj which is then used to call specific pages and then once that loads it is passed to BeautifulSoup for parsing: browserObj.get(url) soup = BeautifulSoup(browserObj.page_source, 'lxml') The error might be pointing to the BeautifulSoup line which is crashing the browser. What is likely causing this, and what can I do to resolve the issue? Edit: Adding stack trace which points to the same thing: Traceback (most recent call last): File "main.py", line 164, in &lt;module&gt; getLeague File "/home/ps/dataparsing/XXX/yyy.py", line 48, in BBB soup = BeautifulSoup…
has answer: http://stackoverflow.com/a/57020784
linked to: http://stackoverflow.com/q/54525301
has comment: http://stackoverflow.com/comment/86545036
favorite count: 0
linked to: http://stackoverflow.com/q/54459701
upvote count: 42
has answer: http://stackoverflow.com/a/55206440
type: Question
has answer: http://stackoverflow.com/a/60178324
tagged with: firefox
tagged with: geckodriver

http://stackoverflow.com/comment/98927902
type: Comment
has text: I see your point, it'd be a `mae`. I don't know, however, why would the `K.abs(y_true)` return zeroes systematically that are then clipped to `k.epsilon`, looks like a bug to me.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/54594876

http://stackoverflow.com/comment/96939032
type: AnswerComment
has text: @Ben.T Hi Ben, can i check with you if there's any way to monitor only 1 mailbox within `OnNewMailEx`? I have been stuck at this for awhile and was wondering if it is either possible to `DispatchWithEvents` a particular mailbox/folder or test if mailitem is from a particular account? I cant seem to find such a property from MSDN. Thank you!
comment on: http://stackoverflow.com/a/49778696
type: Comment
score: 0

http://stackoverflow.com/a/58349659
upvote count: 65
has comment: http://stackoverflow.com/comment/133865719
type: Answer
has comment: http://stackoverflow.com/comment/133865976
has comment: http://stackoverflow.com/comment/106444758
has body: With my PyCharm, I do the following to make its type hinting work: from contextlib import contextmanager from typing import ContextManager @contextmanager def session() -&gt; ContextManager[Session]: yield Session(...) UPD: see comments below. Looks like this thing makes PyCharm happy, but not mypy
has comment: http://stackoverflow.com/comment/111710021
has comment: http://stackoverflow.com/comment/133862493
has comment: http://stackoverflow.com/comment/133865642
has comment: http://stackoverflow.com/comment/111552082
score: 56
has comment: http://stackoverflow.com/comment/133865603
has comment: http://stackoverflow.com/comment/123709678
has comment: http://stackoverflow.com/comment/133867725
answers question: http://stackoverflow.com/q/49733699
has comment: http://stackoverflow.com/comment/119654520
downvote count: 9

http://stackoverflow.com/q/49652184
has comment: http://stackoverflow.com/comment/86312849
has comment: http://stackoverflow.com/comment/86312786
accepted answer: http://stackoverflow.com/a/49652679
score: 1
has answer: http://stackoverflow.com/a/49652679
has title: How to mock your function?
tagged with: python
possible better answer: http://stackoverflow.com/a/49653608
type: Question
has answer: http://stackoverflow.com/a/49653608
answer count: 2
has body: I can't figure out how I can mock my function in python, I've tried to look for some code, but no of it seems to work, consider this layout: | project.py | tests.py project.py: def foobar(): return tests.py: import unittest from unittest.mock import patch import os from project import foobar def os_urandom_mock(): return 'mocked' def foobar_mock(): return 'mocked' class TestProject(unittest.TestCase): # mocked os.urandom worked well @patch('os.urandom', side_effect=os_urandom_mock) def test_os_urandom_mocked(self, os_urandom_mocked): self.assertEqual(os.urandom(), 'mocked') # but this doesn't @patch('project.foobar', side_effect=foobar_mock) def test_foobar_mocked(self, foobar_mocked): self.assertEqual(foobar(), 'mocked') # and this also doesn't work @patch('project.foobar') def test_foobar_mocked_another(self, foobar_mocked): foobar_mocked.return_value = 'mocked' self.assertEqual(foobar(), 'mocked') # and this also doesn't work def test_foobar_mocked_last_try(self): with patch('project.foobar') as foobar_mocked: foobar_mocked.return_value = 'mocked' self.assertEqual(foobar(), 'mocked') unittest.main() so, python3 tests.py: ====================================================================== FAIL: test_foobar_mocked (__main__.TestProject) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Python36\lib\unittest\mock.py", line 1179, in patched return func(*args, **keywargs) File "tests.py", line 24, in test_foobar_mocked self.assertEqual(foobar(), 'mocked') AssertionError: None != 'mocked' ====================================================================== FAIL: test_foobar_mocked_another (__main__.TestProject) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Python36\lib\unittest\mock.py", line 1179, in patched return func(*args, **keywargs) File "tests.py", line 30, in test_foobar_mocked_another self.assertEqual(foobar(), 'mocked') A…
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/13112302
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/49642672
downvote count: 0
tagged with: templates
tagged with: jinja2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49642739
upvote count: 2
has body: I'm using jinja2 to render string. I have a filter named 'get_user_by_id' and other similar filters. I want to rename the filter expression value with a simple variable name. The follow is what I want: {% rename 1|get_user_by_id, 'user'%} {{user.name}} {{user.email}} ... {% rename 5|get_book_by_id, 'book'%} {{book.name}} {{book.price}} ... How can I write the "rename" tag extension with jinja2?
has title: Jinja2 how to rename a expression value
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49642739
answer count: 1

http://stackoverflow.com/comment/86379932
has text: You are welcome. I'm going to have to invent a reason for me to learn more about dask.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49681644
type: AnswerComment

http://stackoverflow.com/a/49732876
accepted answer of: http://stackoverflow.com/q/49732748
score: 1
has body: In case 1 and 2, no lists are being hashed. The list is iterated, and it's elements are hashed. The hashed elements aren't lists, and are otherwise hashable, so it's fine. In case 3 though, the outer list is iterated like before, but each element of the list is another list, which are attempted to be hashed. As you know, that won't end well.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49732748

http://stackoverflow.com/q/49620100
downvote count: 0
tagged with: machine-learning
has body: So I already browsed all the similar questions I found in StackOverflow and unfortunately none of them did it for me. I have a Pipeline that is combining unions and using function transformers get_text_data= FunctionTransformer(return_text, validate=False) get_categorical_data= FunctionTransformer(func=return_categorical, kw_args=dict(columns=categoricalFeatures), validate=False) vectorizer = TfidfVectorizer(strip_accents='ascii',tokenizer=tokenize, min_df=2,stop_words ='english',ngram_range=(1, 2))# clf=svm.SVC(kernel='linear',cache_size=10000, C=1.3)#86.6 with extra text =( # Instantiate Pipeline object: pl pipeline = Pipeline([ ('union', FeatureUnion( transformer_list = [ ('discrete_features', Pipeline([ ('selector', get_categorical_data) ])), ('text_features', Pipeline([ ('selector', get_text_data), ('vectorizer', vectorizer)])) ] )), ('clf', clf) ]) pipeline.fit(x,y) pickleModel(pipeline,'pl_4_2_2018_TS_caseType') By the way, if I don't alias dill as pickle, I get an error saying "I can't pickle lambda objects" After this is pickled, i call the same pipeline and feed it new data pl = loadModel(pipeline_name) all_nonDUDLpredictions=pl.predict(x) This fails however telling me that in _convert_t_indexer raise KeyError ('% is not in index' % objarr[mask]') KeyError: [List of all the categorical features] not in Index I can run the pipeline when I train it and get an accuracy so that seems to work but for some reason I can't feed it new data if I pickle it Any help will be appreciated Thanks
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86247289
has comment: http://stackoverflow.com/comment/86247231
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86288098
has comment: http://stackoverflow.com/comment/86290649
tagged with: python
has comment: http://stackoverflow.com/comment/86286611
has title: How to pickle a Sklearn pipeline with text and non-text features?
answer count: 0
has comment: http://stackoverflow.com/comment/86247264
score: 2
has comment: http://stackoverflow.com/comment/86414409
has comment: http://stackoverflow.com/comment/86247144
upvote count: 2
has comment: http://stackoverflow.com/comment/86247239
type: UnansweredQuestion

http://stackoverflow.com/comment/86321727
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49656072
score: 0
has text: But will it use as much memory?

http://stackoverflow.com/a/50007069
score: 9
has body: You can use keyboard module which you can install using pip with command python -m pip install keyboard. Following code will press the enter key: from keyboard import press press('enter')
downvote count: 0
upvote count: 9
answers question: http://stackoverflow.com/q/49689748
type: Answer

http://stackoverflow.com/comment/86332131
comment on: http://stackoverflow.com/q/49661089
type: Comment
type: QuestionComment
has text: True, @JonathanR my comment wasn't right.
score: 0

qfilesystemmodel
tag name: qfilesystemmodel
tags question: http://stackoverflow.com/q/49718552
type: Tag
tags question: http://stackoverflow.com/q/49617149

http://stackoverflow.com/comment/86314722
type: QuestionComment
comment on: http://stackoverflow.com/q/49627084
score: 0
has text: Filed an issue for the same: https://github.com/pandas-dev/pandas/issues/20608
type: Comment

http://stackoverflow.com/comment/86376079
type: Comment
comment on: http://stackoverflow.com/a/49682067
type: AnswerComment
has text: @Simon `a = b'r'\xb9\xfe''` doesn't looks like a right syntax to me after your edit
score: 1

http://stackoverflow.com/comment/86460987
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49722955
has text: @JamesKPolk I need to delete old bytes because I can receive a big number of messages. If I don't delete them, I will literally have a StackOverflow ;)
score: 0

http://stackoverflow.com/comment/86253481
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49623250
has text: Similarly, `find_elements` returns a list of elements. Lists don't know how to `send_keys` either. And again, it's hard to guess what you might have been expecting that to do.

http://stackoverflow.com/comment/86408738
has text: Is it ok to read in the entire file and then slice the data frame so that you only keep the rows with certain date values? Or is there a reason (perhaps the file is extremely large or you need to do the extremely quickly) that you want to only read certain lines?
score: 0
comment on: http://stackoverflow.com/q/49697699
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49701687
answers question: http://stackoverflow.com/q/49701481
downvote count: 0
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86417096
has body: You only want to append "1" once, so that part shouldn't be in a loop. if vlan in vlan_list: print "Vlan " + vlan + " is already in use, creating new vlan ..." vlan = vlan + "1" print "Vlan chosen is: " + vlan while vlan in vlan_list: print "Vlan " + vlan + " is already in use, creating new vlan ..." vlan = str(int(vlan) + 1) print "Vlan chosen is: " + vlan
accepted answer of: http://stackoverflow.com/q/49701481

http://stackoverflow.com/q/49642982
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/56993118
favorite count: 0
type: Question
upvote count: 8
answer count: 3
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/53990757
has title: ValueError: Cannot serialize function: lambda while using makemigrations
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49643232
has body: When I do python manage.py makemigrations, i get above error and I am unsure where the error is happening. I saw some post regarding this issue but i find mainly in DateTimeField() where the function was passed but in my case I have used auto_now attribute instead of some datetime related function. However, I have used lambda function in the class method as follow. @classmethod def get_content_models(cls): """ Return all Package subclasses. """ is_content_model = lambda m: m is not Package and issubclass(m, Package) def set_helpers(self, context): current_package_id = getattr(current_package, "id", None) current_parent_id = getattr(current_package, "parent_id", None) self.is_current_child = self.parent_id == current_package_id self.is_child = self.is_current_child def is_c_or_a(package_id): parent_id = context.get("_parent_package_ids", {}).get(package_id) return self.id == package_id or (parent_id and is_c_or_a(parent_id)) self.is_current_or_ascendant = lambda: bool(is_c_or_a(current_package_id)) I am not clear on this issue, So i have posted for understanding the cause. Is above code creating that issue? If it is the cause, what should be done instead? I don't know where exactly this issue lies in the models so here is the detail of models.py of package app in gist because the code is a bit huge . It is not reached to booking models so I am only putting the code of package app and here it is https://gist.github.com/SanskarSans/51d2f287309a97163e680cc38abd3e06 UPDATE In my Package models, I have used the custom field and in that field there was the use of lambda instead of callable function and that was creating an issue. Due to the long file of models, I did not paste it here, I apologize for that. Here what I had done in_menus = MenusField(_("Show in menus"), blank=True, null=True) class MenusField(MultiChoiceField): """ ``MultiChoiceField`` for specifying which menus a package should appear in. """ def __init__(self, *args, **kwargs): choices = [t[:2] for t in g…
score: 8
type: UnansweredQuestion

http://stackoverflow.com/comment/86421369
type: AnswerComment
has text: Thank you! I had literally just figured it out maybe about 5 minutes ago! Thank you so much for your input though. Now I won't forget how to do this. haha
comment on: http://stackoverflow.com/a/49704033
score: 0
type: Comment

http://stackoverflow.com/q/49675663
tagged with: python
has title: datas' session not well managed with pyramid_beaker
answer count: 2
tagged with: cookies
score: 1
downvote count: 0
has body: I have the following codes, I'm using pyramid_beaker + gunicorn + pyramid_jinja2. I noticed that when user is logged in, if I quickly and repeatedly do a "GET" to "http://my_server_ip_adress/addClientPersonne", I got many times a permission deny as if the logged user doesn't have "add_client" permission which is not normal. When making a "print session" I can see that sometimes the session has all the authentications informations to allow user to access the link above but another time it doesn't and the access is deny...maybe my configurations about pyramid_beaker are not good? any suggestions? thanks. my production.ini file [app:main] use = egg:annuaireldap#main pyramid.includes = pyramid_beaker pyramid_jinja2 session.key = annuaireldap session.secret = iuyryoiuiytghvfs-tifrsztft session.cookie_on_exception = true session.type = memory my views.py @view_config(route_name="Menu", renderer='templates/menu.jinja2', request_method='GET') def menu(request): bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css') bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js') jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js') custom_css_url = request.static_url('annuaireldap:static/custom_css.css') to_rend = {'bootstrap_css':bootstrap_css_url,'bootstrap_js':bootstrap_js_url,'jquery_js':jquery_js_url,'custom_css':custom_css_url} to_rend.update({'Menu_1':request.route_url('addClientPersonne'), 'Menu_2':request.route_url('addClientEntreprise'), 'Menu_3':request.route_url('SeeAll')}) return to_rend @view_config(route_name='SeeAll', renderer='templates/menu.jinja2', request_method=('GET', 'POST')) def seeall(request): return {} @view_config(route_name='login', renderer='templates/login.jinja2', request_method=('GET', 'POST')) def login(request): bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css') bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js') jquery_js_url = r…
has answer: http://stackoverflow.com/a/54528528
upvote count: 1
has answer: http://stackoverflow.com/a/49695150
favorite count: 0
type: Question
tagged with: beaker
tagged with: pyramid
type: UnansweredQuestion
tagged with: session

http://stackoverflow.com/q/49737909
has title: FLAC conversion utility not available - consider installing the FLAC command line application
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/74836997
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/49738186
type: UnansweredQuestion
downvote count: 2
has body: I am making a simple speech_recognition program in python3.6.3 here is the python code: import speech_recognition as sr import os r = sr.Recognizer() r.energy_threshold = 10000 with sr.Microphone() as source: print('Say something') audio = r.listen(source) print("Done") try: text = r.recognize_google(audio) print(text) os.system("say '"+'I think you said,'+text+'!'+"'") except Exception as e: print(e) When I run it I get this error: OSError:FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac or your operating system's equivalent The surprising thing is I already have flac installed using brew. And I checked the flac installation using the terminal like this: $which flac /usr/local/bin/flac this shows that flac is installed but no still being recognized. I will be my pleasure to have some help with this.
has answer: http://stackoverflow.com/a/75571505
has answer: http://stackoverflow.com/a/49776318
tagged with: speech-recognition
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/75766915

http://stackoverflow.com/q/49644779
has body: As in the Django documentation By default, Django adds a Manager with the name objects to every Django model class How does Django add an attribute to model classes? Whether it is inherited from the models.Model or Django add objects=models.Manager() dynamically to each model?
favorite count: 0
type: Question
tagged with: django-managers
has answer: http://stackoverflow.com/a/49652038
has comment: http://stackoverflow.com/comment/86301719
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49652038
has comment: http://stackoverflow.com/comment/86297435
tagged with: django-queryset
has title: How django add objects attribute to model classes?
downvote count: 0
answer count: 1
tagged with: django-models
score: 1

http://stackoverflow.com/q/49656343
has comment: http://stackoverflow.com/comment/86328137
has answer: http://stackoverflow.com/a/49678940
downvote count: 1
has comment: http://stackoverflow.com/comment/86326983
favorite count: 0
has comment: http://stackoverflow.com/comment/86327998
score: 0
has comment: http://stackoverflow.com/comment/86343292
has title: Black screen on game launch
has comment: http://stackoverflow.com/comment/86328095
has comment: http://stackoverflow.com/comment/86342852
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/86327911
has comment: http://stackoverflow.com/comment/86343085
has comment: http://stackoverflow.com/comment/86342768
has comment: http://stackoverflow.com/comment/86328049
type: Question
has comment: http://stackoverflow.com/comment/86343229
has comment: http://stackoverflow.com/comment/86328013
has body: I'm trying to start a game when I click on "start game". Menu screen is removed and game launches (I can hear the sounds and then being killed by an enemy) but can't see a thing. All I get is a black screen. It's like the game is launched in the background. What am I doing wrong ? updated kv file: &lt;Game_Screen&gt;: name: 'game_screen' on_enter: app.launch_game() &lt;Game_Menu&gt;: FloatLayout: pos_hint: {'center_x': 0.5, 'center_y': 0.5} size_hint: None, None canvas.before: Color: rgba: 1, 0, 0, 1 Rectangle: pos: self.pos size: self.size Label: text: 'SPACE SHOOTER' font_size: 40 font_name: "fonts/Alexis Italic.ttf" color: 0, 1, 0, 1 pos_hint: {'center_x': 0.5, 'center_y': 1.7} BoxLayout: canvas.before: Rectangle: pos: self.pos size: self.size size: self.parent.size pos: self.parent.pos orientation: 'vertical' Label: text: 'menu' font_name: "fonts/Alexis Bold.ttf" font_size: 30 color: 0, 1, 0, 1 Button: text: 'start game' on_press: app.root.current = 'game_screen' Button: text: 'highest score' on_release: Button: text: 'credits' on_release: app.root.current = 'credits' updated Python code: class Game(Widget): # works fine on its own class Game_Menu(Screen): pass class Game_Screen(Screen): pass class Menu_UI(Widget): pass class Credits_Screen(Screen): pass class GameApp(App): sm = ScreenManager() sm.add_widget(Game_Menu(name='menu')) sm.add_widget(Credits_Screen(name='credits')) sm.add_widget(Game_Screen(name='game_screen')) def launch_game(self): game = Game() Window.size = game.size engines1.loop = True engines1.play() return game def build(self): return self.sm if __name__ == '__main__': GameApp().run()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86344199
answer count: 1
has comment: http://stackoverflow.com/comment/86328460
has comment: http://stackoverflow.com/comment/86342947
upvote count: 1

http://stackoverflow.com/a/49677781
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49677717
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86481709
answers question: http://stackoverflow.com/q/49677717
type: Answer
has body: Try using melt: df.melt(id_vars='Date', var_name='Stock Name', value_name='Return') Output: Date Stock Name Return 0 11-30-86 Stock 1 2.45000 1 12-31-86 Stock 1 -2.57000 2 01-31-87 Stock 1 13.50000 3 02-28-87 Stock 1 3.99000 4 11-30-86 Stock 2 0.47021 5 12-31-86 Stock 2 1.09626 6 01-31-87 Stock 2 9.33911 7 02-28-87 Stock 2 4.63777 8 11-30-86 Stock 3 1.45879 9 12-31-86 Stock 3 -2.67784 10 01-31-87 Stock 3 11.14448 11 02-28-87 Stock 3 5.96181

http://stackoverflow.com/q/49657263
has comment: http://stackoverflow.com/comment/86324149
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49657757
has answer: http://stackoverflow.com/a/49657988
answer count: 2
upvote count: 0
has body: I need to read in the scores from a file of students quizzes, and return the highest score out of the 3 attempts.I need to use hash/dictionary in python. Here is what I have so far. STD_ID = {} ATTEMPTS = {} SCORE= {} f= open("std_attempt_score.txt", "r") line = f.readline() for line in f: line = line.rstrip() ents = line.split("\t") did = ents[1] if did in STD_ID: ATTEMPTS[did] += 3 SCORE[did] += int(ents[2]) else: STD_ID[did] = ents[2] ATTEMPTS[did] = 3 SCORE[did] = int(ents[2]) for key in STD_ID: print("Avg score for Student", key, "=",SCORE) Text data in file. FILE STD_ID ATT_NUM SCORE S23Y 1 85 S03X 1 80 S34Z 1 19 S54M 1 23 S34Z 2 25 S01X 1 79 S03X 2 10 S23Y 2 09 S34Z 3 92 S54M 2 96 S23Y 3 74 S54M 3 65 S03X 3 54 My results are as follows: Avg score for Student 1 = {'1': 286, '2': 140, '3': 285} Avg score for Student 2 = {'1': 286, '2': 140, '3': 285} Avg score for Student 3 = {'1': 286, '2': 140, '3': 285}
has comment: http://stackoverflow.com/comment/86323971
downvote count: 2
has comment: http://stackoverflow.com/comment/86324265
has comment: http://stackoverflow.com/comment/86323536
favorite count: 0
type: Question
has title: Take Average of Quiz data using python ( Troubleshooting)
has comment: http://stackoverflow.com/comment/86324398

http://stackoverflow.com/a/49697168
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49697045
has body: Since version 0.15.0 of pandas, you can use the .dt accessor in order to get the date (and ignore the time) which will return datetime.date dtype df['dates_without_time'] = df['datetime'].dt.date

http://stackoverflow.com/a/49756522
accepted answer of: http://stackoverflow.com/q/49756355
type: Answer
answers question: http://stackoverflow.com/q/49756355
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Add the dataframes to a list and concatenate them back later. df_list = [] df_list.append(df['coord']) pd.concat(df_list, ignore_index=True, axis=1)
score: 2

http://stackoverflow.com/comment/86325601
score: 0
type: Comment
type: QuestionComment
has text: Can you provide a description of the dataset? e.g. `print(ds1)`. Better yet would be a Minimal, Complete, and Verifiable example (https://stackoverflow.com/help/mcve) that doesn't require downloading your dataset.
comment on: http://stackoverflow.com/q/49656909

http://stackoverflow.com/a/49650284
score: 0
answers question: http://stackoverflow.com/q/49638219
has body: I'm Closed The Parantheses and Its Worked Thanks For Help Artemis Fowl and Todd W def Corner(n): if n == 3: print('İts An Triangle \nBu Bir Üçgen') elif n == 4: print('İts An Rectangle or Square or Parrallelogram \nBu Bir Dikdörtgen yada Kare yada ParalelKenar') elif n == 5: print('İts An Pentagon \nBu Bir Beşgen') elif n == 6: print('İts An Hexagon \nBu Bir Altıgen') else: print('Bir Köşe Sayısı Girmediniz \nYou Didnt Wrote a Corner Number') print(Corner(6))
type: Answer

http://stackoverflow.com/q/49676893
tagged with: pandas
score: 1
tagged with: python
tagged with: dictionary
has body: I have a dictionary with 3 keys which correspond to field names in a SQL Server table. The values of these keys come from an excel file and I store this dictionary in a dataframe which I now need to insert into a SQL table. This can all be seen in the code below: import pandas as pd import pymssql df=[] fp = "file path" data = pd.read_excel(fp,sheetname ="CRM View" ) row_date = data.loc[3, ] row_sita = "ABZPD" row_event = data.iloc[12, :] df = pd.DataFrame({'date': row_date, 'sita': row_sita, 'event': row_event }, index=None) df = df[4:] df = df.fillna("") print(df) My question is how do I insert this dictionary into a SQL table now? Also, as a side note, this code is part of a loop which needs to go through several excel files one by one, insert the data into dictionary then into SQL then delete the data in the dictionary and start again with the next excel file.
has comment: http://stackoverflow.com/comment/86365091
type: Question
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53017377
has title: How do I insert my Python dictionary into my SQL Server database table?
has answer: http://stackoverflow.com/a/49677101
favorite count: 0
has comment: http://stackoverflow.com/comment/86365333
tagged with: sql-server

http://stackoverflow.com/comment/133002249
comment on: http://stackoverflow.com/a/49685031
type: Comment
type: AnswerComment
has text: Careful, the first solution will output empty columns as `NA` floats rather than `str` despite explicit `dtype=str`. Adding `keep_default_na=False` fixes this, so that everything is _really_ read in as str first.
score: 3

http://stackoverflow.com/comment/86249723
comment on: http://stackoverflow.com/a/49621259
has text: @ Stephen, now I'd like to connect the number 'v for v in answers.values() if len(v) == 1' with its corresponding ndlist value. How can I do that? For example, 14 and 30 in the previous list.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86439023
type: QuestionComment
score: 0
type: Comment
has text: I think it is [this well-known problem of mplot3d.](https://matplotlib.org/mpl_toolkits/mplot3d/faq.html) They suggest using [Mayavi.](http://code.enthought.com/pages/mayavi-project.html)
comment on: http://stackoverflow.com/q/49712546

http://stackoverflow.com/comment/104447944
has text: _Great_ answer. Seems like there's an idea that you must always use `communicate()` when using `PIPE`, which as you point out isn't the case. The docs aren't actually wrong, in that the read line loop prevents _and the child process generates enough output to a pipe such that it blocks..._.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49728599

http://stackoverflow.com/comment/86505325
comment on: http://stackoverflow.com/q/49744750
has text: You should think of split-apply-combine. Split the data, calculate the average and subsequent subtraction and then join it back to form the required DataFrame.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/65127317
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49737354
has body: I used Prometheus_flask_exporter to do that. My gunicorn config file was like this- from prometheus_flask_exporter.multiprocess import GunicornPrometheusMetrics hostname = "0.0.0.0" portname = 8080 def when_ready(server): GunicornPrometheusMetrics.start_http_server_when_ready(8000) def child_exit(server, worker): GunicornPrometheusMetrics.mark_process_dead_on_child_exit(worker.pid) The wsgi file included- from prometheus_flask_exporter import PrometheusMetrics # an extension targeted at Gunicorn deployments for prometheus scraping in flask applications from prometheus_flask_exporter.multiprocess import GunicornPrometheusMetrics application = Flask(__name__, static_url_path='') CORS(application) health = HealthCheck(application, "/healthcheck") metrics = PrometheusMetrics(application) metrics = GunicornPrometheusMetrics(application)
score: 1

http://stackoverflow.com/q/49734446
tagged with: random-forest
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86483198
has body: I can't succeed to evaluate the performance of my model which is a random forest classifier. Please can someone help me to find the right code. depth1 = np.arange(1, 30) estimators1 = np.arange(1, 100) score = [] for depth in depth1: for estimators in estimators1: forest = RandomForestClassifier(n_estimators=estimators, max_depth=depth) forest.fit(X_train, y_train) score.append(forest.score(X_train, y_train)) print("Best depth for {} estimators:{}.".format(estimators1[np.argmax(score)], depth1[np.argmax(score)]))&lt;/i&gt;
has comment: http://stackoverflow.com/comment/86524829
type: Question
tagged with: model
has title: Random Forest Classifier testing the accuracy of the model in Python
has comment: http://stackoverflow.com/comment/86483374
has comment: http://stackoverflow.com/comment/86483016

http://stackoverflow.com/a/49620192
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/117244121
has comment: http://stackoverflow.com/comment/117235190
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49620011
has body: You get the curly braces because you are giving tkinter a tuple. The curly braces are the internal tcl interpreter's method of rendering lists. You should explicitly convert your data to a string to get rid of the curly braces. For example: bouttons_annuler[...].config(text = ' '.join(("Vend", action_corr_numero_ventes_loc, ...))) Of course, you don't have to use join. You can format the data however you want. If you give tkinter a tuple or list, though, you're at the mercy of it deciding how to represent your data.

inheritance
tags question: http://stackoverflow.com/q/49616600
tags question: http://stackoverflow.com/q/49610464
tags question: http://stackoverflow.com/q/49747632
tags question: http://stackoverflow.com/q/49713670
tag name: inheritance
tags question: http://stackoverflow.com/q/49733995
tags question: http://stackoverflow.com/q/49749695
tags question: http://stackoverflow.com/q/49633893
type: Tag
tags question: http://stackoverflow.com/q/49603052

http://stackoverflow.com/q/49724324
type: Question
has comment: http://stackoverflow.com/comment/86463269
has title: Create multiple, new columns from dict values by mapping against a single column
downvote count: 1
tagged with: python
has body: This question is related to posts on creating a new column by mapping/lookup using a dictionary. (Adding a new pandas column with mapped value from a dictionary and pandas - add new column to dataframe from dictionary). However, what if I want to create, multiple new columns with dictionary values. For argument's sake, let's say I have the following df: country 0 bolivia 1 canada 2 ghana And in a different dataframe, I have country mappings: country country_id category color 0 canada 11 north red 1 bolivia 12 central blue 2 ghana 13 south green I've been using pd.merge to merge the the mapping dataframe to my df using country and another index as keys it basically does the job, which gives me my desired output: country country_id category color 0 bolivia 12 central blue 1 canada 11 north red 2 ghana 13 south green But, lately, I've been wanting to experiment with using dictionaries. I suppose a related question is how does one determine to use pd.merge or dictionaries to accomplish my task. For one-off columns that I'll map, I'll create a new column by mapping to a dictionary: country_dict = dict(zip(country, country_id)) df['country_id'] = df['country'].map(entity_dict) It seems impractical to define a function that takes in different dictionaries and to create each new column separately (e.g., dict(zip(key, value1)), dict(zip(key, value2))). I'm stuck on how to proceed in creating multiple columns at the same time. I started over, and tried creating the country mapping excel worksheet as a dictionary: entity_dict = entity.set_index('country').T.to_dict('list') and then from there, converting the dict values to columns: entity_mapping = pd.DataFrame.from_dict(entity_dict, orient = 'index') entity_mapping.columns = ['col1', 'col2', 'col3'] And I've been stuck going around in circles for the past few days. Any help/feedback would be appreciated!
tagged with: dictionary
linked to: http://stackoverflow.com/q/24216425
has answer: http://stackoverflow.com/a/49786116
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49786116
score: 0
has comment: http://stackoverflow.com/comment/86477812
tagged with: mapping
tagged with: pandas
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/29794959
favorite count: 0

http://stackoverflow.com/comment/86445417
type: Comment
comment on: http://stackoverflow.com/q/49716046
type: QuestionComment
score: 0
has text: A dict of dicts

http://stackoverflow.com/q/49749808
accepted answer: http://stackoverflow.com/a/49749872
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49749872
possible better answer: http://stackoverflow.com/a/49750223
answer count: 2
has body: I am using python 2.7, 32 bit on windows 10, 64 bit. Whenever I try to install psychopy module by doing pip install psychopy, I am getting below mentioned error. I am not able to understand what is the problem. I have also made changes in environmental variable to set anconda bin and anaconda scripts as highest priority. I am running same program for last 8 months and never got any kind of problem. I am trying to install everything in new PC and getting this kind of error in my old and new PC. How can fix this problem? Exception: Traceback (most recent call last): File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\users\ravikumar.mevada\anaconda2\lib\site-packages\pip\wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "c:\users\ravikumar.mevada\anaconda2\lib\shutil.py", line 97, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: 'c:\\users\\ravikumar.mevada\\anaconda2\\Lib\\site-packages\\win32\\win32api.pyd'
score: 0
has comment: http://stackoverflow.com/comment/86562907
has title: IOError:[Error 13]: Permission denide: 'c:\\users\\ravikumar.mevada\\anaconda2\\Lib\\site-packages\\win32\\win32api.pyd'
tagged with: pip
tagged with: psychopy
type: Question
has answer: http://stackoverflow.com/a/49750223
tagged with: spyder
tagged with: python

http://stackoverflow.com/comment/137964339
type: QuestionComment
has text: Interesting that your graph is missing the tick label for 5 x 10^1. I have the same issue and came here from Google when I searched for it.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49750107

http://stackoverflow.com/comment/86337718
type: QuestionComment
has text: perhaps you wanna add some more info, like how your generator is yielding your data into your `fit_generator`. Keep in mind that what you've written is **NOT** a generator, but a `fit_generator` which enables a model to train on continuously in-flowing data
comment on: http://stackoverflow.com/q/49663506
score: 0
type: Comment

http://stackoverflow.com/a/49745423
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49743901
answers question: http://stackoverflow.com/q/49743901
has comment: http://stackoverflow.com/comment/86551732
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86542564
type: AcceptedAnswer
downvote count: 0
has body: Look for example: https://matplotlib.org/gallery/mplot3d/2dcollections3d.html from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') # Plot a sin curve using the x and y axes. x = np.linspace(0, 1, 100) y = np.sin(x * 2 * np.pi) / 2 + 0.5 ax.plot(x, y, zs=0, zdir='z', label='curve in (x,y)') # Plot scatterplot data (20 2D points per colour) on the x and z axes. colors = ('r', 'g', 'b', 'k') # Fixing random state for reproducibility np.random.seed(19680801) x = np.random.sample(20 * len(colors)) y = np.random.sample(20 * len(colors)) c_list = [] for c in colors: c_list.extend([c] * 20) # By using zdir='y', the y value of these points is fixed to the zs value 0 # and the (x,y) points are plotted on the x and z axes. ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x,z)') # Make legend, set axes limits and labels ax.legend() ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_zlim(0, 1) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') # Customize the view angle so it's easier to see that the scatter points lie # on the plane y=0 ax.view_init(elev=20., azim=-35) plt.show()

http://stackoverflow.com/comment/86258042
comment on: http://stackoverflow.com/a/49625470
score: 1
type: Comment
has text: fyi, list-comps (`[ ... ]`) are just syntactic sugar for `list()` called on a generator. So it is fine to use `list()` as long as you use a generator inside, not a list comp as otherwise you are calling `list(list())`. However it is more Pythonic to use list-comps
type: AnswerComment

http://stackoverflow.com/comment/86241720
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49617178
has text: It seems you could parse the different parts of docx and then use the Json module to build your customized format. Nothing ready to use, sadly

http://stackoverflow.com/q/49715050
type: UnansweredQuestion
has title: Flask, Python: Trouble getting data from drop down menu to display on return render template
has body: I'm having trouble getting the values/results from the drop down menu to display on my results page. The value in the input box for name displays fine but when I try to display the values from the drop down menu, it errors out. Let me know if you have a solution. Thank you! python, flask: from flask import Flask , render_template, redirect, request app = Flask(__name__) @app.route('/') def main(): return render_template('index.html') @app.route('/results', methods= ['GET','POST']) def next(): name = request.form['Name'] city = request.form.get['city1','city2','city3'] print(name, city) return render_template('results.html', name=name, city = city) if __name__=="__main__": app.run(debug=True) html: Your Name: San Jose Seattle LA
upvote count: 1
tagged with: python
tagged with: flask
downvote count: 1
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86443266
favorite count: 0
has answer: http://stackoverflow.com/a/49715189
type: Question

http://stackoverflow.com/comment/86490214
comment on: http://stackoverflow.com/a/49737650
type: Comment
has text: Thanks for your answer, it makes sense. I am trying to update my dataframe using " k = """ update df_event set Date = REPLACE(Date, '/', '-') """ ((pandasql.sqldf(k, locals())))" " but it says 'no such table: df_event' when there clearly is because it does execute for the query q.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86547241
type: Comment
score: 0
type: AnswerComment
has text: You right!! Thank you, now it is working, I am sorry for this mistake.
comment on: http://stackoverflow.com/a/49741801

http://stackoverflow.com/comment/86458561
type: QuestionComment
has text: Try: `df[df.notnull().all(1)]`
comment on: http://stackoverflow.com/q/49722520
score: 0
type: Comment

http://stackoverflow.com/comment/86292771
has text: @efirvida hello the code is for merge sort, it takes the list A and arranges it in ascending order
comment on: http://stackoverflow.com/q/49636819
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86481492
type: AnswerComment
has text: @DeltaIV: you are right, a generic solution is better than a specific one. But your OP doesn't give us any info on the variation in the filenames you may encounter. Even the split approach is undefined : should we split on the last underscore ? on the second last underscore ? or something else ? As long as you give no details on your data, people can only provide solutions that work on your example...
comment on: http://stackoverflow.com/a/49733450
type: Comment
score: 0

http://stackoverflow.com/q/49757912
type: Question
has body: How to browse HDFS File-system from an UI like Hue does using python? I want to list hdfs files from simple html UI
type: UnansweredQuestion
tagged with: hdfs
tagged with: python
has answer: http://stackoverflow.com/a/49758107
score: 0
has title: Browsing Hdfs Filesystem from UI
answer count: 1

http://stackoverflow.com/comment/86248666
score: 1
has text: Is there a reason you'd want to terminate the first one and not any subsequent ones?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49620862

http://stackoverflow.com/q/49664523
tagged with: tensorflow
favorite count: 0
has body: I have two sets of points, one is a map consisting of x,y coordinates, and the second is a path of x,y coordinates. I'm trying to find the closest map points to my path points, pretty simple. Except my map is 380000 points and my paths (of which I have several) each consist of ~ 350000 points themselves. Other than sampling my data to get smaller datasets, I'm trying to find a faster way to accomplish this task. base algorithm: import pandas as pd from scipy.spatial.distance import cdist ... def closeset_point(point, points): return points[cdist([point], points).argmin()] # log['point'].shape; 333000 # map_data['point'].shape; 380000 closest = [closest_point(log_p, list(map_data['point'])) for log_p in log['point']] as per this example: Find closest point in Pandas DataFrames After converting this to a tqdm progress bar to see how long it would take (as it was taking a while, obviously), I noticed it would take about 10hrs to complete. tqdm loop: for i in trange(len(log), desc='finding closest points'): closest.append(closest_point(log['point'].loc[i], list(map_data['point']))) &gt;&gt; finding closest points: 5%| | 16432/333456 [32:11&lt;10:13:52], 8.60it/s While 10 hours is not impossible, I wonder if there is a way to speed this up? I have a solid gpu/cpu/ram at my disposal so I feel this should be doable. I'm also learning tensorflow (but honestly my math is atrocious so I'm very in the dark with it) Any ideas on how to speed this up with either multi-threading, gpu computation, tensorflow or some other sort of wizardry? inb4 python is slow ;) *edit: image shows what i'm trying to do. green is path, blue is map, orange is what I'm trying to find.
type: Question
tagged with: performance
has title: How can I speed up closest point comparison using cdist or tensorflow?
has comment: http://stackoverflow.com/comment/86340327
linked to: http://stackoverflow.com/q/38965720
accepted answer: http://stackoverflow.com/a/49668372
tagged with: python
has answer: http://stackoverflow.com/a/70964944
possible better answer: http://stackoverflow.com/a/70964944
has comment: http://stackoverflow.com/comment/86341134
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86344753
answer count: 2
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49668372

http://stackoverflow.com/comment/86627602
comment on: http://stackoverflow.com/a/49641301
has text: YES! Thanks a million!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49735850
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86491711
accepted answer of: http://stackoverflow.com/q/49727716
score: 3
answers question: http://stackoverflow.com/q/49727716
type: Answer
has body: From the W3C specification: The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument. This means that p:not(.ignore p) is not supported. Now the reason it's working in the console is because the shorthand $ is overwritten by the page with JQuery which supports a different syntax. Since Selenium rely on the CSS selector from the browser (same as document.querySelector) and not from JQuery, the exception in this case is to be expected. Note that you'll get the exception in the console by either executing document.querySelector('p:not(.ignore p)') or $('p:not(.ignore p)') in a blank page (about:blank). If you wish to use a JQuery selector, then use a JavaScript injection: elms = driver.execute_script("return $('p:not(.ignore p)')")
upvote count: 3

http://stackoverflow.com/a/49730186
has body: I typed which python in terminal and I changed the directory in the Python Interpreter settings
accepted answer of: http://stackoverflow.com/q/49728251
answers question: http://stackoverflow.com/q/49728251
type: Answer
score: 0
type: AcceptedAnswer

matrix
tags question: http://stackoverflow.com/q/49753477
tags question: http://stackoverflow.com/q/49673654
tag name: matrix
tags question: http://stackoverflow.com/q/49756995
tags question: http://stackoverflow.com/q/49720657
tags question: http://stackoverflow.com/q/49639038
tags question: http://stackoverflow.com/q/49617130
tags question: http://stackoverflow.com/q/49743824
tags question: http://stackoverflow.com/q/49729175
tags question: http://stackoverflow.com/q/49684310
tags question: http://stackoverflow.com/q/49717999
tags question: http://stackoverflow.com/q/49671754
type: Tag
tags question: http://stackoverflow.com/q/49658872
tags question: http://stackoverflow.com/q/49633303

http://stackoverflow.com/comment/86623249
comment on: http://stackoverflow.com/q/49753793
type: Comment
type: QuestionComment
has text: TensorFlow may pin some memory, especially variables, for more efficient copies. You can set the environmental variable `TF_CUDA_HOST_MEM_LIMIT_IN_MB`, but likely it'll just get you an error. AFAIK there's no way to tell it to pin less memory, just more with [`force_gpu_compatible`](https://github.com/tensorflow/tensorflow/blob/eaaee5d7aa5df8157c4128568a8f7703458723cd/tensorflow/core/protobuf/config.proto#L73). You could file a feature request for less pinning.
score: 1

pymongo
tags question: http://stackoverflow.com/q/49724882
tags question: http://stackoverflow.com/q/49701351
tags question: http://stackoverflow.com/q/49743662
tags question: http://stackoverflow.com/q/49716646
tags question: http://stackoverflow.com/q/49626941
tags question: http://stackoverflow.com/q/49650320
tags question: http://stackoverflow.com/q/49694585
tags question: http://stackoverflow.com/q/49629011
tags question: http://stackoverflow.com/q/49617127
tags question: http://stackoverflow.com/q/49672083
type: Tag
tag name: pymongo
tags question: http://stackoverflow.com/q/49714006
tags question: http://stackoverflow.com/q/49622511
tags question: http://stackoverflow.com/q/49658725
tags question: http://stackoverflow.com/q/49647759
tags question: http://stackoverflow.com/q/49631163
tags question: http://stackoverflow.com/q/49658679
tags question: http://stackoverflow.com/q/49731562

http://stackoverflow.com/q/49742651
has comment: http://stackoverflow.com/comment/86500423
tagged with: python
has title: pytesseract AttributeError: 'NoneType' object has no attribute 'loader'
tagged with: tesseract
tagged with: python-3.4
score: 0
has comment: http://stackoverflow.com/comment/86500131
tagged with: python-tesseract
answer count: 0
has comment: http://stackoverflow.com/comment/86499981
type: Question
tagged with: python-3.x
has body: I have just installed pytesseract and trying to import it into my python file. My code (here is the site I am referring to): from PIL import Image import pytesseract import argparse import cv2 import os Here is the complete error traceback: Traceback (most recent call last): File "C:/Users/ROCKSTAR/Downloads/TRIVIA/getAnswers.py", line 6, in &lt;module&gt; import pytesseract File "C:\Python34\lib\site-packages\pytesseract\__init__.py", line 1, in &lt;module&gt; from .pytesseract import ( File "C:\Python34\lib\site-packages\pytesseract\pytesseract.py", line 21, in &lt;module&gt; numpy_installed = True if find_loader('numpy') is not None else False File "C:\Python34\Lib\pkgutil.py", line 488, in find_loader return spec.loader AttributeError: 'NoneType' object has no attribute 'loader' Process finished with exit code 1
type: UnansweredQuestion

http://stackoverflow.com/a/49639289
type: Answer
has comment: http://stackoverflow.com/comment/86287688
has comment: http://stackoverflow.com/comment/86289076
answers question: http://stackoverflow.com/q/49639242
has comment: http://stackoverflow.com/comment/86288959
has comment: http://stackoverflow.com/comment/86288987
has body: dictionaries are unordered (well pre 3.6 at least), instead sort the items d = {3: '__init__', 5: 'other', 7: 'hey ', 11: 'hey'} print(sorted(d.items(),key=lambda item:(item[0].strip(),item[1]))) # output =&gt; [(3, '__init__'), (7, 'hey '), (11, 'hey'), (5, 'other')] if you really want it as a dict (for reasons i cant fathom) and you are using 3.6+ then you can just create a new dict from your sorted items d2 = dict(sorted(d.items(),key=lambda item:item[1])) *(note that in 3.6 that dicts maintain order is an implementation detail, not a guarantee, but 3.7+ its part of the language specification) you can do the same thing in earlier pythons using collections.OrderedDict from collections import OrderedDict d2 = OrderedDict(sorted(d.items(),key=lambda item:item[1])) since you cant use builtin sorted here is a bubble sort for you ... although I dont understand how having strangers on the internet write a sort function for you is any better than just using the python builtin sorted def my_bubble_sort(list_thing,key_fn): # sort a list in place by a key fn changed = True while changed: changed = False for i in range(len(list_thing)-1): if key_fn(list_thing[i]) &gt; key_fn(list_thing[i+1]): list_thing[i],list_thing[i+1] = list_thing[i+1],list_thing[i] changed = True d = {3: '__init__', 5: 'other', 7: 'hey ', 11: 'hey'} d_list = d.items() my_bubble_sort(d_list,lambda item:(item[1].strip(),item[0])) print(d_list)
upvote count: 3
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86289118
accepted answer of: http://stackoverflow.com/q/49639242
downvote count: 2

http://stackoverflow.com/q/49660637
has title: Regular Expression in python how to find paired words
type: Question
has comment: http://stackoverflow.com/comment/86331383
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86330945
has answer: http://stackoverflow.com/a/49660822
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49660779
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49660715
has body: I'm doing the cipher for python. I'm confused on how to use Regular Expression to find a paired word in a text dictionary. For example, there is dictionary.txt with many English words in it. I need to find word paired with "th" at the beginning. Like they, them, the, their ..... What kind of Regular Expression should I use to find "th" at the beginning? Thank you!

http://stackoverflow.com/comment/86340147
type: QuestionComment
score: 0
has text: What is the value of `arr`?
comment on: http://stackoverflow.com/q/49665191
type: Comment

http://stackoverflow.com/comment/86307682
type: AnswerComment
comment on: http://stackoverflow.com/a/49649482
score: 1
has text: Have a look at the changed solution. Is this what you wanted?
type: Comment

http://stackoverflow.com/q/49642710
tagged with: python
has body: What I want to achieve value = 'a.b.c.d.e' new_value = value.split('.') new_value[-1] = F ''.join(new_value) Now I would like to achieve this in one line. something like below ''.join(value[-1] = F in value.split('.')) my above expression throws error because it is kind of wrong so is there a possible way to achieve this
has title: Is there a way to convert string to list and update a value of list and convert it back to string in one line
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49642764
score: 0
has answer: http://stackoverflow.com/a/49642764
type: Question
has comment: http://stackoverflow.com/comment/86293038
answer count: 1

http://stackoverflow.com/q/49728381
answer count: 2
tagged with: neural-network
tagged with: machine-learning
upvote count: 1
tagged with: python
type: UnansweredQuestion
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49729147
type: Question
has title: How to define input data in Tensorflow for 1-rank vectors?
has answer: http://stackoverflow.com/a/49729372
tagged with: tensorflow
has body: For a project, I want to train a neural network using Tensorflow. My training data comes from a CSV file (see screenshot). The input elements are thus vectors of 5 floats and my label elements are scalars. I want to train the network over 100 batches of 50 elements. As my input data are vectors, I do not know how to define the placeholder's shape (x = tf.placeholder(tf.float32,[None,?????])). With my current code below, I am getting the following error: ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [?], [05, 30]. (see screenshot for full trace) What am I doing wrong? # coding: utf-8 # In[2]: import tensorflow as tf import csv #get data and divide in batch csvfile=open('data.csv') reader= csv.reader(csvfile) train=[] label=[] for line in reader: train.append(line[0:4]) label.append(line[5]) #get test data testcsvfile=open('testdata.csv') reader1= csv.reader(testcsvfile) i=0 train_test=[] label_test=[] for line in reader1: train.append(line[0:4]) label.append(line[5]) batch = 50 n_batch = 100 #定义两个placeholder x = tf.placeholder(tf.float32,[None]) y = tf.placeholder(tf.float32,[None,5]) keep_prob=tf.placeholder(tf.float32) lr = tf.Variable(0.001, dtype=tf.float32) #创建一个简单的神经网络 W1 = tf.Variable(tf.truncated_normal([50,30],stddev=0.1)) b1 = tf.Variable(tf.zeros([30])+0.1) L1 = tf.nn.tanh(tf.matmul(x,W1)+b1) L1_drop = tf.nn.dropout(L1,keep_prob) W2 = tf.Variable(tf.truncated_normal([30,10],stddev=0.1)) b2 = tf.Variable(tf.zeros([10])+0.1) L2 = tf.nn.tanh(tf.matmul(L1_drop,W2)+b2) L2_drop = tf.nn.dropout(L2,keep_prob) W3 = tf.Variable(tf.truncated_normal([10,5],stddev=0.1)) b3 = tf.Variable(tf.zeros([10])+0.1) prediction = tf.nn.softmax(tf.matmul(L2_drop,W3)+b3) #交叉熵代价函数 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #训练 train_step = tf.train.AdamOptimizer(lr).minimize(loss) #初始化变量 init = tf.global_variables_initializer() #结果存放在一个布尔型列表中 correct_prediction = tf.equal(tf.argmax(y,1),t…
has comment: http://stackoverflow.com/comment/86471117
score: 0

http://stackoverflow.com/q/49742766
has comment: http://stackoverflow.com/comment/86500206
score: -11
upvote count: 0
has comment: http://stackoverflow.com/comment/86500187
answer count: 1
has comment: http://stackoverflow.com/comment/86500235
has comment: http://stackoverflow.com/comment/86500189
has body: In python, how do I quick sort a nested dictionary into an OrderedDict? For example: {'susan': {'number': '5', 'fav_color': 'yellow'}, 'josh': {'number': '1', 'fav_color': 'blue'}, 'casey': {'number': '11', 'fav_color': 'orange'}} I want to sort on number such that I end up with: {'josh': {'number': '1', 'fav_color': 'blue'}, 'susan': {'number': '5', 'fav_color': 'yellow'}, 'casey': {'number': '11', 'fav_color': 'orange'}}
favorite count: 0
has answer: http://stackoverflow.com/a/49742871
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/613183
has title: Quicksort a dict to an OrderedDict
tagged with: python
tagged with: dictionary
downvote count: 11
has comment: http://stackoverflow.com/comment/86500213
tagged with: ordereddictionary

http://stackoverflow.com/a/49658596
upvote count: 1
has body: You cannot write a GUI in Python without importing either a GUI module or importing ctypes. The latter would require calling OS-specific graphics primitives, and would be far worse than doing the same thing in C. (EDIT: see Roland comment below for X11 systems.) The python-coded tkinter mainly imports the C-coded _tkinter, which interfaces to the tcl- and C- coded tk GUI package. There are separate versions of tcl/tk for Windows, *nix, and MacOS.
has comment: http://stackoverflow.com/comment/119779842
answers question: http://stackoverflow.com/q/49658301
has comment: http://stackoverflow.com/comment/86327430
accepted answer of: http://stackoverflow.com/q/49658301
score: 1
has comment: http://stackoverflow.com/comment/86331708
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86327838
has comment: http://stackoverflow.com/comment/86331901
downvote count: 0
type: Answer

http://stackoverflow.com/a/54908495
upvote count: 0
downvote count: 3
answers question: http://stackoverflow.com/q/49704224
has body: import pymysql pymysql.install_as_MySQLdb()
score: -3
type: Answer

http://stackoverflow.com/comment/86345342
type: Comment
comment on: http://stackoverflow.com/a/49667749
score: 0
type: AnswerComment
has text: You choose PIL - the `Image.ANTIALIAS` is a parameter to `resize` that "causes" the blurryness. See [PIL.Image.Image.resize](https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize) and the options you can give it. Use `PIL.Image.BICUBIC` or `PIL.Image.LANCZOS` instead.

http://stackoverflow.com/a/49672823
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49672708
has body: Yes, you can do this with the collections module: from collections import defaultdict, Counter d = defaultdict(lambda: defaultdict(lambda: Counter())) d['A']['B']['C'] += 1 # defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, # {'A': defaultdict(&lt;function __main__.&lt;lambda&gt;.&lt;locals&gt;.&lt;lambda&gt;&gt;, # {'B': Counter({'C': 1})})}) Note this is also possible via only using nested defaultdict: d = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) However, given Counter was created for the specific purpose of incrementing integers, this would be the method I prefer.
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/49672708
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/49705637
has title: how can i get sale order details of an invoice entry from model account.invoice
answer count: 0
tagged with: odoo-10
tagged with: odoo
score: 1
tagged with: odoo-8
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86424842
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86471290
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86443909
tagged with: python
has body: I have a new field in account. invoice od_sale_order_name. I need to get the sale order name field value to this field.but i didn't find relation from account.invoice to sale.order. i'm using new api.i have tried to create a relation using code saleorder_ids=fields.Many2many('sale.order', 'sale_order_invoice_rel', 'invoice_id', 'order_id', 'Sale Order') but it doesn't create the field . please help me Thanks in advance

http://stackoverflow.com/a/49661099
type: Answer
accepted answer of: http://stackoverflow.com/q/49660110
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49660110
has body: you can't assign job to a form field (that's what form.fields['jobWorker'] is). If you want to assign an initial value, you should do: form.fields['jobWorker'].initial = job But I think you want to pass job as the chosen model, you should just do that in data: form_data = {'description': 'description', 'hours': 20, 'jobWorker': job.pk} form = AddHoursForm(form_data) self.assertFalse(form.is_valid)

http://stackoverflow.com/comment/86427922
has text: replacing with `extract_first` and adding `extract` to `selector_list` returns the same list.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49706655

http://stackoverflow.com/a/57527805
downvote count: 0
upvote count: 1
has body: Instead of monitoring outlook from python, try setting up outlook rules for that email and then launch python script via vba. Here is the code to launch the python script from VBA. Note: The code below was taken from here. Sub UruchomBata(MyMail As MailItem) Dim Ret_Val Dim args As String args = "c:\new.py" Ret_Val = Shell("C:\python27\python.exe" &amp; " " &amp; args, vbNormalFocus) End Sub Below this line is the python script for those interested. It is currently set to control the DTR pins on the com1 serial port. The following will need to be save as a yourname.py file import serial from time import sleep conn = serial.Serial('com1', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=0, rtscts=0 ) # Wake Modem conn.setDTR(True) sleep(3) conn.setDTR(False) sleep(1) conn.close() # Start talking try: while True: conn.write('AT'+chr(13)); print conn.readline() # readlines() will probably never return. finally: conn.close()
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49695160

http://stackoverflow.com/q/49728699
has title: python await asyncio.sleep() in while true blocks
tagged with: python
tagged with: git-bash
score: 3
tagged with: while-loop
answer count: 0
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
has body: I have the following python program testing asyncio: import asyncio async def task(): print("doing task") while True: print("while true looping") await asyncio.sleep(2) def main(): loop = asyncio.get_event_loop() try: print("starting loop") loop.run_until_complete( asyncio.gather( task() ) ) finally: loop.close() if __name__ == '__main__': main() I am expecting outputs like the following: starting loop doing task while true loop while true loop ...("while true loop every" 2 seconds) or even: doing task while true loop starting loop while true loop ...("while true loop every" 2 seconds) But instead, the program hangs and outputs nothing. I guess I have misunderstood the way asyncio handles the loop or asyncio.sleep() works, but I thought await asyncio.sleep() passes the control back to the caller thus the other print() can execute. What have I got wrong here and how can I get the desired outputs? EDIT: this seemed to be a problem specific to Git-Bash on Windows, when I tried the program with windows command prompt and powershell, the desired output were shown.
tagged with: python-asyncio
type: UnansweredQuestion

http://stackoverflow.com/comment/86268545
has text: @jdehesa that's very true. a pity to have to use `itertools` to get an acceptable speed. There's also the double flat listcomp for this: `[z for y in x for z in y]`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49630581

http://stackoverflow.com/q/49717068
has body: Currently I am trying to deploy a server for Mit App Inventor, when I browser the project it looks just fine and the local host works as well. The problem is that when I try to deploy it I get an error. I am using python 2.7.8. By the way I am doing this project from my other gmail account. I have tried and retried a thousand times, but with no result. Can you please help me? This is the main error It says that that's an error when reading a line.
answer count: 1
has comment: http://stackoverflow.com/comment/86463637
has title: Google App Engine Deploy Error When Deploying Python
type: Question
type: UnansweredQuestion
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/49936699
has comment: http://stackoverflow.com/comment/86448013
tagged with: python
score: 0

http://stackoverflow.com/q/49680299
has answer: http://stackoverflow.com/a/49681280
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49681339
has comment: http://stackoverflow.com/comment/86373552
downvote count: 3
has comment: http://stackoverflow.com/comment/86373648
answer count: 3
has answer: http://stackoverflow.com/a/49681339
accepted answer: http://stackoverflow.com/a/49680993
favorite count: 0
has comment: http://stackoverflow.com/comment/86373306
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49680993
has comment: http://stackoverflow.com/comment/86373258
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/86373476
has body: There is a list with elements of similar nature (4 7's,3 5's, etc.) that I want to insert in right left order into a another list (). newlst = [] lst = [7, 7, 7, 7, 5, 5, 5, 3, 3, 3, 2, 2] So the first thing being inserted into newlst is the group of 7's: newlst = [7,7,7,7] Subsequently, the group of 5's is inserted into the list on the right: newlst = [7, 7, 7, 7, 5, 5, 5] And then the group of 3's is inserted on the left, and after that the group of 2's is inserted on the right. The final list looks like this newlst = [3, 3, 3, 7, 7, 7, 7, 5, 5, 5, 2, 2] In order to add elements in the list on a right left basis, I did this: for i in lst: lst.insert(0,i) else: lst.append(i) The insert method inserts elements into the 0 index (which is the right of the list) and append adds elements at the end of the list (which is the left of the list). However, I'm having problems adding the group of elements into the newlst. To that end, I thought using a dictionary would be a good idea. myDict = {2: 2, 3: 3, 5: 3, 7: 4} EDIT: for k, v in myDict.items(): if k in lst: for i in range(v): lst.append(i) else: lst.insert(0,i) The intention of this dictionary is for each key, I want to insert the key value 'x' times, e.g. the key 7, would be inserted 4 times: [7,7,7,7]. Is there a way to achieve this in Python so I can get the output newlist: [3, 3, 3, 7, 7, 7, 7, 5, 5, 5, 2, 2] ?
has comment: http://stackoverflow.com/comment/86372600
tagged with: python
has comment: http://stackoverflow.com/comment/86372710
has comment: http://stackoverflow.com/comment/86373539
score: -3
has comment: http://stackoverflow.com/comment/86373665
has title: Inserting a set of elements alternatively
has comment: http://stackoverflow.com/comment/86373592
tagged with: list
has comment: http://stackoverflow.com/comment/86373524

http://stackoverflow.com/comment/86353895
comment on: http://stackoverflow.com/q/49671679
type: QuestionComment
score: 0
has text: Your code works on my machine (with your website and the string "sankaku". [Similar issue](https://stackoverflow.com/questions/35835767/urllib-error-urlerror-urlopen-error-errno-11002-getaddrinfo-failed).
type: Comment

http://stackoverflow.com/q/49604179
tagged with: matplotlib
has title: python matplotlib rounding date
has answer: http://stackoverflow.com/a/49604306
has comment: http://stackoverflow.com/comment/86215522
type: Question
has comment: http://stackoverflow.com/comment/86215468
tagged with: python-3.x
has body: I've been trying to make a plot that has date as the x-axis using matplotlib. However, when i use the code, it seems that it decides to not show the year if there are less than 6 entries in the plot. Example 5 entries: import matplotlib.pyplot as plt import datetime as dt Dates = ['2018/04/01', '2018/04/02', '2018/04/03', '2018/04/04', '2018/04/05'] y = [10, 20, 30, 56, 42] x = [dt.datetime.strptime(date, '%Y/%m/%d').date() for date in Dates] plt.xticks(rotation = 20) plt.plot(x, y) plt.show() The output is this: What i want is for that output(5 entries) to have the same x axis format output as if i had 6 entries. Example of a desired plot: I would guess that my problem has to do with rounding, but i couldn't find any solutions that worked in my case. Thanks in advance!
has comment: http://stackoverflow.com/comment/86215548
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49604306
has comment: http://stackoverflow.com/comment/86215536
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86215600

http://stackoverflow.com/comment/86433289
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49709242
has text: @Ajay but whats wrong with this part I can't see..I just writing a length of the test_size here
type: Comment

http://stackoverflow.com/q/49600496
type: Question
tagged with: python-3.x
has body: I'm trying to print what I've coded in a def. Instead of getting the print as a result, I am getting : &lt;function Partie.afficher_etat_donnes at 0x000000FF03B4C950&gt; The code is thus : class Partie: def __init__(self, plateau, donnes): self.plateau = plateau self.donnes = donnes self.tour = None self.passe = 0 self.gagnant = None @staticmethod def show_instructions(): instructions = """ Game Instructions : """ print(instructions) print(Partie.afficher_etat_donnes) def afficher_etat_donnes(self): for joueur in range(self.nombre_joueurs): print(f"The player {joueur} has {len(donnes[joueur])} dominos in hand.") For the important variables... in this case : joueur = 2 donnes = [[3,1],[3,2]],[[6,6],[6,3] Donnes is just an example of what it can be. I should have as a result : The player 0 has 2 dominos in hand.
has answer: http://stackoverflow.com/a/49600619
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86208190
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86208080
has comment: http://stackoverflow.com/comment/86208381
score: -5
has comment: http://stackoverflow.com/comment/86208374
upvote count: 0
answer count: 1
has title: Printing a def from another def within the same class
has comment: http://stackoverflow.com/comment/86208156
favorite count: 0

http://stackoverflow.com/q/49608352
type: Question
tagged with: python-mock
has comment: http://stackoverflow.com/comment/86223578
tagged with: mocking
accepted answer: http://stackoverflow.com/a/49608618
has title: Django mocks not working as expected
has comment: http://stackoverflow.com/comment/86223850
upvote count: 3
has answer: http://stackoverflow.com/a/49608618
downvote count: 0
answer count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86223992
has body: I'm struggling with django mock; I have even simplified an unit test but the test is still failing. I want to verify that a method is called (even with any parameter), but the "assert_called_once_with" always returns False. Currently I'm trying: @patch('utils.make_reset_password') def test_shouldHaveCalledMakeResetToken(self, mocked): user = User.get(...) make_reset_password(user) mocked.assert_called_once_with(user) Even this simple example is failing with: AssertionError: Expected 'make_reset_password' to be called once. Called 0 times How this is possible? What am I doing wrong? Thanks in advance
tagged with: django-testing
favorite count: 0
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86223625

http://stackoverflow.com/comment/86336062
comment on: http://stackoverflow.com/q/49662964
score: 0
has text: Using smaller marker `','` along with transparency `alpha=0.1` (or any appropriate value) will give you similar visual info and should be very fast
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86414811
type: AnswerComment
has text: **_tkinter.TclError: couldn't open "Python.gif": no such file or directory** I converted the png to gif and ran the code but the error message showed up. I tried fixing it by dragging the gif into the same directory but it didn't do anything.
score: 0
comment on: http://stackoverflow.com/a/49699373
type: Comment

http://stackoverflow.com/comment/86319132
has text: the source code is fairly straightforward: https://github.com/fengsp/flask-session/blob/master/flask_session/sessions.py#L293 considering you are using filesystem as a session probably want to include more information about your environment and i'd first look to make sure file/directory privileges support this type of use case... obviously this would NOT work in any sort of a distributed system... defaults are: https://github.com/fengsp/flask-session/blob/master/flask_session/__init__.py#L71
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49653960

http://stackoverflow.com/q/49671138
score: 0
has comment: http://stackoverflow.com/comment/86353483
linked to: http://stackoverflow.com/q/3682748
has comment: http://stackoverflow.com/comment/86352949
has comment: http://stackoverflow.com/comment/86352954
has comment: http://stackoverflow.com/comment/86353116
has title: Convert UTC datetime to Pacific datetime in Python
has comment: http://stackoverflow.com/comment/86352793
has answer: http://stackoverflow.com/a/70677913
type: Question
has answer: http://stackoverflow.com/a/51578434
answer count: 2
linked to: http://stackoverflow.com/q/38861426
tagged with: timezone
type: UnansweredQuestion
tagged with: utc
tagged with: datetime
tagged with: python
has body: How can I convert UTC to Pacific time zone in Python? I tried this but it is not working from datetime import datetime from pytz import timezone fmt = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTC now_utc = 1348283733848 # Convert to US/Pacific time zone now_pacific = now_utc.astimezone(timezone('US/Pacific')) print now_pacific.strftime(fmt) Error: Traceback (most recent call last): File "<stdin>", line 2, in <module> AttributeError: 'long' object has no attribute 'astimezone I want to convert this UTC 1348283733848 to pacific time zone in human readble format
has comment: http://stackoverflow.com/comment/86353313

http://stackoverflow.com/q/49687071
tagged with: flask
has title: Running a script from user input in flask
has answer: http://stackoverflow.com/a/49687220
has body: I'm using flask to create a webpage for a script I have written and want to ask the user for input, and whatever they input is run in the python script I have written, how can I do this? Here is the flask page I have created from flask import Flask, render_template, redirect, request, url_for #from flask_script import Manager import json import connect import requests from elasticsearch import Elasticsearch app = Flask(__name__) def elastic_search(text): es = Elasticsearch(['10.0.0.9:9200', '10.0.0.15:9200']) word = input(text) res = es.search(index="pastebin-*", doc_type='doc', body={"query": {"bool": {"must": [{"match": {"key": word}}]}}}) return res @app.route('/key', methods=['POST', 'GET']) def key(): if requests.method == 'POST', 'GET': result = request.form['key'] elastic_search(result) return render_template('key.html') @app.route('/result', methods=['POST', 'GET']) def result(): if request.method == 'POST': result = request.form return render_template('result.html', result = result) if __name__ == '__main__': app.run('0.0.0.0') app.run(threaded=True) and here's the HTML &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Key&lt;/title&gt; &lt;link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="styleshee$&gt; &lt;link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet"&gt; &lt;link href="../static/key.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="header"&gt; &lt;h3 class="text-muted"&gt;&lt;Key/h3&gt; &lt;/div&gt; &lt;div class="jumbotron"&gt; &lt;h1&gt;Please Enter Pastebin Key&lt;/h1&gt; &lt;form class="form-signin"&gt; &lt;form action="" method"post"&gt; &lt;label for="Key" class="sr-only"&gt;Key&lt;/label&gt; &lt;input type="text" name="inputKey" id="inputKey" class="form-control" placeholder="Password" required value="{{ request.form.key }}"&gt; &lt;input type="submit" value="Submit"&gt; &lt;&lt;button id="btnEnter" class="bt…
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
score: -1

http://stackoverflow.com/comment/86215034
type: AnswerComment
comment on: http://stackoverflow.com/a/49603903
type: Comment
has text: It springs to life with these tiny additions, see. Enjoy the task.
score: 0

http://stackoverflow.com/comment/86452736
score: 2
comment on: http://stackoverflow.com/a/49719901
type: Comment
has text: docs: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#indexing
type: AnswerComment

http://stackoverflow.com/q/49709753
accepted answer: http://stackoverflow.com/a/49710105
type: Question
tagged with: python-3.x
tagged with: network-programming
upvote count: 1
tagged with: python-requests
has title: Python3 Requests not using passed-in proxy
has answer: http://stackoverflow.com/a/49710105
favorite count: 0
tagged with: proxy
type: AnsweredQuestion
downvote count: 0
score: 1
answer count: 1
has body: Requests isn't using the proxies I pass to it. The site at the url I'm using shows which ip the request came from--and it's always my ip not the proxy ip. I'm getting my proxy ips from sslproxies.org which are supposed to be anonymous. url = 'http://www.lagado.com/proxy-test' proxies = {'http': 'x.x.x.x:xxxx'} headers = {'User-Agent': 'Mozilla...etc'} res = requests.get(url, proxies=proxies, headers=headers) Are there certain headers that need to be used or something else that needs to be configured so that my ip is hidden from the server?
tagged with: python

http://stackoverflow.com/comment/86393107
comment on: http://stackoverflow.com/a/49687505
type: Comment
type: AnswerComment
has text: Give me a few moments to try please
score: 0

http://stackoverflow.com/comment/86406928
has text: But i don't need to make it schedule, it needs to be running full time
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49697010
type: Comment

binary-search-tree
tags question: http://stackoverflow.com/q/49670906
type: Tag
tags question: http://stackoverflow.com/q/49708682
tag name: binary-search-tree
tags question: http://stackoverflow.com/q/49693640
tags question: http://stackoverflow.com/q/49685152

http://stackoverflow.com/comment/86340590
has text: You can examine the type in the database result and use some pre-defined function to cast the XML value to the same type; e.g. `if isinstance(db_value, int): xml_value = int(xml_value)`…
score: 1
comment on: http://stackoverflow.com/q/49658670
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86432601
comment on: http://stackoverflow.com/q/49709434
type: QuestionComment
score: 0
has text: I changed the data dictionary so that last attribute is now 'action':'login_test.cfm', but it still doesn't work. :(
type: Comment

http://stackoverflow.com/comment/86235694
type: Comment
has text: Do u mean I should have it like this? Doesn't seem to to work engSklearnCnn = KerasClassifier(build_fn=buildEngModelByLoading().compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']), epochs=20, batch_size=batchSize, verbose=1)
type: AnswerComment
comment on: http://stackoverflow.com/a/49607792
score: 0

http://stackoverflow.com/a/49680669
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49680331
upvote count: 1
has body: You should create an intermediate DataFrame: import pandas as pd %matplotlib inline import seaborn as sns num_cols = ["Age","Height","Weight","Duration","Heart_Rate","Body_Temp","Calories"] df = pd.DataFrame(columns=num_cols) sns.pairplot(df,size=2)

http://stackoverflow.com/a/49621146
type: Answer
upvote count: 4
has body: Although I wasn't able to get your posted code to run, I did find that the original tutorial code you linked to, can be changed on the url = line to: url = 'https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s' \ + '?max_rows=250' Running python scrape.py then successfully outputs inmates.csv with all available records. In short, this works by: instead of: How do I get to the next page ? we pursue: How do I remove pagination ? we cause the page to send all records at once so there would be no pagination to deal with in the first place This allows us to use the original tutorial code to save the complete set of records. Explanation url = 'https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s' to use the new URL. The old URL in the tutorial: http://www.showmeboone.com/sheriff/JailResidents/JailResidents.asp redirects to this new URL, but doesn't work with our solution so we can't use the old URL \ is a line break allowing me to continue the line of code on the next line, for readability + is to concatenate so we can add the ?max_rows=250. So the result is equivalent to url = 'https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s?max_rows=250' ?max_rows=&lt;number-of-records-to-display&gt; is a query string I found that works for this particular Current Detainees page. This can be found by first noticing the Page Size text entry field meant for users to set a custom rows per page. It shows a default value 50. Examine its HTML code, for example in Firefox browser (52.7.3), use Ctrl+shift+i to show the Firefox's Web Developer Inspector tool window. Click the Select element button (icon resembles a box outline with a mouse cursor arrow on it), then click on the input field containing 50. HTML pane below reveals via highlight: &lt;input class="mrcinput" name="max_rows" size="3" title="max_rowsp" value="50" type="text"&gt;. This means it submits a form variable named max_rows, which is a number, default 50. Some web pages, depending on how …
score: 4
accepted answer of: http://stackoverflow.com/q/49617710
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49617710

http://stackoverflow.com/a/49652860
has body: You can access the arguments passed to the contour function using the joint_kws in the jointplot function. Like this: g = sns.jointplot(x="s_zscore", y="p_zscore", data=scatter_all, kind="kde", space=0, stat_func=None, marginal_kws={"color":"black", "lw":0.5}, joint_kws={"colors":"black","cmap":None, "linewidths":0.5}, shade=False, n_levels=10) The only change I've made is the addition of: joint_kws={"colors":"black","cmap":None, "linewidths":0.5} Here's the output:
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49652354
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49652354
type: Answer

http://stackoverflow.com/comment/86488756
score: 0
comment on: http://stackoverflow.com/q/49737198
type: Comment
type: QuestionComment
has text: `'now'` not `'today'`

http://stackoverflow.com/comment/86342151
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/49665247
has text: How are you including the `tensorflow` library into your project? Have you read & followed the directions over at [Using third-party libraries](https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27)? Also, note that the libraries you are including must be in pure python without any C code (if `tensorflow` has no C code - you likely shouldn't have any issues unless it does extensive writing to local disk as well). If you are still having difficulties - show your `app.yaml`, `appengine_config.py` files and project's directory structure.

http://stackoverflow.com/q/49622226
tagged with: django-templates
type: Question
score: 5
downvote count: 0
tagged with: django
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67663583
answer count: 1
has title: Add StreamingHttpResponse into middle of Django template
linked to: http://stackoverflow.com/q/29964703
has body: Python 3.6.3, Django 2.0.3 I'm new to django, but I'm trying to make a pretty simple site where someone can trigger a few tasks that were previously just misc, stand-alone python scripts. Unfortunately those tasks can take a pretty long time. I want to be able to display the output from those tasks in the middle of the following template (where {{ stream }} is) so the user has some meaningful feedback. {% load pagePieces %} {% page_header %} Home {{ operation }} {{ stream }} {% page_footer %} In my view file I've tried a few different things, but here's about where I'm at now (this is somewhat simplified. I took out some error handling and changed some names): def myaction(request): output_template = loader.get_template('myapp/process_output.html') return StreamingHttpResponse( output_template.render({ 'operation': 'That long running task', "stream": streaming_wrapper() }) ) def streaming_wrapper(): output_template = loader.get_template('myapp/process_output.html') x = yield from a_module.long_running_task() yield output_template.render({ 'operation': 'That long running task', "stream": x }) This does stream the output from long_running_task(), but doesn't load the rest of the template until after it's done. At other points, I've gotten the output to stream after the template, but never in the middle, which looks bad because my template has a header and a footer. I'm not sure how to make this work, and I'm not sure if the answer is in my views or perhaps doing something more complicated with my template. (I'm also aware this is similar to these 2 questions, but neither of them have satisfactory answers and are years old. Django: return a StreamingHttpResponse on an existing html page Django StreamingHttpResponse into a Template)
tagged with: django-views
upvote count: 5
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/15116881

http://stackoverflow.com/a/49716901
type: Answer
answers question: http://stackoverflow.com/q/49701347
score: 2
upvote count: 2
downvote count: 0
has body: You can use Revit API to reload the keynotes, the method KeyBasedTreeEntryTable.Reload just needs a parameter to store warnings thrown during operation, this parameter can be None to make it easy. Also KeyBasedTreeEntryTable should be an instance, the reload method is not static. The cool thing is that you don't need to find any KeyBasedTreeEntryTable instance, because the KeynoteTable class inherits from KeyBasedTreeEntryTable, so the Reload method is already available with the kt instance in your script. (This operation needs a transaction context too, like in the following examples) Simple way kt = DB.KeynoteTable.GetKeynoteTable(revit.doc) t = DB.Transaction(revit.doc) t.Start('Keynote Reload') try: result = kt.Reload(None) t.Commit() except: t.RollBack() forms.alert('Keynote Reloading : {}'.format(result)) # result can be 'Success', 'ResourceAlreadyCurrent' or 'Failure' Complete way kt = DB.KeynoteTable.GetKeynoteTable(revit.doc) # create results object res = DB.KeyBasedTreeEntriesLoadResults() t = DB.Transaction(revit.doc) t.Start('Keynote Reload') try: result = kt.Reload(res) # pass results object t.Commit() except: t.RollBack() # read results failures = res.GetFailureMessages() syntax_err = res.GetFileSyntaxErrors() entries_err = res.GetKeyBasedTreeEntryErrors() # res.GetFileReadErrors() returns files errors, should be already in failures Messages warnings = '' warnings += '\n'.join([message.GetDescriptionText() for message in failures]) if syntax_err: warnings += '\n\nSyntax errors in the files :\n' warnings += '\n'.join(syntax_err) if entries_err: warnings += '\nEntries with error :\n' warnings += '\n'.join([key.GetEntry().Key for key in entries_err]) forms.alert('Keynote Reloading : {}\n{}'.format(result, warnings))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49701347

http://stackoverflow.com/comment/86235993
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49613345
has text: To do that I'll have to wrap the scikit-learn metric as a CNTK variable/Function right? Can you tell me how to do that? Pardon my ignorance, new to this

http://stackoverflow.com/a/49613690
has comment: http://stackoverflow.com/comment/86237127
has comment: http://stackoverflow.com/comment/86237273
has comment: http://stackoverflow.com/comment/86240229
has comment: http://stackoverflow.com/comment/86237032
score: 1
has comment: http://stackoverflow.com/comment/86236650
downvote count: 0
answers question: http://stackoverflow.com/q/49613600
has body: line is not interpreted as a variable. It's just a string. One solution is to use the % operator for string formatting: inf = open('/var/lib/rundeck/output.txt') for line in inf: print line headers = {'Content-Type': 'application/json',} data = '{"fields":{"project":{"key":"TECH"},"parent":{"key":%s},"summary":"Create AD List ","description":"","issuetype":{"name":"Sub-task"},"customfield_10107":{"id":"10400"}}}' % line response = requests.post('https://jira.corp.hentsu.com/rest/api/latest/issue/', headers=headers, data=data, auth=('user', 'pass')) inf.close() Note that line was replaced with %s and then % line was added to the end. This will replace the %s with the value of the variable line.
upvote count: 1
has comment: http://stackoverflow.com/comment/86237324
type: Answer

http://stackoverflow.com/q/49654550
has title: Detect clusters from graph
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
answer count: 0
has body: &nbsp&nbsp&nbsp&nbsp&nbspSorry for my English but I will try to explain my problem statement.I have a csv with near about 156 columns. I want to plot the Scatter graph with one of the columns as X axis and another one as Y axis. By making combinations of 150 columns i will be generating 11K graphs.Now i have to go through each graph to see is there distinguishable clusters in graph.but to go with visual route it will take whole lot of time.and in feature if graph changes i have to repeat the work. So i am looking for solution where i can detect which graph has clusters. I will provide one of the sample graph generated by using python matplot library.Image link here I will also sharing some of the column structure which i am having. col1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; col2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; col3 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;col4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; col5 0.05414 &nbsp; 0.0027070 &nbsp;0.012994&nbsp; 0.0508931 0.042772063 0.00155&nbsp; 0.0001942 &nbsp; 0.000388&nbsp; 0.0120453&nbsp; 0.0069943 I am intermediate at Python-2.7
score: 1
downvote count: 0
tagged with: feature-detection
tagged with: machine-learning
upvote count: 1

http://stackoverflow.com/q/49699779
has answer: http://stackoverflow.com/a/49700614
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86416112
has comment: http://stackoverflow.com/comment/86413060
has title: How to create a nested dictionary from a normal dictionary in Python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49699967
has body: I have the input json list of dictionaries like below: data1 = { { "nm": "Oliver Cromwell", "cty": "United Kingdom", "hse": "Commonwealth", "yrs": "1653-1658" }, { "nm": "Richard Cromwell", "cty": "United Kingdom", "hse": "Commonwealth", "yrs": "1658-1659" }, { "nm": "Charles II", "cty": "United Kingdom", "hse": "House of Stuart", "yrs": "1660-1685" },... I want to create a nested dictionary like below: dic={"United Kingdom”: { "House of Blois” : [“Stephen”], 'yrs': '1135-1154'} I followed this logic but it has a funtional bug: dic={} i=0 while i&lt;len(data): for k,v in data[i].items(): if data[i]['cty'] not in dic: dic[data[i]["cty"]]={} if data[i]['hse'] not in dic[data[i]['cty']]: dic[data[i]['cty']][data[i]['hse']] = [] dic[data[i]['cty']][data[i]['hse']].append(data[i]['nm']) dic['yrs']=data[i]['yrs'] i+=1 But it's not complete: this is the output. {'United Kingdom': {'Commonwealth': ['Commonwealth'], 'House of Angevin': ['Henry II'], 'House of Blois': ['Stephen'], 'House of Denmark': ['Cnut'], 'House of Hanover': ['George I'], 'House of Lancaster': ['Henry IV'], 'House of Normandy': ['William I'], 'House of Orange': ['William III'], 'House of Plantagenet': ['Henry III'], 'House of Saxe-Coburg-Gotha': ['Edward VII'], 'House of Stuart': ['James I'], 'House of Tudor': ['Henry VII'], 'House of Wessex': ['Edmund lronside'], 'House of Windsor': ['George V'], 'House of York': ['Edward IV'] } 'yrs': '1910-1936'}
tagged with: nested
upvote count: 1
has comment: http://stackoverflow.com/comment/86412849
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86413022
has comment: http://stackoverflow.com/comment/86413092
type: UnansweredQuestion

http://stackoverflow.com/q/49713164
has title: Cannot print confusion matrix for model
answer count: 3
tagged with: confusion-matrix
score: 1
has answer: http://stackoverflow.com/a/51187997
accepted answer: http://stackoverflow.com/a/49713212
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49713212
has body: I implemented an MLP and it works perfectly. However, I'm having an issue trying to print the confusion matrix. My model is defined as... logits = layers(X, weights, biases) Where... def layers(x, weights, biases): layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer I train the model on the mnist dataset. After training I am am able to print out the accuracy of the model successfully... pred = tf.nn.softmax(logits) correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print("Accuracy: ", accuracy.eval({X:mnist.test.images, y:mnist.test.labels})) The accuracy gives me 90%. Now I want to print out the confusion matrix of the results. I tried the following... confusion = tf.confusion_matrix( labels=mnist.test.labels, predictions=correct_prediction) But this gives me errors... ValueError: Can not squeeze dim[1], expected a dimension of 1, got 10 for 'confusion_matrix/remove_squeezable_dimensions/Squeeze' (op: 'Squeeze') with input shapes: [10000,10]. What is the proper way to print out the confusion matrix? I've been struggling for some time.
possible better answer: http://stackoverflow.com/a/50542146
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: mnist
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50542146

http://stackoverflow.com/comment/86240617
has text: What do you mean by "where -q does what I need to"? If you can clarify what you're asking for, you may get more useful solutions
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49616754

http://stackoverflow.com/comment/86442992
type: QuestionComment
comment on: http://stackoverflow.com/q/49714954
score: 0
type: Comment
has text: ... I don't really understand your question. A graph is a <Vertices, Edges> tuple. Giving the vertices and the edges is the same as giving the graph.

http://stackoverflow.com/a/49725462
upvote count: 2
has comment: http://stackoverflow.com/comment/86464759
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86465570
accepted answer of: http://stackoverflow.com/q/49725407
score: 2
has body: It looks like you want to remove the row if it is 0 and either previous or next row in same column is 0. You can use shift to look for previous and next value and compare with current value as below: result_df = df[~(((df.ColA.shift(-1) == 0) &amp; (df.ColA == 0)) | ((df.ColA.shift(1) == 0) &amp; (df.ColA == 0)))] print(result_df) Result: ColA 0 1 1 2 2 3 3 0 4 4 5 5 9 1 10 2 11 3 12 0 13 8 14 8 19 9 Update for more than 2 consecutive Following example in link, adding new column to track consecutive occurrence and later checking it to filter: # https://stackoverflow.com/a/37934721/5916727 df['consecutive'] = df.ColA.groupby((df.ColA != df.ColA.shift()).cumsum()).transform('size') df[~((df.consecutive&gt;10) &amp; (df.ColA==0))]
answers question: http://stackoverflow.com/q/49725407
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86464858

http://stackoverflow.com/comment/86427190
has text: Traceback (most recent call last): File "C:\Users\Usama Malik\Desktop\New folder (3)\tesseract-python-master\image_example.py", line 2, in <module> import pytesseract File "C:\Python27\lib\site-packages\pytesseract\__init__.py", line 1, in <module> from .pytesseract import ( File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 9, in <module> import Image File "C:\Python27\lib\site-packages\PIL\Image.py", line 27, in <module> from . import VERSION, PILLOW_VERSION, _plugins ValueError: Attempted relative import in non-package
type: Comment
comment on: http://stackoverflow.com/q/49706968
score: 0
type: QuestionComment

http://stackoverflow.com/q/49750968
has body: I am trying to write in a text (download.txt) the lines from open.txt that there are not the same 'id' and there are not in excepcions (idexception, classexcepcion). I have got writing the 'ids' not repeated and the idexcepcion. MY QUESTION is how to add the condition 'classexception', I tried it but it is impossible. Any idea about dictionaries/conditionals I have to use? c = open('open.txt','r') #structure: name:xxx; id:xxxx; class:xxxx; name:xxx; id:xxxx;class:xxxx etc t=c.read() d=open('download.txt','a') allLines = t.split("\n") lines = {} class=[s[10:-1] for s in t.split() if s.startswith("class")] for line in allLines: idPos = line.find("id:") colPos = line.find(";",idPos) if idPos &gt; -1: id = line[idPos+4: colPos if colPos &gt; -1 else None] if id not in idexception: lines.setdefault(id,line) for l in lines: d.write(lines[l]+'\n') c.close() d.close()
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
has title: write a whole line in a .txt file if not in a .yaml file
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49752026
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49752026
upvote count: 0
answer count: 1

http://stackoverflow.com/q/49636443
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/49616402
favorite count: 0
type: Question
tagged with: kafka-producer-api
has answer: http://stackoverflow.com/a/49758916
tagged with: pykafka
tagged with: python
has body: I am using pykafka and have a producer that is producing asynchronously and using delivery_reports. I know the delivery reports must be read using the "get_delivery_report" method and I know it has to be called in same thread as the message that was produced. However, does get_delievery_report have to be called after each call to produce or can it be called a single time? Will get_delivery_report return all of the failed sends if more than one occurs. For example, say I send 100 messages asynchronously: for x in xrange(100): with topic.get_producer(delivery_reports=Try, sync=False) as producer: producer.produce("Test Message") msg, exc = producer.get_delivery_report() or does it have to be: for x in xrange(100): with topic.get_producer(delivery_reports=Try, sync=False) as producer: producer.produce("Test Message") msg, exc = producer.get_delivery_report() The first seems to run much faster than the second.
accepted answer: http://stackoverflow.com/a/49758916
type: AnsweredQuestion
tagged with: python-2.7
has title: Can I call get_delivery_report from a Kafka produce once after a batch of messages is produced?
score: 1

http://stackoverflow.com/q/49704401
tagged with: line
tagged with: extend
favorite count: 0
accepted answer: http://stackoverflow.com/a/49705139
type: Question
has title: how can I copy specific line of list and paste on specific line of another list in python?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86422602
has answer: http://stackoverflow.com/a/49705139
tagged with: list
tagged with: python
answer count: 1
has body: I have a list which I want to add seven line of it to one line In another list (not with append), I do this works but I get error trainer = [] for j in range (0, 22): for i in range(len(train)): if i//7==j: trainer[j].extend(train[i])
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/86286794
type: Comment
type: QuestionComment
has text: You should run them separately. Don't start new processes in an WSGI app.
comment on: http://stackoverflow.com/q/49639311
score: 3

http://stackoverflow.com/comment/86455320
type: Comment
has text: Great read: [How to debug small programs (#3)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)
type: QuestionComment
comment on: http://stackoverflow.com/q/49721042
score: 0

http://stackoverflow.com/comment/86533254
score: 0
type: Comment
has text: Best of all, you updated the question so that you ask for syntactically legal output. I've retracted my closure vote and reversed the down-vote.
type: QuestionComment
comment on: http://stackoverflow.com/q/49757979

http://stackoverflow.com/comment/86472417
type: AnswerComment
comment on: http://stackoverflow.com/a/49729052
has text: Hi. it worked. I gave some better path and it went fine. Thanks a lot for quick help :)
type: Comment
score: 0

http://stackoverflow.com/q/49667486
tagged with: encryption
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86383151
has comment: http://stackoverflow.com/comment/86359578
has body: I am trying a very basic use case to encrypt and decrypt a sample string. Below is my method. I am using pycryptodome for the encryption. @staticmethod def encryptdecrypt(field): if field is None: return None else: print("Input Text is --&gt; "+field) cipher = AES.new(CryptHelper.secret_key,AES.MODE_EAX) text = cipher.encrypt(field.encode('UTF-8')) print("Encrypted String --&gt; "+str(text)) cipher = AES.new(CryptHelper.secret_key,AES.MODE_EAX) text = cipher.decrypt(text).decode('cp1252') print("Decrypted String --&gt; " +text) I am not able to regenerate the original string. I get gibberish o/ps such as below. I tried with different encodings as I am on Windows 10. But none of the give me the original string. Am I missing something here? Am very new to python. so incase if I am performing a blunder, please do let me know. Input Text is --&gt; Secret Encrypted String --&gt; b'^\xb4\xc7A\xbc\x05' Decrypted String --&gt; &gt;F8Ò³…
score: 1
answer count: 1
tagged with: pycryptodome
tagged with: character-encoding
has answer: http://stackoverflow.com/a/49674386
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: Encrypt Decrypt encoding on Windows Python

http://stackoverflow.com/comment/86413690
type: QuestionComment
has text: Yes: please post example data, the code you have worked out so far, the result(s) you expect ([mcve]).
score: 0
comment on: http://stackoverflow.com/q/49700167
type: Comment

http://stackoverflow.com/q/49635859
type: Question
has comment: http://stackoverflow.com/comment/86279192
linked to: http://stackoverflow.com/q/514371
has body: I know there are several similar questions asked, but mine still remains unanswered. Here's the problem. I used the command python3 -m pip3 install -U scikit-learn to install sklearn, numpy, and scipy. However, when I run: import sklearn from sklearn.linear_model import LogisticRegression in my file, I got an error message like: Traceback (most recent call last): File "sklearn.py", line 4, in &lt;module&gt; import sklearn from sklearn.linear_model import LogisticRegression ModuleNotFoundError: No module named 'sklearn.linear_model'; 'sklearn' is not a package And strangely, when I run import sklearn everything is fine without any error. In fact, I can't use any of the attributes of sklearn, and I can only import sklearn but I can't do anything. By the way, I run my file on MAC OS terminal with python3 command.
upvote count: 3
accepted answer: http://stackoverflow.com/a/49635971
downvote count: 0
has comment: http://stackoverflow.com/comment/86279366
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86279466
tagged with: python
has answer: http://stackoverflow.com/a/49635971
favorite count: 0
has comment: http://stackoverflow.com/comment/86279436
has comment: http://stackoverflow.com/comment/86279131
type: AnsweredQuestion
score: 3
has title: sklearn is installed, but 'sklearn' is not a package in my "sklearn.py" file
answer count: 1
has comment: http://stackoverflow.com/comment/86279203

http://stackoverflow.com/a/67990164
answers question: http://stackoverflow.com/q/49641707
type: Answer
has body: If you want to have the benefits of an sklearn Pipeline (convenience/encapsulation, joint parameter selection, and safety from leakage), you can use a ColumnTransformer: preproc = ColumnTransformer( transformers=[ ('scale', StandardScaler(), ["cost", "sales"]), ], remainder="passthrough", ) (there are several ways to specify which columns go to the scaler, check the docs). Now you have the benefit of saving the scaler object as @Peter mentions, but also you don't have to keep repeating the slicing: df = preproc.fit_transform(df) df_new = preproc.transform(df)
score: 0

http://stackoverflow.com/q/49734274
tagged with: jaydebeapi
type: Question
possible better answer: http://stackoverflow.com/a/73872614
has answer: http://stackoverflow.com/a/73872614
tagged with: python
has title: jaydebeapi Getting column alias names
accepted answer: http://stackoverflow.com/a/50468912
type: AnsweredQuestion
tagged with: sql
answer count: 2
has answer: http://stackoverflow.com/a/50468912
downvote count: 0
upvote count: 1
score: 1
has body: Is there a way to return the aliased column names from a sql query returned from JayDeBeApi? For example, I have the following query: sql = """ SELECT visitorid AS id_alias FROM table LIMIT 1 """ I then run the following (connect_to_vdm() establishes a connection to my DB): curs = connect_to_vdm().cursor() curs.execute(sql) vals = curs.fetchall() I normally retrieve column names like so: desc = curs.description column_names = [col[0] for col in desc] This returns the original column name "visitorid" and not the alias specified in the query "id_alias". I know I could swap the names for the value in Python, but hoping to be able to have this done within the query since it is already defined in the Select statement. This behaves as expected in a SQL client, but I cannot seem to get the Aliases to return when using python/JayDeBeApi. Is there a way to do this using JayDeBeApi? EDIT: I have discovered that structuring my query with a CTE seems to help fix the problem, but still wondering if there is a more straightforward solution out there. Here is how I rewrote the same query: sql = """ WITH cte (id_alias) AS (SELECT visitorid AS id_alias FROM table LIMIT 1) SELECT id_alias from cte"""
favorite count: 0

http://stackoverflow.com/comment/86283195
comment on: http://stackoverflow.com/q/49637222
has text: Where do you want to print everything? Message box or console?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86462777
has text: If you are convinced the problem is a programming problem and not a problem in modeling the physics, please try to boil it down to a MCVE. If the problem is in modeling the physics, you are probably better off asking on Computational Science SE: https://scicomp.stackexchange.com
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49724370
type: QuestionComment

http://stackoverflow.com/comment/86545283
has text: @running.t Hi, i add seyup.py and awscli github url :)
comment on: http://stackoverflow.com/q/49748870
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49653844
has comment: http://stackoverflow.com/comment/86725202
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49653637
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86725830
has body: The Meetup version 2 API responds with a meta dictionary that contains a next key, you should use that. url = '...' while url: data = requests.get(url).json() ... do something with data ... url = data['meta'].get('next')

http://stackoverflow.com/a/49662405
score: 5
has comment: http://stackoverflow.com/comment/131247236
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49662187
upvote count: 5
type: Answer
has body: When using NumPy/Pandas, the key to speed is often applying vectorized functions to the largest arrays/NDFrames possible. The main reason why your original code is slow is because it calls expand_onerow once for each row. The rows are tiny and you have millions of them. To make it faster, we need to find a way to express the calculation in terms of functions applied to whole DataFrames or at least whole columns. This tends to achieve the result with more time having been spent in fast C or Fortran code and less time in slower Python code. In this case, the result can be obtained by making copies of data and shifting the index of the whole DataFrame by i days: new = df.copy() new.index = df.index + pd.Timedelta(days=i) dfs.append(new) and then concatenating the shifted copies: pd.concat(dfs) import pandas as pd import numpy as np myidx = pd.date_range('2016-01-01','2017-01-01') data = pd.DataFrame({'value' : range(len(myidx))}, index = myidx) def expand_onerow(df, ndaysback = 2, nhdaysfwd = 2): new_index = pd.date_range(pd.to_datetime(df.index[0]) - pd.Timedelta(days=ndaysback), pd.to_datetime(df.index[0]) + pd.Timedelta(days=nhdaysfwd), freq='D') newdf = df.reindex(index=new_index, method='nearest') #New df with expanded index return newdf def orig(df, ndaysback=2, ndaysfwd=2): return pd.concat([expand_onerow(data.loc[[x],:], ndaysback = ndaysback, nhdaysfwd = ndaysfwd) for x ,_ in data.iterrows()]) def alt(df, ndaysback=2, ndaysfwd=2): dfs = [df] for i in range(-ndaysback, ndaysfwd+1): if i != 0: new = df.copy() new.index = df.index + pd.Timedelta(days=i) # you could instead use # new = df.set_index(df.index + pd.Timedelta(days=i)) # but it made the timeit result a bit slower dfs.append(new) return pd.concat(dfs) Notice that alt has a Python loop with (essentially) 4 iterations. orig has a Python loop (in the form of a list comprehension) with len(df) iterations. Making fewer function calls and applying vectorized functions to bigger array-like objects is how alt g…
answers question: http://stackoverflow.com/q/49662187
has comment: http://stackoverflow.com/comment/86334960

http://stackoverflow.com/a/49629561
type: Answer
answers question: http://stackoverflow.com/q/49629431
score: 0
has body: Will print(dict(row)[key]) do the job for you?

moviepy
tags question: http://stackoverflow.com/q/49713052
type: Tag
tag name: moviepy
tags question: http://stackoverflow.com/q/49628139
tags question: http://stackoverflow.com/q/49720646

http://stackoverflow.com/q/49755480
has body: I am looking at Python 3.6 documentation where it says By default, section names are case sensitive but keys are not [1]. For the footnote it says [1] (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the Customizing Parser Behaviour section. So I look at "14.2.7. Customizing Parser Behaviour" but I cannot find the description of how to make sections case-insensitive. I want a section like this: [SETTINGS] ... To be accessible like this config['section'], but currently I get an error. This is the only change to the config parser I want to apply.
has comment: http://stackoverflow.com/comment/86526008
score: 1
tagged with: configparser
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86526640
has comment: http://stackoverflow.com/comment/86526281
answer count: 2
has comment: http://stackoverflow.com/comment/86526208
accepted answer: http://stackoverflow.com/a/49758364
linked to: http://stackoverflow.com/q/26179728
has answer: http://stackoverflow.com/a/49758364
downvote count: 0
upvote count: 1
tagged with: python
has title: Case-insensitive sections in ConfigParser
possible better answer: http://stackoverflow.com/a/78548247
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78548247

http://stackoverflow.com/q/49691574
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/86407088
score: 22
has answer: http://stackoverflow.com/a/57860277
answer count: 4
tagged with: python-2.7
upvote count: 22
has answer: http://stackoverflow.com/a/60991360
has body: I'm doing a bulk operation to index 100 documents at once using the python ElasticSearch Client. I want to count the total number of documents in an index. So I do the bulk op and then count the number of documents in an index as below: helpers.bulk(es_client, actions); es_client.count('index').get('count') However the second line still returns the old count, and I tried to run the second line from a different file, which returns the correct result. I suspect that bulk op is not yet completed. Please correct me if I'm wrong, and what would be the workaround to do what I want?
downvote count: 0
has title: Counting number of documents in an index in elasticsearch
has answer: http://stackoverflow.com/a/79021819
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49701084
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/86417147
comment on: http://stackoverflow.com/a/49701538
type: Comment
has text: you likely need to adjust the `range(3, 17)`. I hard coded values which will be dynamically changed via your score.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86501387
type: Comment
has text: @miradulo: that code is more than 10 times slower than what I posted...
type: QuestionComment
comment on: http://stackoverflow.com/q/49742975
score: 0

http://stackoverflow.com/q/49747034
downvote count: 0
tagged with: selenium
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49162667
has comment: http://stackoverflow.com/comment/86509798
has comment: http://stackoverflow.com/comment/86509331
possible better answer: http://stackoverflow.com/a/49747678
has title: Select from a DatePicker in Python
upvote count: 5
linked to: http://stackoverflow.com/q/65136519
has answer: http://stackoverflow.com/a/49747678
tagged with: python
linked to: http://stackoverflow.com/q/21422548
has body: Can anyone help me with the Selenium webdriver (in Python) code to automatically select a date in the input date in the above link. https://www.nseindia.com/products/content/derivatives/equities/archieve_fo.htm It is just one line of code but I've wasted hours behind it. someone please kindly help. I've tried the .send_keys() function and have searched for hours about the datepicker issue. Kindly help.
has answer: http://stackoverflow.com/a/68936032
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49748121
answer count: 3
score: 5
has answer: http://stackoverflow.com/a/49748121

http://stackoverflow.com/comment/86374228
comment on: http://stackoverflow.com/q/49681166
type: Comment
type: QuestionComment
has text: Do you have a sensor for determining the distance of the camera? Otherwise you need stereo vision to accurately judge the distance
score: 0

wrapper
tag name: wrapper
tags question: http://stackoverflow.com/q/49665726
type: Tag

cpython
tags question: http://stackoverflow.com/q/49718945
tags question: http://stackoverflow.com/q/49661409
tags question: http://stackoverflow.com/q/49753612
tags question: http://stackoverflow.com/q/49699286
tags question: http://stackoverflow.com/q/49729340
type: Tag
tag name: cpython
tags question: http://stackoverflow.com/q/49661827

http://stackoverflow.com/a/49718644
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49718626
type: Answer
has body: Use boolean indexing with df.columns: categorical = df.columns[(df.dtypes.values != np.dtype('float64'))] Or get difference of columns selected by select_dtypes: categorical = df.columns.difference(df.select_dtypes('float64').columns) Sample: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7.,8,9,4,2,3], 'D':[1,3,5.,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}) print (df) A B C D E F 0 a 4 7.0 1.0 5 a 1 b 5 8.0 3.0 3 a 2 c 4 9.0 5.0 6 a 3 d 5 4.0 7.0 9 b 4 e 5 2.0 1.0 2 b 5 f 4 3.0 0.0 4 b categorical = df.columns.difference(df.select_dtypes('float64').columns) print (categorical) Index(['A', 'B', 'E', 'F'], dtype='object')
accepted answer of: http://stackoverflow.com/q/49718626
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/86328740
comment on: http://stackoverflow.com/q/49658888
score: 0
has text: my question is how to make random rectangles and scroll the screen.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49661615
has comment: http://stackoverflow.com/comment/86374441
has comment: http://stackoverflow.com/comment/86339886
downvote count: 0
has title: Django Rest Framework ListCreateAPIView not checking has_object_permissions?
answer count: 1
has body: I've been trying to figure this out for almost a full day now, and I can't seem to figure out why has_object_permission method isn't called when the ListCreateAPIView is called in DRF. I've tried all the solutions I could find, but according to the docs check_object_permissions is called in this class already. I know it has to be something stupid I'm missing. Code snippets are below, please help! views.py: from accountability.models import AccountabilityItem from accountability.serializers import AccountabilityItemSerializer from rest_framework import generics from .permissions import InGroup class AccountabilityItemListCreate(generics.ListCreateAPIView): queryset = AccountabilityItem.objects.all() serializer_class = AccountabilityItemSerializer permission_classes = (InGroup,) permissions.py: from rest_framework import permissions class InGroup(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): print('Checking for object') return False Another note, I've added the has_permission method to the permissions.py file, and this method runs all the time no matter what. Thanks!
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/49665174
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
upvote count: 4
score: 4

http://stackoverflow.com/q/49679872
type: Question
tagged with: algorithm
tagged with: python
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86371870
has answer: http://stackoverflow.com/a/49680234
has answer: http://stackoverflow.com/a/49689137
has title: isomorphic python algorithms
has body: Question: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. My code: def isIsomorphic(self, s, t): # write your code here remap = dict() if s == t: return True if len(s) != len(t): return False for i in range(len(s)): if s[i] not in remap.keys() and t[i] in remap.values(): return False elif s[i] not in remap.keys(): remap[s[i]] = t[i] else: if remap[s[i]] != t[i]: return False return True error hint: Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best. Pls ask how i improve my code
has answer: http://stackoverflow.com/a/49680104
upvote count: 2
has comment: http://stackoverflow.com/comment/120795015
has comment: http://stackoverflow.com/comment/86371913
has comment: http://stackoverflow.com/comment/86372100
score: 1
has comment: http://stackoverflow.com/comment/86372025
linked to: http://stackoverflow.com/q/31465669
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49683605
has comment: http://stackoverflow.com/comment/86371495
has answer: http://stackoverflow.com/a/49680363

http://stackoverflow.com/a/49603358
accepted answer of: http://stackoverflow.com/q/49603052
has body: You are mixing attributes and methods. Your "speed" should be an attribute of your class, while "accelerate" should be a method that modifies that attribute. Some code to show what I mean. class Motorcycle: def __init__(self, maxspeed, minspeed, sidecar): self.maxspeed = maxspeed self.minspeed = minspeed self.speed = minspeed # Initial speed is equal to minspeed self.sidecar = sidecar # Printing methods # Print sidecar status def has_sidecar(self): if self.sidecar: print("This motorcycle has a sidecar") else: print("This motorcycle does not have a sidecar") # Print speed def how_fast(self): print ("The current speed of this motorcycle is {}".format(self.speed)) # Methods to change your sidecar status: def add_sidecar(self): self.sidecar = True def remove_sidecar(self): self.sidecar = False # Method to accelerate def accelerate(self, accelerate): if (self.speed + accelerate) &gt; self.maxspeed: print("This motorcycle cannot go that fast") else: self.speed += accelerate motorcycleOne = Motorcycle(90.0, 65.0, True) motorcycleTwo = Motorcycle(85.0, 60.0, False) motorcycleOne.accelerate(30.0) motorcycleTwo.accelerate(20.0) motorcycleOne.how_fast() motorcycleTwo.how_fast() motorcycleOne.has_sidecar() motorcycleTwo.has_sidecar() Gives: This motorcycle cannot go that fast The current speed of this motorcycle is 65.0 The current speed of this motorcycle is 80.0 This motorcycle has a sidecar This motorcycle does not have a sidecar ... But you are not subclassing a class from a base class.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49603052
type: AcceptedAnswer

http://stackoverflow.com/comment/86413295
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49699967
has text: Yes, but I still don't think this is *quite* what you want. Please expand your posted example to include at least two nations in your input dict.

http://stackoverflow.com/a/49681322
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49681262
answers question: http://stackoverflow.com/q/49681262
has comment: http://stackoverflow.com/comment/86374460
has body: You are asking how to open a text file and prompt the user for an input in python. This is done using the open and input function. filename = input("&gt; ") #prompt user for input file = open(filename, r) #open file data = file.read() #transform file to a string To count the number of letters and numbers: print(len(data)) #count the length of the string

http://stackoverflow.com/a/49628158
score: 0
has body: Here with beautiful soap : from bs4 import BeautifulSoup soup = BeautifulSoup(string) tag=soup.div print(tag.string)
type: Answer
answers question: http://stackoverflow.com/q/49627899

http://stackoverflow.com/comment/86394808
type: AnswerComment
comment on: http://stackoverflow.com/a/49690705
score: 0
has text: Sorry but can you share screenshot of your inspected HTML? Thanks.
type: Comment

http://stackoverflow.com/comment/86495885
has text: That's the point, to have a full control of everything. Especially database.
comment on: http://stackoverflow.com/a/49739946
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49733540
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86481400
duplicate of: http://stackoverflow.com/q/46103044
type: UnansweredQuestion
has title: Slice numpy array of dimension N with array of dimension N-1
tagged with: python
tagged with: slice
has body: I'm looking for the most idiomatic and performant way to slice an array of dimension N with an array of dimension N-1 that represents the index of the last dimension to slice. The output would have dimension N-1. As an example: import numpy as np array = np.array([[[1,2], [3,4]], [[5,6], [7,8]]]) index = np.array([[0, 1], [1, 0]]) Results would be: np.array([[1, 4], [6, 7]]) For example, one could imagine an array (lat, lon, alt) and we wish to extract a specific altitude for each (lat, lon). This information is stored in a 2D array. I am looking for a fast solution as the arrays are quite large. Thank you!
tagged with: numpy-slicing
answer count: 0
score: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/46103044
favorite count: 0

http://stackoverflow.com/a/49758123
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49757979
has comment: http://stackoverflow.com/comment/86531507
has comment: http://stackoverflow.com/comment/86534501
type: Answer
answers question: http://stackoverflow.com/q/49757979
has body: As per this stackoverflow answer, you can use a map: map('Age{0}'.format, listB) so: res = dict(zip(listA, list(map('Age:{0}'.format, listB)))) but it's not very readable, imho.
downvote count: 0

http://stackoverflow.com/comment/86235938
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49604689
score: 0
has text: To paraphrase my post I want to see that indeed O=Og+Or+Om. But that's a fair comment because although what I really I mean is that O_s is no longer interesting and just represents an intermediate step in the breakdown of the model, that isn't totally obvious from the way I entered the equations. SFTP has suggested the correct approach though I think.

http://stackoverflow.com/comment/106790226
comment on: http://stackoverflow.com/a/50941664
type: AnswerComment
type: Comment
has text: you clone the first LightGbm and clone again?
score: 0

http://stackoverflow.com/comment/86488808
type: QuestionComment
has text: when i do print(geld_a) it works and i dont get an error? But it doesnt work when i do print ("Sie heben", geld_a ("€ ab")
comment on: http://stackoverflow.com/q/49737117
score: 0
type: Comment

http://stackoverflow.com/comment/86505521
type: AnswerComment
has text: Thanks for suggestion, with this change data[movie] = {}; data[movie]['theater'] = theater getting error: data[movie] += ','+line TypeError: unsupported operand type(s) for +=: 'dict' and 'str'
comment on: http://stackoverflow.com/a/49725040
type: Comment
score: 0

http://stackoverflow.com/comment/86512290
comment on: http://stackoverflow.com/q/49748390
score: 0
type: Comment
type: QuestionComment
has text: What does "complementary" mean here? Do you mean the parent, as in `path.parent`? In that case, you could just do `other_path = path.parent / 'other_file.dat'`

http://stackoverflow.com/comment/86363173
score: 0
type: Comment
type: QuestionComment
has text: dear djangoliv. I believe I read this document carefully.But I don't understand how to transcribe it to my code. Would you help me?
comment on: http://stackoverflow.com/q/49674883

http://stackoverflow.com/comment/86475590
score: 0
comment on: http://stackoverflow.com/q/49728993
has text: xw.Range(sh , (3,2),(10,2)).value = 1, assigns the value automatically to all those cells, the approach that i'm sharing lets you change the value at every cell on Range(sh , (3,2),(10,2)), isn't that what you want? if not, can you share what "Edit a cell then move to the next" means?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49744376
type: Question
tagged with: numpy
has title: Error in image warping code
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
has body: import cv2 import numpy as np point=np.zeros((32,2),np.float32) point2=np.zeros((32,2),np.float32) count=0 def click(event, x, y, flags, param): global count global x1,x2,y1,y2 if event == cv2.EVENT_LBUTTONDOWN: if count%2==0: point[count,0] = x point[count,1] = y print (x,y) x1=x y1=y count+=1 else: point2[count,0] = x point2[count,1] = y print (x,y) x2=x y2=y count+=1 mophing() def mophing(): height,width,channel = img.shape for y in range (height): for x in range (1,width): if(x&lt;x1): xratio=x/x1 else: xratio=(width-x)/(width-x1) dx=int((xratio)*(x2-x1)) img[x,y]=img[x+dx,y] #Result cv2.imshow('change', img) img = cv2.imread('messigray.png') cv2.namedWindow('original') cv2.setMouseCallback('original', click ) cv2.imshow('original', img) cv2.waitKey() It's my Python code I check point1 and point2 in someones example picture using mouseEvent, I would like to Warping between the two clicked pointers. Then I wrote a program that changes the value of X tab only. However, when you run this code, the results at the bottom are printed. 77 96 374 290 Traceback (most recent call last): File "C:\Users\open7\Desktop\MouseWarping.py", line 28, in click mophing() File "C:\Users\open7\Desktop\MouseWarping.py", line 42, in mophing img[x,y]=img[x+dx,y] IndexError: index 480 is out of bounds for axis 0 with size 480 Among the result, The above two values are coordinates of the two clicked points I would like to know the problem and solution to the last line code. And I would like to know whether this code is a NumPy issue or OpenCV problem.
tagged with: opencv
score: 0
has answer: http://stackoverflow.com/a/51384334
answer count: 1

http://stackoverflow.com/comment/86285396
type: AnswerComment
comment on: http://stackoverflow.com/a/49638802
type: Comment
has text: @AmitaiF can you be more specific? what is the error?
score: 0

http://stackoverflow.com/q/49703022
has answer: http://stackoverflow.com/a/49710527
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: spark-streaming
tagged with: pyspark
type: UnansweredQuestion
tagged with: python
has body: from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests import traceback conf = SparkConf() conf.setAppName("TwitterStreamApp") sc = SparkContext(conf=conf) sc.setLogLevel("ERROR") ssc = StreamingContext(sc, 5) ssc.checkpoint("checkpoint_TwitterApp") dataStream = ssc.socketTextStream("localhost", 9001) def aggregate_tags_count(new_values, total_sum): return sum(new_values) + (total_sum or 0) def get_sql_context_instance(spark_context): if ('sqlContextSingletonInstance' not in globals()): globals()['sqlContextSingletonInstance'] = SQLContext(spark_context) return globals()['sqlContextSingletonInstance'] def process_rdd(time, rdd): print("----------- %s -----------" % str(time)) try: print(rdd.collect()) except: print(traceback.print_exc()) def release_rdd(time, rdd): rdd.unpersist() words = dataStream.flatMap(lambda line: line.split(" ")) hashtags = words.map(lambda x: (x, 1)) tags_totals = hashtags.updateStateByKey(aggregate_tags_count) tags_totals.foreachRDD(process_rdd) dataStream.foreachRDD(release_rdd) ssc.start() ssc.awaitTermination() The codes implements a wordcount, and runs without error. But the question is, it is cumulative, whereas I hope the dataStream is cleared every window (5 seconds in my program). For example, If I receive (a, 10) in the first window, (a, 20) in the second window, I hope it to output only (a, 20). However my code outputs the sum of (a, 10) and (a, 20), which is (a, 30) Could anybody help me with that?
has title: How to clear a streaming RDD for every window?
score: -1
tagged with: apache-spark
upvote count: 0

qmainwindow
tags question: http://stackoverflow.com/q/49664603
tag name: qmainwindow
tags question: http://stackoverflow.com/q/49686907
tags question: http://stackoverflow.com/q/49747858
tags question: http://stackoverflow.com/q/49665870
type: Tag

http://stackoverflow.com/comment/86704505
score: 0
has text: No tried both of them just now get the same error
comment on: http://stackoverflow.com/q/49707878
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49609270
answers question: http://stackoverflow.com/q/49609196
score: 0
has body: returant_id = serializers.PrimaryKeyRelatedField(read_only=True) Could you try giving read_only=False Could you check the spelling, returant_id is used in serializers field,'s' is missing. 'resturant_id' is used in fields list
has comment: http://stackoverflow.com/comment/86225211
type: Answer

http://stackoverflow.com/comment/97132304
comment on: http://stackoverflow.com/a/55197033
type: Comment
has text: Well spotted! This is because the edits mu made in OP's question fixed the issue. I've raised a mod flag for rollback request of the edit. Otherwise It makes no sense to have this question here and all answers are in vane.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49609150
score: 0
has body: Your json file is just a specially formatted text file and you can't do import there, at least for simple cases. You have to write a different function/program to create the json from the constants in your py file. The dictionary creation needs to be worked on. You could start by playing with the below code. def py_constants_to_json(output_file_name='info.json'): import abc as C import json const_dict = { 'c1' : C.val1, #from python file 'c2' : C.val2 } with open(output_file_name,'w') as outf: json.dump(const_dict,outf,indent=2)
answers question: http://stackoverflow.com/q/49608967
type: Answer

python-decorators
tags question: http://stackoverflow.com/q/49677110
tags question: http://stackoverflow.com/q/49689424
tags question: http://stackoverflow.com/q/49736023
type: Tag
tag name: python-decorators
tags question: http://stackoverflow.com/q/49683015

http://stackoverflow.com/q/49722529
tagged with: python
has comment: http://stackoverflow.com/comment/86459014
answer count: 2
score: 1
has title: Integrity Error after submission of Registration using Django 2.0
downvote count: 0
has comment: http://stackoverflow.com/comment/86474201
upvote count: 1
has answer: http://stackoverflow.com/a/49763432
favorite count: 0
has body: I keep on getting an Integrity Error (FOREIGN KEY constrain failed) after registration. from django.db import models from .user import User from django.core.validators import RegexValidator from django.db.models.signals import post_save from django.dispatch import receiver class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to='media/pictures/', blank=True) regex = RegexValidator(r'^\d{2}/\d{4}', message='Required. 7 characters or fewer. This value must contain only numeric and slash.') matric_no = models.CharField(validators=[regex], blank=False, max_length=7, unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list address = models.CharField(max_length=150, blank=True) birth_date = models.DateField(null=True, blank=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=False, default='M',) forms.py class StudentProfileForm(forms.ModelForm): avatar = forms.ImageField() class Meta: model = Student fields = ('avatar', 'phone_number', 'address', 'gender', 'matric_no') views.py class StudentRegistrationView(CreateView): model = Student form_class = StudentProfileForm template_name = 'registration.html' def student_registration(request): if request.method == "POST": form = StudentProfileForm(request.POST, request.FILES) if form.is_valid(): register = form.save(False) register.save() return redirect('home') else: form = StudentProfileForm() return render(request, 'accounts/registration.html', {'form': form}) What I think the problem might probably be is matric_no field, or what did you think?
type: Question
has answer: http://stackoverflow.com/a/49722645
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/86414958
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49674212
has text: @Eolmar Any help from your end buddy?
score: 0

http://stackoverflow.com/comment/86242604
type: AnswerComment
comment on: http://stackoverflow.com/a/49617165
score: 0
type: Comment
has text: @user2259963 - you just need to know which of the fields in your 'stream' should be replaced with values from which enums in your code. You don't need to have any other ifs there as the value will be picked up from the name. If you wish, you can do it even without knowing what enums are there by simply trying to find all available in the current scope but that would seem quite a bit wasteful...

http://stackoverflow.com/comment/125843257
type: AnswerComment
comment on: http://stackoverflow.com/a/49644300
has text: @pierrom No, I think MBT's comment can be a bit confusing. the expression `contiguous` here does **not** mean whether the data is stored in contiguous memory blocks or not. Even if a pytorch tensor is not "contiguous", the elements are arranged in contiguous memory blocks. The expression "contiguous" here is related to the order of the elements when pytorch see the tensor.
type: Comment
score: 0

http://stackoverflow.com/q/49621599
has answer: http://stackoverflow.com/a/49623000
accepted answer: http://stackoverflow.com/a/49623000
tagged with: tflearn
tagged with: python
has answer: http://stackoverflow.com/a/65356222
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/65356222
answer count: 2
downvote count: 0
has title: Reshaping an Gym array for TensorFlow
tagged with: openai-gym
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
has body: I am learning how to use Gym environments to train deep learning models built with TFLearn. At the moment my array of observations has the following shape: (210, 160, 3) Any recommendations on what is the best way to reshape this array so it can be used in a TensorFlow classification model?
tagged with: reinforcement-learning

http://stackoverflow.com/comment/86285856
type: QuestionComment
comment on: http://stackoverflow.com/q/49638571
score: 0
has text: My timezone is US Eastern time
type: Comment

http://stackoverflow.com/comment/86347246
type: QuestionComment
has text: Use `enumerate`.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49668648

http://stackoverflow.com/comment/86528503
has text: This `s = smtplib.SMTP_SSL('smtp.gmail.com', 465, timeout=10)` works on my side, is there any corporate firewall between you and gmail? Possibly a proxy? Some meddling with the SSL certificate which makes it invalid? Actually, was there **any recent change in your network recently**?
comment on: http://stackoverflow.com/q/49756437
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86326166
type: QuestionComment
has text: Can you add the relevant HTML of the page you are interacting with? Or the **URL**? I can then build in answer that relates directly to your usecase.
type: Comment
comment on: http://stackoverflow.com/q/49657833
score: 1

http://stackoverflow.com/comment/96992661
type: AnswerComment
type: Comment
has text: @Ben.T apologies Ben my questions typically get down-posted...no choice but to ask through comments - apologies!
comment on: http://stackoverflow.com/a/49778696
score: 0

http://stackoverflow.com/comment/86346460
type: QuestionComment
score: 0
has text: Golden rule: never remove elements while iterating. Didn't try, but are you sure that the above code (on the above *XML*) does what you claim? It seems that `aRemove` will never be true.
comment on: http://stackoverflow.com/q/49667831
type: Comment

http://stackoverflow.com/a/49614542
has comment: http://stackoverflow.com/comment/86236906
answers question: http://stackoverflow.com/q/49614329
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86236210
score: 3
type: Answer
has body: Here is some code that uses the enumerate generator to give code that is more Pythonic than it would be otherwise. enumerate returns a pair of numbers: the first is the index of the item in the list and the second is the item itself. input1 = [1, 2, 3, 0, 4] output1 = [] for ndx, item in enumerate(input1): if item &gt;= 1: tempoutput = input1[:] # a copy of the list tempoutput[ndx] -= 1 output1.append(tempoutput) The variable output1 now has the value as desired, [[0, 2, 3, 0, 4], [1, 1, 3, 0, 4], [1, 2, 2, 0, 4], [1, 2, 3, 0, 3]] Your original code does not work because you made a common mistake. You build up output1 in your first section with output1.append(input1) but that just adds another reference to the input list to output1 rather than adding a copy of the input list. When you change any one of those sub-lists of output1 they all are modified simultaneously, because they are all actually the same list. You instead should add a copy of the input list with output1.append(input1[:]) (Note that I do the same trick in my code to get a copy of the list.) When that change is made to your code, it then gives the correct answer.
accepted answer of: http://stackoverflow.com/q/49614329

http://stackoverflow.com/comment/86371870
comment on: http://stackoverflow.com/q/49679872
type: Comment
type: QuestionComment
has text: sorry, I am a newer, I will notice next time
score: 0

http://stackoverflow.com/comment/86406951
has text: In general, to have a script that runs continuously, you just put a `while True` loop in it (probably with a short `time.sleep()` to prevent it from using 100% of the CPU just waiting for something to do). To keep it running after you log out, you can use `nohup`, `screen`, or `tmux` (assuming Linux host). To control it, you can send it signals with the `kill` command and write a [signal handler](https://docs.python.org/3/library/signal.html) in your Python code. This then becomes more "how do I use my shell" than a programming question.
comment on: http://stackoverflow.com/q/49696958
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86430620
type: QuestionComment
score: 0
has text: @KyleJ. thank you for your answer. I will try your suggestion later today. What file type could be used instead of csv so that once the data is re- ingested is recognized properly?
type: Comment
comment on: http://stackoverflow.com/q/49707924

http://stackoverflow.com/comment/86433041
type: Comment
comment on: http://stackoverflow.com/a/49709607
type: AnswerComment
score: 1
has text: @Kubuntuer82 It's still not a good answer though. It's unpythonic and too hard to read considering how simple of a task this is. You're right that posting a near-identical answer is a questionable practice, but the only reason why they're similar is because they're both based on _my_ ideas. It's not like I copied your code, so what's wrong with me taking credit for my own solution?

http://stackoverflow.com/a/49736618
answers question: http://stackoverflow.com/q/49711987
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/100241720
has comment: http://stackoverflow.com/comment/107430530
type: Answer
has body: Featuretools is particularly focused on helping users avoid data leakage or label leakage. There are two ways to deal with data leakage depending on if you have timestamps or not. Data without timestamps In the case where you don’t have timestamps, you can create one EntitySet using only the training data and then run ft.dfs. This will create a feature matrix using only the training data, but also return a list of feature definitions. Next, you can create an EntitySet using the test data and recalculate the same features by calling ft.calculate_feature_matrix with the list of feature definitions from before. Here’s is what that flow would look like In [1]: import featuretools as ft In [2]: es_train = ft.demo.load_mock_customer(return_entityset=True) In [3]: feature_matrix, feature_defs = ft.dfs(entityset=es_train, ...: target_entity="customers") ...: In [4]: feature_matrix_enc, features_enc = ft.encode_features(feature_matrix, feature_defs) In [5]: feature_matrix_enc Out[5]: zip_code = 02139 zip_code = 60091 zip_code = unknown COUNT(transactions) COUNT(sessions) SUM(transactions.amount) MODE(sessions.device) = desktop MODE(sessions.device) = tablet MODE(sessions.device) = mobile MODE(sessions.device) = unknown ... SUM(sessions.MIN(transactions.amount)) MAX(sessions.SKEW(transactions.amount)) MAX(sessions.MIN(transactions.amount)) SUM(sessions.MEAN(transactions.amount)) STD(sessions.SUM(transactions.amount)) STD(sessions.MEAN(transactions.amount)) SKEW(sessions.MEAN(transactions.amount)) STD(sessions.MAX(transactions.amount)) NUM_UNIQUE(sessions.DAY(session_start)) MIN(sessions.SKEW(transactions.amount)) customer_id ... 1 0 1 0 131 10 10236.77 1 0 0 0 ... 169.77 0.610052 41.95 791.976505 175.939423 9.299023 -0.377150 5.857976 1 -0.395358 2 1 0 0 122 8 9118.81 0 0 1 0 ... 114.85 0.492531 42.96 596.243506 230.333502 10.925037 0.962350 7.420480 1 -0.470007 3 1 0 0 78 5 5758.24 1 0 0 0 ... 64.98 0.645728 21.77 369.770121 471.048551 9.819148 -0.244976 12.537259 1 -0.63042…
accepted answer of: http://stackoverflow.com/q/49711987
score: 2
upvote count: 2

http://stackoverflow.com/a/49601946
upvote count: 1
type: Answer
downvote count: 1
has body: Please don't be frustrated we are here to help you. Use below command in your python script:- sudo -u USER -S password Suppose you are executing a second script as sudo:- echo $password | sudo -u USER -S ./yourscript.sh In python script use like below:- command = 'yourcommand' os.system('echo %s|sudo -u %s -S %s' % (sudoPassword, user, command)) Also simply use like below without user os.system('echo %s|sudo -S %s' % (sudoPassword, command)) os.system('echo %s|sudo -S ' % (sudoPassword))
has comment: http://stackoverflow.com/comment/86211557
has comment: http://stackoverflow.com/comment/86211716
has comment: http://stackoverflow.com/comment/86211315
has comment: http://stackoverflow.com/comment/86211625
has comment: http://stackoverflow.com/comment/86211887
answers question: http://stackoverflow.com/q/49601803
has comment: http://stackoverflow.com/comment/86211799
score: 0
has comment: http://stackoverflow.com/comment/86212023
has comment: http://stackoverflow.com/comment/86211441

http://stackoverflow.com/q/49736440
answer count: 0
has title: Issue with interactive plot on matplotlib within jupyter notebook
has comment: http://stackoverflow.com/comment/86487549
type: Question
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
tagged with: jupyter-notebook
has body: I have this issue after selecting the zoom button on the interactive toolbar beneath the plot. When I click to draw a rectangle (for zooming in to), black lines appears. This only happens in the bottom and right-most side of the plot. I am using Python 3.6.4 and the following packages: matplotlib (2.1.2) jupyter (1.0.0) Code to reproduce issue (within jupyter notebook): import numpy as np from numpy.random import random import matplotlib.pyplot as plt %matplotlib notebook plt.plot(random(100), random(100), '.')
has comment: http://stackoverflow.com/comment/86488448
score: 0

http://stackoverflow.com/a/49624579
has body: I think need list comprehension with zip second and third column: from itertools import product L = [[i, *j] for i, j in product(df['col1'], zip(df['col2'], df['col3']))] df = pd.DataFrame(L, columns=['col1','col2','col3']) print (df) col1 col2 col3 0 a x 10 1 a y 20 2 a z 30 3 b x 10 4 b y 20 5 b z 30 6 c x 10 7 c y 20 8 c z 30
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49624168
answers question: http://stackoverflow.com/q/49624168
score: 1
type: Answer

http://stackoverflow.com/a/49713367
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86440303
type: Answer
answers question: http://stackoverflow.com/q/49713333
has body: This looks a bit like the variable assignment syntax because of the =, but it is actually a very different feature: When you call functions, you can specify which variables to set to what using the "keyword argument" syntax. This allows you to set specific parameters by name: some_func(arg1, arg2, arg5=None) This is very useful with default arguments: def x(a, b, c=None, d=None): pass If you wanted to set d with the normal syntax, you would have to specify an argument for c too. x(1, 2, None, "hi") Using the keyword argument syntax, you can omit this: x(1, 2, d="hi") Keyword arguments are often, like in this case, also used to make the purpose of a parameter clear to the reader. If you see: pixmap.mean(2) It is not immediately clear what the 2 meas. However, if you see pixmap.mean(axis=2) you immediately know what 2 refers to and why it's there Also see this section of the python docs

http://stackoverflow.com/a/78942851
has body: I was looking for the solution and was surprised to see so little on this topic. Coming from .net experience I could not find suitable & simple solution to avoid storing production credentials in source control. What I came with so far and satisfied with how it worked. This is the solution structure: |-- lib |-- configuration.py |-- main.py |-- appconfig.development.py |-- appconfig.production.py First, created a config file template configuration.py: from dataclasses import dataclass from typing import Optional @dataclass class Connection: server: str database: str user: str password: str port: Optional[str] = None # connection config pg_connection: Connection # email email_from: str error_emails: list[str] smtp_server: str smtp_port: int smtp_user: str smtp_password: str Then, in the specific config file, assign values. For example appconfig.development.py: import lib.configuration as config config.pg_connection=config.Connection( server='my.postgres.server', port=12345, database='db', user='user', password='pass' ) config.error_emails = "itdev@mycompany.com" config.email_from = "no_reply@mycompany.com" config.smtp_server = 'smtp.sendgrid.net' config.smtp_port = 587 config.smtp_user = 'any' config.smtp_password = 'any' Finally, load the config in the main at first convenience, better at startup: # load config name from ENV environment variable, default to development env = os.environ.get('ENV', 'development') logging.info("loading configuration for %s", env) spec = importlib.util.spec_from_file_location( name="doesnotmatter", # anything without dots location="appconfig." + env + ".py", ) my_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(my_module) After loading, the configuration can be used in any module like that: import lib.configuration as appconfig msg = EmailMessage() msg['From'] = appconfig.email_from msg['To'] = ", ".join(appconfig.error_emails) server = smtplib.SMTP(appconfig.smtp_server, appconfig.smtp_port) server.login(appconfig…
type: Answer
answers question: http://stackoverflow.com/q/49643793
score: 0

http://stackoverflow.com/comment/87027639
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49651752
has text: Have you read the [official documentation](https://docs.opencv.org/3.4/dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d) of `cv2.HoughCircles`? I think it's we'll explained there, but I can go in more detail if you don't understand it.
score: 0

http://stackoverflow.com/a/49636335
accepted answer of: http://stackoverflow.com/q/49636251
score: 3
answers question: http://stackoverflow.com/q/49636251
has body: You don't have to add a column to df1, you can directly map the values from the groupby df1 to df2. df2['E'] = df2['A'].map(df1.groupby('A').B.mean()) A D E 0 2002-01-13 Joseph 2.9 1 2002-01-13 Emma 2.9 2 2002-01-13 Michael 2.9 3 2002-01-14 Anna 8.5 4 2002-01-14 Yvonne 8.5 5 2002-01-14 Anthony 8.5
has comment: http://stackoverflow.com/comment/86280589
type: Answer
has comment: http://stackoverflow.com/comment/86280397
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49701538
type: Answer
has body: To solve your first issue, you need to iterate via columns. If you zip the lists (via itertools.zip_longest(), as they are not all the same length), you can then go through them in order and truncate the result: import itertools cols = list(itertools.zip_longest(*lst, fillvalue=" ")) for i in range(3, 17): # skip negative signs cols[i] = "".join(cols[i]).replace('-', '*', 1) cols[i] = "".join(cols[i]).replace('/', '*', 1) cols[i] = "".join(cols[i]).replace('\\', '*', 1) fixed = map("".join, zip(*cols[:17])) # no need to zip longest for l in fixed: print(l) See a working example on repl.it, which outputs: 3 *** 2 * * 1 * * 0 *** * -1 * -2 * -3 Note it does pad the lists out with spaces, so you may want to .strip() the results if it isn't just for printing. Adapting that to your score input I'll leave up to you. Another option, which is probably clearer: def convert_and_truncate(lst, cutoff): result = [] for str in lst: str = str[0] + str[1:].replace('-', '*') # skip the negative signs str = str.replace('/', '*') str = str.replace('\\', '*') result.append(str[:cutoff]) # truncate return result Because we're truncating the rest of the list, it doesn't matter that replace is changing them all.
has comment: http://stackoverflow.com/comment/86416916
has comment: http://stackoverflow.com/comment/86417424
has comment: http://stackoverflow.com/comment/86416836
score: 3
has comment: http://stackoverflow.com/comment/86417106
has comment: http://stackoverflow.com/comment/86417147
upvote count: 3
has comment: http://stackoverflow.com/comment/86417149
has comment: http://stackoverflow.com/comment/86417183
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49701164
downvote count: 0
has comment: http://stackoverflow.com/comment/86417268
has comment: http://stackoverflow.com/comment/86417417
has comment: http://stackoverflow.com/comment/86417298
has comment: http://stackoverflow.com/comment/86416789
accepted answer of: http://stackoverflow.com/q/49701164
has comment: http://stackoverflow.com/comment/86427322
has comment: http://stackoverflow.com/comment/86417207

http://stackoverflow.com/a/49706656
downvote count: 0
has body: There are 2 errors in your code: Import all relevant modules: from numpy import linspace is missing. In Python 3.x, map returns an iterator instead of a list. You need to use y = list(map(f,N)). The below code resolving these issues runs successfully: from math import trunc from numpy import linspace from numpy.fft import rfft, irfft from pylab import plot, show def f(t): if trunc(2*t) % 2 == 0: return 1 else: return -1 N = linspace(0,1,1000) y = list(map(f,N)) c = rfft(y) For y as an array, you can use y = np.array(list(map(f,N))).
answers question: http://stackoverflow.com/q/49706228
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86428136
accepted answer of: http://stackoverflow.com/q/49706228
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/86512413
type: AnswerComment
has text: Apologies for the long winded post I figured more detail was better than less. I will keep in mind for next time.
comment on: http://stackoverflow.com/a/49748869
type: Comment
score: 0

http://stackoverflow.com/q/49690720
has comment: http://stackoverflow.com/comment/86393239
tagged with: python
has title: Best and fastest way to use constants
tagged with: optimization
has comment: http://stackoverflow.com/comment/86393176
tagged with: constants
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86393069
has body: Here are the files I have for the moment: main.py functions.py constants.py I am working on a project in python which requires some constants and I decided to stock them in a python file called constants.py which looks like: A = 5 B = 6 C = 7 # etc. This file is both imported as a module in functions.py and main.py However I would like to add some scripting and change these constants in main.py with parameters for examples, but if I change these constant in main.py they don't change anyway in functions.py which uses it a lot And I didn't find any solution to that problem yet, so I am using a dictionary but dictionary takes 3 times longer to access a variable i.e: timeit.timeit(stmt='b = a[5]; b = 0', setup="a = {5:5}", number=5000) # 0.000302988540795468 timeit.timeit(stmt='b = a; b = 0', setup="a = 5", number=5000) # 0.00013507954133143288
has comment: http://stackoverflow.com/comment/86393613
has answer: http://stackoverflow.com/a/49690913
accepted answer: http://stackoverflow.com/a/49690913
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/86393077

http://stackoverflow.com/comment/86272077
score: 0
type: Comment
type: AnswerComment
has text: Works perfectly. It seems so obvious now. Thank you!
comment on: http://stackoverflow.com/a/49632377

http://stackoverflow.com/comment/86528072
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49737317
type: AnswerComment
has text: Coming from another web framework where a similar feature was used quite extensively I think it would be useful as well in django as it would allow to just plug the legacy database easily into a django application. inspectdb already provides that only the reliability needs to be increased as it would open way to interesting opportunities in microservices and other integrations. Unless there are other tools that achieve what inpectdb does I am not aware of.

pyinstaller
tags question: http://stackoverflow.com/q/49727290
tags question: http://stackoverflow.com/q/49624213
tags question: http://stackoverflow.com/q/49710393
tags question: http://stackoverflow.com/q/49720344
tags question: http://stackoverflow.com/q/49698480
type: Tag
tags question: http://stackoverflow.com/q/49620638
tags question: http://stackoverflow.com/q/49688210
tags question: http://stackoverflow.com/q/49755568
tags question: http://stackoverflow.com/q/49662798
tag name: pyinstaller
tags question: http://stackoverflow.com/q/49616095
tags question: http://stackoverflow.com/q/49638700
tags question: http://stackoverflow.com/q/49619412
tags question: http://stackoverflow.com/q/49705245
tags question: http://stackoverflow.com/q/49637331
tags question: http://stackoverflow.com/q/49648642

http://stackoverflow.com/a/49756134
answers question: http://stackoverflow.com/q/49682576
score: 3
type: Answer
has body: Apples and Oranges It really depends on what you want to achieve. For instance, PySpark is not an alternative to Airflow. You can use both, or none of them. You Airflow Operator (the unit of work) can be as simple as "Invoke this PySpark Job". Airflow is not about the processing steps, but the pipeline itself. You'll want to use it if you want traceability, aggregated log handling, SLAs for your pipelines, conditional processing steps, backfilling control, more complex scheduling and so on. Airflow shines specially if you want to have dynamic pipelines. Edit a few YAML files and there you go, your pipelines now have a few extra steps that compute one extra data piece, backfilled historically and automated to update hourly. Of course that's not for free, you're going to implement that logic that turns configuration into Operators. Grape fruit and Grapefruit Airflow can be your orchestration mechanism of choice, but you can decide to achieve the same with a bunch of cron jobs. No sweat. Choosing the processing engine is another sort of problem. Spark is the prom queen these days, and picking Apache Beam is not running away from Spark either. It can operate on Spark and Flink, (batch vs streaming execution engines). But Spark has also a Streaming processing capability getting traction. Choosing between PySpark and Beam is not so much of a scalability concern, but what kind of technology lock-in you'll want to commit yourself to. I suggest you to pick the processing engine that you experimentally confirm that outperforms the current one. Sometimes running a command line utility can be faster than distributed jobs. Scalability is a problem that you solve as you go, because without experimentation you'll often end up with overengineered systems.
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86422257
has text: I think for better performance is best first remove unnecessary data and then `groupby` - generally less data processing, better performance. What do you think?
type: AnswerComment
comment on: http://stackoverflow.com/a/49704494
score: 1
type: Comment

http://stackoverflow.com/a/49742687
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49730750
has body: The reason you got the error because of this reason IndexError: list assignment index out of range Hence you need to use .append to get this working.

http://stackoverflow.com/comment/86284213
type: Comment
comment on: http://stackoverflow.com/q/49637830
type: QuestionComment
score: 0
has text: Yup I got it! See below and thanks for responding!

http://stackoverflow.com/a/49644318
score: 4
upvote count: 4
has body: You can rebuilt the dict using dict-comprehension. During rebuilding, you can use itertools.groupby to group the nested lists on first value of each sublist and sum the second value using a list comprehension: &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; d = {'VIC': [['City West ', 10.0], ['City West ', 30.0], ['Thornbury ', 0.0]], 'NSW': [['Queanbeyan ', 5.0],['Queanbeyan ', 20.0]], 'ACT': [['Civic ', 8.0], ['Civic ', 60.0], ['Civic ', 1.0]]} &gt;&gt;&gt; {k:[[ke,sum([i[1] for i in list(g)])] for ke,g in groupby(sorted(v), key= lambda x: x[0])] for k,v in d.items()} &gt;&gt;&gt; {'NSW': 'Queanbeyan ', 25.0, 'VIC': [['City West ', 40.0], ['Thornbury ', 0.0]], 'ACT': 'Civic ', 69.0} The above expression can also be rewritten using operator.itemgetter instead of lambda to get some performance &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; {k:[[ke,sum([i[1] for i in list(g)])] for ke,g in groupby(sorted(v), key=itemgetter(0))] for k,v in d.items()}
answers question: http://stackoverflow.com/q/49644114
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86312243
has text: hi @wildplasser what if some events can exist multiple times? i.e. ```A->B->B->D``` to ```A->B->B->C->D``` ?
comment on: http://stackoverflow.com/a/49651217
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86326599
has text: Then could you please accept the answer if it solved your issue? That's the standard procedure inside StackExchange websites: it gives credit to the most helpful members of the community and helps visitors to navigate the answers.
comment on: http://stackoverflow.com/a/49647874
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49619897
tagged with: airflow
downvote count: 0
has answer: http://stackoverflow.com/a/49624760
tagged with: python
upvote count: 7
answer count: 1
has body: Using Airflow I want to get the result of an SQL Query fomratted as a pandas DataFrame. def get_my_query(*args, **kwargs) bq_hook = BigQueryHook(bigquery_conn_id='my_connection_id', delegate_to=None) my_query = """ SELECT col1, col2 FROM `my_bq_project.my_bq_dataset.my_table` """ df = bq_hook.get_pandas_df(bql=my_query, dialect='standard') logging.info('df.head()\n{}'.format(df.head())) Above is the python function that I want to execute in a PythonOperator. Here is the DAG: my_dag = DAG('my_dag',start_date=datetime.today()) start = DummyOperator(task_id='start', dag=my_dag) end = DummyOperator(task_id='end', dag=my_dag) work = PythonOperator(task_id='work',python_callable=get_my_query, dag=my_dag) start &gt;&gt; work &gt;&gt; end But, the work step is throwing an exception. Here is the log : [2018-04-02 20:25:50,506] {base_task_runner.py:98} INFO - Subtask: [2018-04-02 20:25:50,506] {gcp_api_base_hook.py:82} INFO - Getting connection using a JSON key file. [2018-04-02 20:25:51,035] {base_task_runner.py:98} INFO - Subtask: [2018-04-02 20:25:51,035] {slack_operator.py:70} ERROR - Slack API call failed (%s) [2018-04-02 20:25:51,070] {base_task_runner.py:98} INFO - Subtask: Traceback (most recent call last): [2018-04-02 20:25:51,071] {base_task_runner.py:98} INFO - Subtask: File "/opt/conda/bin/airflow", line 28, in &lt;module&gt; [2018-04-02 20:25:51,072] {base_task_runner.py:98} INFO - Subtask: args.func(args) [2018-04-02 20:25:51,072] {base_task_runner.py:98} INFO - Subtask: File "/home/airflow/.local/lib/python2.7/site-packages/airflow/bin/cli.py", line 392, in run [2018-04-02 20:25:51,073] {base_task_runner.py:98} INFO - Subtask: pool=args.pool, [2018-04-02 20:25:51,074] {base_task_runner.py:98} INFO - Subtask: File "/home/airflow/.local/lib/python2.7/site-packages/airflow/utils/db.py", line 50, in wrapper [2018-04-02 20:25:51,075] {base_task_runner.py:98} INFO - Subtask: result = func(*args, **kwargs) [2018-04-02 20:25:51,075] {base_task_runner.py:98} INFO - Subt…
type: Question
tagged with: pandas
type: AnsweredQuestion
tagged with: google-bigquery
score: 7
favorite count: 0
has title: How to get the result of an SQL query from Big Query in Airflow?
accepted answer: http://stackoverflow.com/a/49624760

http://stackoverflow.com/comment/86441069
type: Comment
type: QuestionComment
has text: this may help https://stackoverflow.com/questions/869856/how-to-prevent-self-recursive-selection-for-fk-mtm-fields-in-the-django-admi
score: 0
comment on: http://stackoverflow.com/q/49713472

http://stackoverflow.com/comment/124257595
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49671345
score: 0
has text: @rak007 Are you sure it's an error? For me it's just a warning. That's why I'm also here for this question.

http://stackoverflow.com/comment/86207006
score: 0
comment on: http://stackoverflow.com/q/49599865
has text: “I want to retrieve all tuples of the form (1, _) where _ can be any number”. You cannot do this in O(1). Finding a subset of a set where subset criteria can be fulfilled by anywhere from 0-N items is an O(N) operation.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51619514
type: Answer
has body: If you use an LDAP server which supports server-side sorting (see RFC 2891), like OpenLDAP with slapo-sssvlv, you could search the highest number by searching exactly one search result with reversed sorting order. Python snippet based on python-ldap (excerpt from one of Æ-DIR's CLI tools): import ldap from ldap.controls.sss import SSSRequestControl def highest_id(ldap_conn, searchbase, id_attr): &quot;&quot;&quot; search the highest value of `id_attr' by using server-side (reverse) sorting &quot;&quot;&quot; # reverse sorting request control sss_control = SSSRequestControl(criticality=True, ordering_rules=['-'+id_attr]) # send search request msg_id = ldap_conn.search( searchbase, ldap.SCOPE_SUBTREE, '({0}=*)'.format(id_attr), attrlist=[id_attr], sizelimit=1, serverctrls=[sss_control], ) # collect result ldap_result = [] try: for _, res_data, _, res_controls in ldap_conn.results( msg_id, add_ctrls=0 ): ldap_result.extend(res_data) except ldap.SIZELIMIT_EXCEEDED: pass if not ldap_result: logging.error('No entry with attribute %r found!', id_attr) raise ValueError('No LDAP result!') highest_id_number = int(ldap_result[0][1][id_attr][0]) logging.debug('Highest %r value found: %d', id_attr, highest_id_number) return highest_id_number Note that this is not always what you want when assigning new IDs because gaps in the ID number space are not (re-)used. Also make sure to use a server-side unique constraint plugin, e.g. OpenLDAP's overlay slapo-unique. This avoids duplication in case concurrent clients add new entries.
answers question: http://stackoverflow.com/q/49608329
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/q/49737339
tagged with: kivy
type: Question
has comment: http://stackoverflow.com/comment/86562206
type: UnansweredQuestion
answer count: 1
has body: I am trying to print different numbers depending on the location of widgets in kivy using method collide_widget. However, instead of printing 1 or 0 depending on if clause, I get 1 and 0 at the same time and I don't understand why. I have no idea where I am wrong. It would be nice if someone explained this to me. Here is my code. from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.widget import Widget from kivy.properties import StringProperty, ObjectProperty Builder.load_string(''' &lt;Sample@Image&gt;: size: self.size allow_stretch: False keep_ratio: False do_rotation: False &lt;PutOnShelfScreen1&gt;: canvas: Rectangle: source: 'image.png' size: self.size pos: self.pos BoxLayout: orientation: 'horizontal' spacing: 30 padding: [10, 150, 10, 10] Button: id: Tools background_color: [63, 191, 63, 0.3] text: '' Button: id: Transportation background_color: [63, 191, 63, 0.3] text: '' Button: id: Furniture background_color: [63, 191, 63, 0.3] text: '' StencilView: id: elka Scatter: pos: 500, 500 size: my_image1.size Image: id: my_image1 source: 'block_1\\ель.png' StencilView: id: armchair Scatter: pos: 500, 500 size: my_image2.size Image: id: my_image2 source: 'block_1\\armchair.png' on_touch_up: root.Count(Furniture, Tools, Transportation, armchair) ''') class PutOnShelfScreen1(Screen): Tools = Widget() Transportation = Widget() Furniture = Widget() armchair = Widget() def Count(self, Furniture, Tools, Transportation, armchair): if armchair.collide_widget(Furniture) is True: print("1") if armchair.collide_widget(Tools) or armchair.collide_widget(Transportation) is True: print("0") sm = ScreenManager() sm.add_widget(PutOnShelfScreen1(name='class')) class SampleApp(App): def build(self): return (sm) if __name__ == "__main__": SampleApp().run()
has comment: http://stackoverflow.com/comment/86496431
has title: Python kivy. Something wrong with collide_widget or not?
score: 0
has answer: http://stackoverflow.com/a/49776716
tagged with: python

http://stackoverflow.com/q/49681606
has title: Loop: Results to be updated via += if on the same date, otherwise write next line
type: AnsweredQuestion
tagged with: dynamic
tagged with: function
answer count: 1
downvote count: 3
tagged with: loops
upvote count: 1
has comment: http://stackoverflow.com/comment/86375468
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49682298
tagged with: pandas
score: -2
has body: I have a function that produces some output like this date cashflow count etc 1/1/2000 40 3 ... always a one-liner. This is created many times, with same or different dates. Now I would like a record of all results date cashflow count etc 1/1/2000 40 3 ... so if a new result comes in with the same date / index, than it should add and update the field, i.e. via "+=", however if its a different date that does not already exists in the table, than it should just append and provide basis for further "updates", i.e. new result date cashflow count etc 1/1/2000 -20 1 ... then my table should show date cashflow count etc 1/1/2000 20 4 ... however if a new results hits in with a date not yet existing in the table date cashflow count etc 2/1/2000 10 20 ... then my table would look like date cashflow count etc 1/1/2000 20 4 ... 2/1/2000 10 20 ... edit1: It seems my question did not come out clear: How would a program look like that could: 1) if index coincide: update values += 2) if index not does not exist, extend the table by that line edit2: How would I need to change the below code, if my date was set as an index? edit3: Somehow this doesn't work within a loop: In a simple setup each of these one-liners are pd.DataFrames. However, in a loop they seem to be something else, such that I get the error: AttributeError: 'NoneType' object has no attribute 'groupby' If I leave aout the groupbyand use only sum: AttributeError: 'NoneType' object has no attribute 'sum' I think the loop is creating some kind of list of data frames; appending only works though.
has answer: http://stackoverflow.com/a/49682298
tagged with: python

error-messaging
type: Tag
tag name: error-messaging
tags question: http://stackoverflow.com/q/49618205

http://stackoverflow.com/comment/86494392
comment on: http://stackoverflow.com/q/49739560
type: Comment
type: QuestionComment
has text: In addition to `playlist_name` you'd also have `user_first_name` and `user_surname`. Or have just `username` since names might not conveniently work with Western conventions. But still, the principle is to have a single table with fields that allow you to differentiate between playlists.
score: 1

http://stackoverflow.com/comment/86285473
has text: @user2757771 Better to perform reset of device to the normal state let's says 0,0,0 point before every new call. Because in case of terminated program or even blackout on remote site you will lose it state and it can't dump current state into the file. To avoid double execution you can check running scripts smth like "ps aux | grep my_control_script.py" and make decision based on that.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49638005

http://stackoverflow.com/comment/86369608
comment on: http://stackoverflow.com/q/49678975
has text: What happens when you do `import fedex` and `import fedex.config`. Also, what does running `python --version` in the shell output?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49630382
accepted answer: http://stackoverflow.com/a/49630887
answer count: 1
has body: I am trying to prepare a docker-compose file that stands up 2 containers. They are postgres and python app inside an alpine image. Just consider before reading ı need to use python inside alpine. My Dockerfile is: FROM python:3 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD [ "python", "./app.py" ] My app.py file: import psycopg2 from config import config def connect(): """ Connect to the PostgreSQL database server """ conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() # execute a statement print('PostgreSQL database version:') cur.execute ("SELECT * FROM my_table;") # display the PostgreSQL database server version db_version = cur.fetchone() print(db_version) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.') if __name__ == '__main__': connect() I started python container with that command: docker run -it my_image app.py I seperately started 2 container(postgres and python) and make it worked. However my container works only once and its job is to make an select job inside postgresql database. That was first part. My main goal is below. For the simplicity i prepared a docker-compose.yml file: version: '3' services: python: image: python build: context: . dockerfile: Dockerfile postgres: image: postgres:${TAG:-latest} build: context: . environment: POSTGRES_PASSWORD: example ports: - "5435:5432" networks: - postgres networks: postgres: My dockerfile is here When i type docker-compose up my postgres starts but python exits with code 0. my_file_python_1 exited with code 0 What should i do for stands alone container for python apps with docker-compose? It always works only once. I can make …
tagged with: docker
tagged with: postgresql
has answer: http://stackoverflow.com/a/49630887
tagged with: docker-compose
type: AnsweredQuestion
score: 0
has title: Python exits with code 0 immediatelly after stand up with docker
type: Question
tagged with: python

http://stackoverflow.com/comment/86384399
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49643183
score: 0
has text: excel_file1 = 'filepath\\file.xlsx' df1=pd.read_excel(excel_file1,sheet_name=0)..in this sheet the above problem exists...

http://stackoverflow.com/comment/86310741
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49651202
type: Comment
has text: Its the first in the timetable

http://stackoverflow.com/a/49667192
answers question: http://stackoverflow.com/q/49667026
score: 2
type: Answer
has body: The shortest one would be df[df&lt;100]
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/49661552
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86333239
has body: Key Error:'Adj Close' is the answer to your problem A KeyError generally means the key doesn't exist. So, are you sure the path key exists? From the official python docs: exception KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys. For example: mydict = {'a':'1','b':'2'} mydict['a'] '1' mydict['c'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'c'
answers question: http://stackoverflow.com/q/49661414
has comment: http://stackoverflow.com/comment/86333132
has comment: http://stackoverflow.com/comment/86333278

http://stackoverflow.com/a/49733205
answers question: http://stackoverflow.com/q/49720659
upvote count: 5
type: Answer
has body: I'll answer the question with code that works for a single instance (although it shouldn't be hard to edit it for multiple instances by fetching the right player and voice_channel objects from the dictionary). You have to first make a queue that store the urls that your player will play your objects in. I assume that you should also make a dictionary of queues to store the different urls for the different servers. To help manage your stream_player workflow, first declare a voice and player object in the outermost scope. self.player = None self.voice = None The voice object should be set after the bot joins a voice channel: mvoice = await client.join_voice_channel(voice channel id here) self.voice = mvoice We then have to make two functions as Python does not support async lamdas while managing the stream player can only be done from a async function. The play_music function should be called by the bot whenever the user types the relevant command: #pass the url into here when a user calls the bot async def play_music(client, message, url=None): if url is None: #function is being called from after (this will be explained in the next function) if queue.size() &gt; 0: #fetch from queue url = queue.dequeue() else: #Unset stored objects, also possibly disconnect from voice channel here self.player = None self.voice = None return if self.player is None: #no one is using the stream player, we can start playback immediately self.player = await self.voice.create_ytdl_player(url, after=lambda: play_next(client, message)) self.player.start() else: if self.player.is_playing(): #called by the user to add a song queue.enqueue(url) else: #this section happens when a song has finished, we play the next song here self.player = await self.voice.create_ytdl_player(url, after=lambda: play_next(client, message)) self.player.start() The play_next function will be called from the finalizer after the stream player has finished a song and will call the above function again but without the ur…
score: 5
downvote count: 0

http://stackoverflow.com/q/49728262
tagged with: python-requests
has comment: http://stackoverflow.com/comment/86471100
has comment: http://stackoverflow.com/comment/86470432
tagged with: wunderground
type: Question
accepted answer: http://stackoverflow.com/a/49729255
score: 0
has answer: http://stackoverflow.com/a/49729255
has body: I would like to do the following. 1) Goto https://www.wunderground.com/history 2) Submit the form with the following values: Location = 'Los Angeles, CA' Month = 'November' Day = '02' Year = '2017' 3) Retrieve the response and save to a file Here is what I have at the moment, but does not work: import requests url = 'https://www.wunderground.com/history' payload = {'code': 'Los Angeles, CA', 'month': 'November', 'day': '2', 'year':'2017'} r = requests.post(url, params=payload) with open('test.html', 'w') as f: f.write(r.text) I'm not getting the expected response and not sure If I am using requests properly or not. I know there's an API from wunderground but prefer not to use it at the moment. The content of test.html is basically the original page with no historical data. I'm expecting this page: https://www.wunderground.com/history/airport/KCQT/2017/11/2/DailyHistory.html?req_city=Los+Angeles&amp;req_state=CA&amp;req_statename=California&amp;reqdb.zip=90012&amp;reqdb.magic=1&amp;reqdb.wmo=99999
tagged with: submit
tagged with: python
possible better answer: http://stackoverflow.com/a/49729053
tagged with: forms
has answer: http://stackoverflow.com/a/49729053
has title: How to use Python to submit form within Wunderground History page
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/49732036
has body: I need help with some project. Maybe somebody could help me. I got some data in mongodb. Now it looks like: { Order: { order_id: id, SKU: some_vale, date: "10.10.1010", time: "12:12", product_name: some_name, number_of_goodies: some_value } } And I need to group it to look like: { Order: { order_id: id, product: { SKU: some_vale, product_name: some_name, number_of_goodies: some_value } date: "10.10.1010", time: "12:12" } } Now there can be more than one document for one order. They got same order_ID but different products. I was trying to use aggregation, but wasn't really successful. If someone know how to solve this problem using aggrigation?
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 1
type: Question
has title: MongoDB: aggregation. Don't know how to use it correctly
has answer: http://stackoverflow.com/a/49732415
tagged with: mongodb

http://stackoverflow.com/comment/86225933
comment on: http://stackoverflow.com/a/49608760
has text: Got it! Thanks a lot :)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49678125
tagged with: false-positive
tagged with: python
has comment: http://stackoverflow.com/comment/86367987
has body: I have a dataframe object in R/Python that looks like: df columns: fraud = [1,1,0,0,0,0,0,0,0,1] score = [0.84, 1, 1.1, 0.4, 0.6, 0.13, 0.32, 1.4, 0.9, 0.45] When I use roc_curve in Python I get fpr, fnr and thresholds. I have 2 questions, maybe a bit theoretical but please explain it to me: Are these thresholds are calculated actually? I have calculated manually fpr and fnr, but are these thresholds = the score above? How can I generate same fpr, fnr and thresholds in R?
accepted answer: http://stackoverflow.com/a/49678379
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86368129
has title: ROC-AUC FPR FNR in Python and R?
answer count: 1
has comment: http://stackoverflow.com/comment/86367926
downvote count: 1
has answer: http://stackoverflow.com/a/49678379
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86367754
tagged with: roc
tagged with: auc
has comment: http://stackoverflow.com/comment/86367881

http://stackoverflow.com/comment/86303623
has text: Yes! I was just confused and was trying to figure out a way to break out of the loop. Thanks for that
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49647655

http://stackoverflow.com/comment/86393701
score: 0
comment on: http://stackoverflow.com/q/49690613
has text: @jpp, thanks a lot for the answer. I included a running code but without the lines which I need. I would like to solve it without pandas functions etc but just with indexing and nested loops.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49713595
type: UnansweredQuestion
upvote count: 0
has title: binary to decimal converter (including negative)
tagged with: python
score: -1
tagged with: converters
has answer: http://stackoverflow.com/a/49713714
answer count: 1
has comment: http://stackoverflow.com/comment/86440615
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86440562
tagged with: decimal
tagged with: binary
has body: I need to convert from binary values such as '1010' to decimal values. this needs to include negative binary. def BinaryToDecimal (n): n1 = n decimal = 0 i = 0 n = 0 while(n != 0): dec = n % 10 decimal = decimal + dec * pow(2, i) n = n//10 i += 1 print(decimal) This is what i have so far, but it doesn't work. I'm not sure what else to do. Please help! I am not allowed to use any fancy python libraries, I am supposed to write the code manually.

http://stackoverflow.com/q/49735252
score: 2
type: AnsweredQuestion
tagged with: django-models
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49735396
tagged with: django-select-related
has title: Django get dictionary of siblings without using prefetch related?
has answer: http://stackoverflow.com/a/49735396
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86485656
tagged with: one-to-many
upvote count: 2
tagged with: django
tagged with: python
has body: I have three models like the following and have a list of Boys. How can I get a list of each of their sisters? Unfortunately I can not use prefetch related as I am stuck using a very old version of django. class Parent(model.Model): name = models.CharField(max_length=50) class Boy(model.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=50) class Girl(model.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=50) Desired output would be something like this: { boy1: [ sister1, sister2 ], boy2: [ .. ] } Thanks in advance for any help!

http://stackoverflow.com/comment/86444882
type: AnswerComment
has text: @Axioms That would be a "static" Class-Variable, its shared between instances of that class, one changes it - all gets the change. Unless you need to create 20 different worlds, accessing the same `df` I would probably use a `self.df = None` inside the `__init__(self, ... )`, load it inside load `self.df = pd.read_csv(...)` etc.
type: Comment
comment on: http://stackoverflow.com/a/49715880
score: 0

http://stackoverflow.com/comment/135543572
comment on: http://stackoverflow.com/q/49660528
type: QuestionComment
has text: @Paroofkey thanks, i had that problem and I did not even noticed the duplicated column
score: 0
type: Comment

http://stackoverflow.com/comment/86255431
score: 0
comment on: http://stackoverflow.com/q/49623766
type: Comment
type: QuestionComment
has text: size(a(:))` is (4096,1). A column vector. Not quite the same as a 1d numpy array. `[a(:), b(:), c(:)]` will be (4096,3). In `numpy` do you want (3, 4096) or (4096,3) array? `numpy` is C ordered (by default), MATLAB F ordered.

http://stackoverflow.com/comment/86398846
type: Comment
type: QuestionComment
has text: `self.BroadCastSocket.bind(('0.0.0.0', self.MCAST_PORT))` Don't use all interfaces. **Cannot be connected to a broadcasting socket !** It is a weird idea to respond to the municipal announcement (o: .
score: 0
comment on: http://stackoverflow.com/q/49691805

http://stackoverflow.com/q/49707018
downvote count: 3
linked to: http://stackoverflow.com/q/4706499
duplicate of: http://stackoverflow.com/q/6159900
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49707065
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/4706499
score: -3
tagged with: python
possible better answer: http://stackoverflow.com/a/49707065
has body: I am fairly new to python, and have been trying to create a program where I create a file from user inputs. However, I cannot seem to get it to work, and keep getting the error: Traceback (most recent call last): File "my_program.py", line 7, in &lt;module&gt; my_file.append(x) AttributeError: '_io.TextIOWrapper' object has no attribute 'append' I think this means that I cannot append the file, but I am not sure at all why. Here is the relevant part of my program: my_file = "my_file" with open(my_file, 'a') as my_file: lines = True counting_variable = 0 while lines: x = input() my_file.append(x) Thank you very much for any help in advance!
has title: Python: How to append a file in python using inputs?
linked to: http://stackoverflow.com/q/6159900
accepted answer: http://stackoverflow.com/a/49707078
answer count: 3
has answer: http://stackoverflow.com/a/49707092
upvote count: 0
has answer: http://stackoverflow.com/a/49707078

http://stackoverflow.com/q/49603112
accepted answer: http://stackoverflow.com/a/49603716
tagged with: user-input
type: Question
possible better answer: http://stackoverflow.com/a/49603200
has answer: http://stackoverflow.com/a/49603716
answer count: 2
has answer: http://stackoverflow.com/a/49603200
has body: I am trying to create a separate json file for each student from a user input. At the moment, I can only dump all information into one file but I need the dictionary to be in a separate file according to the name from the user input. I am also trying to update a dictionary every time the user input import json def get_input(): #user input to record in log name = input("Name:") d = {} #my dictionary d['date'] = input('Enter a date in YYYY-MM-DD format:') d['hours'] = input("Hours:") return(name,d) out = {} while True: exit = input('Do you want to add another input (y/n)?') if exit.lower() == 'n': break else: name, d = get_input() out[name] = d #dump into separate file according to name from user input if name == 'Jessica': with open('jessica.json','a') as j: json.dump(out, j, indent= 2) elif: name == 'Wendy': with open('wendy.json','a') as w: json.dump(out, w, indent= 2) else: with open('tat.json','a') as t: json.dump(out, t, indent= 2)
tagged with: python
tagged with: dictionary
tagged with: logging
type: AnsweredQuestion
score: 0
has title: How to dump json dictionary into multiple file given condition
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/49714704
score: 2
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/49714254
downvote count: 0
has body: You can use list() method , apart from that you can also use list comprehension method : exstr1 = "BBBBBBDDDDDDHHHGHHFFGGFF" index = [0, 1, 3, 4, 5, 8, 9, 10, 11, 12, 14, 16, 17, 18, 19, 20, 21, 22, 23] data=[i for i in exstr1] for i in index: data[i]='S' print(data) output: ['S', 'S', 'B', 'S', 'S', 'S', 'D', 'D', 'S', 'S', 'S', 'S', 'S', 'H', 'S', 'G', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S']

http://stackoverflow.com/comment/86309884
type: Comment
has text: great, please accept my anwer.
score: 0
comment on: http://stackoverflow.com/q/49647757
type: QuestionComment

http://stackoverflow.com/comment/86246405
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49619443
has text: *"extract those substrings"* is not a clear problem statement. You mean *"split on the hyphen (if any), and return the substring ending in 'Mill' or 'POM'"*

http://stackoverflow.com/comment/86292024
has text: @user7865286 Yes—or, maybe more simply, that the list contains itself: `some_list[0] is some_list`. I thought this would be less surprising than the fact that if `s = 'a'`, `s[0] is s`, so it would help illuminate the problem, but now that I think about it, how many people actually know about recursive lists in Python? The only really obvious example would be a class that explicitly iterates itself, which is too big and distracting to be worth commenting about; better to just go straight to `s[0] is s` for strings as BallpointBen did.
score: 0
comment on: http://stackoverflow.com/q/49641930
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86419386
has text: @npatel OK, then do either of the other two versions I explained first.
type: Comment
comment on: http://stackoverflow.com/a/49702783
type: AnswerComment
score: 0

http://stackoverflow.com/q/49670868
has comment: http://stackoverflow.com/comment/86352921
tagged with: python
linked to: http://stackoverflow.com/q/18035595
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/49671009
has comment: http://stackoverflow.com/comment/86352411
has comment: http://stackoverflow.com/comment/86351860
has answer: http://stackoverflow.com/a/49671014
linked to: http://stackoverflow.com/q/49669856
upvote count: 1
has body: I am manipulating a set, so if you have a set(aka:list) of n distinctive elements, then you have 2^n subset. Here I show how: def powerset(s): x = len(s) masks = [1 &lt;&lt; i for i in range(x)] for i in range(1 &lt;&lt; x): yield [ss for mask, ss in zip(masks, s) if i &amp; mask] l = list(powerset(["A", "B"])) print(l) which gives: [[], ['A'], ['B'], ['A', 'B']] Now how can take the above list eliminate the empty list, and merge the last element such that it becomes: ['A', 'B', 'AB'] I want to repeat this procedure 5 times, taking final output and write its sublist, eliminate the empty list and merge those elements that they fall into the same sublist.
tagged with: powerset
downvote count: 1
has comment: http://stackoverflow.com/comment/86351899
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49671266
possible better answer: http://stackoverflow.com/a/49670942
tagged with: for-loop
has answer: http://stackoverflow.com/a/49671603
has answer: http://stackoverflow.com/a/49671266
answer count: 5
has title: Power set manipulation in Python
has answer: http://stackoverflow.com/a/49670942

http://stackoverflow.com/comment/86462940
has text: I don't want items to be listed unless i do search on them. So the list view is not listing all items (records).
comment on: http://stackoverflow.com/q/49724220
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/73801059
type: Answer
answers question: http://stackoverflow.com/q/49643907
score: 3
upvote count: 3
downvote count: 0
has body: For Pytorch based grad_cam I was getting similar errors in show_cam_on_image and what worked cleanly was input_image = Image.open(filename) img=np.array(input_image.resize((227,227)),np.float32) img *= (1.0/img.max())

http://stackoverflow.com/a/49708097
downvote count: 0
answers question: http://stackoverflow.com/q/49707401
type: Answer
has body: You can use this: desired_value = 0 mylist = [i for i in mylist if i!=desired_value] + [desired_value] You can now change your desired value, you can also make it as a list like this desired_value = [0, 6] mylist = [i for i in mylist if i not in desired_value] + desired_value
upvote count: 1
score: 1

http://stackoverflow.com/a/49724618
has body: I wanted to see 'str' returned when I used df.dtypes, well, .dtypes is a numpy function and anything other than a number representation will be returned as 'object.' So, my values are indeed being read in as strings. Doh. I found the answer here: can not convert column type from object to str in python dataframe This link is helpful, too, for newbies like me: How to get datatypes of all columns using a single command [ Python - Pandas ]?
score: 1
answers question: http://stackoverflow.com/q/49723594
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/q/49652697
favorite count: 0
type: Question
has title: Runtime error: maximum recursion depth exceeded in Odoo 10
has answer: http://stackoverflow.com/a/49658450
accepted answer: http://stackoverflow.com/a/49658450
type: AnsweredQuestion
downvote count: 0
tagged with: odoo-10
upvote count: 1
tagged with: odoo
score: 1
answer count: 1
has body: I am new to odoo and I received this error when I added a function in inherited sale_order_line class.Below is the code. Could you please let me know where I did the blunder? class SaleOrderLine(models.Model): _inherit = 'sale.order.line' product_id = fields.Many2one('product.product', string='Product', domain=[('sale_ok', '=', True)], change_default=True, ondelete='restrict', required=True) salesman_id = fields.Char(string='Salesman') @api.onchange(product_id) @api.depends(salesman_id) def user_id_tracking(self): self.env.cr.execute("""SELECT user_id FROM stock_location as sl WHERE sl.id in (SELECT sq.location_id FROM stock_change_product_qty as sq,product_template as pt WHERE sq.product_id = %d)""", self.product_id) res = self.env.cr.fetchone() self.salesman_id = res[0] lot_id = fields.Many2one('stock.production.lot', string='Lot/Serial Number', copy=False)
tagged with: python

http://stackoverflow.com/q/49661495
favorite count: 0
type: Question
upvote count: 1
type: UnansweredQuestion
answer count: 1
has title: ValueError: Initializer for variable cudnn_gru/opaque_kernel/ is from inside a control-flow construct, such as a loop or conditional
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49662190
downvote count: 0
score: 1
has body: System information Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes OS Platform and Distribution: Ubuntu 16.04 TensorFlow installed from: Binary TensorFlow version: 1.5.0 Python version: 3.5.2 CUDA/cuDNN version: 9.0/7 GPU model and memory: NVIDIA GTX 1080 8GB x 4 Exact command to reproduce: Code as below I have been trying to use a for-loop with tf.cond applied on cudnn_gru to run multiple times on inputs, and the minimum error reproducible code is as below: import tensorflow as tf max_para = tf.placeholder(tf.int32) num_units = 150 inputs = tf.placeholder(tf.float32,shape=[15,8,num_units]) class cudnn_gru: def __init__(self): self.gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units, kernel_initializer=tf.random_normal_initializer(stddev=0.1)) with tf.variable_scope('CUDNN_GRU', reuse=tf.AUTO_REUSE): self.init_fw = tf.get_variable("init_fw",shape=[1, 8, num_units],initializer= tf.zeros_initializer()) self.init_bw = tf.get_variable("init_bw",shape=[1, 8, num_units],initializer= tf.zeros_initializer()) def __call__(self,inputs): out_fw, _ = self.gru_fw(inputs, initial_state=(self.init_fw,)) class cudnn_gru2: def __init__(self): self.gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units-1, kernel_initializer=tf.random_normal_initializer(stddev=0.1)) with tf.variable_scope('CUDNN_GRU', reuse=tf.AUTO_REUSE): self.init_fw = tf.get_variable("init_fw",shape=[1, 8, num_units],initializer= tf.zeros_initializer()) self.init_bw = tf.get_variable("init_bw",shape=[1, 8, num_units],initializer= tf.zeros_initializer()) def __call__(self,inputs): out_fw, _ = self.gru_fw(inputs, initial_state=(self.init_fw,)) def get_output(): gru = cudnn_gru() out = gru(inputs) return tf.constant(1) def get_output2(): gru = cudnn_gru2() out = gru(inputs) return tf.constant(2) for i in range(3): i_ = tf.constant(i) out = tf.cond(i_&lt;max_para,get_output,get_output2) The error stacktrace is as follows: Traceback (most recent call last): File "temp.py"…
tagged with: python
linked to: http://stackoverflow.com/q/49314186

http://stackoverflow.com/q/49685821
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/93684392
has comment: http://stackoverflow.com/comment/86383933
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/71851916
type: UnansweredQuestion
downvote count: 1
favorite count: 0
type: Question
has body: While executing the command pip install bayesianpy I'am getting the error: Could not find a version that satisfies the requirement bayesianpy (from versions: ) No matching distribution found for bayesianpy.
has title: Could not find a version that satisfies the requirement bayesianpy (from versions: ) No matching distribution found for bayesianpy
has answer: http://stackoverflow.com/a/51157175
has comment: http://stackoverflow.com/comment/86383187

http://stackoverflow.com/comment/86337286
type: Comment
score: 0
has text: _Is there a way to validate the client sends back a valid UUID?_ && _I'm also not sure if there's a good way to validate the client sent back a valid value_ - can you clarify what it is you want then? (besides can you do this in JavaScript)
type: QuestionComment
comment on: http://stackoverflow.com/q/49663720

http://stackoverflow.com/comment/86440303
comment on: http://stackoverflow.com/a/49713367
type: Comment
score: 0
type: AnswerComment
has text: Hadn't thought about its purpose in making the parameter clear, good observation to keep in mind.

http://stackoverflow.com/q/49729175
tagged with: matrix
type: Question
tagged with: numpy
tagged with: python-3.x
has body: I'm trying to create a confusion matrix in NumPy, so I initialize a zero-filled matrix with size n x n being n the number of classes in my classifier. After that I iterate over every output (which is a word, or number, or whatever, but is contained in self.clases__), get the indices in the set of clases that correspond to the real label and the output, and try to increase the value at that position by 1. This results in an IndexError exception, here's the output for a simple example: In[99]: e.score([[0.1,0.5,0.7,0.8],[0.4,0.5,0.1,0.1,0.9],[0.1,0.9], [0.1,0.5,0.8,0.2,0.9]],['Clase 1','Clase 2','Clase 2','Clase 1']) Clase 1 -&gt; 0 Clase 1 -&gt; 0 (2, 2) Clase 1 -&gt; 0 Clase 2 -&gt; 1 (2, 2) Traceback (most recent call last): File "&lt;ipython-input-99-2b9291b14506&gt;", line 2, in &lt;module&gt; e.score([[0.1,0.5,0.7,0.8],[0.4,0.5,0.1,0.1,0.9],[0.1,0.9], [0.1,0.5,0.8,0.2,0.9]],['Clase 1','Clase 2','Clase 2','Clase 1']) File "redes.py", line 156, in score conf_matrix[i][j] += 1 IndexError: index 1 is out of bounds for axis 0 with size 1 Here's the code: def score(self,X,Y): salidas_obtenidas = self.clasifica(X) conf_matrix = zeros((len(self.clases__),len(self.clases__)),dtype=int) indexador = array(range(0,len(self.clases__))) for k,obt in enumerate(salidas_obtenidas): i = indexador[self.clases__ == obt] j = indexador[self.clases__ == Y[k]] print("%s -&gt; %d" % (obt,i)) print("%s -&gt; %d" % (Y[k],j)) print(conf_matrix.shape) conf_matrix[i][j] += 1 return conf_matrix The thing that has me stumped is that the shape printed is obviously big enough to be indexed, and yet it raises the exception. I use the numpy classes array and zeros. Also, to my even greater confusion, conf_matrix doesn't update, if I print it at any point in the execution, it just prints a zero-filled matrix, even though before it raises the exception, it should have at least a position with 1 in it. That makes me suspect it's not actually accessing the real matrix, but I have no idea why it wouldn…
tagged with: indexing
has comment: http://stackoverflow.com/comment/86474159
possible better answer: http://stackoverflow.com/a/49731918
tagged with: python
accepted answer: http://stackoverflow.com/a/49731836
has comment: http://stackoverflow.com/comment/86475759
has answer: http://stackoverflow.com/a/49731918
has title: Python/NumPy: IndexError in matrix with enough size
has answer: http://stackoverflow.com/a/49731836
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/a/49736449
has comment: http://stackoverflow.com/comment/86487292
has comment: http://stackoverflow.com/comment/86487259
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49736311
downvote count: 0
type: AcceptedAnswer
has body: You can using unstack with stack df['bins']=pd.cut(df['YearlyAvg'], np.arange(0,1250,50)) df.groupby(['Type','bins']).size().unstack(fill_value=0).stack()# also here will create the multiple index for achieve what you need Out[1783]: Type bins AT267 (0, 50] 0 (200, 250] 1 PQ43 (0, 50] 1 (200, 250] 0 dtype: int64
type: Answer
accepted answer of: http://stackoverflow.com/q/49736311

http://stackoverflow.com/a/49643023
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/86297796
has body: Hi, so you will need some python web framework, as you already mentioned flask could be good option. To deploy your application to the production you will also need a web server running on your remote server. After that, you can setup your web server to communicate with your flask running application. Your flask endpoint could look something like this: @app.route('/evaluate', methods = ['GET', 'POST']) def index(): if request.method == 'POST': # Computed ML output output = compute_data(data) # Format to graph data graph_data = transform_to_graph(output) # Pass data to the template return render_template('graph-view.html', graph_data=graph_data) return render_template('main.html') Where main.html will be page with button and user input: User Input Provide with input This could be pretty simple and straightforward tutorial for Flask basics: https://www.codementor.io/overiq/basics-of-flask-fzvh8ueed. Search for other sources and you will get into that quickly. For deployment you will also need application server running your flask app, as flask by it self isn't production ready. I could recommend Gunicorn, here is one of the many tutorials showing setup of Gunicorn with Nginx proxy web server: https://tutorials.technology/tutorials/71-How-to-setup-Flask-with-gunicorn-and-nginx-with-examples.html. Please search for this topic, there's plenty of tutorials out there.
upvote count: 4
has comment: http://stackoverflow.com/comment/86293866
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49642502
has comment: http://stackoverflow.com/comment/86297546
has comment: http://stackoverflow.com/comment/86294442
accepted answer of: http://stackoverflow.com/q/49642502

http://stackoverflow.com/comment/86336926
type: Comment
type: QuestionComment
has text: @PaulPanzer yes, this is exactly what it is thank you!
comment on: http://stackoverflow.com/q/49663401
score: 0

http://stackoverflow.com/comment/104679458
type: AnswerComment
type: Comment
score: 11
comment on: http://stackoverflow.com/a/51648513
has text: Hi! I am using DRF 3.10.2 with Django 2.2.4. Adding this stub method results in the router ignoring this route :(

http://stackoverflow.com/comment/86453196
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49718970
has text: @jpp, one more thing, every sublist belongs to another class, so every sublist is an object when i try these methods i always end up getting the error [ object is not iterable ] , how can i fix this problem?
type: Comment

http://stackoverflow.com/comment/86246316
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49616684
has text: The reason is that in adminsite you can click on the metabolite and check the information of this metabolite while viewing information of Reactionmeta
score: 0

http://stackoverflow.com/comment/86396519
type: AnswerComment
score: 0
has text: so why it doesn't throw an error after evaluating `print(True and False)`?
type: Comment
comment on: http://stackoverflow.com/a/49692056

http://stackoverflow.com/a/59815193
has body: I find most of the current answers either poor performance-wise or hard to read. An alternative functional way of doing this would be by using such itertools functions as chain.from_iterable, repeat, and count: from itertools import chain, count, repeat initial_list = [1, 2, 3, 5] result = list(chain.from_iterable(map(repeat, count(), initial_list))) # [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49613360
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/49646670
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86303702
has title: Average from two different dataframes
has comment: http://stackoverflow.com/comment/86301452
tagged with: dataframe
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/49647716
has body: I have df like: material plant Order 24990 89952 4568789,5098710 24990 89952 9448609,1007081 166621 3062 18364103 166621 3062 78309139 240758 3062 55146035 276009 3062 38501581,857542 and df1 like: material plant Order m1 m2 m3 m4 m5 24990 89952 4568789 0.123 0.214 0.0 0.0 0.0 24990 89952 5098710 1.000 0.363 0.0 0.0 0.0 24990 89952 9448609 0.0 0.345 0.0 1.0 0.0 24990 89952 1007081 0.0 0.756 0.0 1.0 0.0 166621 3062 18364103 0.0 0.0 0.0 0.0 0.0 166621 3062 78309139 0.0 1.0 0.0 0.0 0.0 240758 3062 55146035 1.0 1.0 1.0 0.0 0.0 276009 3062 38501581 1.0 1.0 1.0 0.0 0.0 276009 3062 38575428 1.0 1.0 1.0 0.0 0.0 I want to iterate through Order in df1 and when there is a match of Order in df2 then find average from m1 to m5. I want to achieve df2 like: material plant Order avg m1 avgm2 avgm3 avgm4 avgm5 24990 89952 4568789,5098710 0.5615 0.2885 0.0 0.0 0.0 24990 89952 9448609,1007081 166621 3062 18364103 166621 3062 78309139 240758 3062 55146035 276009 3062 38501581,857542 I am trying different ways to achieve df2 such as: df2 = (df.groupby(df1, sort=False)['Order'].apply(lambda x: ','.split(x.astype(str))) .mean() .reset_index() .reindex(columns=df.columns)) print (df2) second: group = df.columns[np.r_[0:3, 3:len(df.columns)]] res = df1.groupby(group)['Order'].apply(list).mean().reset_index() But I am not sure if this is the correct way to get it.
has answer: http://stackoverflow.com/a/49647700
accepted answer: http://stackoverflow.com/a/49647700
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86301421
answer count: 2
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/49647716
favorite count: 0

http://stackoverflow.com/q/49720892
score: 0
has body: I want to create a numpy array within a numpy array. If i do it with normal python its something like a = [[1,2], [3,4]] a[0][1] = [1,1,1] print a The result is [[1, [1, 1, 1]], [3, 4]] How can I achieve the same using numpy arrays? The code I have is: a = np.array([(1, 2, 3),(4, 5, 6)]) b = np.array([1,1,1]) a[0][1] = b
accepted answer: http://stackoverflow.com/a/49722146
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/49720957
has comment: http://stackoverflow.com/comment/86455029
has comment: http://stackoverflow.com/comment/86455049
upvote count: 1
has answer: http://stackoverflow.com/a/49722146
has answer: http://stackoverflow.com/a/49720957
downvote count: 1
has comment: http://stackoverflow.com/comment/86454914
has title: Create numpy array within numpy array
has comment: http://stackoverflow.com/comment/86454960
type: AnsweredQuestion

http://stackoverflow.com/comment/87351546
type: AnswerComment
comment on: http://stackoverflow.com/a/50035506
has text: Try change cv2.VideoCapture("rtsp://192.168.0.100:554/onvif1") to cv2.VideoCapture("rtsp://192.168.0.100:554/onvif1", apiPreference=cv2.CAP_FFMPEG). I also edited my answer.
score: 0
type: Comment

http://stackoverflow.com/comment/86460867
type: Comment
comment on: http://stackoverflow.com/a/49723267
score: 0
type: AnswerComment
has text: This doesn't really answer my question at all?

http://stackoverflow.com/q/49698077
has comment: http://stackoverflow.com/comment/86409198
has comment: http://stackoverflow.com/comment/87743904
has comment: http://stackoverflow.com/comment/86409284
tagged with: python
has body: There is a way, using localeon python to get the currency of a specific country or having the currency code, knows which countries that official use this currency?
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/49698247
upvote count: 2
has title: Get currency for country using `locale`
has answer: http://stackoverflow.com/a/50379864
downvote count: 0
favorite count: 0
type: Question
tagged with: currency
tagged with: locale
type: UnansweredQuestion

http://stackoverflow.com/q/49717115
accepted answer: http://stackoverflow.com/a/49778263
upvote count: 2
has answer: http://stackoverflow.com/a/49778263
has comment: http://stackoverflow.com/comment/86449826
tagged with: python
has title: Keras model.evaluate_generator results nearly twice real accuracy?
tagged with: keras
has comment: http://stackoverflow.com/comment/86449852
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86449995
tagged with: deep-learning
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86449817
has comment: http://stackoverflow.com/comment/86449866
has comment: http://stackoverflow.com/comment/86450013
downvote count: 1
has comment: http://stackoverflow.com/comment/86449566
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86450015
has comment: http://stackoverflow.com/comment/86449876
has body: UPDATE: see new section below. When I run model.evaluate_generator it gives me results of 92%. But if I run model.predict_classes on every test image and count the correct classification vs incorrect classification, I get 49%... Clearly something is wrong. Am I misunderstanding the evaluate_generator results, or am I not doing predict_classes right? Here is the model.evaluate_generator call (it gets 92%): print("test_generator from Directory"); test_generator = test_datagen.flow_from_directory( test_dir, target_size=(200, 200), batch_size=20, class_mode='categorical') # finally evaluate this model on the test data results = model.evaluate_generator( test_generator, steps=1) print('Final test accuracy:', (results[1]*100.0)) For the comparison, I test every file and compare to the correct classification (this gets 49%): img_path = os.path.join(bol, file) print(img_path) image = load_img(img_path, target_size=(200, 200)) image = img_to_array(image) image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) image = preprocess_input(image) # classify the image print("classifying image...") y_hat = model.predict_classes(image) print(y_hat[0]) idtype = newdict[y_hat[0]] #this part is to match predicted class with true class destpath = os.path.join(bol, idtype, file) print(idtype) if idtype == cat[1]: correct = correct + 1 count = count + 1 factor = correct / count print(str(count) + " - " + str(correct) + " = " + str(factor)) The full code is here: https://s3.eu-west-2.amazonaws.com/klondon/food_6_VGG_aug_plus_id.py.txt EDIT: With the help of Matias Valdenegro in the comments, I have fixed some bugs with my code. It now uses 'Softmax' output and categorical cross-entropy loss. Full code here: https://s3.eu-west-2.amazonaws.com/klondon/food_6_VGG_aug_plus_id_cat.py.txt However - The core issue remains. There is a huge difference between the results from evaluate_generator (now 71%) and a manual test of the same images using predict_classes (53%). Are there o…

http://stackoverflow.com/comment/86462675
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49723594
has text: I do have NaNs in the columns, so now I'm trying to just read them in as strings and convert to int, float, etc in the code. But I keep having problems with the 'objects' reverting back to 'object' once I do something like df['somecolumn'] = df['somecolumn'].astype('int')

http://stackoverflow.com/comment/118874380
comment on: http://stackoverflow.com/a/49683090
score: 0
type: AnswerComment
has text: Can you please help with pytest equivalent of the same?
type: Comment

http://stackoverflow.com/a/49694481
has comment: http://stackoverflow.com/comment/86404764
answers question: http://stackoverflow.com/q/49693649
has comment: http://stackoverflow.com/comment/86404153
upvote count: 2
has comment: http://stackoverflow.com/comment/86403596
downvote count: 0
has comment: http://stackoverflow.com/comment/86403229
score: 2
has body: You should have read in the data using a decimal=',' argument if you used pd.read_csv. Otherwise, if you're stuck with this data frame, you can dump it out to a csv and try again. pd.read_csv(pd.io.common.StringIO(df.to_csv(index=False)), decimal=',') 0 1 2 3 4 5 6 7 8 0 1 9.5 50.6 45.759628 2.6 6.5 11.0 8.9 NaN 1 2 10.5 59.9 74.445390 0.0 4.5 8.9 NaN NaN 2 3 20.1 37.7 NaN 0.8 2.5 9.7 6.7 4.2 3 4 10.7 45.2 10.971085 0.4 3.1 6.9 5.5 4.7 4 5 13.2 39.9 9.233933 0.0 5.8 9.2 7.4 4.3 Filling in missing data becomes easy. d = pd.read_csv(pd.io.common.StringIO(df.to_csv(index=False)), decimal=',') d.fillna(d.mean()) 0 1 2 3 4 5 6 7 8 0 1 9.5 50.6 45.759628 2.6 6.5 11.0 8.900 4.4 1 2 10.5 59.9 74.445390 0.0 4.5 8.9 7.125 4.4 2 3 20.1 37.7 35.102509 0.8 2.5 9.7 6.700 4.2 3 4 10.7 45.2 10.971085 0.4 3.1 6.9 5.500 4.7 4 5 13.2 39.9 9.233933 0.0 5.8 9.2 7.400 4.3
has comment: http://stackoverflow.com/comment/86404067
has comment: http://stackoverflow.com/comment/86403291
type: Answer
has comment: http://stackoverflow.com/comment/86404428

http://stackoverflow.com/comment/86405587
type: Comment
comment on: http://stackoverflow.com/a/49694718
type: AnswerComment
has text: Thanks. While Aran-Fey's answer does answer the question I asked, your answer shows me how to do what I actually wanted, so both equally valid IMO :)
score: 1

http://stackoverflow.com/q/49708126
favorite count: 0
type: Question
tagged with: python-3.x
has body: a=[2,1] b=['app','applied'] f={} for id in a: for name in b: f[id]=name the output is {2:'app', 1: 'app'} after i generated another for loop for c in f: print(c) Then output is 2,1 not show value and I tried for c,k in f: print(c,k) return error But i need both key and value Please help me I Tried many time cannot get solution. I bind two different list in dictionary but get only key value but value should only one value to bind in key. Please help me
has answer: http://stackoverflow.com/a/49708292
accepted answer: http://stackoverflow.com/a/49708292
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86429563
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86430145
upvote count: 0
answer count: 1
downvote count: 1
has title: dictionary binding two different list

http://stackoverflow.com/a/49637568
type: Answer
answers question: http://stackoverflow.com/q/49635871
has body: Let's start from the beginning: You seem to want to iterate through every line of your file to create an array. The iteration should be over range(0, len(data)), not range(0, len(data) - 1): the last element of the range is exclusive, so you are currently skipping the last line. In fact, you can write simply range(len(data)), or what is even more Pythonic, do for y in data: y = y[1:41] Based on what comes later, you want the 40 elements of y starting with the second element. In that case y[1:41] is correct (you don't need the trailing :1). If you didn't mean to skip the first element, use y[0:40], or more Pythonically y[:40]. Remember that the indexing is zero-based and the stop index is exclusive. Each element of your y list is not a number. It is a string, which you read from a file. Normally, you could convert it to a list of numbers using y = [float(x) for x in y] OR y = list(map(float, y)) Your code is instead creating a nested list for each element, splitting it by its digits. Is this really what you intend? It certainly does not seem that way from the rest of the question. create2Darray seems to expect a list of 4n numbers, and break it into a 2D list of size n-by-4. If you want to keep using pure Python at this point, you can shorten the code using range: def create2Darray(arr): return [arr[i:i + 4] for i in range(0, len(arr), 4)] The result of the 2D operation is appended to a 3D list with label_data.append(y). Currently, because of the digit splitting, label_data is a 4D list with a ragged 4th dimension. It is pretty inefficient to append a list that way. You would do much better to have a small function containing the statements in the body of your for loop, and use that in a list comprehension. Finally, you convert your 4D array (which should probably be 3D), into a numpy array. This operation fails because your numbers don't all have the same number of digits. Once you fix step #3, the error will go away. There still remains the question of why you want…
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49737317
answers question: http://stackoverflow.com/q/49736688
has comment: http://stackoverflow.com/comment/86528072
score: 0
has comment: http://stackoverflow.com/comment/86490860
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86526931
has comment: http://stackoverflow.com/comment/86526633
has body: This was a bug in Django's introspection code. You can change the models to use django.contrib.postgres.fields, and add import django.contrib.postgres.fields to your models.py. The issue will be fixed in Django 2.0.5 by Django ticket 29307.
accepted answer of: http://stackoverflow.com/q/49736688
has comment: http://stackoverflow.com/comment/86526322
type: Answer

http://stackoverflow.com/a/49630016
type: Answer
answers question: http://stackoverflow.com/q/49623406
has body: As mentioned in the comments, the login form is submitted to /login/auth. But, the cookie is generated from the /login URL. Use the following code: form = {'username': USERNAME, 'password': PASSWORD} with requests.Session() as s: # Get the cookie s.get('https://www.voobly.com/login') # Post the login form data s.post('https://www.voobly.com/login/auth', data=form) # Go to home page r = s.get('https://www.voobly.com/welcome') # Check if username is in response.text print(USERNAME in r.text) # True r2 = s.get('https://www.voobly.com/profile/view/124993231/Matches') if "Page Access Failed" in r2.text: print("Failed") else: print("Worked!") # Worked! Note: The Go to home page part is not at all needed for the login. It's used just to show that the login is successful.
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49623406
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86272570
has comment: http://stackoverflow.com/comment/86272482

http://stackoverflow.com/q/49711107
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: swagger
has title: Getting Type Error when include Djoser urls together with Swagger
favorite count: 0
type: Question
has body: I have django-swagger working properly with my API. However, when i try including Djoser urls to my urlpatterns, I get the following traceback: Internal Server Error: /docs/ Traceback (most recent call last): File "/Users/bo/env/home365/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework_swagger/views.py", line 32, in get schema = generator.get_schema(request=request) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/schemas/generators.py", line 286, in get_schema links = self.get_links(None if public else request) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/schemas/generators.py", …
has comment: http://stackoverflow.com/comment/93167394
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/92635644
tagged with: django-swagger

http://stackoverflow.com/comment/111552082
type: AnswerComment
comment on: http://stackoverflow.com/a/58349659
score: 1
type: Comment
has text: I guess mypy is too strict :D I don't have a better annotation at the moment

http://stackoverflow.com/a/49618033
has body: It looks like your code extract contains methods of some class, whose full definition is not shown, and you are calling one method from another method (self._slow_trap_ramp(j)). When you call a method, Python automatically passes self before any other arguments. So you need to change def _slow_trap_ramp(self) to def _slow_trap_ramp(self, j). Update in response to comment To really help, we would need to see more of the class you are writing, and also some info on the other objects you are calling. But I am going to go out on a limb and guess that your code looks something like this: InstrumentsClass.py class KeysightB2962A def __init__(self): ... def set_trap_ramp(self): ... ExperimentsSubClasses.py class FraunhoferAveraging def __init__(self): ... def slow_trap_ramp(self, j): ... Current version of main.py import InstrumentsClass, ExperimentsSubClasses class MyClass def __init__(self) ... def demag_chip(self): coil_probe_constant = float(514.5) field_sweep = [50 * i * (-1)**(i + 1) for i in range(20, 0, -1)] #print as list for j in field_sweep: ramp = self._slow_trap_ramp(j) def _set_trap_ramp(self): set_trap_ramp = InstrumentsClass.KeysightB2962A.set_trap_ramp return set_trap_ramp def _slow_trap_ramp(self): slow_trap_ramp = ExperimentsSubClasses.FraunhoferAveraging.slow_trap_ramp return slow_trap_ramp if __name__ == "__main__": my_obj = MyClass() my_obj.demag_chip() If this is the case, then these are the main problems: Python passes self and j to MyClass._slow_trap_ramp, but you've only defined it to accept self (noted above), you are using class methods from KeysightB2962A and FraunhoferAveraging directly instead of instantiating the class and using the instance's methods, and you are returning references to the methods instead of calling the methods. You can fix all of these by changing the code to look like this (see embedded comments): New version of main.py import InstrumentsClass, ExperimentsSubClasses class MyClass def __init__(self) # create instances of …
has comment: http://stackoverflow.com/comment/86248416
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/86285207
answers question: http://stackoverflow.com/q/49614485
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86212523
has text: @MartyB yep , also update your own approach , thank you :-)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49602357

http://stackoverflow.com/a/49661854
score: 1
has comment: http://stackoverflow.com/comment/86333964
type: Answer
has comment: http://stackoverflow.com/comment/86335428
has comment: http://stackoverflow.com/comment/86334371
has comment: http://stackoverflow.com/comment/86334583
has comment: http://stackoverflow.com/comment/86334235
has comment: http://stackoverflow.com/comment/86333754
has comment: http://stackoverflow.com/comment/86334319
downvote count: 0
has body: Your JSON has newlines in it. But your code is reading one row at a time and expecting it to be a complete JSON text: for row in f: row_counter += 1 row = json.loads(row) That's not going to work. If your file is just a single JSON text, just read the whole thing: with open("learning_data/{}/RC_{}".format(timeframe.split('-')[0], timeframe), buffering=1000) as f: row_counter += 1 row = json.load(f) You may want to rename row to something more meaningful, like contents. If your file is a sequence of JSON texts, and you're generating the file yourself, the right thing to do is to change the way you generate it. A stream of arbitrary JSON texts is not really a valid format. But if you really want to build a format on top of that, you can—e.g., escape all the newlines so that you can parse it line by line. Or you can use a real format. Or you can just write out a big JSON array instead of a bunch of separate JSON texts. If you can't change the file, you need a strategy to parse it. All of these are almost right: Use the json module's raw_decode method to read the next JSON text and return the decoded value plus the offset to the next one. Balance brackets and braces and split every time the count goes to 0. Scan for newlines and then backtrack to check for open brackets and braces. Other than bad error handling, the only serious problem with any of these is that they can't possibly do the right thing for numbers as top-level texts. If your top-level texts are all objects, that's not a problem. So: with open("learning_data/{}/RC_{}".format(timeframe.split('-')[0], timeframe), buffering=1000) as f: contents = f.read() decoder = json.JSONDecoder() while contents: row, idx = decoder.raw_decode(contents) row_counter += 1 contents = contents[idx:].lstrip() # etc. Although if your file is gigantic, you almost certainly want to mmap it and pass a slice/memoryview to raw_decode—or, if that doesn't work because you have Unicode text, you may have to buffer up chunks manually. Not…
has comment: http://stackoverflow.com/comment/86334506
upvote count: 1
answers question: http://stackoverflow.com/q/49661771

http://stackoverflow.com/q/49635196
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49635691
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86278463
has title: Django form not storing values on validation fail
has comment: http://stackoverflow.com/comment/86278390
answer count: 1
has body: I can't get Django to retain entered form values when validation fails. I have created a test page and used the code in the Django guide, and it still doesn't work. From the Django guide: We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required. And here is my code: #views.py def test(request): if request.method == 'POST': form = NewAwardForm(request.POST) if form.is_valid(): return redirect('/test/') else: form = NewAwardForm() print(form) return render(request, 'test.html', {'form': form}) test.html &lt;form action="/test/" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; forms.py class NewAwardForm(forms.Form): recipient_email = forms.EmailField(label='Recipient Email', max_length=100) Can anyone spot my mistake?
tagged with: django
has comment: http://stackoverflow.com/comment/86277970
has comment: http://stackoverflow.com/comment/86277774
accepted answer: http://stackoverflow.com/a/49635691
type: Question

http://stackoverflow.com/comment/86490544
type: AnswerComment
comment on: http://stackoverflow.com/a/49738002
has text: Thank you very much but it assumes that the last level starts with 'Third_level'
type: Comment
score: 0

http://stackoverflow.com/a/49735106
score: 1
has body: For me I think it is better pass your list of Counter to df directly df=pd.DataFrame(counter_list) s=df.div(df.sum(1),0) s Out[1718]: A B C 0 0.400000 0.400000 0.200000 1 0.375000 0.375000 0.250000 2 0.333333 0.333333 0.333333 3 0.357143 0.285714 0.357143 4 0.333333 0.333333 0.333333 .. ... ... ... 15 0.302326 0.348837 0.348837 16 0.306122 0.336735 0.357143 17 0.317757 0.327103 0.355140 18 0.310924 0.336134 0.352941 19 0.312500 0.328125 0.359375 [20 rows x 3 columns]
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49734582
type: Answer

http://stackoverflow.com/a/49637997
answers question: http://stackoverflow.com/q/49637830
has comment: http://stackoverflow.com/comment/86283759
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86284227
has body: The string is indeed a placeholder for an expected argument, and it is called a metavariable. The string used is controlled by the metavar keyword argument to add_argument. The default (None) specifies the destination name in all caps. Use the empty string to suppress it, or pass any other string (such as '&lt;value&gt;') to change it. parser.add_argument('-s', '--start', dest='start', action='store', metavar='', help='enter the starting value')
has comment: http://stackoverflow.com/comment/86283945
has comment: http://stackoverflow.com/comment/86283832
type: Answer
accepted answer of: http://stackoverflow.com/q/49637830

fingerprint
tags question: http://stackoverflow.com/q/49733271
tag name: fingerprint
type: Tag

http://stackoverflow.com/a/49662910
has body: I don't see the correlation between the values in the slices array and the raw string presented above them but, based on the rest of the explanation I believe you could proceed as follows: 1) convert the slices array to a numeric form usable as string ranges: (only do this once if the ranges are the same for every row of data) ranges = [ (int(r[0]),int(r[1])) for r in [ s.split(":") for s in slices] ] 2) For each row in your data set, extract the parameter values based on the ranges: params = [ [p,None][p==''] for p in [ line[start:end].strip() for start,end in ranges ] ] # Note: [p,None][p==''] is a compact alternative to: None if p == '' else p 3) use the parameter value list with unpacking (*) to instantiate your model object: (this assumes that the slice ranges are in the same order as the constructor's parameters) agr = PdsAGRMZDataModels(*params) # Based on your sample data and slices this would produce seemingly # misaligned data content. # # agr.bm == '958.860 L B NA0.000' # agr.kg == None # agr.abm_saa == '0' # ... [EDIT] avoiding the positional issue: If you want to work around the parameter position/count constraint, you could use a dictionary structure for the slice definitions so that the extracted data gets associated names that match the function parameters. For example: slices = { 'kg':(3,23), 'bm':(23,24), 'xyz':(5,52) } Using the slices dictionary, the line's data can produce named values in a dictionary as well: data = { p:[v,None][v==''] for p,v in [(p,line[r[0]:r[1]].strip()) for p,r in slices.items()] } Then, you can use the inspect module to obtain the list of arguments for the PdsAGRMZDataModels() constructor and map them, in the right order, to the named values you do have (and use None for values you don't have). This mapping will always produce the right number of parameters in the appropriate order (independently of the source data). [EDIT]: getargspec to getfullargspec import inspect params = [data[arg] if arg in data else None for arg i…
has comment: http://stackoverflow.com/comment/86354893
has comment: http://stackoverflow.com/comment/86403261
type: Answer
accepted answer of: http://stackoverflow.com/q/49662409
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86400979
upvote count: 1
answers question: http://stackoverflow.com/q/49662409

http://stackoverflow.com/comment/86299988
has text: Is it only `pycurl`, or is it not working for any packages? Does it work from the command line? Have you configured PyCharm to use the virtualenv you're installing `pycurl` in?
type: QuestionComment
comment on: http://stackoverflow.com/q/49645581
type: Comment
score: 1

http://stackoverflow.com/comment/94390258
type: Comment
comment on: http://stackoverflow.com/a/49661183
type: AnswerComment
has text: @Ajax none of that seems to affect how numba divides up the input matrices between workers. The workers seem to always operate on rows (in memory). Note that I'm not wondering how to transpose the data. For example what I'd like to do is create a `guvectorize` ufunc that sums the rows of a matrix in memory (which I know how to do) and another `guvectorize` ufunc the sums the columns of the same matrix in memory (which I don't know how to do).
score: 0

http://stackoverflow.com/comment/86521834
comment on: http://stackoverflow.com/q/49753655
score: 4
type: Comment
type: QuestionComment
has text: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

http://stackoverflow.com/comment/86332679
comment on: http://stackoverflow.com/q/49661089
score: 0
type: Comment
type: QuestionComment
has text: adding MULTILINE flag didnt help

http://stackoverflow.com/comment/89280355
has text: Thank you for replying. I am facing difficulties in tracing the output. I have one ontology which contain error because I have put Student and Unit as a disjoint class and as well as equivalent class to see what output hermit gives me. But it shows same output for both correct and incorrect file. Please have a look on this question. https://stackoverflow.com/questions/51147628/consistency-checking-using-hermit-reasoner-in-python-for-an-ontology Thanks in advance.
comment on: http://stackoverflow.com/a/49688765
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49679855
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/86371404
upvote count: 1
tagged with: python
has title: No module named 'ImageDraw'
has answer: http://stackoverflow.com/a/54019179
has answer: http://stackoverflow.com/a/49680051
favorite count: 0
has body: I am trying to make a wordcloud in Python. Ran this code: from PIL import Image import ImageDraw img_grey = Image.new("L", (10, 15)) draw = ImageDraw.Draw(img_grey) and I am getting this error No module named 'ImageDraw' PS: i already installed pip in command prompt
score: -1
has comment: http://stackoverflow.com/comment/86371814
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86371760

http://stackoverflow.com/q/49756273
downvote count: 1
has body: Trying to make a python script that runs some bash jobs (for flashing) in separate threads using subprocess.Popen. While running I want to read the stdout of the processes so I can show some progress to the user in a simple curses interface. So each thread runs something like this: def worker(panel): panel['status'] = 'STARTING' panel['process'] = Popen([SCRIPTFILE, panel['ip'], FWFILE, JADFILE, EXEFILE], stdout=PIPE, bufsize=1048576) panel['status'] = 'RUNNING' line = " " while line: line = panel['process'].stdout.readline() panel['status'] = line panel['status'] = 'DONE' I see in my UI that the status gets stuck on STARTING in this case, but looking at IP traffic it seems that it actually runs but never returns any output. So it seems as Popen actually runs the job but doesn't return. And as soon as the other processes finish it seems it stops hanging and I get all the data at once as it was buffered. I have seen warnings about reading from stdout on a subprocess, but those warnings seem to be related to other scenarios. And I can't really use communicate() instead as it waits for the process to finish. Any idea what could make Popen hang like this? Tried to make a minimal version showing the problem here (running with python 2.7 on Linux (change find path in script if windows)): import curses import time from subprocess import * import threading def check_done(panels): done = True for panel in panels: if panel['status'] != 'DONE': done = False break return done def flash_worker(panel): panel['status'] = 'STARTING' panel['process'] = Popen(["find", "/usr"], stdout=PIPE, bufsize=1048576) panel['status'] = 'RUNNING' line = " " while line: line = panel['process'].stdout.readline() panel['status'] = line panel['status'] = 'DONE' def ui_worker(panels): stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.scrollok(1) stdscr.erase() stdscr.refresh() while not check_done(panels): y = 0 stdscr.clear() stdscr.addstr(y, 0, "IP") stdscr.addstr(y, …
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Problems with python subprocess and stdout
linked to: http://stackoverflow.com/q/18421757
upvote count: 0
has comment: http://stackoverflow.com/comment/86553648
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49770386
tagged with: freeze
has comment: http://stackoverflow.com/comment/86527696
tagged with: subprocess
tagged with: popen
answer count: 1

http://stackoverflow.com/a/49715877
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/49715854
type: Answer
has body: You have to use the global keyword inside the function rather than outside. All the df that you have defined inside your function are locally scoped. Here is the right way - df = pd.DataFrame() # No need to use global here def __init__(self, master): global df # declare here df = None .... def load(self): global df # declare here .... df = pd.read_csv(filepath) def save(self): global df # declare here .... df = df.append(...)
downvote count: 0

http://stackoverflow.com/q/49614516
type: UnansweredQuestion
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/86235676
score: 0
has answer: http://stackoverflow.com/a/49614548
has body: I am currently trying to learn Python and having learned the basics I decided to try to make an address book program. I am having trouble loading the contacts after they have been saved though. Here's what I have so far, import pickle contacts = {} class Contact: def __init__(self, name, phone, address): self.name = name self.phone = phone self.address = address Name = input('Contacts Name - ') Phone = input('Phone Number - ') Address = input('Address - ') contacts[Name] = Contact(Name, Phone, Address) with open('SaveFile', 'wb') as f: pickle.dump(contacts, f) this all seems to work fine and the contacts dictionary is saved but when I try to load the contacts back after I have cleared the dictionary it does not work for some reason, def load(): with open('SaveFile', 'rb') as f: contacts = pickle.load(f) I don't get an error message but the dictionary stays empty. Any help with this would be much appreciated!
has title: Loading a saved dictionary (containing objects as values) from a file using pickle
has answer: http://stackoverflow.com/a/49614602
tagged with: load
type: Question
answer count: 2

http://stackoverflow.com/comment/86366545
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49677414
has text: Not exactly, I want the same behavior. I just want to load the file from different folders depending on if it's run by tests or as "main"
score: 0

http://stackoverflow.com/comment/86380898
score: 0
type: Comment
has text: Thanks a lot for your time, was a huge help.
comment on: http://stackoverflow.com/a/49678668
type: AnswerComment

http://stackoverflow.com/comment/86211706
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49602228
has text: can you please reformat your code so we know what you're trying to do?

http://stackoverflow.com/comment/86417144
has text: The second problem is that, as your last comment says, you're avoiding creating these folders in `C:\DATA` itself—but that's exactly what the error message you get later is complaining about, that you didn't create `C:\DATA\test`. I don't know what you're doing that raises that exception, but whatever it is, either you're calling something wrong so it's asking for directories it shouldn't be, or you're calling something right and you were wrong to skip creating those directories because they're necessary.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49701092
type: QuestionComment

http://stackoverflow.com/comment/86542496
has text: @ekhumoro Thanks, you were totally right, I had understood incorrectly the behaviour of this feature, my bad, I've tested again and it works accordingly to what you've explained in your previous comment. Do you know how the cache is managed by QFileSystemModel? ie: LRU or similar? Asking you cos if the cache grows with no limit the app will become eventually really slow... and i guess you can't flush the cache, can you? :/
type: AnswerComment
comment on: http://stackoverflow.com/a/49743670
score: 0
type: Comment

http://stackoverflow.com/comment/86512330
score: 0
comment on: http://stackoverflow.com/q/49748917
has text: Try integrating in H264 with the raw data to encode and compress it.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49654453
accepted answer: http://stackoverflow.com/a/49716673
tagged with: python
has title: Python & rsync: how to deal with identical filenames?
has answer: http://stackoverflow.com/a/49716673
type: AnsweredQuestion
score: 0
tagged with: rsync
tagged with: filenames
answer count: 1
has body: I'm using rsync to automatically copy files to a remote server. Since space is restricted on my internal HDD, I also use rsync to subsequently move these files (i.e., using --remove-source-files) to an external HDD upon successful upload. The files are photographs taken using a remote camera capture application, which names the files in sequence (DSC0001.JPG, DSC0002.JPG, etc.). The sequence seems to be specific to a "session": if I quit the remote capture application and start it again, it will begin at 1 (provided the folder is empty). I have everything scripted in Python (2.6, since running on very old MacBook), so should anything crash, it is restarted again. Now, here comes the problem: should the remote capture application crash and restart, and should rsync have just finished uploading &amp; moving all the files, then the JPG numbering will start again at 1. Subsequently, when rsync will again upload &amp; move the new files, there will be a clash of names, since DSC0001.JPG already exists on the external HDD. From what I gather, rsync will simply overwrite the duplicate, unless I specify --ignore-existing. But in that case the new DSC0001.JPG (and all subsequent images) are not synced anymore. Is there a way to solve this using rsync that the post I link to above missed, or is it best to deal with this in the Python script (and if so, how?)? Thanks!
type: Question

http://stackoverflow.com/a/49754839
has comment: http://stackoverflow.com/comment/86525218
has body: I would use some form of join, in this case crossJoin. Here's a MWE: from pyspark.sql import SparkSession import pyspark.sql.functions as F spark = SparkSession.builder.getOrCreate() df = spark.createDataFrame([(3, 'en'), (4, 'ua')], ['value', 'lang']) classes = spark.createDataFrame([(1, 2.), (2, 3.)], ['class_key', 'class_value']) res = df.crossJoin(classes).withColumn('modified', F.col('value') + F.col('class_value')) res.show() For saving as separate CSV's I think there is no better way than to use a loop.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49754476
accepted answer of: http://stackoverflow.com/q/49754476
type: AcceptedAnswer
type: Answer
upvote count: 1

http://stackoverflow.com/comment/86222831
score: 0
has text: Try removing the `else: break;` lines.
type: QuestionComment
comment on: http://stackoverflow.com/q/49608130
type: Comment

http://stackoverflow.com/comment/86349251
score: 0
type: Comment
has text: Oh I see ! Thank you for the explanation :)
comment on: http://stackoverflow.com/a/49654399
type: AnswerComment

http://stackoverflow.com/q/49723251
tagged with: python
linked to: http://stackoverflow.com/q/2709821
has body: I'm in the process of learning Python through a book, one of the questions was to create a class called Country which held the parameters shown below, then to create a method called is_larger that would return a boolean indicating whether the first country was larger, in area, than the other considering this code: &gt;&gt;&gt; canada = Country( 'Canada', 34482779, 9984670) &gt;&gt;&gt; usa = Country( 'United States of America' , 313914040, 9826675) &gt;&gt;&gt; canada. is_larger(usa) True Here's the solution from the book: class Country(): def __init__(self, name, population, area): """ (Country, str, int, int) A new Country named name with population people and area area. &gt;&gt;&gt; canada = Country('Canada', 34482779, 9984670) &gt;&gt;&gt; canada.name 'Canada' &gt;&gt;&gt; canada.population 34482779 &gt;&gt;&gt; canada.area 9984670 """ self.name = name self.population = population self.area = area def is_larger(self, other): """ (Country, Country) -&gt; bool Return whether this country is larger than other. &gt;&gt;&gt; canada = Country('Canada', 34482779, 9984670) &gt;&gt;&gt; usa = Country('United States of America', 313914040, 9826675) &gt;&gt;&gt; canada.is_larger(usa) True &gt;&gt;&gt; usa.is_larger(canada) False """ return self.area &gt; other.area I can apply this after seeing the answer, but I just don't understand the process and I'm keen on fully understanding the code. Method is_larger holds two parameters, one being self. Should the method not be: def is_larger(self, country1, country2): How was an object used as the self parameter? If my question is confusing, please let me know and I'll try to clarify what's going on in my head lol.
type: AnsweredQuestion
score: 2
tagged with: oop
duplicate of: http://stackoverflow.com/q/2709821
answer count: 1
tagged with: methods
accepted answer: http://stackoverflow.com/a/49723271
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49723271
upvote count: 2
has title: Object used as "self" argument?
downvote count: 0

http://stackoverflow.com/comment/86523055
type: QuestionComment
score: 1
has text: Done. Updated the path in question.
comment on: http://stackoverflow.com/q/49752788
type: Comment

http://stackoverflow.com/a/49678749
has body: Managed to get it done with Subquery() weight = OrderLine.objects.filter(product=OuterRef('pk'), order__date__gte=date).order_by().values('product') sum_weight = weight.annotate(total=Sum('weight')).values('total') templates = Template.objects.filter(product=OuterRef('pk')).order_by().values('product') count_templates = templates.annotate(count=Count('*')).values('count') query = query.annotate(weight_sold=Subquery(sum_weight, output_field=DecimalField()), template_count=Subquery(count_templates))
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49671917
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86391651
answers question: http://stackoverflow.com/q/49671917
has comment: http://stackoverflow.com/comment/86375795

http://stackoverflow.com/comment/86378524
has text: @DanielChenYin: As I mentioned, your observed behavior would occur if the caller of your function (or their caller, etc.) wrapped the execution in a `try`/`except` that suppressed the error. You need to provide a *complete* example, enough for us to reproduce, per [MCVE].
comment on: http://stackoverflow.com/q/49680149
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49654530
has comment: http://stackoverflow.com/comment/86317850
tagged with: types
downvote count: 2
answer count: 1
upvote count: 1
has title: What datatype is being used here?
favorite count: 0
has body: I stumbled across this working code in Python but I am unsure on how to use that datatype. global_widgets = {} def register_widget(self, widget_object): if widget_object.gid not in self.global_widgets: self.global_widgets[widget_object.gid] = widget_object def get_widget(self, widget_gid): if widget_gid in self.global_widgets: return self.global_widgets[widget_gid] else: return None I am new but I assume that the used Datatype is like a HashMap in Java. Is my assumption right that this datatype maps any value to a string (widget_object.gid) and that global_widgets[???] the question tags can be replaced with any datatype and not just numbers?
type: Question
accepted answer: http://stackoverflow.com/a/49654576
has answer: http://stackoverflow.com/a/49654576
tagged with: python
has comment: http://stackoverflow.com/comment/86317892
score: -1
has comment: http://stackoverflow.com/comment/86317887
type: AnsweredQuestion

http://stackoverflow.com/q/49712430
has comment: http://stackoverflow.com/comment/86470055
has comment: http://stackoverflow.com/comment/86444633
has title: Scraping specific javascript variables from HTML using python requests
has body: I am currently making a GET request on python, and in the response it returns a few specific variables that I need to extract and "save" as variables in my code for future use in the code. The variables are called accessToken, ivString, and fpAccountId. Each of them are equal something and that is what I need to extract. Here is how it looks in the GET request response HTML: var accessToken = "8CULRLPATAMoPf3fIRKJ7D13e3Dtchruqu="; var ivString = "2e84726625315acjfshfsf=="; var encryptedFpAccountId = "NArzA4fzqrskjfs6sf=="; These are the 3 that I need. The code that I have so far has been using Beautiful Soup to extract the HTML but I am unsure of how to get these values into a simplified version so I can use the variables in my future code. Here is what I have so far using beautiful soup to get the response: uSoup = BeautifulSoup(b.text, 'html.parser') data = uSoup.find_all('script')[16].string b is the resonse
has comment: http://stackoverflow.com/comment/86438612
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has comment: http://stackoverflow.com/comment/86438540
has comment: http://stackoverflow.com/comment/86462832
tagged with: python-requests
has comment: http://stackoverflow.com/comment/86438945
has answer: http://stackoverflow.com/a/50525694
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/86438620
type: Question
has comment: http://stackoverflow.com/comment/86438628
has comment: http://stackoverflow.com/comment/86438779
has comment: http://stackoverflow.com/comment/86438402
type: UnansweredQuestion
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/86438391
has comment: http://stackoverflow.com/comment/86438542
score: 0

http://stackoverflow.com/q/49619872
favorite count: 0
type: Question
has body: So I have roughly 6600 image URLs that I want to read them from a pickle file in order to download their images locally. The two main problems I could not solve: 1) URLs that throw UnicodeEncodeError error. I tried many available solution online and none worked so I ended up forgetting about that URL but I prefer if there is a way to hack it. This is URLs that contain Chinese of Polaska characters for example. 2) The other error is as follows (one example): ssl.CertificateError: hostname 'www.straitstimes.com.sg' doesn't match either of 'gp1.adn.edgecastcdn.net', 'gs1.adn.edgecastcdn.net', 'ne1.adn.edgecastcdn.net', 'www.uship.com', 'www.bluefly.com', 'www.belleandclive.com', 'is.belleandclive.com', 'connections.cochlear.com', 'assets.pokemon.com', 'www.shopperschoice.com', 'www.biznessapps.com', 'cdn.shocho.co', 'secure.hibustudio.com', 'www.stardoll.com', 'adn.wiredrive.com', 'www.speedtest.net', 'www.cduniverse.com', 'ak-site-origin-cover.cduniverse.com', 'cover.cduniverse.com', 'g.cduniverse.com', 'www.renttherunway.com', 'cdn2.navexglobal.com', 'www.chdist.com', 'www.thefanorama.com', 'cdn2.mediasilo.com', 'cdn.citadoncw.com', 'www.woodcraft.com', 'marketing-admin.upsight-api.com', 'www.edgecast.com' It happened when I needed to download the image from https://static.straitstimes.com.sg/sites/default/files/styles/x_large/public/articles/2017/09/23/ST_20170923_WONZ_3440048.jpg?itok=-iG-zSvr as you see the image is available. I wonder how my code below could be modified to overcome these two issues rather than try except phrase. import pickle import urllib.request import re import requests from urllib.parse import quote # img = urllib.request.urlopen(quote(value)) # img = urllib.urlopen(quote(value)) import time count = 0 with open('images.pickle', 'rb') as handle: b = pickle.load(handle) print(len(b)) for key, value in b.items(): print(value) print(key, value) #value = iriToUri(value) if value != 'NA': count += 1 print(value) try: img = urllib.request.urlopen(qu…
tagged with: python
tagged with: utf-8
tagged with: urllib
tagged with: python-3.x
answer count: 0
score: 2
upvote count: 2
has title: Dealing with weird URLs when retrieving their images ssl.CertificateError: hostname doesn't match and UnicodeEncodeError
type: UnansweredQuestion
tagged with: url
downvote count: 0

http://stackoverflow.com/comment/86422193
comment on: http://stackoverflow.com/a/49704368
type: Comment
type: AnswerComment
has text: @AmalSailendran - are you sure that the CSV you've posted looks exactly like that? Could the rows be actually within quotes? You can try setting a delimiter to a comma explicitly with `csv.reader(f, delimiter=",")` but that should be the default behavior anyway.
score: 0

http://stackoverflow.com/comment/86354232
type: Comment
comment on: http://stackoverflow.com/q/49671808
type: QuestionComment
has text: your issues is you're using csv.DictWriter wrong - this line `csv.writerow(fieldname)` in particular. the input of `.writerow()` has to be a `dict` not a list [csv](https://docs.python.org/2/library/csv.html)
score: 0

http://stackoverflow.com/q/49644385
has comment: http://stackoverflow.com/comment/86298667
has title: How to construct *array of lists of arrays* when the nested arrays have the same length?
has comment: http://stackoverflow.com/comment/86297554
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/86304356
has body: I want to construct an array of list of arrays but my method breaks down if the arrays inside the list have equal dimensions. I make a list of lists of arrays and then I convert that list into an array import numpy as np foo = [[np.array([4. , 0. , 0.1]), np.array([5. , 0. , 0.1])], [np.array([6. , 0. , 0.5])], [], [], []] foo = np.array(foo) foo which results in an array of list of arrays: Out[40]: array([list([array([4. , 0. , 0.1]), array([5. , 0. , 0.1])]), list([array([6. , 0. , 0.5])]), list([]), list([]), list([])], dtype=object) perfect. Now consider the case where array dimensions are equal: bar = [[np.array([4. , 0. , 0.1])], [np.array([4. , 0. , 0.1])], [np.array([4. , 0. , 0.1])], [np.array([4. , 0. , 0.1])], [np.array([4. , 0. , 0.1])]] bar = np.array(bar) print(bar) The same method results in merely nested arrays. Out[1]: array([[[4. , 0. , 0.1]], [[4. , 0. , 0.1]], [[4. , 0. , 0.1]], [[4. , 0. , 0.1]], [[4. , 0. , 0.1]]]) Is there a way to make bar an array of list of arrays? (I would like to have this format because I am appending more arrays to the individual lists)
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86296583
has comment: http://stackoverflow.com/comment/86387529
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: arrays
tagged with: python

http://stackoverflow.com/comment/86471484
comment on: http://stackoverflow.com/q/49668749
type: QuestionComment
type: Comment
has text: I am using the current version 0.12.15. DO I have to use 0.12.14?
score: 0

http://stackoverflow.com/a/49634239
has body: You can still pass a list of Bird objects by creating a __repr__ for each Bird class: class Bird(object): def __init__(self, name): self.name = name def __enter__(self): print("enter " + str(self.name)) return self def __exit__(self, type, value, traceback): print("exit " + str(self.name)) def __repr__(self): return '{}({})'.format(self.__class__.__name__, self.name) with Bird([Bird("A"), Bird("B")]) as f: print(f) print('-'*10) with Bird('chicken') as f: print(f) Output: enter [Bird(A), Bird(B)] Bird([Bird(A), Bird(B)]) exit [Bird(A), Bird(B)] ---------- enter chicken Bird(chicken) exit chicken
answers question: http://stackoverflow.com/q/49633428
type: Answer
score: 0

http://stackoverflow.com/comment/86230841
type: Comment
has text: Thank you very much. Just to note, you've printed the result out to the console, but I changed that for a second. Plus for the solution, for sure. Perfect.
comment on: http://stackoverflow.com/a/49611968
score: 0
type: AnswerComment

http://stackoverflow.com/q/49701752
has comment: http://stackoverflow.com/comment/86417186
has title: Python append array to the last column
type: AnsweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
score: 1
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49701790
has body: the below array is a result of my model, how to append it back to my dataframe's last column In[] logireg.predict(X.head(5)) Out[] array([0, 0, 0, 1, 0], dtype=int64) dataframe data: age job month 33 blue apr 56 admin jun 37 tech aug 76 retired jun 56 service may expected output age job month predict 33 blue apr 0 56 admin jun 0 37 tech aug 0 76 retired jun 1 56 service may 0 use for loop or zip function?
has answer: http://stackoverflow.com/a/49701790
tagged with: dataframe

http://stackoverflow.com/comment/86466272
comment on: http://stackoverflow.com/q/49726193
type: QuestionComment
has text: @VipinMohan Sir, I'm importing it as `from django.core.exceptions import ValidationError`. Also, If I remove this ValidationError line from View, everything starts working fine!
type: Comment
score: 0

http://stackoverflow.com/comment/86496851
has text: Possible duplicate of [Using subdomains in django](https://stackoverflow.com/questions/31178022/using-subdomains-in-django)
comment on: http://stackoverflow.com/q/49740594
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49701458
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86416855
score: 0
answers question: http://stackoverflow.com/q/49701438
type: Answer
accepted answer of: http://stackoverflow.com/q/49701438
has body: for key in f loops over lines in the file, not characters. You need to loop over the characters in the line. for key in f: result += ''.join([CODE.get(char, char) for char in key])
has comment: http://stackoverflow.com/comment/86416913

http://stackoverflow.com/a/49730282
type: Answer
has body: def initMe(self): i = 1 box = QVBoxLayout(self) self.setLayout(box) Rufnummer = 0 result = APIConnect.list_users() anrufe = APIConnect.anrufe() for e in result: self.User = box.addWidget(QPushButton(e[6]+"\n"+e[7])) box.addStretch(1) self.setGeometry(50, 50, 200, 750) self.setWindowTitle("CTI") self.setWindowIcon(QIcon("telefon.png")) #---------------add this-------------------- self.__timer = QTimer() self.__timer.timeout.connect(self.ontimeout) self.__timer.start(1000) #------------------------------------------- self.show()
answers question: http://stackoverflow.com/q/49728012
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86353771
comment on: http://stackoverflow.com/q/49671731
has text: use pandas dataframes and you can filter for `Quantity == 0` [pandas](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html)
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49710609
type: Answer
score: 0
has body: You can try dict approach: listA = ['a1', 'a2', 'a3', 'a4'] listB = ['b2', 'b4'] final_list={} import itertools for i in itertools.product(listA,listB): data,data1=list(i[0]),list(i[1]) if data[1]==data1[1]: final_list[i[0]]=i else: if i[0] not in final_list: final_list[i[0]]=(i[0],None) print(final_list.values()) output: [('a2', 'b2'), ('a3', None), ('a4', 'b4'), ('a1', None)]
answers question: http://stackoverflow.com/q/49703095

http://stackoverflow.com/q/49632451
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49771955
has title: Tensorflow TypeError: Can't convert 'numpy.int64' object to str implicitly
has comment: http://stackoverflow.com/comment/86403835
tagged with: pandas
has answer: http://stackoverflow.com/a/49771955
tagged with: python
tagged with: numpy
upvote count: 2
answer count: 1
score: 1
downvote count: 1
has body: Here is my jupyter notebook : import pandas as pd from pprint import pprint import pickle import numpy as np with open('preDF.p', 'rb') as f: preDF = pickle.load(f) #pprint(preDF) df = pd.DataFrame(data=preDF) #df.rename(columns={166: '166'}, inplace=True) df.head() 0 1 2 3 4 5 6 7 8 9 ... 157 158 159 160 161 162 163 164 165 166 0 3 8 1 13 15 13 9 12 12 1 ... 0 0 0 0 0 0 0 0 0 1 1 3 1 13 15 13 9 12 12 1 27 ... 0 0 0 0 0 0 0 0 0 1 2 3 8 1 13 15 13 9 12 12 1 ... 0 0 0 0 0 0 0 0 0 1 3 13 5 20 18 9 3 1 18 9 1 ... 0 0 0 0 0 0 0 0 0 1 4 3 8 12 15 18 8 5 24 9 4 ... 0 0 0 0 0 0 0 0 0 2 5 rows × 167 columns import numpy as np #msk = np.random.rand(len(df)) &lt; 0.8 #train = df[msk] #test = df[~msk] from sklearn.model_selection import KFold kf = KFold(n_splits=2) train = df.iloc[train_index] test = df.iloc[test_index] train.columns = train.columns.astype(np.int32) test.columns = test.columns.astype(np.int32) import tensorflow as tf def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((dict(features.astype(np.int32)), labels.astype(np.int32))) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset def eval_input_fn(features, labels, batch_size): """An input function for evaluation or prediction""" features=dict(features.astype(np.int32)) if labels is None: # No labels, use only features. inputs = features else: inputs = (features, labels) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices(inputs) # Batch the examples assert batch_size is not None, "batch_size must not be None" dataset = dataset.batch(batch_size) # Return the dataset. return dataset def load_data(train,test,y_name=166): train_x, train_y = train, train.pop(y_name) test_x, test_y = test, test.pop(y_name) return (train_x, train_y), (test_x, test_y) def main(train,test): batch_size = np.int32…
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86400444
favorite count: 0

http://stackoverflow.com/comment/86480574
type: Comment
has text: But i have strings also in rows, it's throwing me error: ValueError: could not convert string to float: 'Script'.
comment on: http://stackoverflow.com/a/49733131
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86384953
comment on: http://stackoverflow.com/a/49677140
type: AnswerComment
has text: Thanks again @syllogism_. I was thinking that because begin_training() was generating an optimizer it would be better to keep the same for the whole process.
score: 0
type: Comment

http://stackoverflow.com/a/49744826
has comment: http://stackoverflow.com/comment/86504226
has body: If a package is not updated on pypi, you cannot pip install packagename to get the latest version. If you absolutely want the latest version you can install it directly from git git clone &lt;git URL of library&gt; cd into the directory and install the package: sudo python setup.py install
type: Answer
has comment: http://stackoverflow.com/comment/86504341
has comment: http://stackoverflow.com/comment/86504186
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/49744793
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49744793
has comment: http://stackoverflow.com/comment/86504296

http://stackoverflow.com/comment/86309638
comment on: http://stackoverflow.com/a/49636500
score: 0
type: AnswerComment
has text: @pensfute: did you really remove the white ?
type: Comment

http://stackoverflow.com/a/49720365
has body: (Spyder maintainer here) You can save all console output to an Html file, by doing right click on it and selecting the option called Save as HTML/XML, as shown below:
upvote count: 7
has comment: http://stackoverflow.com/comment/91380048
score: 7
has comment: http://stackoverflow.com/comment/89802148
type: Answer
answers question: http://stackoverflow.com/q/49716523
has comment: http://stackoverflow.com/comment/91354966
downvote count: 0

http://stackoverflow.com/a/49636527
has comment: http://stackoverflow.com/comment/86280587
score: 1
type: AcceptedAnswer
upvote count: 1
has body: You can using ffill after replace '0' to np.nan df['Cat_for_Analysis']=df.replace('0',np.nan)'Category','Sub_Cat'.bfill(1).iloc[:,0] df Out[876]: Product_ID Category Sub_Cat Cat_for_Analysis 0 32432 0 Gadget Gadget 1 24085 BigTech Computer BigTech 2 54398 SmallTech Gadget SmallTech 3 97456 0 Computer Computer
accepted answer of: http://stackoverflow.com/q/49636459
downvote count: 0
has comment: http://stackoverflow.com/comment/86280664
type: Answer
answers question: http://stackoverflow.com/q/49636459

http://stackoverflow.com/q/49611538
tagged with: input
tagged with: python
possible better answer: http://stackoverflow.com/a/49611667
has title: How can I prompt the user to assign a new name to each value in a list?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49611667
has body: So I need to name each item in the list being created from the first user input. my first line of code is as follows: num_assessment = int(input('How many assessments per student?')) Now I need the user to name each item in the list; for example: How many assessments per student?:2 What type of assessment was assessment 1? Essay How many marks is the Essay worth? 30 What type of assessment was assessment 2 ? Test How many marks is the Test worth? 70 What is the function I can use to perform this?
answer count: 2
downvote count: 4
upvote count: 1
accepted answer: http://stackoverflow.com/a/49611784
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49611784
score: -3

lines
tags question: http://stackoverflow.com/q/49672553
type: Tag
tag name: lines
tags question: http://stackoverflow.com/q/49714244

http://stackoverflow.com/comment/86259666
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49625618
has text: @IljaEverilä should this work also for bulk inserts then?
score: 0

http://stackoverflow.com/q/49683026
tagged with: python
tagged with: append
score: -1
has answer: http://stackoverflow.com/a/49683335
type: AnsweredQuestion
has body: My goal is to get the values in the same index of two different lists (keyNum and stringNum) to add up and the sum to be in a new separate list (encNum). However, when I run the code, it doesn't fully run through the entire list. Here's the code: def encrypt(key, string): letters = 'abcdefghijklmnopqrstuvwxyz' keyNum = [] stringNum = [] encNum = [] for symbol in key: numKey = letters.find(symbol) keyNum.append(numKey) for symbol in string: numString = letters.find(symbol) stringNum.append(numString) for element in stringNum: a = keyNum.pop(0) b = stringNum.pop(0) c = a + b encNum.append(c) print keyNum print stringNum print encNum
has comment: http://stackoverflow.com/comment/86377754
upvote count: 0
has comment: http://stackoverflow.com/comment/86377764
answer count: 1
accepted answer: http://stackoverflow.com/a/49683335
has title: Popping and appending to new list not working in python
downvote count: 1
linked to: http://stackoverflow.com/q/1207406
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/1207406

http://stackoverflow.com/comment/86394160
type: QuestionComment
type: Comment
has text: Just fixed the title. Thanks for pointing out.
comment on: http://stackoverflow.com/q/49691170
score: 1

http://stackoverflow.com/q/49699242
answer count: 1
has comment: http://stackoverflow.com/comment/89291152
has body: I'm trying to build an LSTM autoencoder as shown here. My code: from keras.layers import Input, LSTM, RepeatVector from keras.models import Model inputs = Input(shape=(window_length, input_dim)) encoded = LSTM(latent_dim)(inputs) decoded = RepeatVector(window_length)(encoded) decoded = LSTM(input_dim, return_sequences=True)(decoded) model = Model(inputs, decoded) model.fit(batch_size=512) The shape of the dataset is: (rows, window_length, input_dim). When I try to call fit() I get this error: ValueError: Cannot feed value of shape (512, 221) for Tensor u'lstm_2_target:0', which has shape '(?, ?, ?)' This model it's really simple, I don't understand what is the problem. EDIT Model summary: Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 10, 221) 0 _________________________________________________________________ lstm_1 (LSTM) (None, 128) 179200 _________________________________________________________________ repeat_vector_1 (RepeatVecto (None, 10, 128) 0 _________________________________________________________________ lstm_2 (LSTM) (None, 10, 221) 309400 ================================================================= Total params: 488,600 Trainable params: 488,600 Non-trainable params: 0
has comment: http://stackoverflow.com/comment/86412105
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51727722
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86414659
has title: Multiple time series prediction with LSTM Autoencoder in Keras
has comment: http://stackoverflow.com/comment/86414130
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/89288161
tagged with: lstm
score: 0
tagged with: autoencoder

http://stackoverflow.com/comment/86477827
has text: Don't name your file `pandas.py`
type: Comment
comment on: http://stackoverflow.com/q/49731879
score: 4
type: QuestionComment

http://stackoverflow.com/comment/86440000
type: AnswerComment
comment on: http://stackoverflow.com/a/49711755
type: Comment
has text: @ShanZhengYang: `len(list(grp))` is basically always fastest unless it causes you to exceed RAM limits and end up paging out to disk (which seems highly unlikely in this case). There's more detail in [my old answer on this topic](https://stackoverflow.com/a/34404546/364696).
score: 0

http://stackoverflow.com/comment/86222402
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49607858
has text: What is "the Web playground"? `dict.sort` does not exist in any version of Python. Unless you were using a "Python-like language" like Boo or something instead of Python, you must have had a list when you tried it there, or you must have done something different (and valid) like `sorted_hour_count = sorted(hour_count.items())`.

http://stackoverflow.com/comment/86233678
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49612548
has text: If your Lambda function has an allow s3:Get* policy on all S3 resources then your S3 bucket does not need a bucket policy that also allows access from that same Lambda function (at least for Get*).

http://stackoverflow.com/comment/86236906
score: 0
type: Comment
has text: @fletcht91: See the addition to my answer for an explanation of your mistake and how to correct it. The problem is not in the loop but how you added the input list to your output list.
type: AnswerComment
comment on: http://stackoverflow.com/a/49614542

http://stackoverflow.com/q/49650618
type: Question
tagged with: numpy
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49650798
linked to: http://stackoverflow.com/q/24870953
has answer: http://stackoverflow.com/a/49650798
has comment: http://stackoverflow.com/comment/86309612
tagged with: python
has comment: http://stackoverflow.com/comment/86309407
type: AnsweredQuestion
score: 3
tagged with: pandas
has title: python rename multiple columns and roundup dataframe
upvote count: 3
answer count: 1
downvote count: 0
has body: import pandas as pd sample = pd.DataFrame({'k1':[1.1455,2.444,3.5,4.9], 'k2':['b','c','d','e']}) it can rename columns successfully sample.rename(columns = { 'k1' : '3', 'k2' : '5'},inplace = True) case 1: don't know the problem in the function -rename columns def rename1(df): print(df) test1 = df.rename(columns = { 'k1' : 'num', 'k2' : 'name'},inplace = True) print(test1) return test1 rename1(sample) Q1: Why the output will be none? case 2: 1. roundup the number 2. rename all columns def rename2(df): print(df) test2 = [] test2 = df.rename(columns = { 'k1' : df['num'].apply(lambda num : int(round(num))), 'k2' : df['name']},inplace = True) print(test2) return test2 rename2(sample) roundup data print(sample['k1'].apply(lambda num : int(round(num)))) Q2: How to roundup the value based on the specific column properly? expected the result num name 0 1 b 1 2 c 2 4 d 3 5 e This is my sample data. I'm new in python. I'm trying to rename multiple columns for my data frame but I don't know the problem.
favorite count: 0

http://stackoverflow.com/q/49691946
has answer: http://stackoverflow.com/a/49692961
tagged with: django
tagged with: python
has title: Display queried API results on a html page using python django
has body: I'm currently creating a python app using the django webframework, that allows users to query an external API to get information about food nutrition (e.g calories, fats). Currently, when the user inputs their food in a search bar on the webpage, the API is queried and displayed in the terminal. I'm trying to display the information on the webpage but am having trouble rendering the data. form.py class NutritionForm(forms.Form): food = forms.CharField(max_length=100000) def search(self): # result = {} food = self.cleaned_data['food'] headers = { 'x-app-id': "ff0ccea8", 'x-app-key': "605660a17994344157a78f518a111eda", 'x-remote-user-id': "7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632", 'Content-Type': "application/x-www-form-urlencoded", } url = 'https://trackapi.nutritionix.com/v2/natural/nutrients' body = { 'query': food, 'timezone': 'US/Eastern', } response = requests.request("POST", url, data=body, headers=headers) data = response.json() print ('food name: ', data['foods'][0]['food_name']) print ('food calories: ', data['foods'][0]['nf_calories']) print ('food protein: ', data['foods'][0]['nf_protein']) print ('food fats: ', data['foods'][0]['nf_total_fat']) views.py def nutritionix(request): search_result = {} if 'food' in request.POST: form = NutritionForm(request.POST) if form.is_valid(): search_result = form.search() else: form = NutritionForm() return render(request, 'nutrition/nutrition.html', {'form': form, 'search_results': search_result}) This is my html page that I am using to try and display the information. However, when I run the search, the API is queried, displayed in the terminal but, doesn't show up on the webpage. html {% block content %} Nutritionix API {% csrf_token %} {{ form.as_p }} Search Food info {% block body %} Food name: {{ food }} {% endblock %} {% endblock %} Its not printing onto webpage, am I doing this correctly?
accepted answer: http://stackoverflow.com/a/49692961
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
type: Question
tagged with: api

firefox
type: Tag
tags question: http://stackoverflow.com/q/49658070
tags question: http://stackoverflow.com/q/49734915
tags question: http://stackoverflow.com/q/49750037
tags question: http://stackoverflow.com/q/49622197
tag name: firefox

http://stackoverflow.com/q/49720878
score: 15
has comment: http://stackoverflow.com/comment/86454921
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49720907
has comment: http://stackoverflow.com/comment/86455160
answer count: 3
has comment: http://stackoverflow.com/comment/86454877
has comment: http://stackoverflow.com/comment/86459527
downvote count: 2
has answer: http://stackoverflow.com/a/76458631
tagged with: pathlib
has answer: http://stackoverflow.com/a/69929885
has comment: http://stackoverflow.com/comment/86455009
favorite count: 0
upvote count: 17
type: Question
has body: Whenever I write: import pathlib or from pathlib import path I got this: ImportError: No module named pathlib I tried also naming it os.path. I'm on Python 2.7.14 Is pathlib in Python 2 or only in 3? If it's not available, what else can I use?
type: UnansweredQuestion
tagged with: python
has title: Can't import pathlib

http://stackoverflow.com/comment/86487739
type: QuestionComment
score: 2
has text: your `Third_level1` is not replaced by a 1.
comment on: http://stackoverflow.com/q/49736700
type: Comment

http://stackoverflow.com/comment/86325262
type: Comment
has text: @C.Wang No, I mean: don't do this. Just import your modules the way you mention at the beginning of your question.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49657919

http://stackoverflow.com/a/49616801
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49616754
has comment: http://stackoverflow.com/comment/86242838
has body: You can just reset sys.argv: argv = list(sys.argv) argv.remove("-q") sys.argv = tuple(argv)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86276266
accepted answer of: http://stackoverflow.com/q/49616754
upvote count: 1

http://stackoverflow.com/q/49681954
has comment: http://stackoverflow.com/comment/86385937
has comment: http://stackoverflow.com/comment/86386084
score: 0
has comment: http://stackoverflow.com/comment/86378186
has comment: http://stackoverflow.com/comment/86378212
has comment: http://stackoverflow.com/comment/86386194
has comment: http://stackoverflow.com/comment/86378237
has comment: http://stackoverflow.com/comment/86378199
has comment: http://stackoverflow.com/comment/86377532
tagged with: sqlite
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/86385666
has answer: http://stackoverflow.com/a/49696613
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86375906
has comment: http://stackoverflow.com/comment/86405660
has body: I have some code from my class. It's about making one database from another. There is a INSERT method. It takes really long time. I read the FAQ, and i know that I need to put BEGIN TRANSACTION and COMMIT around the multiple INSERT, but i swear, I tried every place of c.execute(''BEGIN TRANSACTION") and c.execute("COMMIT") - always same ca 5 kb/s. Please show me where is the proper place for those instruction, or tell me what else could be a problem. For the record - I'm working with 5400 RPM hard drive. Here is original code: import sqlite3 conn = sqlite3.connect('/path/to/database.db') c = conn.cursor() with open('sqlite-sakila-schema.sql', 'r', encoding='utf-8') as create_file: create_query = create_file.read() with open('sqlite-sakila-insert-data.sql', 'r', encoding='utf-8') as insert_file: insert_query = insert_file.read() c.executescript(create_query) c.executescript(insert_query) conn.commit() conn.close() edited: first file: https://raw.githubusercontent.com/jOOQ/jOOQ/master/jOOQ-examples/Sakila/sqlite-sakila-db/sqlite-sakila-schema.sql second one: https://raw.githubusercontent.com/jOOQ/jOOQ/master/jOOQ-examples/Sakila/sqlite-sakila-db/sqlite-sakila-insert-data.sql It is all about INSERTs. There is couple tables, whole sql file started with deleting from those tables, and then 231K lines of INSERTS code like below. Insert into language (language_id,name,last_update) Values ('1','English','2006-02-15 05:02:19.000') ; Insert into language (language_id,name,last_update) Values ('2','Italian','2006-02-15 05:02:19.000') ; Insert into language (language_id,name,last_update) Values ('3','Japanese','2006-02-15 05:02:19.000') ; Insert into language (language_id,name,last_update) Values ('4','Mandarin','2006-02-15 05:02:19.000') ;
has title: Wrapping INSERT by BEGIN TRANSACTION and COMMIT
has comment: http://stackoverflow.com/comment/86376720

http://stackoverflow.com/q/49611510
has title: What should the input be to the "Decoder" of "Sequence-to-Sequence" model?
has answer: http://stackoverflow.com/a/49611832
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: keras-layer
has body: I am developing a sequence-to-sequence model (paper) for text generation. I am not using 'teacher-forcing" at the decoder side, i.e. output of decoder at t0 is fed to input of decoder at time t1. Now, in reality, output of a decoder (LSTM/GRU) is passed through a Dense layer, which in tern generates the index of the word, which is considered as the output of the decoder. But, for feeding the output to next layer, should we feed the h_t ( i.e. output of decoder/ hidden state of the decoder) to the next step, or the word-embedding of next word is the correct choice ?
answer count: 1
tagged with: machine-learning
tagged with: recurrent-neural-network
tagged with: keras
type: Question

http://stackoverflow.com/comment/86563237
has text: Thanks, that's great. It shows me how much I still have to learn in python :) The only thing is that columns 'hour' and 'date' are now based on login_time. Small addition inside function process_record(t) just before 'yield' fixes this: `r['hour']=(t.hour+i)%24 ` `r['date']+=pd.Timedelta(days=((t.hour+i)//24)) `
type: Comment
comment on: http://stackoverflow.com/a/49753942
score: 0
type: AnswerComment

specifications
type: Tag
tag name: specifications
tags question: http://stackoverflow.com/q/49688210

http://stackoverflow.com/q/49604001
tagged with: list
answer count: 3
linked to: http://stackoverflow.com/q/21542694
score: 0
has comment: http://stackoverflow.com/comment/86215333
has answer: http://stackoverflow.com/a/49604015
has answer: http://stackoverflow.com/a/49604031
type: Question
linked to: http://stackoverflow.com/q/38722105
tagged with: python-3.x
has body: For instance, instead of something like: My friends are Kate My friends are Matt I want to print out: My friends are Kate, Matt myFriends = [] def add_new_friend(): while True: newFriend = input("Add your new friend (Enter blank to quit):") if newFriend == "": break elif newFriend == "check": check_friends() else: myFriends.append(newFriend) for friend in range(len(myFriends)): print(myFriends[friend])
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49604049
tagged with: python
has title: How do I print the values of a list in one line rather than separately
linked to: http://stackoverflow.com/q/34619384

http://stackoverflow.com/comment/86387396
has text: Nothing abnormal. I used the logs to find where it was hanging since it's not easy to attach a debugger to a running Python program.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49686876

http://stackoverflow.com/comment/86364112
comment on: http://stackoverflow.com/a/49675543
type: AnswerComment
has text: Your solution works great! I'm pretty new to this,would you mind explaining the "following-sibling" as well as the two colons? I would like to know their usage and meanings please. Same with "preceding", if you're willing. Your help is very VERY much appreciated, I've been banging my head on this for two days. Thanks!
score: 0
type: Comment

http://stackoverflow.com/a/49702474
has comment: http://stackoverflow.com/comment/86418707
answers question: http://stackoverflow.com/q/49702214
type: Answer
has comment: http://stackoverflow.com/comment/86418693
upvote count: 27
score: 27
accepted answer of: http://stackoverflow.com/q/49702214
has comment: http://stackoverflow.com/comment/86418633
has comment: http://stackoverflow.com/comment/134766475
downvote count: 0
has body: The problem is this line in your request headers: "accept-encoding": "gzip, deflate, br", That br requests Brotli compression, a new-ish compression standard (see RFC 7932) that Google is pushing to replace gzip on the web. Chrome is asking for Brotli because recent versions of Chrome understand it natively. You're asking for Brotli because you copied the headers from Chrome. But requests doesn't understand Brotli natively. You can pip install brotli and register the decompresser or just call it manually on res.content. But a simpler solution is to just remove the br: "accept-encoding": "gzip, deflate", … and then you should get gzip, which you and requests already know how to handle.
type: AcceptedAnswer

tuples
tags question: http://stackoverflow.com/q/49757471
tags question: http://stackoverflow.com/q/49752739
tag name: tuples
tags question: http://stackoverflow.com/q/49626782
tags question: http://stackoverflow.com/q/49637892
tags question: http://stackoverflow.com/q/49722196
tags question: http://stackoverflow.com/q/49615328
tags question: http://stackoverflow.com/q/49730922
tags question: http://stackoverflow.com/q/49642143
tags question: http://stackoverflow.com/q/49724651
tags question: http://stackoverflow.com/q/49641150
tags question: http://stackoverflow.com/q/49650090
type: Tag
tags question: http://stackoverflow.com/q/49628086

http://stackoverflow.com/comment/96579076
comment on: http://stackoverflow.com/a/49675283
has text: @zwep this was resolved in 2.2.4. Are you sure you've updated?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86431495
comment on: http://stackoverflow.com/q/49708993
has text: add `&` at the end of the line e.g `python home/ubuntu/pyscript.py &`, run in background, also you should append output to file for debug and monitoring `python home/ubuntu/pyscript.py >> pyscript.log 2>&1 &`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86470810
has text: You want to get the attributes which are descriptors by name?
score: 0
comment on: http://stackoverflow.com/q/49728405
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49645988
type: Answer
has body: From the Flask-Session documentation: https://pythonhosted.org/Flask-Session/ PERMANENT_SESSION_LIFETIME: the lifetime of a permanent session as datetime.timedelta object. Starting with Flask 0.8 this can also be an integer representing seconds.
score: 0
answers question: http://stackoverflow.com/q/49645765

http://stackoverflow.com/q/49678384
has comment: http://stackoverflow.com/comment/101321908
has title: How to get all requests from selenium webdriver in Python
has comment: http://stackoverflow.com/comment/86370141
tagged with: phantomjs
upvote count: 2
tagged with: selenium
score: 1
tagged with: web-crawler
tagged with: har
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86369549
type: Question
has answer: http://stackoverflow.com/a/49697580
type: UnansweredQuestion
has body: I am trying to build an automated tool to validate a web analytics tag implementation. I am using Python 3 + Selenium and PhantomJS to automate browsing and collect the tags that are firing. I am using the code below to crawl the web pages and get the har log with all requests, similar to what the network tab in Google Chrome does. The issue is, for some websites it works perfectly and I can see the google-analytics.com/collect? calls. For others I can see it on Google Chrome network tab, but my crawler wont register it. I am sure I am waiting the page to load, but still it does not work. Example page where I find the analytics/collect? call in the har log: https://www.stackoverflow.com Example of page where I don't find it the analytics/collect? call in the har log, but find it on the chrome network tab. https://www.nike.com.br Code to instantiate a webdriver def get_driver(): desired_capabilities = DesiredCapabilities.PHANTOMJS.copy() service_args = ['--ignore-ssl-errors=yes'] desired_capabilities['phantomjs.page.customHeaders.User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' driver = webdriver.PhantomJS(service_args=service_args, desired_capabilities=desired_capabilities) driver.set_page_load_timeout(60) return driver Code to parse the har log def get_requests(url): driver = get_driver() try: driver.get(url) print(j) except Exception as e: print(e) return None log = driver.get_log('har') log = json.loads(log[0]['message']) log_list = log['log']['entries'] return log_list
tagged with: python

http://stackoverflow.com/a/49758105
downvote count: 0
has body: See the Python tutorial on Using Lists as Stacks and the documentation on Classes. Just two slight modifications, and it seems to work: class myStack: def __init__(self): self.container = [] def __repr__(self): return "Stack({})".format(self.container) def push(self,item): self.container.append(item) def iter(self): return self.container.reverse() # ! def pop(self): return self.container.pop() def len(self): return len(self.container) # ! s = myStack() print(s) s.push("something") print(s) s.push("something completely different") print(s) print(s.len()) s.iter() print(s) s.pop() print(s) s.pop() print(s) s.pop() print(s) produces Stack([]) Stack(['something']) Stack(['something', 'something completely different']) 2 Stack(['something completely different', 'something']) Stack(['something completely different']) Stack([]) Traceback (most recent call last): File "t.py", line 37, in &lt;module&gt; s.pop() File "t.py", line 16, in pop return self.container.pop() IndexError: pop from empty list You could prevent this last error by first checking if the pop() can be done. See Emulating container types regarding all the "special" class methods. So to access an element by index just like with a list, e.g s[1], you might add def __getitem__(self,key): return self.container[key] and get e.g. something completely different.
upvote count: 1
answers question: http://stackoverflow.com/q/49757833
score: 1
type: Answer

http://stackoverflow.com/comment/86415036
type: QuestionComment
has text: Sorry, I should have specified, but I've hid the ability to close the script from the user, but they can still access task manager and close the script that way(windows doesn't let you block) so I do need to exit it immediately. I think I will look into your first suggestion if no other alternative exists
comment on: http://stackoverflow.com/q/49700290
score: 0
type: Comment

http://stackoverflow.com/a/49746941
has body: The term "daemon" is probably more confusing than helpful here. It means something you don't have to wait/join. For a thread, that actually means a thread that will be implicitly killed on exit—but for a child process, it means one that will run in the background and continue to do so even if its parent, its session, its tty, etc. all die. The subprocess docs don't even mention the term, possibly to avoid this confusion. At any rate, if you want children that automatically go away with the parent no matter what on all platforms, you need to do that explicitly. For a nice design where there's a top-level script that has access to all the Popen object, the easy way to do that is at the top level: if __name__ == '__main__': try: # do a bunch of stuff, including launching lots of children finally: for p in childprocs: p.kill() for p in childprocs: p.wait() You can of course get fancier by waiting with a timeout and then terminating, or just terminate them without trying to kill first, or send different signals, or… whatever you want. But this is the basic idea. In some cases, it's even nicer to use a with statement with an ExitStack that you add the children to as they're created. On the other hand, in some complex scripts, there's really no good way to access the children from the top level, and you have to use something cruftier like atexit handlers. But there's another simple design that often works. If you're not running too many children, you can spawn a thread just to wait on each one, or even to just run them instead of creating a Popen. If you are running lots of children, a single thread can loop through them waiting with a timeout, although this can be a lot more fiddly to get right (and waste resources if you don't). Then it's just a matter of managing your threads, and they automatically manage your children.
type: Answer
answers question: http://stackoverflow.com/q/49746712
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/49968681
has body: You can generate data conforming to normal distribution easily using R, you can follow the following steps #Read the data into a dataframe library(data.table) data = data = fread("data.csv", sep=",", select = c("latitude", "longitude")) #Remove duplicate and null values df = data.frame("Lat"=data$"latitude", "Lon"=data$"longitude") df1 = unique(df[1:2]) df2 &lt;- na.omit(df1) #Determine the mean and standard deviation of latitude and longitude values meanLat = mean(df2$Lat) meanLon = mean(df2$Lon) sdLat = sd(df2$Lat) sdLon = sd(df2$Lon) #Use Normal distribution to generate new data of 1 million records newData = list() newData$Lat = sapply(rep(0, 1000000), function(x) (sum(runif(12))-6) * sdLat + meanLat) newData$Lon = sapply(rep(0, 1000000), function(x) (sum(runif(12))-6) * sdLon + meanLon) finalData = rbind(df2,newData) now final data contains both old records and new records Write the finalData dataframe to a CSV file and you can read it from Scala or python
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49702979
downvote count: 0
answers question: http://stackoverflow.com/q/49702979
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/q/49757499
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86529979
has title: Python arranging strings in a list
type: Question
has comment: http://stackoverflow.com/comment/86530005
has body: I'm new to python programming language and recently I've just encountered this problem and I really want to know how to solve it so here's the input: list = ["Sam-11,Mark-10,Mike-14","Martha-12,Emma-9,Kyla-13"] the output should be like this: Mark-10, Emma-9 // Prints the names with the least age in the two strings inside the list including their age
accepted answer: http://stackoverflow.com/a/49757644
upvote count: 0
has comment: http://stackoverflow.com/comment/86530072
score: -3
answer count: 1
has comment: http://stackoverflow.com/comment/86530225
has comment: http://stackoverflow.com/comment/86530322
has answer: http://stackoverflow.com/a/49757644
has comment: http://stackoverflow.com/comment/86530202
has comment: http://stackoverflow.com/comment/86530269
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86530017
linked to: http://stackoverflow.com/q/49671990

http://stackoverflow.com/a/49758402
has comment: http://stackoverflow.com/comment/86534732
has comment: http://stackoverflow.com/comment/86534589
type: Answer
has comment: http://stackoverflow.com/comment/86532045
has body: The sample your network is failing to predict is ([0,0], -1), which is a result of the lack of bias. For I = [0,0], we have H = dot(Wh,I) = [0,0,..0]. Since tanh(0) = 0, the network is unable to learn any transformation of zero to non-zero at any layer. Adding bias will solve the issue; a hacky solution can be achieved by adding a 3rd column to your dataset filled with any constant, to emulate the effect of bias.
has comment: http://stackoverflow.com/comment/86535747
has comment: http://stackoverflow.com/comment/86535445
has comment: http://stackoverflow.com/comment/86534613
has comment: http://stackoverflow.com/comment/86533553
has comment: http://stackoverflow.com/comment/86533412
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86531826
has comment: http://stackoverflow.com/comment/86535308
accepted answer of: http://stackoverflow.com/q/49754939
has comment: http://stackoverflow.com/comment/86532385
has comment: http://stackoverflow.com/comment/86535521
has comment: http://stackoverflow.com/comment/86532031
has comment: http://stackoverflow.com/comment/86533605
score: 0
has comment: http://stackoverflow.com/comment/86532568
answers question: http://stackoverflow.com/q/49754939

http://stackoverflow.com/q/49696795
tagged with: python
has answer: http://stackoverflow.com/a/49702494
has body: i want to extract all links in a page and this is my code, but it does nothing, when i print the fetched page i prints it well but for parsing it doesn't do anything!! from html.parser import HTMLParser import urllib import urllib.request class myParser(HTMLParser): def handle_starttag(self, tag, attrs): if (tag == "a"): for a in attrs: if (a[0] == "href"): link = a[1] if (link.find('http') &gt;= 1): print(link) newParser = myParser() newParser.feed(link) url = "http://www.asriran.com" req = urllib.request.Request(url) response = urllib.request.urlopen(req) handle = response.read() parser = myParser() print (handle) parser.feed(str(handle))
tagged with: urllib
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86411974
answer count: 1
has title: extracting links from a page in python 3
tagged with: html-parsing
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49702494

http://stackoverflow.com/a/49703096
has body: Do you want something like this output ? { "title": "Charlie's Angels", "review": "I don't really like this 'movie'" "review": "I don't really like 'this movie'" "review": "I don't really like 'this' movie" "review": "'I don't' really like 'this' movie" } I used 2 regex to get this output. (?&lt;=\w(?='\w))' Demo,,, which is used in pre-process for replacing the ' inside a word to another distinctive strings(@@@ in this case). And Replace ' to " in the case of matching this regex. (?m)(?&lt;=\s)(?!'[^']*(?:(?:'[^']*){2})*$)'|'(?=[\.\s\,\:])(?=[^']*(?:(?:'[^']*){2})*$) Demo Pre-word single quote matching condition: a space exists before the quote and the number of afterward quotes must be odd. Post-word single quote matching condition: the number of afterward quotes must be even and only allowed character exists after the quote. Python scripts may be like this ss="""{ 'title': 'Charlie's Angels', 'review': 'I don't really like this 'movie'' 'review': 'I don't really like 'this movie'' 'review': 'I don't really like 'this' movie' 'review': ''I don't' really like 'this' movie' }""" import re rexpre= re.compile(r"(?&lt;=\w(?='\w))'") rexquot= re.compile(r"(?m)(?&lt;=\s)(?!'[^']*(?:(?:'[^']*){2})*$)'|'(?=[\.\s\,\:])(?=[^']*(?:(?:'[^']*){2})*$)") ss=re.sub('@@@',"'",rexquot.sub('"',rexpre.sub("@@@",ss))) print(ss)
type: Answer
answers question: http://stackoverflow.com/q/49700931
score: 0

http://stackoverflow.com/comment/86252620
type: QuestionComment
has text: The API Call and Data Parsing: https://sdbrett.com/BrettsITBlog/2017/03/python-parsing-api-xml-response-data/
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49622811

http://stackoverflow.com/q/49660813
favorite count: 0
has title: Efficient way to extract individual bit values from a hexa string
type: Question
accepted answer: http://stackoverflow.com/a/49661076
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49661076
upvote count: 1
score: 1
has body: I'm developing a real-time application where I have to process a line of data as fast as possible to send it over to an app. These lines arrive at a very fast rate, around 40k per minute. The task is to extract the value of certain individual bits from the hexa data in the line. I have a solution already but I doubt it's the most efficient one, so I'm asking if you can improve it. A sample line of data: p1 p2 p3 len data 1497383697 0120 000 5 00 30 63 4f 15 len is how many bytes are in the data, data is what we're working with. Let's say I want to extract 3 bits starting from the 11th from the left. Converting the hexa to binary with padding: 0x0030634f15 = 0000 0000 0011 0000 0110 0011 0100 1111 0001 0101 The wanted value is 0b110 which is 6 in decimal. My working solution for the problem is this: # 11 and 3 in the example start = config.getint(p, 'start') length = config.getint(p, 'length') parts = line.split() hexadata = ''.join(parts[4:]) bindata = bin(int(hexadata, 16))[2:].zfill(len(hexadata) * 4) val = int(bindata[start:start + length], 2) val will hold the value 6 in the end. Any other, more efficent way to do this? Thank you
has comment: http://stackoverflow.com/comment/86331536
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86331669
tagged with: bitwise-operators

http://stackoverflow.com/comment/86428092
type: QuestionComment
comment on: http://stackoverflow.com/q/49707401
score: 3
has text: what's wrong with your first solution? `[0] + [i for i in mylist if i != 0]`
type: Comment

http://stackoverflow.com/comment/86435610
comment on: http://stackoverflow.com/a/49697062
type: Comment
score: 0
has text: thank you for your help, I was able to find correct code with little modification / addition to your code.
type: AnswerComment

http://stackoverflow.com/q/49752255
has answer: http://stackoverflow.com/a/71142441
has body: I have received the following error while trying to delete a Message: 2018-04-10 13:58:57,646 (__init__.py:292 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body: [b'{"ok":false,"error_code":400,"description":"Bad Request: message can\'t be deleted"}']" Why message can't be deleted? import config import telebot bot = telebot.TeleBot(config.token) @bot.message_handler(content_types=["text"]) def repeat_all_messages(message): bot.send_message(message.chat.id, 'Hello World') bot.delete_message(message.chat.id, message.message_id) if __name__ == '__main__': bot.polling(none_stop=True)
has answer: http://stackoverflow.com/a/49763617
has comment: http://stackoverflow.com/comment/86521320
favorite count: 0
type: Question
tagged with: telegram-bot
type: UnansweredQuestion
has title: Telegram bot can't delete message
downvote count: 5
tagged with: python
score: -1
upvote count: 4
has answer: http://stackoverflow.com/a/49752457
answer count: 3
has comment: http://stackoverflow.com/comment/86518924

http://stackoverflow.com/q/49645675
tagged with: ogr2ogr
tagged with: osgeo
tagged with: python
type: UnansweredQuestion
has body: I'm trying to write a script that creates multiple ogr2ogr calls to a WFS service (in a loop). For some reason i can't use the osgeo lib (it's a work computer, with limited access..), so i figured i would give the Subprocess lib a try. My though process so far is: open OSGeo4W shell transfer string from script to shell command line loop for multiple ogr2ogr calls Code: import subprocess p = subprocess.Popen(r'C:\Program Files\QGIS 2.18\OSGeo4W.bat', stdout=subprocess.PIPE, stdin=subprocess.PIPE) call = 'ogr2ogr -f "CSV" "folder_on_pc" WFS:"dbname" -sql "SELECT * from specific_layer where attribute&gt;=20180311 ORDER BY attribute"' subprocess.check_call(call, shell=True) output = p.communicate(call)[0] I know the ogr2ogr call works, but can't seem to make the command line 'type it'. If this is a completly wrong approach, please tell me. I appriciate all help.
has title: Using Osgeo4w shell via. python script
answer count: 0
downvote count: 0
tagged with: shell
score: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49705422
has comment: http://stackoverflow.com/comment/86424277
has comment: http://stackoverflow.com/comment/86424673
has comment: http://stackoverflow.com/comment/86424582
type: Answer
has comment: http://stackoverflow.com/comment/86424508
has comment: http://stackoverflow.com/comment/86424829
downvote count: 0
answers question: http://stackoverflow.com/q/49705263
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86424982
accepted answer of: http://stackoverflow.com/q/49705263
has body: Seeing the code you just added, try to rewrite X,Y like this: X=list(map(float,isheet.col_values(0))) Y=list(map(float,isheet.col_values(1))) Another: Your function can be simplified as a sum of all errors instead. import numpy as np # Another way of writing it #def L(X,Y,c,b,d): # error=0 # a=Y[0] # for x,y in zip(X,Y): # error += ((c*x+(a/b)*np.sqrt(b**2-x**2)+d)-y)**2 # return error # Or even better: def L(X,Y,c,b,d): a = Y[0] error = sum(((c*x+(a/b)*np.sqrt(b**2-x**2)+d)-y)**2 for x,y in zip(X,Y)) return error X = [2.2,2.2,3.2] Y = [2.0,2.1,3.1] c = 1 b = 20 d = 1 print(L(X,Y,c,b,d)) Returns: 29.148285465180138 Where as, chaning X and Y to: X = [2.2,2.2,3.2,'a'] Y = [2.0,2.1,3.1,'b'] Returns: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

http://stackoverflow.com/q/49739245
has comment: http://stackoverflow.com/comment/86527929
has body: I have spent a good amount of time trying to determine what is going wrong exactly, with the code I am using to convert pdf to docx (and doc to docx) using LibreOffice. I have used both the windows run interface to test-run some of the code I have found to be relevant, and have tried on python as well, neither of which works. I have LibreOffice v6.0.2 installed on windows. I have been using variations of this code to attempt to convert some pdf files to docx of which the specific pdf file is not really relevant: import subprocess lowriter='C://Program Files/LibreOffice/program/swriter.exe' subprocess.run('{} --invisible --convert-to docx --outdir &quot;{}&quot; &quot;{}&quot;' .format(lowriter,'dir', 'filepath.pdf',),shell=True) I have tried code, again, in both the run interface on the windows os, and through python using the above code, with no luck. I have tried without the outdir as well, just in case I was writing that incorrectly, but always get a return code of 1: CompletedProcess(args='C://Program Files/LibreOffice/program/swriter.exe --invisible --convert-to docx --outdir &quot;{dir}&quot; {filepath.pdf}&quot;', returncode=1) The dir and filepath.pdf are place holders I have put. I have a similar problem with the doc to docx conversion.
tagged with: libreoffice
score: 1
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/docx
has title: Having trouble using Python and LibreOffice to convert pdf to docx and doc to docx
type: Question
tagged with: file-conversion
accepted answer: http://stackoverflow.com/a/49763069
has answer: http://stackoverflow.com/a/49763069
possible better answer: http://stackoverflow.com/a/65934160
tagged with: python
has comment: http://stackoverflow.com/comment/86493360
has answer: http://stackoverflow.com/a/65934160
tagged with: doc
linked to: http://stackoverflow.com/q/26358281
upvote count: 2
type: AnsweredQuestion
answer count: 2

pca
tag name: pca
tags question: http://stackoverflow.com/q/49736849
tags question: http://stackoverflow.com/q/49640315
type: Tag
tags question: http://stackoverflow.com/q/49713947
tags question: http://stackoverflow.com/q/49690003

http://stackoverflow.com/q/49741359
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/49741414
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49741414
tagged with: list
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/49741801
downvote count: 1
favorite count: 0
type: Question
has body: I have a table on excel, and I would like to check if some element is empty, for misstyping or whatelse. So, I want to check all of elements which are placed at [1]. import csv matrix = csv.reader(open("matrix1.csv","rb")) arr = range(50) x = 0 for row in matrix: arr[x] = row x += 1 i = 0 len = len(arr) for i in range(len): if ((arr[i][1]) is None): print("it is empty") TypeError: 'int' object is not subscriptable But, if i code like my code below, it works, but my console still says: TypeError: 'int' object is not subscriptable for i in range(len): if ((arr[i]) != 0): print(arr[i][1]) Full console output: 585957 Traceback (most recent call last): 545253 515359 575951 File "C:/PycharmProjects/test.py", line 17, in 525356 print(arr[i][1]) 565958 585754 TypeError: 'int' object is not subscriptable 505152 535250 It means, it gives me the elements I want, but it is still not cool. What am I missing? Thanks!
has comment: http://stackoverflow.com/comment/86497315
has title: If statements and 2D array in Python
accepted answer: http://stackoverflow.com/a/49741801

http://stackoverflow.com/comment/86271530
score: 0
has text: If you don't have the statement in parenthesis, it will just return the result of the `else` instead of evaluating the else and appending it to the string.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49630944

http://stackoverflow.com/comment/86328522
score: 0
comment on: http://stackoverflow.com/q/49659027
type: Comment
type: QuestionComment
has text: Thats the second reason for an mvce ;) by preparing it, you overthink it again :) - you can self answer it and accept int in 48h - that way you keep the 2 score on your question. Or delete it.

http://stackoverflow.com/comment/86496931
type: Comment
type: AnswerComment
has text: it would be better to implement this in a `FuncFormatter` in case the limits change
comment on: http://stackoverflow.com/a/49740904
score: 1

http://stackoverflow.com/comment/86312150
comment on: http://stackoverflow.com/q/49651927
type: Comment
score: 0
has text: @Psytho how could I get the output 25
type: QuestionComment

http://stackoverflow.com/q/49650036
has answer: http://stackoverflow.com/a/49673170
score: 0
tagged with: neural-network
answer count: 1
tagged with: tensorflow
type: Question
has title: TensorFlow | RNN not training (saving)
tagged with: python
type: UnansweredQuestion
tagged with: recurrent-neural-network
has body: I am currently working on a RNN which should generate text based on sample text with which it was trained. But for some reason no matter how long I train it it's always spilling out nonsense. You can find the GitHub repo here. Network definition ## RNN with num_layers LSTM layers and a fully-connected output layer ## The network allows for a dynamic number of iterations, depending on the inputs it receives. ## ## out (fc layer; out_size) ## ^ ## lstm ## ^ ## lstm (lstm size) ## ^ ## in (in_size) class ModelNetwork: def __init__(self, in_size, lstm_size, num_layers, out_size, session, learning_rate=0.003, name="rnn"): self.scope = name self.in_size = in_size self.lstm_size = lstm_size self.num_layers = num_layers self.out_size = out_size self.session = session self.learning_rate = tf.constant( learning_rate ) # Last state of LSTM, used when running the network in TEST mode self.lstm_last_state = np.zeros((self.num_layers*2*self.lstm_size,)) with tf.variable_scope(self.scope): ## (batch_size, timesteps, in_size) self.xinput = tf.placeholder(tf.float32, shape=(None, None, self.in_size), name="xinput") self.lstm_init_value = tf.placeholder(tf.float32, shape=(None, self.num_layers*2*self.lstm_size), name="lstm_init_value") # LSTM self.lstm_cells = [ tf.contrib.rnn.BasicLSTMCell(self.lstm_size, forget_bias=1.0, state_is_tuple=False) for i in range(self.num_layers)] self.lstm = tf.contrib.rnn.MultiRNNCell(self.lstm_cells, state_is_tuple=False) # Iteratively compute output of recurrent network outputs, self.lstm_new_state = tf.nn.dynamic_rnn(self.lstm, self.xinput, initial_state=self.lstm_init_value, dtype=tf.float32) # Linear activation (FC layer on top of the LSTM net) self.rnn_out_W = tf.Variable(tf.random_normal( (self.lstm_size, self.out_size), stddev=0.01 )) self.rnn_out_B = tf.Variable(tf.random_normal( (self.out_size, ), stddev=0.01 )) outputs_reshaped = tf.reshape( outputs, [-1, self.lstm_size] ) network_output = ( tf.matmul( outputs_reshaped, self.rnn_out_W ) + se…

http://stackoverflow.com/a/49616682
has body: How can I compare the floats within two columns row by row? I would suggest to use pandas apply like so: def compare_floats(row): return row['col1'] == row['col2'] # you can use any comparison you want here df['col3'] = df.apply(compare_floats, axis=1)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86240620
has comment: http://stackoverflow.com/comment/86240334
answers question: http://stackoverflow.com/q/49616424
has comment: http://stackoverflow.com/comment/86240527

http://stackoverflow.com/a/49640459
type: Answer
answers question: http://stackoverflow.com/q/49640298
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86288915
has body: Even better, reverse the dictionary, so you have something like: v_map = { 1: 'Car', 2: 'Car', 3: 'Car', 4: 'Chicken legs', 5: 'Chicken legs', 6: 'Chicken legs', 7: 'Coronary artery bypass graft surgery', ... 12: 'Coronary artery bypass graft surgery' } Now your new column is simply a matter of plugging in v_map[df['Value']] for the strings in the new column.
score: 2

http://stackoverflow.com/q/49600183
downvote count: 2
has body: If any values are entered in the list, they are printed. If no value is entered in the list, it should print out -1 v = [13,26,27,29,59,62] def search_list(v,n): if n ==v: print(n) else: print(-1) print(search_list(v,13)) I wrote code like this. But the results are shown below -1 None
accepted answer: http://stackoverflow.com/a/49600251
upvote count: 1
has comment: http://stackoverflow.com/comment/86207554
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49600308
possible better answer: http://stackoverflow.com/a/49600308
has answer: http://stackoverflow.com/a/49600251
tagged with: python
score: -1
has title: code that will return the values from the list
has answer: http://stackoverflow.com/a/49605373
has comment: http://stackoverflow.com/comment/86207395
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/86207450

http://stackoverflow.com/a/49718970
accepted answer of: http://stackoverflow.com/q/49718888
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/86451144
has comment: http://stackoverflow.com/comment/86451328
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49718888
downvote count: 1
has comment: http://stackoverflow.com/comment/86543032
has comment: http://stackoverflow.com/comment/86451006
has comment: http://stackoverflow.com/comment/86453196
has comment: http://stackoverflow.com/comment/86450988
has comment: http://stackoverflow.com/comment/86451263
type: Answer
has body: One method is to use collections.Counter. The idea is to count the number of series per (user, program) combination using a dictionary. Then filter for count greater than 1 via a dictionary comprehension. from collections import Counter lst = [(9600002, 42, 3), (9600001, 17, 3), (9600003, 11, 1), (9600002, 14, 5), (9600001, 17, 1), (9600003, 11, 4), (9600001, 17, 4), (9600001, 14, 3), (9600002, 42, 6), (9600002, 42, 1)] c = Counter() for user, program, season in lst: c[(user, program)] += 1 print(c) # Counter({(9600002, 42): 3, (9600001, 17): 3, (9600003, 11): 2, # (9600002, 14): 1, (9600001, 14): 1}) res = {k: v for k, v in c.items() if v &gt; 1} print(res) # {(9600002, 42): 3, (9600001, 17): 3, (9600003, 11): 2} print(res.keys()) # dict_keys([(9600002, 42), (9600001, 17), (9600003, 11)]) Note on Counter versus defaultdict(int) Counter is twice as slow as defaultdict(int), see benchmarking below. You can switch easily to defaultdict(int) if performance matters and none of these features are relevant to you: Missing Counter keys don't get added automatically when querying. You can add / subtract Counter objects. Counter offers additional methods, e.g. elements, most_common. Benchmarking on Python 3.6.2. from collections import defaultdict, Counter lst = lst * 100000 def counter(lst): c = Counter() for user, program, season in lst: c[(user, program)] += 1 return c def dd(lst): d = defaultdict(int) for user, program, season in lst: d[(user, program)] += 1 return d %timeit counter(lst) # 900 ms %timeit dd(lst) # 450 ms
has comment: http://stackoverflow.com/comment/86451719
has comment: http://stackoverflow.com/comment/86451106
has comment: http://stackoverflow.com/comment/86451660
has comment: http://stackoverflow.com/comment/86451082
has comment: http://stackoverflow.com/comment/86451642

http://stackoverflow.com/q/49680972
has title: Building Python 3 without running unit tests
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/44708262
answer count: 0
type: UnansweredQuestion
tagged with: dreamhost
has comment: http://stackoverflow.com/comment/86374311
has comment: http://stackoverflow.com/comment/86379530
has body: In trying to install a custom Python 3 environment on my webhost (Dreamhost), make fails because the webhost's process monitor sees the unit tests as taking too much CPU. While I am able to install the untested Python binaries with make install anyway, I would love to be able to do the build without it even trying to run the unit tests in the first place (mostly to avoid getting the "helpful" automated email from Dreamhost that suggests I upgrade to a VPS). Since I'm only building stable releases of Python it's pretty much guaranteed that the unit tests would all pass anyway. So, is there an option to python's ./configure or make that will cause it to skip attempting to run the test suite?
has comment: http://stackoverflow.com/comment/86379464
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86379513
tagged with: python

http://stackoverflow.com/q/49693468
has answer: http://stackoverflow.com/a/49693674
score: 0
tagged with: pandas
tagged with: python
has body: I am trying to use a predefined integer to integer python dictionary in order to map the corresponding rows in a pandas dataframe to a new row without success. I have the following dataframe: data=np.array([ ['Item 1',7365301,"Cool item."] ]) items = pd.DataFrame(data = data, columns = ['name','id','description']) I have a python dictionary, that maps from int->int like so: item_map = {7365301: 10} I am trying to map the values in my dictionary to a new column by using Pandas map like: items['id2'] = items['id'].map(inverse_item_map) which ends up with the following: name id description id2 0 Item 1 7365301 Cool item. NaN or like: items['id2'] = items['id'].map(inverse_item_map).astype(int) which throws a ValueError: Cannot convert non-finite values (NA or inf) to integer What's going on here? Am I doing something wrong here? Why is this operation unsuccessful?
type: Question
has title: Map Integer Dictionary to Pandas Dataframe
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/49720776
has answer: http://stackoverflow.com/a/49721037
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has title: Find last position in Python
has comment: http://stackoverflow.com/comment/86454683
has body: I am learning Python and I am trying to resolve this problem without len() but I am still stuck. Here is a quiz explanation. Define a procedure, find_last, that takes as input two strings, a search string and a target string, and returns the last position in the search string where the target string appears, or -1 if there are no occurrences. Example: find_last('aaaa', 'a') returns 3 Make sure your procedure has a return statement. Here is my code: def find_last(search, target): target = search.find(target) while target: if target == -1: return target else: return target +1 return target Thank you.
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86454707
type: UnansweredQuestion

http://stackoverflow.com/a/49801182
has comment: http://stackoverflow.com/comment/86803960
has comment: http://stackoverflow.com/comment/86814518
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49734694
answers question: http://stackoverflow.com/q/49734694
has body: It indeed is quite easy in Python as well. For a fully contained example, see my example script below (python3). The code is documented by comments. If you need further clarification, please ask :) #!/usr/bin/python3 # Import Basic OS functions import os # Import modules for CGI handling import cgi, cgitb, jinja2 import urllib.request # enable debugging cgitb.enable() # print content type print("Content-type:text/html\r\n\r\n") # HTML INPUT FORM HTML = """ Upload File File: {% if filedata %} {{filedata}} {% endif %} """ inFileData = None form = cgi.FieldStorage() UPLOAD_DIR='uploads' # IF A FILE WAS UPLOADED (name=file) we can find it here. if "file" in form: form_file = form['file'] # form_file is now a file object in python if form_file.filename: uploaded_file_path = os.path.join(UPLOAD_DIR, os.path.basename(form_file.filename)) with open(uploaded_file_path, 'wb') as fout: # read the file in chunks as long as there is data while True: chunk = form_file.file.read(100000) if not chunk: break # write the file content on a file on the hdd fout.write(chunk) # load the written file to display it with open(uploaded_file_path, 'r') as fin: inFileData = "" for line in fin: inFileData += line headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} print(jinja2.Environment().from_string(HTML).render(filedata=inFileData))
has comment: http://stackoverflow.com/comment/86822056
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87063053

http://stackoverflow.com/comment/86382438
score: 0
has text: On SO it is expected that you add such information to the question instead of linking it.
comment on: http://stackoverflow.com/q/49685416
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49644242
downvote count: 0
upvote count: 1
has body: We would like to develop high performance WSGI application in python. This application should serve html or JSON both depening on requirement.There will not be any backend database. As per my understanding Django not suits well to my requirements. It seems me using Django is overburden because we don't need many of its features. What we basically need is router+controller+view. Also performance is our big concern. I am going though different banchmarkings and found that Djnago is really slow. https://falconframework.org/ Keeping all this in view it seems me that we should write our own framework by using some fastest router libraries but this will still be reinventing the wheels. Please note I have developed database centric web application in Django and it worth to use Django there. But when there is no database and performance really matters then based on different banchmark and own experience it not seems good choice. Is there any other better minimal web framework that we can use? Or if suggestion is to write new one then it will be great if you provide few examples. Below are few links: https://docs.pylonsproject.org/projects/webob/en/stable/do-it-yourself.html http://funwithlinux.net/2015/11/how-to-write-a-python-web-framework-from-scratch/ Any expert guidance is really helpful! Thanks in advance
favorite count: 0
type: Question
has title: High performance WSGI application
type: UnansweredQuestion
tagged with: wsgi
tagged with: python
has comment: http://stackoverflow.com/comment/86296521
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86296349
answer count: 0
score: 1

http://stackoverflow.com/comment/86483529
score: 0
comment on: http://stackoverflow.com/q/49688481
has text: @MazelTov, since I need to do some cleanup logic before the job is killed, I actually need to work with the soft limit.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86308066
type: AnswerComment
type: Comment
has text: If you just want to count each time movieID is found in list, then `.map(lambda tup: (tup[0], (tup[1][0], 1 if tup[1][0] in tup[1][1] else 0)))` is what you're looking for
comment on: http://stackoverflow.com/a/49648845
score: 0

http://stackoverflow.com/a/49681926
has comment: http://stackoverflow.com/comment/86540364
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/49680553
has body: If all you want is a list of the filenames from a given directory containing a given substring then something like this should work: #!python import os dir='.' # Replace with path to your directory: absolute or relative pattern = 'foo' # Replace with your target substring matching_files = [f for f in os.listdir(dir) if pattern in f] That's all you need for the simplest case. You can then iterate over the list of matching_files If you want to walk down a directory tree with os.walk() then you have to search the third item from each tuple returned by the generator. os.walk() recurses down a tree returning a tuple for each subdirectory. Each of these consists of three items: the leading path, the list of subdirectories below that, and the list of filenames (directory entries for anything OTHER than a subdirectory) at that node. However, there's also a trick! You'll need to prefix each match with that dirpath item at that level. In other words for every match in tuple(os.walk(...))[2] (the list) you need to yield the concatenation of that with the corresponding string from tuple(os.walk(...))[0] to get a full (absolute or relative) path to the matching filename. One way to get a feel for how this works is to load up your Python interpreter (preferably iPython from the Jupyter project), instantiate a generator with walker = os.walk(dir) (where dir is any valid directory to use as the starting point) and then call this = next(walker) and you can look at this[0] and this[2] before going on to look at the next(walker). Let's start with code which returns a list using simple substring matching (as I did with my previous example, but over multiple lines for clarity): #!python results = list() dir = '.' walker = os.walk(dir) delimiter = os.path.sep pattern = '.txt' for p,_,f in walker: matches = ['%s%s%s' % (p, delimiter, x) for x in f if pattern in f] results.extend(matches) In this case I'm using the tuple unpacking of the for loop to give me the path and file list component…
has comment: http://stackoverflow.com/comment/86515804
upvote count: 5
type: Answer

http://stackoverflow.com/a/49665056
has body: For me working: d1 = { "members": [ { "firstname": "John", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-1234", "mobile": "", }, { "firstname": "Jane", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-4321", "mobile": "916-555-7890", }], "teamname": "1", "team_size": "5", "team_status": "low" } d2 = { "members": [ { "firstname": "John", "lastname": "Doe", "orgname": "Anon", "phone": "916-555-1234", "mobile": "", }], "teamname": "1", "team_size": "5", "team_status": "low" } df1 = json_normalize(d1, 'members', ['team_size', 'team_status','teamname']) print (df1) firstname lastname mobile orgname phone team_size teamname \ 0 John Doe Anon 916-555-1234 5 1 1 Jane Doe 916-555-7890 Anon 916-555-4321 5 1 team_status 0 low 1 low df2 = json_normalize(d2, 'members', ['team_size', 'team_status','teamname']) print (df2) firstname lastname mobile orgname phone team_size teamname \ 0 John Doe Anon 916-555-1234 5 1 team_status 0 low
accepted answer of: http://stackoverflow.com/q/49664978
has comment: http://stackoverflow.com/comment/86340009
has comment: http://stackoverflow.com/comment/86340382
has comment: http://stackoverflow.com/comment/86340041
has comment: http://stackoverflow.com/comment/86340047
has comment: http://stackoverflow.com/comment/86365562
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49664978
score: 0

http://stackoverflow.com/a/49802495
has comment: http://stackoverflow.com/comment/101265437
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/106010364
has body: I just wanted to report my findings about loading a gensim embedding with PyTorch. Solution for PyTorch 0.4.0 and newer: From v0.4.0 there is a new function from_pretrained() which makes loading an embedding very comfortable. Here is an example from the documentation. import torch import torch.nn as nn # FloatTensor containing pretrained weights weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]]) embedding = nn.Embedding.from_pretrained(weight) # Get embeddings for index 1 input = torch.LongTensor([1]) embedding(input) The weights from gensim can easily be obtained by: import gensim model = gensim.models.KeyedVectors.load_word2vec_format('path/to/file') weights = torch.FloatTensor(model.vectors) # formerly syn0, which is soon deprecated As noted by @Guglie: in newer gensim versions the weights can be obtained by model.wv: weights = model.wv Solution for PyTorch version 0.3.1 and older: I'm using version 0.3.1 and from_pretrained() isn't available in this version. Therefore I created my own from_pretrained so I can also use it with 0.3.1. Code for from_pretrained for PyTorch versions 0.3.1 or lower: def from_pretrained(embeddings, freeze=True): assert embeddings.dim() == 2, \ 'Embeddings parameter is expected to be 2-dimensional' rows, cols = embeddings.shape embedding = torch.nn.Embedding(num_embeddings=rows, embedding_dim=cols) embedding.weight = torch.nn.Parameter(embeddings) embedding.weight.requires_grad = not freeze return embedding The embedding can be loaded then just like this: embedding = from_pretrained(weights) I hope this is helpful for someone.
has comment: http://stackoverflow.com/comment/92681029
has comment: http://stackoverflow.com/comment/106017311
type: Answer
has comment: http://stackoverflow.com/comment/92688963
has comment: http://stackoverflow.com/comment/109041581
has comment: http://stackoverflow.com/comment/109041944
accepted answer of: http://stackoverflow.com/q/49710537
has comment: http://stackoverflow.com/comment/101735961
score: 85
upvote count: 85
answers question: http://stackoverflow.com/q/49710537
downvote count: 0

http://stackoverflow.com/a/49727625
type: Answer
score: 3
answers question: http://stackoverflow.com/q/49727534
upvote count: 3
downvote count: 0
has body: j is pythons notation for the imaginary number i (which is sqrt(-1))

http://stackoverflow.com/comment/127912915
type: AnswerComment
score: 1
type: Comment
has text: I was trying to unzip in a shared folder location. Issue was resolved when I used the absolute path.
comment on: http://stackoverflow.com/a/55924135

http://stackoverflow.com/a/49682298
has comment: http://stackoverflow.com/comment/86376969
type: Answer
accepted answer of: http://stackoverflow.com/q/49681606
has body: You can use DataFrame.append and then group by the column you want to use as an index. Let's say that total_df is the table to which you want to add new rows, new_df is the table containing those new rows and date is the column to be used as index. Then you can use: total_df.append(new_df).groupby(by='date').sum()
has comment: http://stackoverflow.com/comment/86383372
has comment: http://stackoverflow.com/comment/86386396
answers question: http://stackoverflow.com/q/49681606
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86524208
has text: Oh ! My big mistake. I don't why the url in file has gone. Right now, It works. but I have another problem. @Jeril
comment on: http://stackoverflow.com/q/49753830
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49703407
tagged with: regex
has answer: http://stackoverflow.com/a/49703459
possible better answer: http://stackoverflow.com/a/49703459
answer count: 4
has answer: http://stackoverflow.com/a/49703467
has body: I have a string that looks like this: a = '2017-11-02T00:00:10' I want to match the last group, which is 10 in my string. So, something like this: 2017-11-02T00:00: and 10 I tried re.match(r':\d+$', a), re.match(r':00$', a), re.match(r':00+$', a) But none of them seems to work. Can anyone please explain why my regex expression isn't working, and how to capture the last group from my string? The output can be lenient as long as I can confirm that the last millisecond equals 10
accepted answer: http://stackoverflow.com/a/49703467
has answer: http://stackoverflow.com/a/49703551
type: AnsweredQuestion
score: 0
has title: Python Regex - match the last group
tagged with: match
type: Question
has answer: http://stackoverflow.com/a/49703511
tagged with: python

http://stackoverflow.com/a/49634456
score: 3
has comment: http://stackoverflow.com/comment/137305502
has comment: http://stackoverflow.com/comment/86284351
type: Answer
has body: The precise problem this question asks is "How can I label a set of multiple matches uniquely when all I have is pairwise matches?" This is a standard graph theory problem: getting from sets of edges to connected components. Just for some intuition: The idea is you have edges (pairs of feature matches). So for e.g. in the above graph, (2, 1) is an edge. And (1, 3), and (5, 6), and so on. So since 2 is matched with 1, and 1 with 3, really, 1, 2, and 3 are all probably the same feature. And so you can group the same features together by finding all the components which are connected together in this graph. Note that the graph need only be described by these pairs and nothing more. You already have code to compute your matches. I'll provide some code to compute the connected components. No guarantees that this code is particularly fast, but it should be robust to whatever types of data you're using. Note however that each distinct node that you send in has to have distinct data as this uses sets. def conncomp(edges): """Finds the connected components in a graph. Parameters ---------- edges : sequence A sequence of pairs where the pair represents an undirected edge. Returns ------- components : list A list with each component as a list of nodes. Only includes single nodes if the node is paired with itself in edges. """ # group edge pairs together into a dict pair_dict = defaultdict(set) nodes = set([num for pair in edges for num in pair]) for node in nodes: for pair in edges: if node in pair: pair_dict[node] = pair_dict[node].union(set(pair)) # run BFS on the dict components = [] nodes_to_explore = set(pair_dict.keys()) while nodes_to_explore: # while nodes_to_explore is not empty node = nodes_to_explore.pop() component = {node} neighbors = pair_dict[node] while neighbors: # while neighbors is non-emtpy next_node = neighbors.pop() if next_node in nodes_to_explore: nodes_to_explore.remove(next_node) next_nodes = set([val for val in pair_dict[next_node] if val not in comp…
has comment: http://stackoverflow.com/comment/86286025
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49629221
answers question: http://stackoverflow.com/q/49629221
upvote count: 3

http://stackoverflow.com/q/49642105
answer count: 1
tagged with: scrapy
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86315148
tagged with: pagination
tagged with: python
has title: Scrapy pagination
has body: I am facing a issue with scrapy pagination. Here is the html: NEXT Scrapy python approach: #follow pagination links next_page_url = response.css("#next_achive_button").extract_first() if next_page_url: next_page_url = response yield scrapy.Request(url=next_page_url, callback=self.parse) I need some help to solve this, when I click next button it should go to the next page. However, I see the next href is on onclick="return false;" I don't know how to do solve this issue. Could you please provide me with some hints how to solve the issue above. Thanks.
has comment: http://stackoverflow.com/comment/86360030
has answer: http://stackoverflow.com/a/49670828
has comment: http://stackoverflow.com/comment/86292075
has comment: http://stackoverflow.com/comment/86303710
type: UnansweredQuestion

http://stackoverflow.com/comment/91918197
score: 0
type: QuestionComment
has text: Possible duplicate of [How to set Python's default version to 3.x on OS X?](https://stackoverflow.com/q/18425379/608639)
type: Comment
comment on: http://stackoverflow.com/q/49704364

http://stackoverflow.com/comment/86335675
has text: That is the one I was using, but I downloaded it again through the link you provided and executed the test but still having the same problem. I am using the current build of Chrome 65.
comment on: http://stackoverflow.com/q/49658070
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86455549
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49721143
type: Comment
has text: Python uses _INDENTATION:_ to declare scopes. Please fix your code so it is euqal to what you have.

http://stackoverflow.com/a/49636600
type: Answer
has comment: http://stackoverflow.com/comment/86281237
has comment: http://stackoverflow.com/comment/86281370
score: 0
answers question: http://stackoverflow.com/q/49636047
has body: You can declare them outside of your method body on top of your script if you're sure that you wouldn't need to change them at any instance of you calling your method. Your sample script would look like: from yourImports import * # just below your import statements url = r'https://your_url.com' usr = 'the_username' password = 'your password' downloaded_file_name = r'myFile.txt' new_file_name = 'my_new_file' def reports(): driver = webdriver.Chrome('location of webdriver') driver get(url) usernamebox = driver.find_element_by_name('username') userbox.send_keys(usr) .... I strongly recommend not using pass as a variable name in place for password since pass is a known keyword in python and naming a variable would shadow the keyword and python interpreter wouldn't allow it. Other approaches: using a dictionary to hold values and using the keys to fetch values. using a config text file to store these things and putting them at a directory path so that if you package your code (like an .exe) and you want to change these credentials, you can just change the config file.

http://stackoverflow.com/comment/86519307
comment on: http://stackoverflow.com/q/49752105
has text: Also, modifying `kappa` may increase or decrease occurrences of correct results: [It has the free parameter `kappa` which control the balance between exploration and exploitation](https://github.com/fmfn/BayesianOptimization/blob/master/examples/visualization.ipynb)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86401343
type: AnswerComment
has text: Thank you for your answer I will check your solution and will update you.
type: Comment
comment on: http://stackoverflow.com/a/49694167
score: 0

http://stackoverflow.com/comment/86502415
type: QuestionComment
has text: @szymon Yes, every profile is generated twice (after I add Profile model into the project). Those blocked ID are the ones before I added Profile model.
comment on: http://stackoverflow.com/q/49726326
type: Comment
score: 0

http://stackoverflow.com/comment/86475142
score: 2
has text: Not to start a flamewar, but php really encourages bad habits. Go for option two.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49730635

http://stackoverflow.com/comment/101546903
type: AnswerComment
score: 1
type: Comment
has text: Found the issue. By comparing with the premade code, I found that my `app.py` file should be in the main dir, not inside the `app` dir.
comment on: http://stackoverflow.com/a/49801351

http://stackoverflow.com/comment/86443770
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49715312
has text: This will only help if there is a modification to a model _after_ it is initially created.

http://stackoverflow.com/comment/86406858
type: Comment
type: QuestionComment
score: 0
has text: thanks, but that didn't seem to result in any difference.
comment on: http://stackoverflow.com/q/49696876

http://stackoverflow.com/q/49677501
type: Question
tagged with: outlook
has comment: http://stackoverflow.com/comment/86380534
tagged with: email-attachments
has answer: http://stackoverflow.com/a/49677725
type: UnansweredQuestion
tagged with: python
has body: i was trying to make a Python script to automate certain aspects in my outlook account in a manner that: whenever i receive emails with attachments containing a certain SUBJECT they are automatically downloaded to a folder on my system. Here is my code: import win32com.client import os current_path = os.getcwd() outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items for m in messages: if m.Subject == "TEST MAIL": print("message body:", m.body) attachment = messages.Attachments for x in attachment: x.SaveASFile(os.path.join(current_path, x.FileName)) The above code doesen't work and throws an exception:pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
score: 0
answer count: 1
has title: Filtering Outlook Mails on a date range and downloading attachments that satisfy a given sub condition?
has comment: http://stackoverflow.com/comment/86367368

http://stackoverflow.com/a/49705013
downvote count: 1
answers question: http://stackoverflow.com/q/49703418
type: Answer
has body: I looked more into the "adding" comment, and its being printed by pandas_datareader. Specifically mstar/daily.py. It appears that retry count is never incremented. Which creates the recursive stack overflow error. def _dl_mult_symbols(self, symbols): failed = [] symbol_data = [] for symbol in symbols: params = self._url_params() params.update({"ticker": symbol}) try: resp = requests.get(self.url, params=params) except Exception: if symbol not in failed: if self.retry_count == 0: warn("skipping symbol %s: number of retries " "exceeded." % symbol) pass else: print("adding %s to retry list" % symbol) failed.append(symbol) else: if resp.status_code == requests.codes.ok: jsondata = resp.json() if jsondata is None: failed.append(symbol) continue jsdata = self._restruct_json(symbol=symbol, jsondata=jsondata) symbol_data.extend(jsdata) else: raise Exception("Request Error!: %s : %s" % ( resp.status_code, resp.reason)) time.sleep(self.pause) if len(failed) &gt; 0 and self.retry_count &gt; 0: # TODO: This appears to do nothing since # TODO: successful symbols are not added to self._dl_mult_symbols(symbols=failed) self.retry_count -= 1 else: self.retry_count = 0 if not symbol_data: raise ValueError('All symbols were invalid') elif self.retry_count == 0 and len(failed) &gt; 0: warn("The following symbols were excluded do to http " "request errors: \n %s" % failed, SymbolWarning) symbols_df = DataFrame(data=symbol_data) dfx = symbols_df.set_index(["Symbol", "Date"]) return dfx
upvote count: 0
score: -1

http://stackoverflow.com/comment/86522523
type: Comment
has text: I want to find duplicates in col1,col2,col3 only after that i need to remove records if pairs found. My expected output is not same in your answer
comment on: http://stackoverflow.com/a/49753853
type: AnswerComment
score: 0

http://stackoverflow.com/q/49749981
type: AnsweredQuestion
answer count: 8
score: 36
upvote count: 36
tagged with: pycharm
downvote count: 0
has answer: http://stackoverflow.com/a/50335132
has comment: http://stackoverflow.com/comment/86519122
accepted answer: http://stackoverflow.com/a/50335132
has title: Cannot find declaration to go to, error in PyCharm
has answer: http://stackoverflow.com/a/78205894
has comment: http://stackoverflow.com/comment/86553646
has answer: http://stackoverflow.com/a/77639768
has answer: http://stackoverflow.com/a/70948307
linked to: http://stackoverflow.com/q/25695803
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/68959559
has answer: http://stackoverflow.com/a/75034074
has comment: http://stackoverflow.com/comment/86537008
has body: I changed my project code from Python 2.7 to 3.x. After these changes when I hover over any method and press Ctrl I get a message: cannot find declaration to go to I'm trying to update PyCharm from 2017.3 to 18.1, I removed the .idea directory but my issue still persists.
has comment: http://stackoverflow.com/comment/86518204
linked to: http://stackoverflow.com/q/37891188
has comment: http://stackoverflow.com/comment/86653434
possible better answer: http://stackoverflow.com/a/70948307
has answer: http://stackoverflow.com/a/52749421
tagged with: python
has answer: http://stackoverflow.com/a/78702844

http://stackoverflow.com/q/49678660
has comment: http://stackoverflow.com/comment/86373847
has body: Since some days ago I was unaware of the __index__() method until reading this question. After that, I have been reading about it in the documentation, PEP and in other SO questions. I understood that whenever the [] operator was used in objects that could be sliced (in my case I'm interested in lists, numpy arrays and pandas), the value either for slicing or for indexing was obtained so that lst[key]=lst[key.__index__()] was fulfilled. However, as in one of the questions, the result depended on whether PyPy or CPython was used, so I decided to check when was slicing actually done with __index__ and when it was not. I have done the following (in CPython 2.7.14): lst = range(10) array = np.arange(10) series = pd.Series(lst) And defined the following classes: class MyIndex: def __index__(self): return 2 class MyInt(int): def __index__(self): return 3 class MyStr(str): def __index__(self): return 4 Then I tried to acces the defined objects with this used defined objects, obtaining the following: Note: I am not posting the complete error message for readability purposes. For MyIndex class, expected output 2: print lst[MyIndex()] print array[MyIndex()] print series[MyIndex()] # Output: 2 2 AttributeError: MyIndex instance has no attribute '__trunc__' For MyInt class, expected output 3: # Case 1 print lst[MyInt()] print array[MyInt()] print series[MyInt()] # Output 0 0 0 # Case 2 print lst[MyInt(2)] print array[MyInt(2)] print series[MyInt(2)] # Output 2 2 2 For MyStr class, expected output 4: # Case 1 print lst[MyStr()] print array[MyStr()] print series[MyStr()] # Output 4 4 KeyError: '' # Case 2 print lst[MyStr('a')] print array[MyStr('a')] print series[MyStr('a')] # Output 4 IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices KeyError: 'a' I'm really puzzled by this, mainly by the following points: With lists the __index__ method is used but not for int and its childrens. Numpy uses __index__…
has answer: http://stackoverflow.com/a/49679410
tagged with: indexing
score: 4
type: AnsweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/86373871
tagged with: slice
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has title: When is `__index__` called for lists and numpy arrays?
linked to: http://stackoverflow.com/q/27449310
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49679410
linked to: http://stackoverflow.com/q/49633222

http://stackoverflow.com/comment/133085786
has text: Works great. Fast. Example !unzip drive/MyDrive/feedback-prize-2021/train.zip -d drive/MyDrive/feedback-prize-2021/train/
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/58515693

http://stackoverflow.com/a/49744762
has body: DyZ's solution would work, for options sake I'll show another way to do it. You could use a try except statement. Using your small example from above: try: print (doc['N8:EntityList']['N8:Entity'][4]['N1:Director']['@xsi:type']) except TypeError: print (doc['N8:EntityList']['N8:Entity'][5]['N1:Director'][0]['@xsi:type']) If you don't know what try catch statements are there is lots of helpful documentation if you google it, but here are a couple of resources (for python 2.7). https://docs.python.org/2.7/library/exceptions.html https://www.python-course.eu/exception_handling.php
answers question: http://stackoverflow.com/q/49744326
type: Answer
score: 0

http://stackoverflow.com/a/49652608
upvote count: 1
answers question: http://stackoverflow.com/q/49652445
score: 1
type: Answer
downvote count: 0
has body: If you are sure the data type is integer, use %02d%02d%04d instead.

http://stackoverflow.com/comment/86331116
type: AnswerComment
has text: Thank you so much! This is what I exactly wanted.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49660655

http://stackoverflow.com/a/49605126
has body: I think your angle(x) function wants to take a number of sides and give an approximation for pi, so the name isn't the best description of the function, but that doesn't really matter. The main issue here seems to be some confusion around function arguments and return values. Anyway, the angle(x) function should take an input of the number of sides, which we can call sides, so we can change that to angle(sides). We can find the angle y with y = 360.0/sides. The side length of each triangle, is (0.5-(math.cos(math.radians(y))*0.5))**0.5, because math.cos() takes an angle in radians. The function returns the function argument x (which we changed to sides), but we want to return the total perimeter of our n-gon, which is z. The function never changes within the loop, so finally we can move the angle(sides) function to the beginning so we aren't defining the function for every value of n. For the actual calculation, we just go over increasing values of n and print each approximation of pi. We can set a limit of 100 sides by changing the while loop to while n &lt; 100, and we print(angle(n)) for each value of n. Here is my refined code. import math def angle(sides): y = 360.0/sides z = sides * (0.5-(math.cos(math.radians(y))*0.5))**0.5 return z n = 1 while n &lt; 100: n += 1 print(angle(n))
type: Answer
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49604654
upvote count: 1

http://stackoverflow.com/comment/86291639
has text: But your variables are named `x0` and `x2`. This is extremely bad practice if you want to iterate over them as a group. How about using a `dict` so that you can properly iterate? Other than that does this answer answer the question you asked?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49641951
type: Comment

http://stackoverflow.com/comment/136214420
type: Comment
type: AnswerComment
score: 1
has text: "but we would have to go back to the begining of the tensor after we reach the end" - if there would be a modulo operation (mod the num elems), then such stride should be correct, right? I wonder if it might make sense to allow for that.
comment on: http://stackoverflow.com/a/69637289

http://stackoverflow.com/comment/86235625
score: 0
comment on: http://stackoverflow.com/q/49614467
type: Comment
type: QuestionComment
has text: @MattM. Yeah, I did try. It didn't work. Sorry, but wanted to know why it didn't work, the reasoning. :)

http://stackoverflow.com/a/49676259
score: 0
has body: Your Python converts into text, the text representation of the 8 characters in the file. Hence, instead of print(' '.join(str(ord(c)) for c in datastring)) you should have put print(' '.join(str(ord(c)) for c in data)) which you can then write to a file using standard techniques. ie. (Python 2) &gt;&gt;&gt; data=b'\x14\x12\x1c\x1a#\x00-d' &gt;&gt;&gt; print(' '.join(str(ord(c)) for c in data)) 20 18 28 26 35 0 45 100 (Python 3) &gt;&gt;&gt; data=b'\x14\x12\x1c\x1a#\x00-d' &gt;&gt;&gt; print(' '.join(str(c) for c in data)) 20 18 28 26 35 0 45 100
has comment: http://stackoverflow.com/comment/86364663
answers question: http://stackoverflow.com/q/49676043
type: Answer

http://stackoverflow.com/comment/86429254
type: QuestionComment
comment on: http://stackoverflow.com/q/49683697
score: 0
has text: It is work checking `sys.exec_prefix` and `sys.path` to make sure that the kernel running in jupyter is pointing to the locations you think it is.
type: Comment

http://stackoverflow.com/a/49696726
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49695960
type: Answer
accepted answer of: http://stackoverflow.com/q/49695960
has body: Moving url(r'^test/', webapp_views.home, name='test') before url(r'^admin/', admin.site.urls) solves the problem although I do not know why. urlpatterns = [ url(r'^test/', webapp_views.home, name='test'), url(r'^admin/', admin.site.urls), url(r'^connect/', views.CustomObtainAuthToken.as_view()), url(r'^membership_create/', views.MembershipCreate.as_view()), url(r'^auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()), url(r'^auth/connect_with_credentials/', views.TokenViewWithData.as_view()), url(r'^debug/', views.UserLoginAndIdView.as_view()), url(r'^auth/', include('rest_framework_social_oauth2.urls'), ) ]
score: 2
upvote count: 2

http://stackoverflow.com/a/49665746
type: AcceptedAnswer
has body: If you run the client on another machine, you have to connect to the host of the server, not to "localhost": host='&lt;server_host&gt;' Run ipconfig on your Windows server machine and look for "IPv4 address".
score: 4
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49665324
answers question: http://stackoverflow.com/q/49665324
downvote count: 0

http://stackoverflow.com/comment/86233168
type: Comment
type: QuestionComment
has text: @d-coder: `True` and `False` are simple names, and therefore belong to some scope, as any other variable. Why don't you worry about any other constant being overwritten?
comment on: http://stackoverflow.com/q/49612205
score: 0

http://stackoverflow.com/q/49677222
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14088294
tagged with: video-streaming
tagged with: python-3.x
has answer: http://stackoverflow.com/a/76281354
type: UnansweredQuestion
has title: Video Stream broadcast from Axis IP-camera results in async_lock error
tagged with: ip-camera
tagged with: python
tagged with: opencv
upvote count: 3
score: 3
downvote count: 0
has body: I have an AXIS IP camera which I can check it with http and rtsp protocols. http://ca.me.ra.ip/axis-cgi/mjpg/video.cgi?resolution=1024x768&dummy=1520 rtsp://ca.me.ra.ip:554/axis-media/media.amp?videocodec=h264&resolution=640x480 What I'm trying to do is get the stream, buffer it in my server and then broadcast it, so that with one connection to the camera, I can preview it to multiple users. I somehow worked it out by this code: #!/usr/bin/python ''' Author: Igor Maculan - n3wtron@gmail.com A Simple mjpg stream http server ''' import cv2 from PIL import Image import threading from http.server import BaseHTTPRequestHandler,HTTPServer from socketserver import ThreadingMixIn from io import StringIO,BytesIO import time capture=None class CamHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path.endswith('.mjpg'): self.send_response(200) self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary') self.end_headers() while True: try: rc,img = capture.read() if not rc: continue imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) jpg = Image.fromarray(imgRGB) tmpFile = BytesIO() jpg.save(tmpFile,'JPEG') self.wfile.write("--jpgboundary".encode()) self.send_header('Content-type','image/jpeg') self.send_header('Content-length',str(tmpFile.getbuffer().nbytes)) self.end_headers() jpg.save(self.wfile,'JPEG') time.sleep(0.05) except KeyboardInterrupt: break return if self.path.endswith('.html'): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(' '.encode()) self.wfile.write(' '.encode()) self.wfile.write(' '.encode()) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def main(): global capture capture = cv2.VideoCapture("rtsp://ca.me.ra.ip:554/axis-media/media.amp?videocodec=h264&resolution=640x480") capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320); capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240); capture.set(cv2.CAP_PROP_SATURATION,0.2); global img try: ser…
linked to: http://stackoverflow.com/q/21631799
answer count: 1

http://stackoverflow.com/comment/86376207
type: Comment
type: QuestionComment
has text: what is the "thresh" function? where does it come from?
score: 0
comment on: http://stackoverflow.com/q/49682197

http://stackoverflow.com/comment/86474682
score: 0
type: QuestionComment
has text: how is `extract` defined?
type: Comment
comment on: http://stackoverflow.com/q/49730540

http://stackoverflow.com/a/49663407
has body: You should use a higher order function (a function that returns a function). To demonstrate, I will not use tkinter but the principle is the same: In [25]: def some_func_maker(letter): ...: def some_func(): ...: print(letter) ...: return some_func ...: In [26]: buttons = [] In [27]: from string import ascii_uppercase as alphabet In [28]: for i in range(26): ...: buttons.append(some_func_maker(alphabet[i])) ...: In [29]: for b in buttons: b() 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 Note, you can inline this if you don't want to keep a some_func_maker around using a lambda: In [37]: buttons = [] ...: for c in alphabet: ...: buttons.append( ...: (lambda x: lambda: some_function(x))(c) ...: ) ...: In [38]: for b in buttons: b() 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 A common trick is that is less verbose is to use a default-argument with your lambda, however, I consider this more hacky, although it is quite common in Python: In [43]: buttons = [] ...: for c in alphabet: ...: buttons.append( ...: lambda x=c: some_function(x) ...: ) ...: In [44]: buttons[0]() A In [45]: buttons[1]() B In [46]: buttons[-1]() Z Note also, it is consider an antipattern to use for i in range(n): some_iterable[i] when you can simply iterate over the iterable instead. Usually, you just want the actual value, so you just do for x in some_iterable.
answers question: http://stackoverflow.com/q/49663292
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49663292
type: AcceptedAnswer

http://stackoverflow.com/comment/86227382
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49607290
type: Comment
has text: Hi @DebanjanB, thks so much for your comments. I tried your code and it still opens in the same tab. The page I am trying to scrape is this one. [link](https://www.skillsconnect.gov.sg/sop/WebPageHandler?pn=WP_TMCourseSearch&p=L3E&action=advance) You can try entering a keyword like 'data' inside the first textbox and click the 'Search' button. A new page will then open and the first link that is visible is "Data Interpretation & Analysis" I am trying to open up this link in a new tab. Using the code you gave, it still opens up the link in the same tab :( Any idea why? thank you! :)

http://stackoverflow.com/comment/86309737
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49636500
has text: What do you mean by removing? I made it transparent on the alpha channel yes, but of course he is still here

http://stackoverflow.com/comment/86447239
type: AnswerComment
has text: That makes it perfectly clear! Thank you very much for the wonderful explanation, it really helps a lot!
score: 0
comment on: http://stackoverflow.com/a/49716779
type: Comment

http://stackoverflow.com/q/49728277
has answer: http://stackoverflow.com/a/67957318
has answer: http://stackoverflow.com/a/49728426
has answer: http://stackoverflow.com/a/49728527
favorite count: 0
type: Question
upvote count: 2
has body: I did a pip operation and got a suggestion from pip to upgrade: You are using pip version 9.0.1, however version 9.0.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Unfortunately I upgraded using sudo, even though I'm not convinced it is what actually caused my problems: sudo pip install --upgrade pip Now whatever I try, pip complains about me not using pip 9.0.1: pip Traceback (most recent call last): File "/usr/local/opt/python/libexec/bin/pip", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3019, in &lt;module&gt; @_call_aside File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3003, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3032, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 657, in _build_master return cls._build_from_requirements(__requires__) File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 670, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 849, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application I want to either downgrade or reinstall, but all suggestions I find suggest doing pip uninstall pip or similar and that is not really an option at this point. Any suggestions?
has title: How to uninstall corrupt pip
possible better answer: http://stackoverflow.com/a/49728527
tagged with: pip
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/57466187
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49728426
downvote count: 0

http://stackoverflow.com/comment/86417230
comment on: http://stackoverflow.com/q/49701383
type: Comment
type: QuestionComment
score: 0
has text: @hulkinBrain Ok, sorry, just wanted to clarify.

http://stackoverflow.com/comment/86490860
has text: The idea is not have to intervene manually on the models.py file, so I can run scripts automatically with some cron job and keep all the django projects in sync with the database. I am thinking of using a custom manage.py command to add these imports.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49737317
type: Comment

http://stackoverflow.com/a/49696972
answers question: http://stackoverflow.com/q/49696818
has comment: http://stackoverflow.com/comment/86407138
has comment: http://stackoverflow.com/comment/86407190
type: Answer
has body: IIUC, to drop all columns where the column as all zeros, you can use: df.drop(df.columns[df.eq(0).all()], axis=1) Update: Where columns A and C are your two checking columns, you can use this: df.drop(df.index[(df.C.eq(0) | df.A.eq(0))])
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/49633969
answers question: http://stackoverflow.com/q/49633765
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86281384
downvote count: 0
has body: Assuming you have your data in a dataframe, you can split into columns using pd.Series.apply: import pandas as pd df = pd.DataFrame({0:[(1,'2000-01-04',328647,5000), (2,'2000-01-09',465858,5000), (3,'2000-01-09',378115,5000), (4,'2000-01-14',121895,5000), (5,'2000-01-16',325172,5000), (6,'2000-01-16',156062,5000), (7,'2000-01-17',472142,5000)]}) df[[0, 1, 2, 3]] = df[0].apply(pd.Series) # 0 1 2 3 # 0 1 2000-01-04 328647 5000 # 1 2 2000-01-09 465858 5000 # 2 3 2000-01-09 378115 5000 # 3 4 2000-01-14 121895 5000 # 4 5 2000-01-16 325172 5000 # 5 6 2000-01-16 156062 5000 # 6 7 2000-01-17 472142 5000
type: Answer

http://stackoverflow.com/comment/86279057
comment on: http://stackoverflow.com/q/49635509
score: 0
has text: Another question - are the arrays in the tuples all the same shape? In the example they are (1,) and (2,) shaped.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49657553
tagged with: pandas
tagged with: matplotlib
tagged with: python
type: Question
has title: 3D plot in pandas DataSeries
has comment: http://stackoverflow.com/comment/86324539
answer count: 0
has comment: http://stackoverflow.com/comment/86324478
type: UnansweredQuestion
score: 0
has body: I need to construct a 3D plot where X and Y axis indicate the size fo the ex_one and ex_two respectively. Z represent the relations between the ex_one and ex_two manifested in 'weight' column. I have following dataset: ex_one fake_date ex_two weight 0 1 2001-07-30 695 1 1 10 2004-02-07 1405 1 2 100 2000-09-19 4832 1 3 100 2003-03-11 626 1 4 1000 2000-01-04 3993 1 5 100001 2000-01-16 213974 2 6 100001 2000-02-01 136902 1 7 100001 2000-02-08 100005 1 8 100001 2000-10-18 213963 1 9 100001 2000-12-22 100006 1 My goal here is to do a 3D plot X = df.groupby(df['ex_one']).count() --&gt; represents ex_one Y = df.groupby(df['ex_two']).count() --&gt; represents ex_two Z = **a series that counts df['weight'] if weight exists in ex_one and ex_two** I am stuck how to do counts for Z. If I do plot for ex_one and ex_two which is easy (2D), I get following plot.

http://stackoverflow.com/a/49712199
type: Answer
has body: You need to use from multiprocessing.pool import Pool Pool doesn't exist in the multiprocessing package but it exists in the pool subpackage under multiprocessing. The directory structure is multiprocessing/ __init__.py pool.py When you do from multiprocessing import pool You are actually trying to import from __init__.py which doesn't have the Pool class, pool.py has the Pool class. Hope this helps. reference - Python multiprocessing source code on github
answers question: http://stackoverflow.com/q/49643077
score: 0

http://stackoverflow.com/q/49683367
tagged with: python
type: Question
downvote count: 0
duplicate of: http://stackoverflow.com/q/19451144
duplicate of: http://stackoverflow.com/q/10434599
upvote count: 1
has body: I have some dynamically generated content populated by JS within the following attribute: &lt;div id="connection" class="fp"&gt; XX &lt;/div&gt; How can I have the generated content "XX" available in my Python code? I'm using Flask framework. I know that using Input and Select attribute its possible as for example, &lt;input name= EMAILS type="email"&gt; then, @app.route("/", methods=['POST']) def upload(): request.form.get('EMAILS') But it's not possible for &lt;p&gt; or &lt;div&gt;.
answer count: 1
tagged with: javascript
tagged with: flask
has title: Getting content from Non-Select/Input HTML attribute Python?
duplicate of: http://stackoverflow.com/q/3066070
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49683454
accepted answer: http://stackoverflow.com/a/49683454
score: 1
tagged with: http://stackoverflow.com/tag/html
linked to: http://stackoverflow.com/q/19451144

http://stackoverflow.com/q/49691601
has comment: http://stackoverflow.com/comment/86396231
downvote count: 0
has title: cv2.dnn' has no attribute 'readNet' using python 3.6 and opencv3.4.1
has answer: http://stackoverflow.com/a/55845461
has answer: http://stackoverflow.com/a/67806101
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/87673746
accepted answer: http://stackoverflow.com/a/49693391
has answer: http://stackoverflow.com/a/49693391
possible better answer: http://stackoverflow.com/a/55845461
tagged with: python
score: 4
tagged with: python-3.6
upvote count: 4
type: AnsweredQuestion
has body: I have downloaded the source code of Opencv3.4.1 from github and I have built it from the source using CMake. Everything went very well and it's installed! But When I run this script: https://github.com/opencv/opencv/blob/master/samples/dnn/object_detection.py I get the following error: Traceback (most recent call last): File "object_detection.py", line 52, in &lt;module&gt; net = cv.dnn.readNet(args.model, args.config, args.framework) AttributeError: module 'cv2.dnn' has no attribute 'readNet' System information (version) OpenCV =&gt; 3.4.1 Operating System / Platform =&gt; Windows 64 Bit Python =&gt;3.6 When I run print(cv.__version__) I get 3.4.1 But I can't find the that function or any other new features in the 3.4.1 version! I have built from the source on Ubuntu 16.04 and on Windows 10. But still no luck! the source is downloaded from Github https://github.com/opencv/opencv/archive/3.4.1.zip Does anyone has any tips?
answer count: 3
has comment: http://stackoverflow.com/comment/86397209

http://stackoverflow.com/comment/93511394
score: 0
comment on: http://stackoverflow.com/q/49750173
type: Comment
type: QuestionComment
has text: have you found a way to do this

http://stackoverflow.com/comment/86307145
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49648419
type: AnswerComment
has text: thank you. but i get red line under the "Application excel = new Application();"

http://stackoverflow.com/q/49611095
has comment: http://stackoverflow.com/comment/86228673
has comment: http://stackoverflow.com/comment/86228646
has title: Trouble with call function
favorite count: 0
type: Question
upvote count: 0
downvote count: 8
score: -8
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49611223
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49611223
has body: I wrote the parser log_file. But i can`t understand why I can not call a function in this block. Help me please.
has comment: http://stackoverflow.com/comment/86228958

http://stackoverflow.com/q/49615816
has comment: http://stackoverflow.com/comment/86239377
answer count: 0
type: UnansweredQuestion
has title: How to replace String values in a pandas dataframe column with pre-selected substring values?
has body: I'd like to replace string values within a certain column of a pandas dataframe in python 3 with a particular set of substrings. If the string value in a column contains one of the substrings I have in a separate list(or whatever other data structure that's suitable), then replace the value in the dataframe with that particular substring. If the string value doesn't have any of the selected substrings, then remove it all together from the dataframe. For example: Index A B C 0 .... Ottawa ON and Hull .... 1 .... Grand Forks BC .... 2 .... Frank AB .... 3 .... Prairies .... And I have a list or really any common data structure that holds the following substring values : "ON", "BC", "AB" My result should look like this: Index A B C 0 .... ON .... 1 .... BC .... 2 .... AB .... I can't seem to come up with a clean way of addressing my problem. Any help will be much appreciated. Thank you!
downvote count: 0
tagged with: python
tagged with: string
linked to: http://stackoverflow.com/q/41954822
has comment: http://stackoverflow.com/comment/86238352
favorite count: 0
score: 3
tagged with: pandas
upvote count: 3
duplicate of: http://stackoverflow.com/q/41954822
tagged with: dataframe
tagged with: replace
type: Question

http://stackoverflow.com/comment/86278140
comment on: http://stackoverflow.com/q/49635215
type: Comment
type: QuestionComment
has text: Are there any column headers? What is the output supposed to look like? you should probably use header parameter to start at the right row
score: 0

http://stackoverflow.com/comment/86387586
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49687220
type: Comment
has text: Okay I told you to change the `key` to `inputKey`

http://stackoverflow.com/comment/86442194
type: Comment
comment on: http://stackoverflow.com/q/49714520
has text: Please include the _complete_ error message in your question.
type: QuestionComment
score: 3

http://stackoverflow.com/comment/86363240
type: QuestionComment
comment on: http://stackoverflow.com/q/49673654
score: 0
has text: @hpaulj There is a `fractions` module in Python's standard library!
type: Comment

http://stackoverflow.com/a/49621552
type: Answer
has body: You will need to keep track of the keys and the value in that dict like: for k, v in answers.items(): if len(v) &gt; 1: T.add_edge(v[0], v[1]) else: T.add_edge(k, v[0])
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49621514
answers question: http://stackoverflow.com/q/49621514
downvote count: 0
score: 1

lstm
tags question: http://stackoverflow.com/q/49703387
tags question: http://stackoverflow.com/q/49638038
tags question: http://stackoverflow.com/q/49668169
tags question: http://stackoverflow.com/q/49649236
tags question: http://stackoverflow.com/q/49611307
tags question: http://stackoverflow.com/q/49670832
tags question: http://stackoverflow.com/q/49721810
tags question: http://stackoverflow.com/q/49638685
tags question: http://stackoverflow.com/q/49699242
tags question: http://stackoverflow.com/q/49664069
tags question: http://stackoverflow.com/q/49750367
tags question: http://stackoverflow.com/q/49654739
tags question: http://stackoverflow.com/q/49658423
type: Tag
tag name: lstm
tags question: http://stackoverflow.com/q/49674079
tags question: http://stackoverflow.com/q/49617130

http://stackoverflow.com/comment/86425417
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49706062
score: 2
has text: How are you getting those images? Could you provide some sample code so that we can see roughly what you're doing?

http://stackoverflow.com/comment/86295762
score: 1
comment on: http://stackoverflow.com/a/49635841
type: Comment
type: AnswerComment
has text: It needs to be a big enough int to hold a pointer. Practically size_t does that (although it isn't guaranteed...). Although I think `uintptr_t` would actually have been the right thing to use

http://stackoverflow.com/comment/86403606
has text: This is usually formulated as product of binary-vars and continuous variables (assuming some bounding). This needs to be linearized like for example described [here](https://orinanobworld.blogspot.de/2010/10/binary-variables-and-quadratic-terms.html). There is no automatic-way in cvxpy.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49682748

http://stackoverflow.com/comment/86415903
has text: Use the `timeit` module to find out..
type: QuestionComment
comment on: http://stackoverflow.com/q/49701143
score: 5
type: Comment

http://stackoverflow.com/q/49747045
has comment: http://stackoverflow.com/comment/86509019
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/86508893
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86508476
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49836160
has comment: http://stackoverflow.com/comment/86509111
has body: I want to apply a function row-wise to a dataframe that looks like this: name value 'foo' 2 'bar' 4 'bar' 3 'foo' 1 . . . . . . 'bar' 8 Speed is important to me since I am operating on multiple 90GB datasets, so I have been attempting to vectorize the following operation for use in df.apply: Conditioned on the 'name', I want to plug 'value' into a separate function, perform some arithmetic on the result, and write to a new column 'output'. Something like, funcs = {'foo': &lt;FunctionObject&gt;, 'bar': &lt;FunctionObject&gt;} def masterFunc(row): correctFunction = funcs[row['name']] row['output'] = correctFunction(row['value']) + 3*row['value'] df.apply(masterFunc, axis=1). In my real problem, I have 32 different functions that could apply to the 'value' based on the 'name'. Each of those individual functions (fooFunc, barFunc, zooFunc, etc) are already vectorized; they are scipy.interp1d functions built like this: separateFunc = scipy.interpolate.interp1d(x-coords=[2, 3, 4], y-coords=[3, 5, 7]) #separateFunc is now a math function, y=2x-1. use case: y = separateFunc(3.5) # y == 6 However, I am not sure how I can vectorize the masterFunc itself. It seems like choosing which function to 'pull out' to apply to the 'value' is very expensive, because it requires a memory access at each iteration (with my current method of storing the functions in hashtables). However, the alternative just seems to be a bunch of if-then statements, which also seems impossible to vectorize. How can I speed this up? Actual code, with repetitive parts removed for brevity: interpolationFunctions = {} #the 'interpolate.emissionsFunctions' are a separate function which does some scipy stuff interpolationFunctions[2] = interpolate.emissionsFunctions('./roadtype_2_curve.csv') interpolationFunctions[3] = interpolate.emissionsFunctions('./roadtype_3_curve.csv') def compute_pollutants(row): funcs = interpolationFunctions[row['roadtype']] speed = row['speed'] length = row['length'] row['CO2-Atm'] = f…
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/49836160
has comment: http://stackoverflow.com/comment/86508373
downvote count: 0
tagged with: scipy
tagged with: data-science
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86508534
has title: Speed up or vectorize pandas apply function - require a conditional application of a function
score: 3
has comment: http://stackoverflow.com/comment/86508649
tagged with: python
has comment: http://stackoverflow.com/comment/86509211

http://stackoverflow.com/comment/86244942
has text: Python is case-sensitive.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49618953

http://stackoverflow.com/comment/86354982
has text: I am using the following code but it is storing same values multiple times in the list for example, it is storing 'a':[10:10] for me. Can you please tell me where I am going wrong. Below is my code: def idf_total_updated(node): dic=defaultdict(list) next_node=[] for child in node.children: next_node.append(child) for k,v in child.idf.items(): dic[k].append(v) if next_node: for i in next_node: idf_total_updated(i) return dic
comment on: http://stackoverflow.com/a/49671481
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49658308
answer count: 2
downvote count: 4
upvote count: 31
has title: How does the logical `and` operator work with integers?
has answer: http://stackoverflow.com/a/49658343
has comment: http://stackoverflow.com/comment/86326036
favorite count: 0
type: AnsweredQuestion
has body: So, I was playing with the interpreter, and typed in the following: In [95]: 1 and 2 Out[95]: 2 In [96]: 1 and 5 Out[96]: 5 In [97]: 234324 and 2 Out[97]: 2 In [98]: 234324 and 22343243242 Out[98]: 22343243242L In [99]: 1 or 2 and 9 Out[99]: 1 Initially I thought that it has to do with False and True values, because: In [101]: True + True Out[101]: 2 In [102]: True * 5 Out[102]: 5 But that doesn't seem related, because False is always 0, and it seems from the trials above that it isn't the biggest value that is being outputted. I can't see the pattern here honestly, and couldn't find anything in the documentation (honestly, I didn't really know how to effectively look for it). So, how does int(x) [logical operation] int(y) work in Python?
accepted answer: http://stackoverflow.com/a/49658338
tagged with: expression
has answer: http://stackoverflow.com/a/49658338
linked to: http://stackoverflow.com/q/18195322
tagged with: python
type: Question
duplicate of: http://stackoverflow.com/q/47007680
score: 27
possible better answer: http://stackoverflow.com/a/49658343

http://stackoverflow.com/comment/86422329
comment on: http://stackoverflow.com/q/49704528
score: 2
has text: By definition the deepcopy should be slower in the worst scenario. But you could assert that on your own with a benchmark.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86215670
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49602975
has text: Oh, sorry, my mistake. Do you mind trying the following code: df.groupby(['Week/Year', 'feature']).size().plot(x='Week/Year', kind ='bar')

http://stackoverflow.com/comment/86274905
type: QuestionComment
score: 2
has text: Can u post your sample data from excel file?
comment on: http://stackoverflow.com/q/49633725
type: Comment

http://stackoverflow.com/q/49642573
has title: How to find python scripts by the libraries they use?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86293686
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: websocket
has body: Would be really useful for development help. I'm looking for examples of pythons websockets module but I cant find it because everything is called websockets.
type: Question
has comment: http://stackoverflow.com/comment/86293466
tagged with: python

http://stackoverflow.com/comment/86404854
score: 0
type: AnswerComment
has text: thank you for updating your answer, kindly see the the `gif` picture I added to the question, the interpreter doesn't print unless there is a print statement, or in Python3 a print function, and that's what's expected from it. but still as in your answer when evaluating the first part passed to the print function `print(True and False)` >>> `None` so now we have `None and (True or False)` without print statement/function so that shouldn't show any output on the screen, just like if I run `(True and False) or (True or False)` no output is printed.
comment on: http://stackoverflow.com/a/49692061
type: Comment

http://stackoverflow.com/a/49732303
has comment: http://stackoverflow.com/comment/86483895
has comment: http://stackoverflow.com/comment/86483701
has body: The following code perfectly works: import requests import json req = requests.get('https://jsonplaceholder.typicode.com/posts/1') req_json = json.loads(req.content) for key, value in req_json.items(): print (key, value) Depending on the URL, the resulting JSON could be "too deeply nested". If the error occurred on json.loads, you'll have to find a JSON decoder that uses a stack instead of recursive calls. If the error occurred on the print statement, avoid printing that dictionary (or define your own function that uses a stack instead).
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/86487900
has comment: http://stackoverflow.com/comment/86486576
has comment: http://stackoverflow.com/comment/86491126
has comment: http://stackoverflow.com/comment/86485115
has comment: http://stackoverflow.com/comment/86488088
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86487775
has comment: http://stackoverflow.com/comment/86481765
answers question: http://stackoverflow.com/q/49732069
has comment: http://stackoverflow.com/comment/86483964

http://stackoverflow.com/a/49696443
score: 4
has comment: http://stackoverflow.com/comment/86406465
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49696135
has comment: http://stackoverflow.com/comment/86406549
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49696135
has body: When reading a workbook with multiple sheets, pandas.read_excel returns a dictionary of DataFrames where the keys of the dictionary are the names of the sheets. It seems like you want to add a column code to each DataFrame based on the values in a list. Your code: for i in codes: for key in df.keys(): df['Sheet1']['Code'] = i Has two issues. Firstly, inside the loop you are not using the key at all. You're always accessing "Sheet1". Secondly, this is a double for loop which means it will iterate over every sheet for every code. What you want instead is to loop over the values in parallel. Basically you want to do the following: for i in range(len(codes)): code = codes[i] key = df.keys()[i] df[key]['Code'] = code This is exactly what zip() does. So, you can write the above loop more compactly as: for code, key in zip(codes, df.keys()): df[key]['Code'] = code Not this assumes that the length of codes is equal to the number of keys in the dictionary df. Afterwards, you can concatenate all of the DataFrames using pandas.concat: combined = pd.concat(df) Which works because concat: takes a sequence or mapping of Series, DataFrame ... If a dict is passed, the sorted keys will be used as the keys argument, unless > it is passed, in which case the values will be selected (see below).
type: Answer

http://stackoverflow.com/q/49721211
has comment: http://stackoverflow.com/comment/86517637
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86460717
has title: Python + Selenium: webdriver find XPath
has body: I want to click the link /any/path (on both the same) by using: webdriver.find_element_by_xpath() First I want to find "Firstname". From "Firstname" I want to find "Lastname". I don't want to find "Firstname" and "Lastname" separately. I need an XPath which includes "Firstname" and from there to "Lastname". I know that i can find it seperately with "//*[contains(text(),'Firstname')]". I want to click /any/path. Note: The path changes, so I can't search for just the path: Is there any other possibility to find "Lastname" via "Firstname"?
tagged with: element
answer count: 1
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/86531013
has answer: http://stackoverflow.com/a/49747473
tagged with: webdriver
has comment: http://stackoverflow.com/comment/86495040
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86529650
tagged with: find
has comment: http://stackoverflow.com/comment/86456290
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/49676760
type: Question
has title: SQLAlchemy: Simple ordering across many-to-many relationship
linked to: http://stackoverflow.com/q/44648635
type: UnansweredQuestion
upvote count: 5
tagged with: python
duplicate of: http://stackoverflow.com/q/44648635
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/86369746
score: 5
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49676983
has body: I'm pretty new to SQLAlchemy, and am trying to figure out how to set up the most straightforward order_by on a many-to-many relationship with an Association Object. I saw a few questions here about ordering by the count, but not this more basic one. Assume these tables (simplified from the actual ones): class Event(db.Model): __tablename__ = 'event' id = db.Column(db.Integer, primary_key=True) description = db.Column(db.String(255)) date = db.Column(db.Date) guests = db.relationship('Guest_Event', back_populates='event') class Guest(db.Model): __tablename__ = 'guest' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(256)) events = db.relationship('Guest_Event', back_populates='guest') class Guest_Event(db.Model): __tablename__ = 'guest_event' id = db.Column('id', db.Integer, primary_key=True) guest_id = db.Column('guest_id', db.Integer, db.ForeignKey('guest.id')) event_id = db.Column('event_id', db.Integer, db.ForeignKey('event.id')) guest = db.relationship('Guest', back_populates='events') event = db.relationship('Event', back_populates='guests') All I want to do is to have something like: event = Event.query.get(id) # Then in a Jinja2 template: The following people were at this event: {% for guest_event in event.guests %} {{ guest_event.guest.name }} {% endfor %} where this list is ordered by guest.name, or similarly guest = Guest.query.get(id) # Jinja2: {{ guest.name }} was at these events: {% for guest_event in guest.events %} {{ guest_event.event.date }}: {{ guest_event.event.description }} {% endfor %} where this is ordered by event.date, possibly descending. I've tried putting order_by='Guest.name' in the Guest_Event class or the Event class, both of which throw an SQL error "Unknown column guest.name in order clause", not surprisingly since this query is only operating on the association table. But I don't know what else to do. Ultimately I'd like to make an Association Proxy, since I'd like to just be able to do for guest in event.gues…
favorite count: 0

http://stackoverflow.com/q/49738284
tagged with: python
linked to: http://stackoverflow.com/q/12200114
has title: Python estimated param
has body: I have data x and I want to optimize two parameters m,s, but i don't know how do that. I trying many of option but still it's no working. Result of esti_parametrs should be [0,1]. Can someone help me? from scipy import optimize import numpy as np x=np.random.randn(100) def gaus(x,m,s): return np.log(1 / (np.sqrt(2 * np.pi) * s) * np.exp(- (x - m) ** 2 / (2 * s ** 2))) initial_guess=[0,0] esti_parametrs=optimize.minimize(lambda m,s: -gaus(x,m,s),initial_guess) print(esti_parametrs)
has comment: http://stackoverflow.com/comment/86493577
has comment: http://stackoverflow.com/comment/86491398
answer count: 0
score: 0
tagged with: scipy
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86494829

http://stackoverflow.com/comment/86391721
type: AnswerComment
comment on: http://stackoverflow.com/a/49687505
type: Comment
score: 0
has text: @asimo - Can you change data for new condition with expected output?

http://stackoverflow.com/q/49669647
tagged with: django-rest-framework
answer count: 1
type: Question
has title: How Can I Store and serve an image in Django Rest Framework using Mongoengine (Mongodb module for Django)
tagged with: python
type: UnansweredQuestion
tagged with: mongoengine
tagged with: mongodb
has body: here is my models.py : models.py class Resource(Document): instruction = fields.StringField(required=True) picture = fields.ImageField(required=False) and my serializer : class ResourceSerializer(serializers.DocumentSerializer): class Meta: model = Resource fields = '__all__' and my views.py class ResourceViewSet(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = ResourceSerializer def get_queryset(self): return Resource.objects() and this is the response that i get when im trying to list the pictures HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": "5ac4886a91a48946801813c9", "instruction": "test", "picture": "5ac4886991a48946801813bf" } ] note : mongodb using gridfs to storing the imagefiles in case that mongodb using gridfs to storing the imagefiles , how can i send the images to client ?
score: 0
has answer: http://stackoverflow.com/a/49673822
tagged with: django

http://stackoverflow.com/a/49759299
answers question: http://stackoverflow.com/q/49754741
downvote count: 0
type: Answer
has body: If you pip install python-dateutil from dateutil.rrule import rrule, MONTHLY, weekdays from dateutil.parser import parse import math def month_week(date): return math.ceil((date - date.replace(day=1)).days / 7 ) or 1 start_date = parse(input("Enter a startdate: ")) for day in rrule(freq=MONTHLY, count=5, dtstart=start_date, byweekday=weekdays[start_date.weekday()]( month_week(start_date)), ): print("Date: ", day.date()) will do what you expect for 2018-04-13. From your question I'm not sure what your expected output would be for 2018-09-01 (1st Saturday of September) or 2018-01-29 (5th Friday in January). So you may want to change the month_week function to return the weeknumber of the month you expect it to be.
score: 2
upvote count: 2

http://stackoverflow.com/q/49608179
favorite count: 0
tagged with: celery
type: Question
has answer: http://stackoverflow.com/a/49611359
tagged with: rest
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51186525
score: 6
tagged with: python
upvote count: 6
answer count: 3
has body: Is there a way to use Celery for: Queue a HTTP call to external URL with Form parameters (HTTP Post to URL) The external URL will respond HTTP response, 200, 404, 400 etc, if response is in form of error non-200-ish response it will retry for a certain number of retry and will retire as needed Add Task / Job / Work queue into Celery using REST API, passing the URL to call and Form parameters
has answer: http://stackoverflow.com/a/58300556
has title: Celery REST API
downvote count: 0

http://stackoverflow.com/comment/86244123
has text: @JohanL "dutch" things?
score: 0
comment on: http://stackoverflow.com/a/49618400
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49663704
has comment: http://stackoverflow.com/comment/104632057
favorite count: 0
type: Question
has body: I am using this Python library for Hidden Markov Model. https://github.com/hmmlearn/hmmlearn //use whole sequence for HMM training rescaled_model = GaussianHMM(n_components= 3, covariance_type="full", n_iter=2000).fit(rescaled_A) rescaled_hidden_states = rescaled_model.predict(rescaled_A) //use partial sequence for HMM training train_len = int(len(rescaled_A) * 0.999) model_test = GaussianHMM(n_components= 3, covariance_type="full", n_iter=2000).fit(rescaled_A**[:train_len]**) hidden_states_test = model_test.predict(rescaled_A) print('rescaled_hidden_states: ', collections.Counter(rescaled_hidden_states)) print('hidden_states_test: ', collections.Counter(hidden_states_test)) As we can see, the decoded hidden state changes b/c of the training/testing data split. The first case has 2305 hidden state 1, while the second case has 2305 hidden state 0. This changes label which makes it impossible to correctly predict next hidden state and interpret its meaning. rescaled_hidden_states: Counter({1: 2305, 2: 1537, 0: 744}) hidden_states_test: Counter({0: 2305, 2: 1534, 1: 747})
has comment: http://stackoverflow.com/comment/86447431
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: hmmlearn decoded hidden states changes
downvote count: 0
tagged with: machine-learning
tagged with: python
tagged with: hidden-markov-models
score: 2

http://stackoverflow.com/comment/86244241
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49618052
type: QuestionComment
has text: ahhh I know what the issue is :)

http://stackoverflow.com/comment/86490036
type: Comment
comment on: http://stackoverflow.com/a/49712680
type: AnswerComment
score: 0
has text: Thank you so much for your help. it has been fun understanding how Bytecode works.

http://stackoverflow.com/comment/86518054
score: 0
comment on: http://stackoverflow.com/q/49702876
type: Comment
type: QuestionComment
has text: What does "doesn't work" mean _exactly_?

http://stackoverflow.com/comment/86465169
type: Comment
type: QuestionComment
has text: @miradulo from where `code_num` came?
comment on: http://stackoverflow.com/q/49725522
score: 0

http://stackoverflow.com/a/49758102
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49757135
has body: I've never used BeautifulSoup before and haven't used Python in ages but something like this should work (though you should add error checking): # Get the content of the claims section # input: # soup - the root soup document def getClaimsContent(soup): # the text content of the Claims section claimsContent = ""; # first horizontal line starting the Claims section # might have to be "soup.find_all(isClaimsHeader)" firstHR = soup.find(isClaimsHeader).find('hr'); # for every sibling, until the next horizontal line... node = firstHR.next_sibling; while(node.name.lower() != 'hr'): claimsContent += node.get_text(); node = node.next_sibling; return claimsContent; # Returns true if '&lt;CENTER&gt;... Claims ...&lt;/CENTER&gt;' is the current tag def isClaimsHeader(tag): # can be simplified, just expanded for debugging if (tag.name.lower() == 'center'): text = tag.get_text().lower(); # for debugging, make sure the text actually equals 'claims' print('center text: ' + text); return (text == 'claims'); I hope I got everything right.. please let me know if this actually works.
accepted answer of: http://stackoverflow.com/q/49757135
type: Answer

http://stackoverflow.com/comment/86431940
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49709237
has text: It seems need `GDP['Average'] = np.average(GDP.iloc[:,0:], axis=1)`
score: 0

http://stackoverflow.com/a/49620268
score: 12
accepted answer of: http://stackoverflow.com/q/49620189
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86261440
upvote count: 12
has body: As the error suggests, your model doesn't have an id field. It has three fields, name, formula, and product. You have primary_key=True for the product field, so Django does not automatically create the id field.
answers question: http://stackoverflow.com/q/49620189
type: Answer

http://stackoverflow.com/comment/86410834
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49695402
score: 0
has text: And just a note: If you want to read the entire image as array, you can use ReadAsArray without any parameters. I find that somewhat simpler (I am guessing that xsize and ysize is meant as the image size)

http://stackoverflow.com/comment/129165187
type: Comment
type: AnswerComment
has text: Another thing that worked for me was `cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)`
score: 1
comment on: http://stackoverflow.com/a/49901961

http://stackoverflow.com/comment/86249502
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49621259
has text: `[v for v in answers.values() if len(v) > 1]` But then how will you which is goes with?